#!/usr/bin/env python3 """spec-md.py - turn typst's HTML export of the spec into site markdown. usage: spec-md.py spec.html out.md typst has no markdown writer, so the HTML export is reduced to what goldmark reads and handed to pandoc for headings, lists, tables, links and emphasis. The typst heading ids are put back, because the spec cross-references its sections by them, and the MathML is carried over untouched: browsers render it natively and the page ships no TeX script. """ import re import subprocess import sys FRONT = """--- title: Specification weight: 60 source: formal/zash-spec.typ notitle: true --- """ def tables(body): """A table whose first row is all bold has a header; typst writes no
; in a list item only its children count. The outline is an unnumbered
" if items == 0 else "") elif tag == "
\1", body
)
for _ in range(2): # underlined links nest one inside the other
body = re.sub(
r'(.*?)', r"\1", body
)
body = re.sub(r'(.*?)', r"\1", body)
body = tables(body)
# A code block without a class is written as an indented block; the page
# fences them, so they survive a table or a list around them.
body = body.replace("", '')
text = subprocess.run(
["pandoc", "-f", "html", "-t", "gfm", "--wrap=none"],
input=blocks(body),
capture_output=True,
text=True,
check=True,
).stdout
# pandoc's gfm writer drops heading ids; the spec links to them. A
# heading written as text would shift every id after it, so count first.
lines = text.splitlines()
numbered = [i for i, line in enumerate(lines) if re.match(r"#{1,6} ", line)]
if len(numbered) != len(heads):
sys.exit(f"spec-md.py: {len(numbered)} headings, {len(heads)} ids")
for i, anchor in zip(numbered, heads, strict=True):
if anchor:
lines[i] = f"{lines[i]} {{#{anchor}}}"
text = "\n".join(lines)
for i in reversed(range(len(maths))):
text = text.replace(f"MATH-{i}", maths[i])
try:
with open(dst, "w", encoding="utf-8") as fp:
fp.write(FRONT + "\n" + re.sub(r"\n{3,}", "\n\n", text).strip() + "\n")
except OSError as e:
sys.exit(f"spec-md.py: {e}")
if __name__ == "__main__":
main()