attempt to better toc

This commit is contained in:
Ville Rantanen
2023-01-03 12:12:43 +02:00
parent 75696edcfc
commit 808ff54d76

View File

@@ -1,19 +1,51 @@
#!/bin/bash #!/usr/bin/env python3
function helpexit() {
echo "Print out TOC of a markdown document"
echo "Give filename(s) as the argument"
echo " -n to number TOC elements instead of bullet"
exit
}
[[ -z "$1" ]] && helpexit
[[ "$1" = "-h" ]] && helpexit
[[ "$1" = "-n" ]] && {
NUMBER=1
shift
}
[[ "$NUMBER" -eq 1 ]] && { import argparse
grep ^# "$@" | sed -e 's,^#,1.,' -e ':loop' -e 's,1.#, 1.,' -e 't loop' | pandoc -t markdown_strict import sys
} || {
grep ^# "$@" | sed -e 's,^#,*,' -e ':loop' -e 's,*#, *,' -e 't loop'
} def get_opts():
parser = argparse.ArgumentParser(description="TOC for markdown.")
parser.add_argument("-n", help="Number TOC", action="store_true")
parser.add_argument("-l", help="TOC as links", action="store_true")
parser.add_argument(
"markdown",
help="Filename to read. - for stdin",
action="store",
default="-",
nargs="?",
)
args = parser.parse_args()
return args
def main():
opts = get_opts()
if opts.markdown == "-":
fp = sys.stdin
else:
fp = open(opts.markdown, "rt")
bullet = "-"
counters = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
lastlev = 0
for row in fp:
if row.startswith("#"):
headers, title = row.strip().split(" ", 1)
if opts.l:
title = "[{}](#{})".format(title, title.lower().replace(" ", "-"))
pad = headers.count("#") - 1
if pad < lastlev:
counters = [x if i <= pad else 0 for i, x in enumerate(counters)]
counters[pad] += 1
lastlev = pad
if opts.n:
bullet = "{:d}.".format(counters[pad])
print("{}{} {}".format(pad * " ", bullet, title))
print("")
if __name__ == "__main__":
main()