Grapho: generate html table of contents

This commit is contained in:
Nero 2022-07-02 15:14:45 +00:00
parent 071c9af7bb
commit 48589f14b8
1 changed files with 95 additions and 2 deletions

97
md2html
View File

@ -1,9 +1,13 @@
#!/usr/bin/awk -f
#!/bin/sh
tmpfile=".$$.$1.md2html"
awk '
BEGIN {
indent = 0
prefix = "html/body/"
print("<!DOCTYPE html>")
level("html/head")
toc=0
}
function headers() {
@ -58,7 +62,7 @@ function escape(text) {
return text
}
function inline(text) {
function inline(text) {
text = escape(text)
text = gensub(/\*\*([^\*]*)\*\*/, "<strong>\\1</strong>", "g", text)
text = gensub(/\*([^\*]*)\*/, "<em>\\1</em>", "g", text)
@ -134,6 +138,11 @@ function inline(text) {
d=length($1)
gsub(/^#* /, "", $0)
if (d==1 && !meta["title"]) meta["title"] = $0
if (d!=1 && toc==0) {
level(prefix "summary")
level(prefix)
toc=1
}
id1=$0
gsub(/[^a-zA-Z0-9]/, "", id1)
hash[d]=id1
@ -170,4 +179,88 @@ function inline(text) {
}
END {
level("")
}' > "$tmpfile"
sed -n '/<summary>/!p;//q' "$tmpfile"
awk '
BEGIN {
indent = 4
level("summary")
}
function oneliner(tag, str, args) {
printf("%0" indent "s<%s>%s</%s>\n", "", tag args, inline(str), tag)
}
function level(new) {
split(new, a, "/")
split(old, b, "/")
for (common = 0; common < 10; common++) {
if (common >= length(a)) break
if (common >= length(b)) break
if (a[common] != b[common]) break
}
for (i = length(b); i >= common; --i) {
if (b[i]) {
indent = indent - 2
if (b[i]=="pre") {
printf("</%s>\n", b[i])
} else {
printf("%0" indent "s</%s>\n", "", b[i])
}
}
}
for (i = common; i < length(a); i++) {
if (a[i]) {
printf("%0" indent "s<%s>\n", "", a[i])
indent = indent + 2
}
}
old = new
}
function escape(text) {
gsub(/&/, "\\&amp;", text)
gsub(/</, "\\&lt;", text)
gsub(/>/, "\\&gt;", text)
gsub(/\"/, "\\&quot;", text)
return text
}
function inline(text) {
text = escape(text)
text = gensub(/\*\*([^\*]*)\*\*/, "<strong>\\1</strong>", "g", text)
text = gensub(/\*([^\*]*)\*/, "<em>\\1</em>", "g", text)
text = gensub(/`([^`]*)`/, "<code>\\1</code>", "g", text)
text = gensub(/\[(.*)\]\((.*)\)/, "<a href=\"\\2\">\\1</a>", "g", text)
return text
}
/<h[2-6] / {
id=$0
gsub(/^.*id=\"/,"",id)
gsub(/\">.*$/,"",id)
d=$1
gsub(/^<h/, "", d)
gsub(/ *<[^>]*>/, "", $0)
trg="summary/ul"
for(i=2;i<d;i++) trg=trg "/li/ul"
level(trg)
level(trg "/li")
oneliner("a", $0, " href=\"#" id "\"")
}
END {
level("")
}
' < "$tmpfile"
sed -e '1,/<\/summary>/ d' "$tmpfile"
rm "$tmpfile"