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
@@ -1,7 +1,14 @@
1
- """Render one page's translated blocks at their original bbox positions.
1
+ """Render one page's translated blocks where the original printed them.
2
2
 
3
3
  Usage:
4
4
  python md2overlay.py <blocks.json> <out.pdf> <page-width-pt> <page-height-pt> <font-class>
5
+
6
+ Placement is baseline-anchored, not box-top anchored: xelatex is run twice — the
7
+ first pass finds where each block's text really landed, the second pass shifts it
8
+ back onto the printed baseline and (for blocks that do not fit) shrinks it. The
9
+ measured result is written next to the block cache as `page-NNN.layout.json`,
10
+ which is what the reader's boxes use. The geometry and the sidecar contract are
11
+ shared with the Typst engine (`overlay_layout.py`).
5
12
  """
6
13
  import json
7
14
  import os
@@ -10,6 +17,21 @@ import subprocess
10
17
  import sys
11
18
 
12
19
  from md2tex import cjk_font, convert, sanitize_display_math
20
+ from overlay_layout import (
21
+ align_name,
22
+ alignment_of,
23
+ baseline_of,
24
+ body_of,
25
+ inline_formula,
26
+ layout_target,
27
+ leading_of,
28
+ measure_page,
29
+ plan_adjustments,
30
+ room_below,
31
+ room_right,
32
+ start_x,
33
+ write_layout,
34
+ )
13
35
 
14
36
  blocks_path, out_path = sys.argv[1], sys.argv[2]
15
37
  page_width = float(sys.argv[3])
@@ -17,184 +39,157 @@ page_height = float(sys.argv[4])
17
39
  font_class = sys.argv[5] if len(sys.argv) > 5 else "10pt"
18
40
  font_pt = float(font_class.replace("pt", ""))
19
41
 
42
+ # Translated body text may not fall below this size (the requirement's "no
43
+ # unreadable 4–6pt text"). A block that still does not fit at the floor keeps the
44
+ # floor and is marked `overflow` instead of being squeezed further.
45
+ MIN_PT = 9.0
46
+
20
47
  with open(blocks_path, encoding="utf-8") as handle:
21
48
  blocks = json.load(handle)
22
49
 
23
50
 
24
- def overlaps_x(left, right):
25
- """True when two blocks share horizontal space, i.e. stack vertically."""
26
- return not (left[0] + left[2] <= right[0] or right[0] + right[2] <= left[0])
27
-
28
-
29
- def same_line(first, second):
30
- """True when two boxes really share a printed line.
31
-
32
- Boxes that merely touch by a fraction of a point must not count: a paragraph
33
- and the heading right under it were treated as one line, and the heading got
34
- pushed to the page edge."""
35
- first_top, first_bottom = float(first[1]), float(first[1]) + float(first[3])
36
- second_top, second_bottom = float(second[1]), float(second[1]) + float(second[3])
37
- overlap = min(first_bottom, second_bottom) - max(first_top, second_top)
38
- return overlap > 0.5 * min(float(first[3]), float(second[3]))
39
-
40
-
41
- def room_below(block):
42
- """Points available from this block's top to the next block that sits under
43
- it. Text may use the page's white space but must never run into a neighbour;
44
- that balance is what keeps a tightened paragraph readable instead of 3pt."""
45
- x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
46
- limit = page_height - y * page_height - 4.0
47
- for other in blocks:
48
- if other is block:
49
- continue
50
- other_box = other.get("bbox") or [0, 0, 1, 1]
51
- if not overlaps_x([x, y, width], other_box):
52
- continue
53
- gap = (float(other_box[1]) - y) * page_height
54
- # A box that starts barely below this one is a fragment on the same
55
- # line, not something underneath: counting it squeezed blocks to 4pt.
56
- if max(2.0, font_pt * 0.6) < gap < limit:
57
- limit = gap
58
- return max(6.0, limit)
59
-
60
-
61
- def room_right(block):
62
- """Normalized right edge this block may use: its own width or the start of
63
- the next block beside it. Short blocks such as "if dim V = n." were forced
64
- into two lines by their narrow box and then shrank to 4pt; letting them use
65
- the empty space beside them keeps them one readable line."""
66
- x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
67
- right = x + width
68
- limit = 0.985
69
- for other in blocks:
70
- if other is block:
71
- continue
72
- other_box = other.get("bbox") or [0, 0, 1, 1]
73
- if not same_line(block.get("bbox") or [0, 0, 1, 1], other_box):
74
- continue
75
- start = float(other_box[0])
76
- if start > right + 0.005:
77
- limit = min(limit, start - 0.004)
78
- return max(x + 0.08, limit)
79
-
80
-
81
- def inline_formula(md):
82
- """Turn a standalone `$$...$$` block into one inline math run.
83
-
84
- A formula block's box is one line tall in the original, while a display
85
- equation needs about twice that; rendering it as display forced adjustbox to
86
- shrink it to 6pt. Inline keeps it the same optical size as the body text."""
87
- body = md.strip()
88
- if body.startswith("$$") and body.endswith("$$") and body.count("$$") == 2:
89
- return "$%s$" % " ".join(body[2:-2].split())
90
- return ""
91
-
92
-
93
- def start_x(block):
94
- """Left edge to use, pushed right past a same-line neighbour it would overlap.
95
-
96
- PyMuPDF sometimes splits one printed line into two boxes whose x ranges
97
- overlap ("p⁰ = …" and "(g 为 G 的阶)。"). Drawn at their own x the two runs
98
- collide, because the Chinese formula is wider than the English one; starting
99
- the right-hand run after the left run keeps the line readable."""
100
- x, y, width, height = [float(value) for value in block.get("bbox") or [0, 0, 1, 1]]
101
- for other in blocks:
102
- if other is block:
51
+ def build_run(adjustments):
52
+ """One xelatex input: textblocks and the boxes they were placed in."""
53
+ parts = []
54
+ placed = []
55
+ for block_index, block in enumerate(blocks, start=1):
56
+ md = (block.get("md") or "").strip()
57
+ if md == "":
103
58
  continue
104
- other_box = other.get("bbox") or [0, 0, 1, 1]
105
- if not same_line(block.get("bbox") or [0, 0, 1, 1], other_box):
106
- continue
107
- other_left, other_right = float(other_box[0]), float(other_box[0]) + float(other_box[2])
108
- if other_left < x - 0.002 and other_right > x + 0.01:
109
- x = min(0.9, other_right + 0.006)
110
- return x
111
-
112
-
113
- parts = []
114
- for block in blocks:
115
- md = (block.get("md") or "").strip()
116
- if md == "":
117
- continue
118
- bbox = block.get("bbox") or [0, 0, 1, 1]
119
- x, y, width, _height = [float(value) for value in bbox]
120
- room = room_below(block)
121
- body = ""
122
- left = start_x(block)
123
- x_pt = max(0.0, left * page_width)
124
- y_pt = max(0.0, y * page_height)
125
- # Keep every block inside its own box width. Borrowing the space to the
126
- # right made the translation wider than the box the reader draws around the
127
- # original text, so the reveal clipped whole words; wrapping (and, when
128
- # really tight, scaling) stays inside the block instead.
129
- w_pt = max(40.0, min(width * page_width, page_width - x_pt - 4.0))
130
- # Very narrow boxes ("if dim V = n.") cannot hold one Chinese line at body
131
- # size and used to collapse to 4pt after wrapping. A slightly smaller face
132
- # keeps them on one line and inside the box. The block's own printed size
133
- # (pdf_blocks reports it relative to the page's body text) keeps headings
134
- # and titles at their larger look instead of shrinking them to body size.
135
- block_scale = float(block.get("size") or 1.0)
136
- block_scale = max(0.85, min(1.6, block_scale))
137
- body_pt = font_pt * block_scale * (0.8 if w_pt < 90.0 else 1.0)
138
- if room < body_pt * 2.6 and "$$" in md:
139
- # Too little room for a display equation: keep the math inline, including
140
- # prose that carries an inline `$$...$$` fragment.
141
- body = inline_formula(md)
59
+ bbox = block.get("bbox") or [0, 0, 1, 1]
60
+ x, y, width, _height = [float(value) for value in bbox]
61
+ room = room_below(block, blocks, page_height, font_pt)
62
+ left = start_x(block, blocks)
63
+ right = room_right(block, blocks)
64
+ x_pt = max(0.0, left * page_width)
65
+ # Use the white space beside a short block before shrinking the text: a
66
+ # Chinese translation is wider than the English it replaces.
67
+ w_pt = max(40.0, min((right - left) * page_width, page_width - x_pt - 4.0))
68
+ adjustment = adjustments.get(str(block.get("id") or "")) or {}
69
+ body_pt = body_of(block, adjustments, font_pt, MIN_PT)
70
+ lead_pt = leading_of(block, body_pt, page_height)
71
+ target = baseline_of(block, page_height, font_pt)
72
+ y_pt = max(0.0, float(adjustment.get("y", target)))
73
+ h_pt = max(6.0, min(room, page_height - y_pt - 4.0))
74
+ body = ""
75
+ # The inline/display decision must not flip between the two passes: the
76
+ # unshrunk size decides.
77
+ if room < body_of(block, {}, font_pt, MIN_PT) * 2.6 and "$$" in md:
78
+ body = inline_formula(md)
79
+ if body == "":
80
+ body = convert(md.replace("$$", "$").split("\n"), "", drop_leading_heading=False)
142
81
  if body == "":
143
- body = convert(md.replace("$$", "$").split("\n"), "", drop_leading_heading=False)
144
- if body == "":
145
- # Same normalization the reading PDF gets: display math rebuilt on its own
146
- # lines. Without it, a one-line `$$...$$` swallowed the prose after it and
147
- # the paragraph came out as broken math.
148
- body = convert(sanitize_display_math(md).split("\n"), "", drop_leading_heading=False)
149
- if body.strip() == "":
150
- continue
151
- # Cap the block at the white space below it: a Chinese paragraph is often
152
- # taller than the English it replaces. Text may borrow a paragraph gap but
153
- # never runs into the next block, and adjustbox only shrinks when the text
154
- # still exceeds that room, so most blocks keep their natural size.
155
- h_pt = room
156
- parts.append(
157
- "\\begin{textblock}{%.2f}(%.2f,%.2f)\n"
158
- "\\begin{adjustbox}{max width=%.2fpt,max totalheight=%.2fpt}\n"
159
- "\\begin{minipage}[t]{%.2fpt}\\raggedright\\fontsize{%.1f}{%.1f}\\selectfont\n%s\n\\end{minipage}\n"
160
- "\\end{adjustbox}\n"
161
- "\\end{textblock}\n"
162
- % (w_pt, x_pt, y_pt, w_pt, h_pt, w_pt, body_pt, body_pt * 1.25, body)
163
- )
164
-
165
- tex = r"""\documentclass[UTF8,%s]{ctexart}
82
+ body = convert(sanitize_display_math(md).split("\n"), "", drop_leading_heading=False)
83
+ if body.strip() == "":
84
+ continue
85
+ # A zero-width, white, 1pt marker on the block's first line. `\leavevmode`
86
+ # is load-bearing: a minipage starts in vertical mode, so a bare `\hbox`
87
+ # would open a line of its own and push the translation one baseline down.
88
+ # A block whose body starts with display math would put the marker on an
89
+ # empty line, so those are measured geometrically instead.
90
+ # `convert()` emits display maths as `\[…\]`, not `$$…$$`. A marker in
91
+ # front of it would open a line of its own and shift the equation, so
92
+ # those blocks carry no marker and are claimed by their reserved
93
+ # rectangle in measure_page.
94
+ stripped_body = body.lstrip()
95
+ display_first = stripped_body.startswith("$$") or stripped_body.startswith("\\[")
96
+ marker_number = block_index
97
+ marker = "MD%03d" % marker_number
98
+ prefix = "\\leavevmode\\hbox to 0pt{\\color{white}\\fontsize{1pt}{1pt}\\selectfont %s}" % marker
99
+ if display_first:
100
+ # The marker ends its line so the display equation keeps its own; the
101
+ # second pass puts the equation back on the printed baseline, and the
102
+ # marker line above it is invisible.
103
+ prefix += "\\par"
104
+ parts.append(
105
+ "\\begin{textblock}{%.2f}(%.2f,%.2f)\n"
106
+ "\\begin{minipage}[t]{%.2fpt}%s\\fontsize{%.1f}{%.1f}\\selectfont\n%s%s\n\\end{minipage}\n"
107
+ "\\end{textblock}\n"
108
+ % (w_pt, x_pt, y_pt, w_pt, alignment_of(block), body_pt, lead_pt, prefix, body)
109
+ )
110
+ placed.append({
111
+ "id": str(block.get("id") or ""),
112
+ "marker": marker,
113
+ "rect": (x_pt, y_pt, x_pt + w_pt, y_pt + h_pt),
114
+ "target": target,
115
+ "room": h_pt,
116
+ "body": body_pt,
117
+ "leading": lead_pt,
118
+ "align": align_name(block),
119
+ "y": y_pt,
120
+ })
121
+ return parts, placed
122
+
123
+
124
+ def compile_page(parts, work, out_pdf):
125
+ """Write the page's TeX and compile it; returns the PDF path."""
126
+ tex = r"""\documentclass[UTF8,%s]{ctexart}
166
127
  \usepackage[paperwidth=%.4fin,paperheight=%.4fin,margin=0pt]{geometry}
167
128
  \usepackage{fontspec}
129
+ \usepackage{xcolor}
168
130
  \setCJKmainfont{%s}
169
131
  \usepackage{amsmath,amssymb}
170
132
  \usepackage[absolute,overlay]{textpos}
171
133
  \usepackage{adjustbox}
172
- \setlength{\TPHorizModule}{1pt}
173
- \setlength{\TPVertModule}{1pt}
134
+ %% Positions and widths are handed over in PDF big points (bp, 1/72in) because
135
+ %% that is what the page rect and PyMuPDF use; with 1pt modules every placement
136
+ %% drifted by 0.375 percent (2bp at the right edge) and `box` in layout.json was
137
+ %% where the text actually printed.
138
+ \setlength{\TPHorizModule}{1bp}
139
+ \setlength{\TPVertModule}{1bp}
140
+ %% A positioned block is not a paragraph: ctexart's 2em first-line indent pushed
141
+ %% the first line 2em past the placed box (and clipped it at the page edge).
142
+ \setlength{\parindent}{0pt}
174
143
  \pagestyle{empty}
175
144
  \begin{document}
176
145
  %s
177
146
  \end{document}
178
147
  """ % (font_class, page_width / 72.0, page_height / 72.0, cjk_font(), "\n".join(parts))
