#!/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 --- """ def tables(body): """A table whose first row is all bold has a header; typst writes no .""" def fix(match): table = match.group(0) row = re.search(r".*?", table, re.S) if not row or row.group(0).count("") != row.group(0).count(""): return table head = row.group(0).replace("", "").replace("", "") end = row.end() return table[: row.start()] + "" + head + "" + table[end:] return re.sub(r".*?
", fix, body, flags=re.S) def blocks(body): """
is a rule, so it becomes

; in a list item only its children count. The outline is an unnumbered

    , shown as a bullet list. """ out = [] items = 0 stack = [] for tag in re.split(r"(<[^>]+>)", body): if re.match(r"": items -= 1 out.append(tag) elif re.match(r"") elif tag == "
": out.append(f"") elif tag == "
": stack.append("p" if items == 0 else "") out.append("

" if items == 0 else "") elif tag == "

": out.append("

" if stack.pop() else "") else: out.append(tag) return "".join(out) def main(): if len(sys.argv) != 3: sys.exit("usage: spec-md.py spec.html out.md") src, dst = sys.argv[1:] try: with open(src, encoding="utf-8") as fp: page = fp.read() except OSError as e: sys.exit(f"spec-md.py: {e}") body = page.split("", 1)[1].split("", 1)[0] heads = re.findall(r'', body) # Math goes through pandoc untouched, so it is parked on placeholders. maths = [] def park(match): maths.append(match.group(0)) return f"MATH-{len(maths) - 1}" body = re.sub(r"]*>.*?", park, body, flags=re.S) body = re.sub( r'(.*?)', r"\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)
    # The page has a contents list in the sidebar; the document's own one is
    # dropped, like the one in README.md and DESIGN.md on the site.
    text = re.sub(r"^## Contents\n.*?(?=^## )", "", text, flags=re.S | re.M)
    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()