dsh-pdf-workbench 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +29 -7
  2. package/client.js +4585 -530
  3. package/docs/LAYOUT.md +56 -0
  4. package/docs/RELEASE.md +214 -57
  5. package/docs/TESTING.md +16 -0
  6. package/docs/ci.md +164 -0
  7. package/docs/copy/templates.md +110 -0
  8. package/docs/copy/terms.md +62 -0
  9. package/docs/decisions.md +444 -0
  10. package/docs/features.md +61 -0
  11. package/docs/feedback/.gitkeep +0 -0
  12. package/docs/requirements/.gitkeep +0 -0
  13. package/docs/requirements/2026-11-25-v1.5/346/224/271/350/277/233/351/234/200/346/261/202.md +622 -0
  14. package/docs/reviews/.gitkeep +0 -0
  15. package/docs/reviews/T-20261124-01.md +180 -0
  16. package/docs/reviews/T-20261124-03.md +85 -0
  17. package/docs/reviews/T-20261124-04.md +106 -0
  18. package/docs/reviews/T-20261124-05.md +94 -0
  19. package/docs/reviews/T-20261124-07.md +115 -0
  20. package/docs/reviews/T-20261124-08.md +292 -0
  21. package/docs/reviews/T-20261124-09.md +112 -0
  22. package/docs/reviews/T-20261124-10.md +112 -0
  23. package/docs/roles/ci.md +98 -0
  24. package/docs/roles/programmer.md +98 -0
  25. package/docs/roles/requirements.md +68 -0
  26. package/docs/tests/.gitkeep +0 -0
  27. package/docs/tests/T-20261124-01.md +146 -0
  28. package/docs/tests/T-20261124-03.md +81 -0
  29. package/docs/tests/T-20261124-04.md +51 -0
  30. package/docs/tests/T-20261124-05.md +51 -0
  31. package/docs/tests/T-20261124-07.md +60 -0
  32. package/docs/tests/T-20261124-08.md +61 -0
  33. package/docs/tests/T-20261124-09.md +60 -0
  34. package/docs/tests/T-20261124-10.md +61 -0
  35. package/docs/todo.md +835 -0
  36. package/index.js +337 -1
  37. package/package.json +1 -1
  38. package/src/host/backup.js +172 -33
  39. package/src/host/book-wizard.js +454 -0
  40. package/src/host/digest.js +4 -0
  41. package/src/host/engine.js +88 -0
  42. package/src/host/exports.js +159 -0
  43. package/src/host/http.js +28 -1
  44. package/src/host/imports.js +650 -0
  45. package/src/host/index-source.js +117 -11
  46. package/src/host/library-export.js +162 -0
  47. package/src/host/pdf-source.js +6 -2
  48. package/src/host/routes.js +1020 -120
  49. package/src/host/shortcut.js +238 -0
  50. package/src/host/storage.js +421 -0
  51. package/src/host/translate-blocks.js +49 -45
  52. package/src/host/translate-job.js +37 -10
  53. package/src/host/translate.js +19 -45
  54. package/src/host/translation-cache.js +209 -0
  55. package/src/host/typst-install.js +132 -0
  56. package/src/host/zip.js +486 -4
  57. package/tools/latex_to_typst.py +1353 -0
  58. package/tools/md2overlay.py +147 -152
  59. package/tools/md2overlay_typst.py +312 -0
  60. package/tools/md2typst.py +818 -0
  61. package/tools/overlay_layout.py +332 -0
  62. package/tools/pdf_blocks.py +82 -10
  63. package/tools/realign_overlay.py +4 -1
  64. package/tools/rebuild_overlay.py +3 -1
  65. package/tools/split_pdf.py +158 -0
  66. package/tools/typst_runtime.py +98 -0
  67. package/vendor/katex/LICENSE +21 -0
  68. package/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  69. package/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  70. package/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  71. package/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  72. package/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  73. package/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
  74. package/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  75. package/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
  76. package/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
  77. package/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  78. package/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
  79. package/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  80. package/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  81. package/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  82. package/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
  83. package/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  84. package/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  85. package/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  86. package/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  87. package/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  88. package/vendor/katex/katex.min.css +1 -0
  89. package/vendor/katex/katex.min.js +1 -0
  90. package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +9 -1
  91. package/src/host/book-import.js +0 -98