179
-
180
- # Build next to the output instead of a fresh temp directory: some sandboxes
181
- # allow writes in the destination directory but not in a mkdtemp directory.
182
- work = os.path.abspath(out_path) + ".work"
183
- os.makedirs(work, exist_ok=True)
184
- tex_path = os.path.join(work, "doc.tex")
185
- pdf_path = os.path.join(work, "doc.pdf")
186
- try:
148
+ tex_path = os.path.join(work, "doc.tex")
149
+ pdf_path = os.path.join(work, "doc.pdf")
150
+ if os.path.exists(pdf_path):
151
+ os.remove(pdf_path)
187
152
  with open(tex_path, "w", encoding="utf-8") as handle:
188
153
  handle.write(tex)
189
-
190
154
  result = subprocess.run(
191
155
  ["xelatex", "-interaction=nonstopmode", "doc.tex"],
192
156
  cwd=work, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180,
193
157
  )
194
158
  if not os.path.exists(pdf_path):
195
159
  raise SystemExit("xelatex failed: " + (result.stdout or "")[-800:])
160
+ return pdf_path
196
161
 
162
+
163
+ # Build next to the output instead of a fresh temp directory: some sandboxes
164
+ # allow writes in the destination directory but not in a mkdtemp directory.
165
+ work = os.path.abspath(out_path) + ".work"
166
+ os.makedirs(work, exist_ok=True)
167
+ try:
168
+ applied = {}
169
+ parts, placed = build_run(applied)
170
+ pdf_path = compile_page(parts, work, out_path)
171
+ measured = measure_page(pdf_path, placed)
172
+ # Corrections accumulate: a display equation's first placement can be a line
173
+ # off, and a block without a new step keeps the placement it already earned.
174
+ for _attempt in range(3):
175
+ step = plan_adjustments(placed, measured, font_pt, MIN_PT)
176
+ changed = False
177
+ for block_id, adjustment in step.items():
178
+ current = applied.setdefault(block_id, {})
179
+ if "y" in adjustment and current.get("y") != adjustment["y"]:
180
+ current["y"] = adjustment["y"]
181
+ changed = True
182
+ if "scale" in adjustment and current.get("scale") != adjustment["scale"]:
183
+ current["scale"] = adjustment["scale"]
184
+ changed = True
185
+ if not changed:
186
+ break
187
+ parts, placed = build_run(applied)
188
+ pdf_path = compile_page(parts, work, out_path)
189
+ measured = measure_page(pdf_path, placed)
197
190
  os.replace(pdf_path, out_path)
