|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import sys |
| 4 | +import re |
| 5 | + |
| 6 | +headings = re.compile('<(h[12])>([^<]*)</h[12]>') |
| 7 | +strong = re.compile('<p><strong>([^<]*)</strong>') |
| 8 | +HEADING_LEVELS = { 'h1': 0, 'h2': 1 } |
| 9 | +PERMA_LINK_CHAR='🔗' |
| 10 | + |
| 11 | +def build_loc(sections): |
| 12 | + # Build index on top of the man page |
| 13 | + out = list() |
| 14 | + yield '<div class="LOC">' |
| 15 | + for lvl, text, link in sections: |
| 16 | + if lvl == 0: |
| 17 | + continue |
| 18 | + out.append(f'<a href="#{link}">{text.capitalize()}</a>') |
| 19 | + yield ' | '.join(out) |
| 20 | + yield '</div>' |
| 21 | + |
| 22 | +def add_header_ids(buf): |
| 23 | + # Add on-hover perma links for headers |
| 24 | + sections = list() |
| 25 | + for match in headings.finditer(buf): |
| 26 | + all, el, value = (match.group(x) for x in range(3)) |
| 27 | + target = value.lower().replace(' ', '_') |
| 28 | + sections.append((HEADING_LEVELS[el], value, target)) |
| 29 | + buf = buf.replace(all, f'<{el} id="{target}">' + |
| 30 | + f'<a class="perma" href="#{target}">{PERMA_LINK_CHAR}</a>{value}</{el}>') |
| 31 | + buf = buf.replace('<!--%%%TOC%%%-->', '\n'.join(build_loc(sections))) |
| 32 | + return buf |
| 33 | + |
| 34 | +def add_item_ids(buf): |
| 35 | + # Add on-hover perma links for entries other than headers |
| 36 | + for match in strong.finditer(buf): |
| 37 | + all, value = (match.group(x) for x in range(2)) |
| 38 | + target = f'entry_{value.lower()}' |
| 39 | + for repl in (' ', '>'): |
| 40 | + target = target.replace(repl, '_') |
| 41 | + for repl in ('"', "'", '<', '\n', '/'): |
| 42 | + target = target.replace(repl, '') |
| 43 | + target = target.rstrip('_') |
| 44 | + buf = buf.replace(all, f'<p><strong id="{target}">' + |
| 45 | + f'<a class="perma" href="#{target}">{PERMA_LINK_CHAR}</a>{value}</strong>') |
| 46 | + return buf |
| 47 | + |
| 48 | +def fix_bullet_formatting(buf): |
| 49 | + # Really ought to try to understand+fix this upstream, |
| 50 | + # but for now, let's just get it working |
| 51 | + return buf.replace("·</p>\n<p>", "· ") |
| 52 | + |
| 53 | +def main(argv): |
| 54 | + with open(argv[0], 'r') as file: |
| 55 | + buf = file.read() |
| 56 | + |
| 57 | + buf = fix_bullet_formatting(buf) |
| 58 | + buf = add_header_ids(buf) |
| 59 | + buf = add_item_ids(buf) |
| 60 | + |
| 61 | + with open(argv[0], 'w') as file: |
| 62 | + file.write(buf) |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + main(sys.argv[1:]) |
| 66 | + |
0 commit comments