From da5e20e8675cefe426a03d35f2eb3209fd44ab41 Mon Sep 17 00:00:00 2001 From: Ville Rantanen Date: Thu, 23 Mar 2023 17:58:49 +0200 Subject: [PATCH] insert TOC with code --- reporting/md-toc | 54 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/reporting/md-toc b/reporting/md-toc index bf64eb3..d0d2ca3 100755 --- a/reporting/md-toc +++ b/reporting/md-toc @@ -4,26 +4,20 @@ import argparse import sys import re +MARKERSTART = "[TOCSTART]: #" +MARKEREND = "[TOCEND]: #" + def get_opts(): - parser = argparse.ArgumentParser( description="TOC for markdown.", - epilog="""Automatic TOC guide: -Add these hidden comments in the markdown: -[TOCSTART]: # -[TOCEND]: # - -Then, use this command to generate TOC: (make a backup first...) - sed -i -n \\ - -e '1,/^\[TOCSTART\]: #/p;/^\[TOCEND\]: #/,$p' \\ - -e '/^\[TOCSTART\]: #/r '<( md-toc document.md ) \\ - document.md -""", formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument("-n", help="Number TOC", action="store_true") parser.add_argument("-l", help="TOC as links", action="store_true") + parser.add_argument( + "-a", help="Print whole Markdown, with TOC included.", action="store_true" + ) parser.add_argument( "markdown", help="Filename to read. - for stdin", @@ -41,12 +35,18 @@ def main(): fp = sys.stdin else: fp = open(opts.markdown, "rt") + markdown = fp.read().splitlines() bullet = "-" counters = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] lastlev = 0 re_anchor = re.compile("[^0-9a-z-]") - for row in fp: + + entries = [] + marker_found = False + marker_end_found = False + to_remove = [] + for i, row in enumerate(markdown): if row.startswith("#"): headers, title = row.strip().split(" ", 1) if opts.l: @@ -60,8 +60,32 @@ def main(): if opts.n: bullet = "{:d}.".format(counters[pad]) - print("{}{} {}".format(pad * " ", bullet, title)) - print("") + entries.append("{}{} {}".format(pad * " ", bullet, title)) + if row == MARKERSTART: + marker_found = True + if marker_found and not marker_end_found: + to_remove.append(i) + if row == MARKEREND: + marker_end_found = True + + # Just print the TOC + if not opts.a: + print("\n".join(entries)) + return + # Print whole document + if marker_found and not marker_end_found: + raise ValueError(f"End marker '{MARKEREND}' not found in document") + + markdown = [row for i, row in enumerate(markdown) if i not in to_remove] + entries = [MARKERSTART, *entries, "", MARKEREND] + toc_position = 0 + if len(to_remove) > 0: + toc_position = to_remove[0] + + for i, row in enumerate(markdown): + if i == toc_position: + print("\n".join(entries)) + print(row) if __name__ == "__main__":