From 48589f14b847cd4e4a3fca47b7fff209780ba607 Mon Sep 17 00:00:00 2001 From: Nero <41307858+nero@users.noreply.github.com> Date: Sat, 2 Jul 2022 15:14:45 +0000 Subject: [PATCH] Grapho: generate html table of contents --- md2html | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 95 insertions(+), 2 deletions(-) diff --git a/md2html b/md2html index 11c42b4..4590889 100755 --- a/md2html +++ b/md2html @@ -1,9 +1,13 @@ -#!/usr/bin/awk -f +#!/bin/sh +tmpfile=".$$.$1.md2html" + +awk ' BEGIN { indent = 0 prefix = "html/body/" print("") 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(/\*\*([^\*]*)\*\*/, "\\1", "g", text) text = gensub(/\*([^\*]*)\*/, "\\1", "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 '//!p;//q' "$tmpfile" + +awk ' +BEGIN { + indent = 4 + level("summary") } + +function oneliner(tag, str, args) { + printf("%0" indent "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("\n", b[i]) + } else { + printf("%0" indent "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(/&/, "\\&", text) + gsub(//, "\\>", text) + gsub(/\"/, "\\"", text) + return text +} + +function inline(text) { + text = escape(text) + text = gensub(/\*\*([^\*]*)\*\*/, "\\1", "g", text) + text = gensub(/\*([^\*]*)\*/, "\\1", "g", text) + text = gensub(/`([^`]*)`/, "\\1", "g", text) + text = gensub(/\[(.*)\]\((.*)\)/, "\\1", "g", text) + return text +} + +/.*$/,"",id) + d=$1 + gsub(/^]*>/, "", $0) + trg="summary/ul" + for(i=2;i/ d' "$tmpfile" + +rm "$tmpfile"