attempt to better toc
This commit is contained in:
@@ -1,19 +1,51 @@
|
||||
#!/bin/bash
|
||||
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
|
||||
}
|
||||
#!/usr/bin/env python3
|
||||
|
||||
[[ "$NUMBER" -eq 1 ]] && {
|
||||
grep ^# "$@" | sed -e 's,^#,1.,' -e ':loop' -e 's,1.#, 1.,' -e 't loop' | pandoc -t markdown_strict
|
||||
} || {
|
||||
grep ^# "$@" | sed -e 's,^#,*,' -e ':loop' -e 's,*#, *,' -e 't loop'
|
||||
}
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user