insert TOC with code

This commit is contained in:
Ville Rantanen
2023-03-23 17:58:49 +02:00
parent 9124ddcaac
commit da5e20e867

View File

@@ -4,26 +4,20 @@ import argparse
import sys import sys
import re import re
MARKERSTART = "[TOCSTART]: #"
MARKEREND = "[TOCEND]: #"
def get_opts(): def get_opts():
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="TOC for markdown.", 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, formatter_class=argparse.RawTextHelpFormatter,
) )
parser.add_argument("-n", help="Number TOC", action="store_true") parser.add_argument("-n", help="Number TOC", action="store_true")
parser.add_argument("-l", help="TOC as links", 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( parser.add_argument(
"markdown", "markdown",
help="Filename to read. - for stdin", help="Filename to read. - for stdin",
@@ -41,12 +35,18 @@ def main():
fp = sys.stdin fp = sys.stdin
else: else:
fp = open(opts.markdown, "rt") fp = open(opts.markdown, "rt")
markdown = fp.read().splitlines()
bullet = "-" bullet = "-"
counters = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] counters = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
lastlev = 0 lastlev = 0
re_anchor = re.compile("[^0-9a-z-]") 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("#"): if row.startswith("#"):
headers, title = row.strip().split(" ", 1) headers, title = row.strip().split(" ", 1)
if opts.l: if opts.l:
@@ -60,8 +60,32 @@ def main():
if opts.n: if opts.n:
bullet = "{:d}.".format(counters[pad]) bullet = "{:d}.".format(counters[pad])
print("{}{} {}".format(pad * " ", bullet, title)) entries.append("{}{} {}".format(pad * " ", bullet, title))
print("") 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__": if __name__ == "__main__":