insert TOC with code
This commit is contained in:
@@ -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__":
|
||||
|
||||
Reference in New Issue
Block a user