191
+ write_layout(placed, measured, layout_target(blocks_path, out_path),
192
+ page_width, page_height, font_pt)
198
193
  finally:
199
194
  shutil.rmtree(work, ignore_errors=True)
200
195
  print(out_path)
@@ -0,0 +1,312 @@
1
+ """Render one page's translated blocks with Typst (v1.5 D engine).
2
+
3
+ Usage:
4
+ python md2overlay_typst.py <blocks.json> <out.pdf> <page-width-pt> <page-height-pt> <font-class>
5
+
6
+ Same contract as `md2overlay.py`: the page's blocks are placed at their printed
7
+ positions, the first pass measures where the text really landed, the second pass
8
+ puts it on the printed baseline and shrinks what still does not fit, and the
9
+ measured result is written beside the block cache as `page-NNN.layout.json` —
10
+ the same shape the reader's DOM text layer already consumes.
11
+
12
+ The difference is the engine: Typst `place()`/`measure()` (one binary) instead of
13
+ xelatex + textpos. Text and maths are converted from the cached LaTeX markdown by
14
+ `latex_to_typst.py`.
15
+ """
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import sys
21
+
22
+ from latex_to_typst import convert_latex
23
+ from md2tex import cjk_font, sanitize_display_math
24
+ from overlay_layout import (
25
+ align_name,
26
+ baseline_of,
27
+ body_of,
28
+ inline_formula,
29
+ layout_target,
30
+ leading_of,
31
+ measure_page,
32
+ plan_adjustments,
33
+ room_below,
34
+ room_right,
35
+ start_x,
36
+ write_layout,
37
+ )
38
+ from typst_runtime import run_typst
39
+
40
+ blocks_path, out_path = sys.argv[1], sys.argv[2]
41
+ page_width = float(sys.argv[3])
42
+ page_height = float(sys.argv[4])
43
+ font_class = sys.argv[5] if len(sys.argv) > 5 else "10pt"
44
+ font_pt = float(font_class.replace("pt", ""))
45
+
46
+ MIN_PT = 9.0
47
+
48
+ # Typst's line pitch with `top-edge: "ascender", bottom-edge: "descender"` is
49
+ # (ascender + descender) + par leading. The ratios are the measured metrics of
50
+ # the product's CJK face (Microsoft YaHei); another face changes the pitch by a
51
+ # few percent, while the printed baseline itself is corrected by measurement.
52
+ ASCENT_RATIO = 0.81201
53
+ DESCENT_RATIO = 0.25342
54
+
55
+ with open(blocks_path, encoding="utf-8") as handle:
56
+ blocks = json.load(handle)
57
+
58
+ MATH_SPLIT = re.compile(r"(\$\$[\s\S]*?\$\$|\$[^$\n]+?\$)")
59
+ LIST_LINE = re.compile(r"^\s*(?:[-*+]|\d+\.)\s+(.*)$")
60
+ HEADING_LINE = re.compile(r"^\s*#{1,6}\s+(.*)$")
61
+ TABLE_LINE = re.compile(r"^\s*\|.*\|\s*$")
62
+
63
+ WARNINGS = []
64
+
65
+
66
+ def warn(message):
67
+ if message not in WARNINGS:
68
+ WARNINGS.append(message)
69
+
70
+
71
+ def escape_typst(text):
72
+ """Escape prose for Typst markup; maths is inserted separately."""
73
+ out = []
74
+ for char in text:
75
+ if char in "#$[]*_<>@~`":
76
+ out.append("\\" + char)
77
+ elif char == "\\":
78
+ out.append("#sym.backslash")
79
+ else:
80
+ out.append(char)
81
+ return "".join(out)
82
+
83
+
84
+ def inline_style(text):
85
+ """Bold/italic/inline-code inside one prose run, escaped piece by piece."""
86
+ nodes = []
87
+ for piece in re.split(r"(\*\*[^*]+\*\*|`[^`]+`)", text):
88
+ if piece == "":
89
+ continue
90
+ if piece.startswith("**") and piece.endswith("**") and len(piece) >= 4:
91
+ nodes.append("*" + escape_typst(piece[2:-2]) + "*")
92
+ elif piece.startswith("`") and piece.endswith("`") and len(piece) >= 2:
93
+ nodes.append("`" + piece[1:-1].replace("`", "") + "`")
94
+ else:
95
+ nodes.append(escape_typst(piece))
96
+ return "".join(nodes)
97
+
98
+
99
+ def math_to_typst(latex, display):
100
+ """One formula as Typst markup; a failed conversion stays visible."""
101
+ result = convert_latex(latex, display=display)
102
+ if result.typst is None:
103
+ reason = result.error["message"] if result.error else "unknown"
104
+ warn("formula left as source (%s): %s" % (reason, latex[:60]))
105
+ return "#text(fill: rgb(\"#b03a2e\"))[%s]" % escape_typst(latex)
106
+ for item in result.warnings:
107
+ warn("formula downgraded (%s): %s" % (item.get("code", ""), item.get("message", "")))
108
+ body = result.typst.strip()
109
+ if display:
110
+ return "$ " + body + " $"
111
+ return "$" + body + "$"
112
+
113
+
114
+ def prose_block(text):
115
+ """A run of prose lines as one Typst paragraph or list."""
116
+ lines = [line for line in text.split("\n") if line.strip() != ""]
117
+ matches = [LIST_LINE.match(line) for line in lines]
118
+ if lines and all(match is not None for match in matches):
119
+ return "\n".join("- " + inline_style(match.group(1)) for match in matches)
120
+ return inline_style(" ".join(line.strip() for line in lines))
121
+
122
+
123
+ def md_to_typst(md, inline_formulas):
124
+ """Translated block markdown -> Typst markup (prose, maths, small structure)."""
125
+ text = sanitize_display_math(md).strip()
126
+ if inline_formulas:
127
+ # A block too short for a display equation gets it inline, with its line
128
+ # breaks collapsed — Typst inline maths cannot span lines.
129
+ text = re.sub(r"\$\$([\s\S]*?)\$\$",
130
+ lambda match: "$" + " ".join(match.group(1).split()) + "$",
131
+ text)
132
+ parts = MATH_SPLIT.split(text)
133
+ output = []
134
+ prose = []
135
+ inline_math = {}
136
+ for part in parts:
137
+ if part == "":
138
+ continue
139
+ if part.startswith("$$") and part.endswith("$$") and part.count("$$") >= 2:
140
+ if prose:
141
+ output.append(prose_block("".join(prose)))
142
+ prose = []
143
+ output.append(math_to_typst(part[2:-2].strip(), True))
144
+ continue
145
+ if part.startswith("$") and part.endswith("$") and len(part) >= 2:
146
+ # A placeholder survives prose escaping; the maths is swapped in after
147
+ # the prose is clean, so its backslashes are not mistaken for markup.
148
+ key = "zMt%dZ" % len(inline_math)
149
+ inline_math[key] = part[1:-1].strip()
150
+ prose.append(key)
151
+ continue
152
+ prose.append(part)
153
+ if prose:
154
+ output.append(prose_block("".join(prose)))
155
+ content = "\n\n".join(piece for piece in output if piece.strip() != "")
156
+
157
+ def restore(match):
158
+ latex = inline_math.get(match.group(0))
159
+ return match.group(0) if latex is None else math_to_typst(latex, False)
160
+
161
+ return re.sub(r"zMt\d+Z", restore, content)
162
+
163
+
164
+ def build_page(adjustments):
165
+ """One Typst document: placed textblocks and the boxes reserved for them."""
166
+ font = cjk_font()
167
+ parts = [
168
+ "#set page(width: %.4fpt, height: %.4fpt, margin: 0pt)" % (page_width, page_height),
169
+ '#set text(font: ("%s", "New Computer Modern"), lang: "zh")' % font,
170
+ "#set par(justify: false)",
171
+ ]
172
+ placed = []
173
+ for block_index, block in enumerate(blocks, start=1):
174
+ md = (block.get("md") or "").strip()
175
+ if md == "":
176
+ continue
177
+ bbox = block.get("bbox") or [0, 0, 1, 1]
178
+ x, y, width, _height = [float(value) for value in bbox]
179
+ room = room_below(block, blocks, page_height, font_pt)
180
+ left = start_x(block, blocks)
181
+ right = room_right(block, blocks)
182
+ x_pt = max(0.0, left * page_width)
183
+ w_pt = max(40.0, min((right - left) * page_width, page_width - x_pt - 4.0))
184
+ adjustment = adjustments.get(str(block.get("id") or "")) or {}
185
+ body_pt = body_of(block, adjustments, font_pt, MIN_PT)
186
+ lead_pt = leading_of(block, body_pt, page_height) * float(adjustment.get("leading", 1.0))
187
+ # Even a tightened leading stays a line, not a squeeze.
188
+ lead_pt = max(body_pt * 1.02, lead_pt)
189
+ target = baseline_of(block, page_height, font_pt)
190
+ y_pt = max(0.0, float(adjustment.get("y", target)))
191
+ h_pt = max(6.0, min(room, page_height - y_pt - 4.0))
192
+ base_pt = body_of(block, {}, font_pt, MIN_PT)
193
+ inline_formulas = room < base_pt * 2.6 and "$$" in md
194
+ text = sanitize_display_math(md).strip()
195
+ display_only = (not inline_formulas) and re.fullmatch(r"\$\$[\s\S]*\$\$", text) is not None \
196
+ and text.count("$$") == 2
197
+ if not display_only and not inline_formulas and "$$" in text:
198
+ # Typst ignores a block equation placed inside a paragraph, so a
199
+ # display formula mixed with prose is set inline and reported.
200
+ warn("display formula inside a paragraph rendered inline")
201
+ content = md_to_typst(md, inline_formulas or (not display_only and "$$" in text))
202
+ if content.strip() == "":
203
+ continue
204
+ marker_number = len(placed) + 1
205
+ marker = "MD%03d" % marker_number
206
+ # The marker is its own absolutely placed element, written just before the
207
+ # block in the content stream. It costs no layout (unlike an inline box,
208
+ # which made a following `(` a function call) and it lets the sequence
209
+ # attribution find every block, display equations included.
210
+ parts.append("#place(dx: %.2fpt, dy: %.2fpt, text(size: 1pt, fill: white)[%s])" %
211
+ (x_pt, y_pt, marker))
212
+ align = align_name(block)
213
+ if display_only:
214
+ # A block equation is a block element: it must not sit inside `par`,
215
+ # which would make Typst drop it. It is centred like the LaTeX one.
216
+ inner = "align(center)[#text(size: %.2fpt)[%s]]" % (body_pt, content)
217
+ else:
218
+ justify = align == "justify"
219
+ paragraph = "par(leading: %.3fpt, justify: %s)[#text(size: %.2fpt, top-edge: \"ascender\", bottom-edge: \"descender\")[%s]]" % (
220
+ max(0.0, lead_pt - (ASCENT_RATIO + DESCENT_RATIO) * body_pt),
221
+ "true" if justify else "false",
222
+ body_pt,
223
+ content,
224
+ )
225
+ if align == "center":
226
+ inner = "align(center)[%s]" % paragraph
227
+ elif align == "right":
228
+ inner = "align(right)[%s]" % paragraph
229
+ else:
230
+ inner = paragraph
231
+ parts.append("#place(dx: %.2fpt, dy: %.2fpt, block(width: %.2fpt, %s))" % (x_pt, y_pt, w_pt, inner))
232
+ placed.append({
233
+ "id": str(block.get("id") or ""),
234
+ "marker": marker,
235
+ "rect": (x_pt, y_pt, x_pt + w_pt, y_pt + h_pt),
236
+ "target": target,
237
+ "room": h_pt,
238
+ "body": body_pt,
239
+ "leading": lead_pt,
240
+ "align": align,
241
+ "y": y_pt,
242
+ })
243
+ return "\n".join(parts) + "\n", placed
244
+
245
+
246
+ def compile_page(document, work, out_pdf):
247
+ """Write the page's Typst source and compile it; returns the PDF path."""
248
+ typ_path = os.path.join(work, "doc.typ")
249
+ pdf_path = os.path.join(work, "doc.pdf")
250
+ if os.path.exists(pdf_path):
251
+ os.remove(pdf_path)
252
+ with open(typ_path, "w", encoding="utf-8") as handle:
253
+ handle.write(document)
254
+ run_typst(["compile", "doc.typ", "doc.pdf"], cwd=work, timeout=120)
255
+ if not os.path.exists(pdf_path):
256
+ raise SystemExit("typst did not produce a PDF")
257
+ return pdf_path
258
+
259
+
260
+ work = os.path.abspath(out_path) + ".work"
261
+ os.makedirs(work, exist_ok=True)
262
+ try:
263
+ applied = {}
264
+ document, placed = build_page(applied)
265
+ pdf_path = compile_page(document, work, out_path)
266
+ measured = measure_page(pdf_path, placed)
267
+ # Typst's line box can grow on the first line when it contains a tall formula,
268
+ # so one correction pass is not always enough. Corrections accumulate: a
269
+ # block without a new step keeps the placement it already earned, instead of
270
+ # snapping back to the printed baseline estimate.
271
+ # Typst's line box can grow on the first line when it contains a tall formula,
272
+ # so one correction pass is not always enough. Corrections accumulate: a
273
+ # block without a new step keeps the placement it already earned, instead of
274
+ # snapping back to the printed baseline estimate.
275
+ limit = min(font_pt, MIN_PT)
276
+ for _attempt in range(3):
277
+ step = plan_adjustments(placed, measured, font_pt, MIN_PT)
278
+ changed = bool(step)
279
+ for block_id, adjustment in step.items():
280
+ current = applied.setdefault(block_id, {})
281
+ if "y" in adjustment:
282
+ current["y"] = adjustment["y"]
283
+ if "scale" in adjustment:
284
+ current["scale"] = adjustment["scale"]
285
+ # A block already at the size floor cannot shrink any more; tightening its
286
+ # leading is the remaining way to keep the paragraph inside its room.
287
+ for entry, row in zip(placed, measured):
288
+ if row is None or row["bounds"] is None:
289
+ continue
290
+ height = row["bounds"].height
291
+ if height <= entry["room"] + 0.5 or entry["body"] > limit + 0.01:
292
+ continue
293
+ factor = max(0.85, entry["room"] / height)
294
+ current = applied.setdefault(entry["id"], {})
295
+ previous = float(current.get("leading", 1.0))
296
+ following = max(0.85, previous * factor)
297
+ if following < previous - 0.002:
298
+ current["leading"] = following
299
+ changed = True
300
+ if not changed:
301
+ break
302
+ document, placed = build_page(applied)
303
+ pdf_path = compile_page(document, work, out_path)
304
+ measured = measure_page(pdf_path, placed)
305
+ os.replace(pdf_path, out_path)
306
+ write_layout(placed, measured, layout_target(blocks_path, out_path),
307
+ page_width, page_height, font_pt)
308
+ finally:
309
+ shutil.rmtree(work, ignore_errors=True)
310
+ for message in WARNINGS:
311
+ print("warning: " + message, file=sys.stderr)
312
+ print(out_path)