@@ -0,0 +1,818 @@
1
+ """把整章译文 markdown 排成 Typst 文档并编译成读版 PDF(v1.5 D 的读版内核)。
2
+
3
+ py -3 tools/md2typst.py <src.md> <out.pdf> [title]
4
+
5
+ 环境变量(与 tools/md2tex.py 对齐):
6
+
7
+ MATH_DESK_TYPST typst 可执行文件(解析顺序见 tools/typst_runtime.py)
8
+ MATH_DESK_FONTSIZE 9 / 10 / 11 / 12pt,默认 11pt
9
+ MATH_DESK_PAPER "宽,高"(英寸);缺省 A4,页边距 2.4cm
10
+ MATH_DESK_NO_TITLE 1 = 文首不排标题(即使命令行给了 title)
11
+ MATH_DESK_CJKFONT 中文字体家族,默认 Microsoft YaHei
12
+
13
+ 数学:每个 `$…$` / `$$…$$` 都交给 tools/latex_to_typst.py 转成 Typst 数学。
14
+ 转换器明确拒绝的构造(\\color、\\phantom、\\vspace 等)不会让整章失败:原始
15
+ LaTeX 以等宽字体照排,并向 stderr 打一条
16
+ `warning: formula not converted at line N (display math): …`。
17
+ 一章里有坏公式,读者看到的是那一行 LaTeX,而不是打不开的 PDF。
18
+
19
+ 和 tools/md2tex.py 的关系:CLI、环境变量、markdown 覆盖、正文观感都对齐它,
20
+ 但排版内核换成 Typst(无需 TeX 发行版,字体走系统字体)。两处有意的差异:
21
+
22
+ * `MATH_DESK_NO_TITLE=1` 优先于命令行给的 title(md2tex 里显式 title 优先);
23
+ * 文首的 `##` 标题不再丢弃(md2tex 会丢,避免和 title 重复;读版 PDF 宁可多
24
+ 一行,也不吞掉译文)。
25
+
26
+ 降级都不会静默,一律带一条 `warning:`:
27
+ * 公式转换失败 -> 原始 LaTeX 等宽照排(不中断整章);
28
+ * 表格超过 12 列 -> 逐行文本;
29
+ * 整篇第一次编译失败 -> 不排强调(`*`/`_`)重排一次;
30
+ * 环境变量写错 -> 退回默认纸张/字号。
31
+ """
32
+ import os
33
+ import re
34
+ import shutil
35
+ import sys
36
+ from collections import deque
37
+
38
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
39
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
40
+
41
+ HERE = os.path.dirname(os.path.abspath(__file__))
42
+ if HERE not in sys.path:
43
+ sys.path.insert(0, HERE)
44
+
45
+ import typst_runtime
46
+ from latex_to_typst import convert_latex
47
+
48
+ # A4 与 2.4cm 页边距,和 md2tex 的 geometry 一致(1in = 72pt,1cm = 28.35pt)。
49
+ A4_WIDTH = 595.28
50
+ A4_HEIGHT = 841.89
51
+ MARGIN = 68.03
52
+ DEFAULT_PT = 11.0
53
+ FONT_SIZES = (9.0, 10.0, 11.0, 12.0)
54
+
55
+ # 行距:xelatex 的 \linespread{1.32} 在 ctexart 11pt 下实测基线间距 17.88pt、
56
+ # 字号 10.91pt(≈1.64em)。Typst 的 par.leading 是行高之外的额外空隙(基础行高
57
+ # 在 11pt / Microsoft YaHei 下是 8.32pt),0.87em 得到 8.32+9.57≈17.9pt,和
58
+ # md2tex 的读版观感一致。直接写 leading: 1.32em 会比 md2tex 松 5pt。
59
+ LEADING_EM = 0.87
60
+
61
+ FENCE_RE = re.compile(r"^\s*```")
62
+ HEADING_RE = re.compile(r"^(#{1,6})\s+(.*)$")
63
+ LIST_RE = re.compile(r"^(\s*)([-*+]|\d+[.)])\s+(.*)$")
64
+ ROW_RE = re.compile(r"^\s*\|.*\|\s*$")
65
+ SEPARATOR_CELLS_RE = re.compile(r"^[\s:|-]+$")
66
+ LINK_OR_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\([^)]*\)|\[([^\]]+)\]\([^)]*\)")
67
+
68
+ RULE_LINES = ("---", "***", "___")
69
+ PAGEBREAK_LINES = ("\\newpage", "<!-- pagebreak -->")
70
+ # 中文收尾标点:既不能出现在行首(Typst 在行内公式/代码这种「对象」之后允许
71
+ # 断行,会把它们顶到下一行行首),也要跟着行间公式走(`$$…$$。` 的句号)。
72
+ CLOSING_PUNCTUATION = ",、。;:?!)》」』】”’"
73
+ # Typst markup 里要转义的字符:反斜线、代码/数学/强调/标签/引用起始符,以及
74
+ # 会提前闭合 content block 的方括号(本模块把正文放进 [...] 里排版)。
75
+ SPECIAL_MARKUP = set("\\#$*_`<>@~[]")
76
+ # 表格超过这个列数就没法在读版页面上排了,降级成逐行文本并 warning。
77
+ MAX_TABLE_COLUMNS = 12
78
+
79
+ USAGE = (
80
+ "用法:py -3 tools/md2typst.py <src.md> <out.pdf> [title]\n"
81
+ "\n"
82
+ "把一章 markdown 译文排成 Typst 文档并编译成读版 PDF(v1.5 D)。\n"
83
+ "环境变量:MATH_DESK_TYPST、MATH_DESK_FONTSIZE(9/10/11/12pt,默认 11)、\n"
84
+ " MATH_DESK_PAPER(\"宽,高\" 英寸)、MATH_DESK_NO_TITLE=1、MATH_DESK_CJKFONT\n"
85
+ )
86
+
87
+
88
+ # ---------------------------------------------------------------- 环境与版式
89
+ def warn(message):
90
+ """降级路径的唯一出口:stderr + `warning:` 前缀,测试按这个前缀计数。"""
91
+ print("warning: " + message, file=sys.stderr)
92
+
93
+
94
+ def font_size():
95
+ raw = os.environ.get("MATH_DESK_FONTSIZE", "").strip()
96
+ if raw == "":
97
+ return DEFAULT_PT
98
+ value = raw[:-2].strip() if raw.lower().endswith("pt") else raw
99
+ try:
100
+ size = float(value)
101
+ except ValueError:
102
+ warn("MATH_DESK_FONTSIZE=%r 不是字号,改用 %.0fpt" % (raw, DEFAULT_PT))
103
+ return DEFAULT_PT
104
+ if size not in FONT_SIZES:
105
+ warn("MATH_DESK_FONTSIZE=%r 不在 9/10/11/12pt 里,改用 %.0fpt" % (raw, DEFAULT_PT))
106
+ return DEFAULT_PT
107
+ return size
108
+
109
+
110
+ def paper_size():
111
+ """(宽, 高),单位 pt。MATH_DESK_PAPER 用英寸,和 md2tex 的 geometry 一致。"""
112
+ raw = os.environ.get("MATH_DESK_PAPER", "").strip()
113
+ if "," in raw:
114
+ width_text, _, height_text = raw.partition(",")
115
+ try:
116
+ width = float(width_text) * 72.0
117
+ height = float(height_text) * 72.0
118
+ except ValueError:
119
+ warn("MATH_DESK_PAPER=%r 不是 \"宽,高\" 英寸数值,改用 A4" % raw)
120
+ return A4_WIDTH, A4_HEIGHT
121
+ # 2in–40in:再小排不下一个中文字,再大基本是把单位写错了。
122
+ if 144.0 <= width <= 2880.0 and 144.0 <= height <= 2880.0:
123
+ return width, height
124
+ warn("MATH_DESK_PAPER=%r 超出 2–40 英寸,改用 A4" % raw)
125
+ elif raw != "":
126
+ warn("MATH_DESK_PAPER=%r 不是 \"宽,高\" 形式,改用 A4" % raw)
127
+ return A4_WIDTH, A4_HEIGHT
128
+
129
+
130
+ def cjk_font():
131
+ """中文正文字体。SimSun 在显示器上太细,默认用 Windows 自带的雅黑。"""
132
+ raw = os.environ.get("MATH_DESK_CJKFONT", "").strip()
133
+ return raw if raw != "" else "Microsoft YaHei"
134
+
135
+
136
+ def typst_string(text):
137
+ return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
138
+
139
+
140
+ def preamble():
141
+ """Typst 文档设置,对应 md2tex 的 PREAMBLE(观感逐项对齐)。"""
142
+ width, height = paper_size()
143
+ size = font_size()
144
+ lines = [
145
+ "// 由 tools/md2typst.py 生成(v1.5 D:Typst 读版 PDF)。",
146
+ "// 要改版式请改工具里的 preamble(),不要手改这个临时文件。",
147
+ "#set page(",
148
+ " width: %.2fpt," % width,
149
+ " height: %.2fpt," % height,
150
+ " margin: %.2fpt," % MARGIN,
151
+ " numbering: \"1\",",
152
+ ")",
153
+ "#set text(font: (%s, \"New Computer Modern\"), lang: \"zh\", size: %.2fpt)"
154
+ % (typst_string(cjk_font()), size),
155
+ "#set par(",
156
+ " justify: true,",
157
+ " leading: %gem," % LEADING_EM,
158
+ " spacing: 0.35em,",
159
+ " first-line-indent: (amount: 2em, all: true),",
160
+ ")",
161
+ "#set heading(numbering: none)",
162
+ "#show heading.where(level: 1): it => block(",
163
+ " above: 1.15em, below: 0.65em,",
164
+ ")[#text(size: 1.28em, weight: \"bold\", it.body)]",
165
+ "#show heading.where(level: 2): it => block(",
166
+ " above: 1em, below: 0.55em,",
167
+ ")[#text(size: 1.14em, weight: \"bold\", it.body)]",
168
+ "#show heading.where(level: 3): it => block(",
169
+ " above: 0.9em, below: 0.5em,",
170
+ ")[#text(size: 1.04em, weight: \"bold\", it.body)]",
171
+ "#set list(indent: 1.4em, body-indent: 0.6em, spacing: 0.45em)",
172
+ "#set enum(indent: 1.4em, body-indent: 0.6em, spacing: 0.45em)",
173
+ "#show quote.where(block: true): it => block(",
174
+ " width: 100%,",
175
+ " stroke: (left: 2pt + luma(180)),",
176
+ " inset: (left: 10pt, top: 2pt, bottom: 2pt),",
177
+ " above: 0.6em, below: 0.6em,",
178
+ ")[#text(style: \"normal\", it.body)]",
179
+ "#show raw.where(block: true): it => block(",
180
+ " width: 100%,",
181
+ " inset: 8pt,",
182
+ " stroke: 0.5pt + luma(200),",
183
+ " radius: 2pt,",
184
+ " fill: luma(250),",
185
+ " above: 0.7em, below: 0.7em,",
186
+ ")[#text(size: 0.9em, it)]",
187
+ "#show math.equation.where(block: true): set block(above: 0.8em, below: 0.8em)",
188
+ "#show table: set text(size: 0.95em)",
189
+ ]
190
+ return "\n".join(lines)
191
+
192
+
193
+ # ------------------------------------------------------------------ 行内排版
194
+ def escape_markup(text):
195
+ """把一段纯文本变成 Typst markup 文本(`*`、`$`、`#` 之类都转义)。"""
196
+ out = []
197
+ index = 0
198
+ length = len(text)
199
+ while index < length:
200
+ char = text[index]
201
+ # `//` 在 markup 里是行注释起始(前面有空格时会把整行后半段吃掉),
202
+ # 所以成对的斜线逐个转义;单个 `/` 不是特殊字符,保持原样。
203
+ if char == "/" and text[index + 1:index + 2] == "/":
204
+ out.append("\\/\\/")
205
+ index += 2
206
+ continue
207
+ if char in SPECIAL_MARKUP:
208
+ out.append("\\" + char)
209
+ else:
210
+ out.append(char)
211
+ index += 1
212
+ return "".join(out)
213
+
214
+
215
+ def raw_inline(text, collapse=True):
216
+ """等宽照排一段文字(转换失败的公式、行内代码)。"""
217
+ if collapse:
218
+ text = " ".join(text.split())
219
+ ticks = max((len(run) for run in re.findall(r"`+", text)), default=0)
220
+ fence = "`" * (ticks + 1)
221
+ pad = " " if text.startswith("`") or text.endswith("`") else ""
222
+ return fence + pad + text + pad + fence
223
+
224
+
225
+ def describe_failure(result):
226
+ if result.error:
227
+ category = str(result.error.get("category") or "error")
228
+ message = str(result.error.get("message") or "").strip()
229
+ return "%s: %s" % (category, message) if message else category
230
+ return "转换结果为空"
231
+
232
+
233
+ def formula(latex, line, display, suffix=""):
234
+ """一个公式 -> Typst 数学;转换不出来就等宽照排 + warning,不中断整章。"""
235
+ body = latex.replace("$", "").strip()
236
+ result = convert_latex(body, display=display)
237
+ typst = (result.typst or "").strip()
238
+ if typst == "":
239
+ warn(
240
+ "formula not converted at line %d (%s): %s"
241
+ % (line, "display math" if display else "inline math", describe_failure(result))
242
+ )
243
+ return raw_inline(body) + escape_markup(suffix)
244
+ if display:
245
+ if suffix:
246
+ # 句末标点放进公式里,跟着居中的行间公式走,不在页面左边留一行「。」
247
+ return '$ %s "%s" $' % (typst, suffix)
248
+ return "$ %s $" % typst
249
+ return "$%s$" % typst
250
+
251
+
252
+ def glue_closing_punctuation(rendered, text, index):
253
+ """把紧跟行内对象的中文收尾标点并进同一个不可断行盒子。
254
+
255
+ `$x$;` 这种位置 Typst 允许断行,实测会把「;」顶到下一行行首(中文排版
256
+ 不该出现的行首标点)。#box 让公式和标点成为不可分割的一格。
257
+
258
+ `#box[…]` 是代码表达式,后面紧跟 `(`、`[`、`.` 会被 Typst 当成函数调用或
259
+ 字段访问("expected function, found content"),这种位置退回不 box:宁可
260
+ 偶尔一个标点顶到行首,也不要整章编译失败。
261
+ """
262
+ start = index
263
+ while index < len(text) and text[index] in CLOSING_PUNCTUATION:
264
+ index += 1
265
+ if index == start:
266
+ return rendered, start
267
+ if index < len(text) and text[index] in "([.":
268
+ return rendered, start
269
+ return "#box[%s%s]" % (rendered, text[start:index]), index
270
+
271
+
272
+ def render_inline(text, line, depth=0, plain=False):
273
+ """markdown 行内语法 -> Typst markup(数学单独走 formula())。
274
+
275
+ `plain=True` 是兜底模式:不排粗体/斜体,把 `*`、`_` 全部当普通字符转义。
276
+ 只在整个文档第一次编译失败时用(见 render()),保证再怪的强调写法也不会
277
+ 让一章打不开——数学、代码、表格、列表照旧。
278
+ """
279
+ slots = []
280
+
281
+ def hold(rendered):
282
+ slots.append(rendered)
283
+ return "\x01%d\x01" % (len(slots) - 1)
284
+
285
+ # 图片整段丢弃(md2tex 也丢);链接只留文字,`![…](…)` 之后不再参与转义。
286
+ if "[" in text:
287
+ text = LINK_OR_IMAGE_RE.sub(
288
+ lambda match: hold(
289
+ "" if match.group(0).startswith("!")
290
+ else render_inline(match.group(2), line, plain=plain)
291
+ ),
292
+ text,
293
+ )
294
+
295
+ out = []
296
+ buffer = []
297
+
298
+ def flush():
299
+ if buffer:
300
+ out.append(escape_markup("".join(buffer)))
301
+ buffer.clear()
302
+
303
+ index = 0
304
+ length = len(text)
305
+ while index < length:
306
+ char = text[index]
307
+ if char == "$":
308
+ if text.startswith("$$", index):
309
+ end = text.find("$$", index + 2)
310
+ if end < 0:
311
+ buffer.append(text[index:index + 2])
312
+ index += 2
313
+ continue
314
+ flush()
315
+ warn("display math inside a paragraph at line %d: 已按行内公式排版" % line)
316
+ out.append(formula(text[index + 2:end], line, display=False))
317
+ index = end + 2
318
+ continue
319
+ end = text.find("$", index + 1)
320
+ if end < 0:
321
+ buffer.append(char)
322
+ index += 1
323
+ continue
324
+ body = text[index + 1:end]
325
+ if body.strip() == "":
326
+ buffer.append(text[index:end + 1])
327
+ index = end + 1
328
+ continue
329
+ flush()
330
+ piece, index = glue_closing_punctuation(formula(body, line, display=False), text, end + 1)
331
+ out.append(piece)
332
+ continue
333
+ if char == "`":
334
+ end = text.find("`", index + 1)
335
+ if end < 0:
336
+ buffer.append(char)
337
+ index += 1
338
+ continue
339
+ flush()
340
+ piece, index = glue_closing_punctuation(
341
+ raw_inline(text[index + 1:end], collapse=False), text, end + 1
342
+ )
343
+ out.append(piece)
344
+ continue
345
+ # 强调只认「内容里没有同类记号、首尾不是空白」的成对标记(和 md2tex
346
+ # 的正则、Typst 的强调边界都一致):`***粗斜体***`、`2*3*4` 这类含糊
347
+ # 写法宁可原样转义,也不要让一个落单的 `*` 去段落末尾找配对——那会生成
348
+ # 无法编译的 markup,或者把半段话变成斜体。
349
+ if not plain and depth == 0 and text.startswith("**", index):
350
+ end = text.find("**", index + 2)
351
+ if end > index + 2 and "*" not in text[index + 2:end] \
352
+ and not text[index + 2].isspace() and not text[end - 1].isspace():
353
+ flush()
354
+ inner = render_inline(text[index + 2:end], line, depth + 1, plain)
355
+ out.append("*" + inner + "*")
356
+ index = end + 2
357
+ continue
358
+ if not plain and depth == 0 and text.startswith("__", index):
359
+ end = text.find("__", index + 2)
360
+ if end > index + 2 and "_" not in text[index + 2:end] \
361
+ and not text[index + 2].isspace() and not text[end - 1].isspace():
362
+ flush()
363
+ inner = render_inline(text[index + 2:end], line, depth + 1, plain)
364
+ out.append("*" + inner + "*")
365
+ index = end + 2
366
+ continue
367
+ if not plain and depth == 0 and char == "*":
368
+ end = text.find("*", index + 1)
369
+ if end > index + 1 and not text.startswith("**", index + 1) \
370
+ and not text.startswith("**", end) \
371
+ and not text[index + 1].isspace() and not text[end - 1].isspace():
372
+ flush()
373
+ inner = render_inline(text[index + 1:end], line, depth + 1, plain)
374
+ out.append("_" + inner + "_")
375
+ index = end + 1
376
+ continue
377
+ buffer.append(char)
378
+ index += 1
379
+ flush()
380
+ rendered = "".join(out)
381
+ for slot, value in enumerate(slots):
382
+ rendered = rendered.replace("\x01%d\x01" % slot, value)
383
+ return rendered
384
+
385
+
386
+ def text_block(text, line, plain=False):
387
+ """一行块级文字 -> Typst markup,避开行首会被当成结构标记的字符。"""
388
+ rendered = render_inline(text, line, plain=plain)
389
+ if rendered[:1] in ("=", "/"):
390
+ rendered = "\\" + rendered
391
+ return rendered
392
+
393
+
394
+ # -------------------------------------------------------------- 数学定界归一
395
+ def normalize_math_delimiters(line):
396
+ """把模型爱用的 \\(…\\) 和 \\[…\\] 归一成 $…$ 和 $$…$$(同 md2tex)。"""
397
+ line = re.sub(r"(?<!\\)\\\(", "$", line)
398
+ line = re.sub(r"(?<!\\)\\\)", "$", line)
399
+ line = re.sub(r"(?<!\\)\\\[", "$$", line)
400
+ line = re.sub(r"(?<!\\)\\\]", "$$", line)
401
+ return line
402
+
403
+
404
+ def split_tail_punctuation(tail):
405
+ """`$$…$$。` 里紧跟公式的句末标点:它属于公式,不属于下一段。"""
406
+ end = 0
407
+ while end < len(tail) and tail[end] in CLOSING_PUNCTUATION:
408
+ end += 1
409
+ return tail[:end], tail[end:]
410
+
411
+
412
+ def tokenize(lines):
413
+ """把源行切成四元组 ("text", 行, 行号, "") / ("display", 公式, 行号, 句末标点)。
414
+
415
+ 行间公式连同它跨的若干行被单独提出来,前后文各自成段;代码块里的 `$$`
416
+ 和 `\\(` 原样保留,不动(样板里的代码不该被数学归一化改写)。多行行间公式
417
+ 遇到空行就收手:宁可留一条 warning,也不要让一个没闭合的 `$$` 吞掉整章。
418
+ """
419
+ tokens = []
420
+ in_code = False
421
+ queue = deque((index, line) for index, line in enumerate(lines))
422
+ while queue:
423
+ index, line = queue.popleft()
424
+ line_number = index + 1
425
+ if FENCE_RE.match(line):
426
+ in_code = not in_code
427
+ tokens.append(("text", line, line_number, ""))
428
+ continue
429
+ if in_code:
430
+ tokens.append(("text", line, line_number, ""))
431
+ continue
432
+ line = normalize_math_delimiters(line)
433
+ if "$$" not in line:
434
+ tokens.append(("text", line, line_number, ""))
435
+ continue
436
+ start = line.find("$$")
437
+ prefix = line[:start]
438
+ if prefix.strip():
439
+ tokens.append(("text", prefix, line_number, ""))
440
+ rest = line[start + 2:]
441
+ end = rest.find("$$")
442
+ if end >= 0:
443
+ suffix, tail = split_tail_punctuation(rest[end + 2:])
444
+ tokens.append(("display", rest[:end].strip(), line_number, suffix))
445
+ if tail.strip():
446
+ queue.appendleft((index, tail))
447
+ continue
448
+ parts = [rest]
449
+ closed = False
450
+ suffix = ""
451
+ while queue:
452
+ next_index, next_line = queue.popleft()
453
+ if FENCE_RE.match(next_line):
454
+ parts.append(next_line)
455
+ continue
456
+ if next_line.strip() == "":
457
+ break
458
+ next_line = normalize_math_delimiters(next_line)
459
+ position = next_line.find("$$")
460
+ if position < 0:
461
+ parts.append(next_line)
462
+ continue
463
+ parts.append(next_line[:position])
464
+ closed = True
465
+ suffix, tail = split_tail_punctuation(next_line[position + 2:])
466
+ if tail.strip():
467
+ queue.appendleft((next_index, tail))
468
+ break
469
+ if not closed:
470
+ warn("unclosed display math at line %d: 已按到空行为止收尾" % line_number)
471
+ body = " ".join(part.strip() for part in parts if part.strip())
472
+ tokens.append(("display", body, line_number, suffix))
473
+ return tokens
474
+
475
+
476
+ # ------------------------------------------------------------------ 块级排版
477
+ def next_list_item(tokens, start):
478
+ """松散列表:空行之后若还是列表项,就不算断开。"""
479
+ index = start
480
+ while index < len(tokens):
481
+ kind, value, _line, _suffix = tokens[index]
482
+ if kind != "text":
483
+ return None
484
+ if value.strip() == "":
485
+ index += 1
486
+ continue
487
+ return LIST_RE.match(value)
488
+ return None
489
+
490
+
491
+ def longest_backtick_run(lines):
492
+ longest = 0
493
+ for line in lines:
494
+ for run in re.findall(r"`+", line):
495
+ longest = max(longest, len(run))
496
+ return longest
497
+
498
+
499
+ def code_block(tokens, index):
500
+ _kind, value, _line, _suffix = tokens[index]
501
+ info = value.strip()[3:].strip()
502
+ body = []
503
+ index += 1
504
+ while index < len(tokens):
505
+ kind, value, _line, _suffix = tokens[index]
506
+ if kind == "text" and FENCE_RE.match(value):
507
+ index += 1
508
+ break
509
+ body.append(value.rstrip())
510
+ index += 1
511
+ fence = "`" * max(3, longest_backtick_run(body) + 1)
512
+ language = ""
513
+ if info:
514
+ language = re.sub(r"[^A-Za-z0-9_+.-]", "", info.split()[0])
515
+ text = "\n".join(body)
516
+ return "%s%s\n%s\n%s" % (fence, language, text, fence), index
517
+
518
+
519
+ def split_cells(line):
520
+ text = line.strip()
521
+ if text.startswith("|"):
522
+ text = text[1:]
523
+ if text.endswith("|") and not text.endswith("\\|"):
524
+ text = text[:-1]
525
+ cells = []
526
+ current = []
527
+ escaped = False
528
+ for char in text:
529
+ if escaped:
530
+ # `\|` 原样留在单元格里:数学里的 \| 是范数记号,不能当表格分隔符。
531
+ current.append(char)
532
+ escaped = False
533
+ continue
534
+ if char == "\\":
535
+ current.append(char)
536
+ escaped = True
537
+ continue
538
+ if char == "|":
539
+ cells.append("".join(current).strip())
540
+ current = []
541
+ continue
542
+ current.append(char)
543
+ cells.append("".join(current).strip())
544
+ return cells
545
+
546
+
547
+ def table_block(tokens, index, plain=False):
548
+ """管道表格 -> Typst table(booktabs 风格横线);太宽就降级并 warning。"""
549
+ rows = []
550
+ start_line = tokens[index][2]
551
+ while index < len(tokens):
552
+ kind, value, line, _suffix = tokens[index]
553
+ if kind != "text" or not ROW_RE.match(value):
554
+ break
555
+ cells = split_cells(value)
556
+ if not SEPARATOR_CELLS_RE.match("".join(cells)):
557
+ rows.append((cells, line))
558
+ index += 1
559
+ if not rows:
560
+ warn("table at line %d has no rows; 已丢弃" % start_line)
561
+ return "", index
562
+ columns = max(len(cells) for cells, _line in rows)
563
+ if columns > MAX_TABLE_COLUMNS:
564
+ warn(
565
+ "table at line %d has %d columns (max %d); 已降级为逐行文本"
566
+ % (start_line, columns, MAX_TABLE_COLUMNS)
567
+ )
568
+ paragraphs = []
569
+ for cells, line in rows:
570
+ paragraphs.append(text_block(" | ".join(cells), line, plain))
571
+ return "\n\n".join(paragraphs), index
572
+ lines = [
573
+ "#table(",
574
+ " columns: (%s)," % ", ".join(["1fr"] * columns),
575
+ " align: left,",
576
+ " stroke: none,",
577
+ " inset: (x: 6pt, y: 4pt),",
578
+ " table.hline(stroke: 0.7pt),",
579
+ ]
580
+ for row_index, (cells, line) in enumerate(rows):
581
+ padded = cells + [""] * (columns - len(cells))
582
+ rendered = ", ".join("[" + text_block(cell, line, plain) + "]" for cell in padded[:columns])
583
+ if row_index == 0:
584
+ lines.append(" table.header(%s)," % rendered)
585
+ lines.append(" table.hline(stroke: 0.4pt),")
586
+ else:
587
+ lines.append(" %s," % rendered)
588
+ lines.append(" table.hline(stroke: 0.7pt),")
589
+ lines.append(")")
590
+ return "\n".join(lines), index
591
+
592
+
593
+ def quote_block(tokens, index, plain=False):
594
+ line_number = tokens[index][2]
595
+ parts = []
596
+ while index < len(tokens):
597
+ kind, value, _line, _suffix = tokens[index]
598
+ if kind != "text" or not value.lstrip().startswith(">"):
599
+ break
600
+ parts.append(value.lstrip(">").strip())
601
+ index += 1
602
+ text = " ".join(part for part in parts if part)
603
+ return "#quote(block: true)[%s]" % text_block(text, line_number, plain), index
604
+
605
+
606
+ def add_list_item(levels, lines, indent_text, marker, item, line, plain=False):
607
+ """列表项入栈:按缩进算层数,Typst 用两个空格表示一层。"""
608
+ width = len(indent_text.expandtabs(4))
609
+ kind = "ol" if marker[0].isdigit() else "ul"
610
+ while levels and width < levels[-1][0]:
611
+ levels.pop()
612
+ if not levels or width > levels[-1][0]:
613
+ levels.append([width, kind])
614
+ elif levels[-1][1] != kind:
615
+ levels[-1][1] = kind
616
+ # 同一层换了种类,Typst 会另起一个列表;空一行让它重新编号。
617
+ lines.append("")
618
+ depth = len(levels) - 1
619
+ lines.append(" " * depth + ("+" if kind == "ol" else "-") + " " + text_block(item, line, plain))
620
+
621
+
622
+ def render_blocks(tokens, plain=False):
623
+ out = []
624
+ paragraph = []
625
+ paragraph_line = 0
626
+ list_levels = []
627
+ list_lines = []
628
+
629
+ def flush_paragraph():
630
+ nonlocal paragraph, paragraph_line
631
+ if paragraph:
632
+ text = " ".join(part.strip() for part in paragraph if part.strip())
633
+ paragraph = []
634
+ if text:
635
+ out.append(text_block(text, paragraph_line, plain))
636
+
637
+ def flush_list():
638
+ nonlocal list_lines, list_levels
639
+ if list_lines:
640
+ out.append("\n".join(list_lines))
641
+ list_lines = []
642
+ list_levels = []
643
+
644
+ index = 0
645
+ while index < len(tokens):
646
+ kind, value, line, suffix = tokens[index]
647
+ if kind == "display":
648
+ flush_paragraph()
649
+ flush_list()
650
+ out.append(formula(value, line, display=True, suffix=suffix))
651
+ index += 1
652
+ continue
653
+ stripped = value.strip()
654
+ if stripped == "":
655
+ if list_levels and next_list_item(tokens, index + 1) is not None:
656
+ index += 1
657
+ continue
658
+ flush_paragraph()
659
+ flush_list()
660
+ index += 1
661
+ continue
662
+ if FENCE_RE.match(value):
663
+ flush_paragraph()
664
+ flush_list()
665
+ block, index = code_block(tokens, index)
666
+ out.append(block)
667
+ continue
668
+ if ROW_RE.match(value) and index + 1 < len(tokens) \
669
+ and tokens[index + 1][0] == "text" and ROW_RE.match(tokens[index + 1][1]) \
670
+ and SEPARATOR_CELLS_RE.match("".join(split_cells(tokens[index + 1][1]))):
671
+ flush_paragraph()
672
+ flush_list()
673
+ block, index = table_block(tokens, index, plain)
674
+ if block:
675
+ out.append(block)
676
+ continue
677
+ heading = HEADING_RE.match(value)
678
+ if heading:
679
+ flush_paragraph()
680
+ flush_list()
681
+ # md2tex 的层级映射:`#`/`##` 都是 section,`###` 起往下才细分。
682
+ level = min(max(len(heading.group(1)) - 1, 1), 3)
683
+ out.append("=" * level + " " + text_block(heading.group(2).strip(), line, plain))
684
+ index += 1
685
+ continue
686
+ item = LIST_RE.match(value)
687
+ if item:
688
+ flush_paragraph()
689
+ add_list_item(list_levels, list_lines, item.group(1), item.group(2),
690
+ item.group(3), line, plain)
691
+ index += 1
692
+ continue
693
+ if value.lstrip().startswith(">"):
694
+ flush_paragraph()
695
+ flush_list()
696
+ block, index = quote_block(tokens, index, plain)
697
+ out.append(block)
698
+ continue
699
+ if stripped in RULE_LINES:
700
+ flush_paragraph()
701
+ flush_list()
702
+ out.append(
703
+ "#block(above: 0.8em, below: 0.8em)["
704
+ "#line(length: 100%, stroke: 0.5pt + luma(150))]"
705
+ )
706
+ index += 1
707
+ continue
708
+ if stripped in PAGEBREAK_LINES:
709
+ flush_paragraph()
710
+ flush_list()
711
+ out.append("#pagebreak()")
712
+ index += 1
713
+ continue
714
+ if list_lines:
715
+ flush_list()
716
+ if not paragraph:
717
+ paragraph_line = line
718
+ paragraph.append(value)
719
+ index += 1
720
+ flush_paragraph()
721
+ flush_list()
722
+ return "\n\n".join(out)
723
+
724
+
725
+ # ---------------------------------------------------------------- 文档与编译
726
+ def title_block(title, plain=False):
727
+ """文首标题,对应 md2tex 的 \\section*{title}(比正文大一号、加粗)。"""
728
+ return (
729
+ '#block(above: 0em, below: 0.9em)[#text(size: 1.42em, weight: "bold")[%s]]'
730
+ % text_block(title, 0, plain)
731
+ )
732
+
733
+
734
+ def convert(markdown, plain=False):
735
+ """markdown 全文 -> Typst 正文(不含文档设置)。"""
736
+ return render_blocks(tokenize(markdown.split("\n")), plain)
737
+
738
+
739
+ def build_document(markdown, title, plain=False):
740
+ pieces = [preamble()]
741
+ if title.strip():
742
+ pieces.append(title_block(title, plain))
743
+ body = convert(markdown, plain).strip()
744
+ if body:
745
+ pieces.append(body)
746
+ return "\n\n".join(pieces) + "\n"
747
+
748
+
749
+ def write_typ(path, document):
750
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
751
+ handle.write(document)
752
+
753
+
754
+ def compile_document(typ_path, work, target, document):
755
+ """写 .typ、编译、把 PDF 拷到目标位置。编译失败抛 SystemExit(带 stderr 尾部)。"""
756
+ write_typ(typ_path, document)
757
+ produced = os.path.join(work, "doc.pdf")
758
+ typst_runtime.run_typst(["compile", typ_path, produced], cwd=work)
759
+ if not os.path.isfile(produced):
760
+ raise SystemExit("typst 没有生成 PDF:%s" % produced)
761
+ shutil.copyfile(produced, target)
762
+
763
+
764
+ def render(src, out_path, title):
765
+ """读 md、生成 .typ、交给 typst 编译,临时目录收尾删除。
766
+
767
+ 第一次编译失败时会用 plain 模式(不排强调)重排一次并 warning:模型偶尔
768
+ 写出 `***粗斜体***`、`2*3*4` 这种让人误解的强调,宁可少一点粗体,也不要
769
+ 整章打不开。第二次仍失败才把 typst 的报错抛出去。
770
+ """
771
+ with open(src, encoding="utf-8-sig") as handle:
772
+ markdown = handle.read()
773
+ target = os.path.abspath(out_path)
774
+ parent = os.path.dirname(target)
775
+ if parent:
776
+ os.makedirs(parent, exist_ok=True)
777
+ # 临时文件放在输出旁边(`out.pdf.work`),不用 mkdtemp:和 md2overlay 一样,
778
+ # 某些受限环境只允许往目标目录写。
779
+ work = target + ".work"
780
+ os.makedirs(work, exist_ok=True)
781
+ typ_path = os.path.join(work, "doc.typ")
782
+ try:
783
+ try:
784
+ compile_document(typ_path, work, target, build_document(markdown, title))
785
+ except SystemExit as first:
786
+ if not typst_runtime.typst_available():
787
+ # 没装 typst 不是排版问题:把安装提示原样抛出去,不重试。
788
+ raise
789
+ warn(
790
+ "typst 首次编译失败,改用不排强调的纯文本模式重排:%s"
791
+ % str(first).replace("\n", " ")[:200]
792
+ )
793
+ compile_document(typ_path, work, target, build_document(markdown, title, plain=True))
794
+ finally:
795
+ shutil.rmtree(work, ignore_errors=True)
796
+
797
+
798
+ def main(argv):
799
+ if len(argv) < 3:
800
+ print(USAGE, file=sys.stderr)
801
+ return 2
802
+ src, out = argv[1], argv[2]
803
+ no_title = os.environ.get("MATH_DESK_NO_TITLE") == "1"
804
+ if len(argv) > 3 and not no_title:
805
+ title = argv[3]
806
+ elif no_title:
807
+ title = ""
808
+ else:
809
+ title = os.path.splitext(os.path.basename(src))[0]
810
+ if not os.path.isfile(src):
811
+ raise SystemExit("找不到输入文件:%s" % src)
812
+ render(src, out, title)
813
+ print(out)
814
+ return 0
815
+
816
+
817
+ if __name__ == "__main__":
818
+ sys.exit(main(sys.argv))