#!/bin/sh
set -eu
src=${1:?source markdown}
template=${2:?html template}
out=${3:?output html}
tmp="${out}.body"
if command -v cmark >/dev/null 2>&1; then
cmark --unsafe "$src" > "$tmp"
else
awk '
function esc(s) {
gsub(/&/, "\\&", s)
gsub(/, "\\<", s)
gsub(/>/, "\\>", s)
return s
}
function inline_code(s, out, pre, code, post) {
out = ""
while(match(s, /`[^`]+`/)) {
pre = substr(s, 1, RSTART - 1)
code = substr(s, RSTART + 1, RLENGTH - 2)
post = substr(s, RSTART + RLENGTH)
out = out esc(pre) "" esc(code) ""
s = post
}
return out esc(s)
}
function close_list() {
if(in_list) {
print ""
in_list = 0
}
}
function close_para() {
if(in_para) {
print "
"
in_code = 1
}
next
}
in_code {
print esc($0)
next
}
/^# / {
close_para()
close_list()
text = substr($0, 3)
printf "%s
\n", slug(text), inline_code(text)
next
}
/^## / {
close_para()
close_list()
text = substr($0, 4)
printf "%s
\n", slug(text), inline_code(text)
next
}
/^### / {
close_para()
close_list()
text = substr($0, 5)
printf "%s
\n", slug(text), inline_code(text)
next
}
/^#### / {
close_para()
close_list()
text = substr($0, 6)
printf "%s
\n", slug(text), inline_code(text)
next
}
/^- / {
close_para()
if(!in_list) {
print ""
in_list = 1
}
print "- " inline_code(substr($0, 3)) "
"
next
}
/^$/ {
close_para()
close_list()
next
}
{
close_list()
if(!in_para) {
printf ""
in_para = 1
} else {
printf "\n"
}
printf "%s", inline_code($0)
}
END {
close_para()
close_list()
if(in_code)
print "
"
}
' "$src" > "$tmp"
fi
# cmark does not add heading IDs. Use the same slugs as the fallback renderer
# so published API links work regardless of the installed Markdown renderer.
python3 - "$tmp" <<'PY'
import html
import posixpath
import re
import sys
from pathlib import Path
path = Path(sys.argv[1])
used = set()
def anchor(match):
level, attributes, label = match.groups()
existing = re.search(r'\bid="([^"]+)"', attributes)
plain = html.unescape(re.sub(r'<[^>]+>', '', label))
slug = existing[1] if existing else re.sub(r'[^A-Za-z0-9]+', '-', plain).strip('-').lower()
candidate = slug
suffix = 1
while candidate in used:
candidate = f'{slug}-{suffix}'
suffix += 1
used.add(candidate)
attributes = re.sub(r'\s+id="[^"]+"', '', attributes)
return f'