1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
|
#!/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 <th>."""
def fix(match):
table = match.group(0)
row = re.search(r"<tr>.*?</tr>", table, re.S)
if not row or row.group(0).count("<strong>") != row.group(0).count("<td>"):
return table
head = row.group(0).replace("<td>", "<th>").replace("</td>", "</th>")
end = row.end()
return table[: row.start()] + "<thead>" + head + "</thead>" + table[end:]
return re.sub(r"<table>.*?</table>", fix, body, flags=re.S)
def blocks(body):
"""<div> is a rule, so it becomes <p>; in a list item only its children count.
The outline is an unnumbered <ol>, shown as a bullet list.
"""
out = []
items = 0
stack = []
for tag in re.split(r"(<[^>]+>)", body):
if re.match(r"<li\b", tag):
items += 1
out.append(tag)
elif tag == "</li>":
items -= 1
out.append(tag)
elif re.match(r"<ol\b", tag):
stack.append("ul" if "list-style-type: none" in tag else "ol")
out.append(f"<{stack[-1]}>")
elif tag == "</ol>":
out.append(f"</{stack.pop()}>")
elif tag == "<div>":
stack.append("p" if items == 0 else "")
out.append("<p>" if items == 0 else "")
elif tag == "</div>":
out.append("</p>" 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("<body", 1)[1].split(">", 1)[1].split("</body>", 1)[0]
heads = re.findall(r'<h[1-6](?: id="([^"]*)")?>', 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"<math[^>]*>.*?</math>", park, body, flags=re.S)
body = re.sub(
r'<span style="display: inline-block">(.*?)</span>', r"<code>\1</code>", body
)
for _ in range(2): # underlined links nest one inside the other
body = re.sub(
r'<span style="text-decoration: underline">(.*?)</span>', r"\1", body
)
body = re.sub(r'<span class="prefix">(.*?)</span>', 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("<pre><code>", '<pre><code class="text">')
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()
|