tydo 0.1.0__py3-none-any.whl

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.
tydo/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Convert Typst source to editable DOCX."""
2
+
3
+ from .converter import convert
4
+ from .model import (
5
+ ConfigurationError,
6
+ ConversionError,
7
+ ConversionOptions,
8
+ ConversionResult,
9
+ StrictConversionError,
10
+ )
11
+
12
+ __all__ = [
13
+ "ConfigurationError",
14
+ "ConversionError",
15
+ "ConversionOptions",
16
+ "ConversionResult",
17
+ "StrictConversionError",
18
+ "convert",
19
+ ]
tydo/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
tydo/_drawings.py ADDED
@@ -0,0 +1,178 @@
1
+ """Identify supported drawing elements and verify recovered SVG placements."""
2
+
3
+ import copy
4
+
5
+ from lxml import html
6
+
7
+ from ._html import discard_unused_math_styles
8
+
9
+ PRIMITIVES = ("rect", "square", "circle", "ellipse", "line", "polygon", "curve")
10
+ COMPOSITIONS = ("stack", "rotate", "scale", "move", "skew")
11
+ CANVAS_TRIGGERS = ("place", "align")
12
+ DRAWING_ELEMENTS = (*PRIMITIVES, *COMPOSITIONS, *CANVAS_TRIGGERS)
13
+ DRAWING_XPATH = "//*[@data-tw-drawing]"
14
+
15
+ _PICTURE_RULE = """
16
+ #let tw-horizontal-rule(it) = {
17
+ let fields = it.fields()
18
+ let length = fields.at("length", default: 30pt)
19
+ let has-end = fields.at("end", default: none) != none
20
+ let angle = fields.at("angle", default: 0deg)
21
+ not has-end and angle == 0deg and type(length) == relative and length.ratio > 0%
22
+ }
23
+ #let tw-picture(it) = context if target() == "html" {
24
+ html.elem("span", attrs: ("data-tw-drawing": "1"), html.frame(it))
25
+ } else { it }
26
+ """
27
+
28
+ _COMPOSITION_RULES = """
29
+ #let tw-drawing-info(node) = {
30
+ let kind = repr(node.func())
31
+ if node.func() == math.equation {
32
+ let inline-label = node.fields().at("block", default: true) == false and not node.has("label")
33
+ return (valid: inline-label, paints: false, placed: false)
34
+ }
35
+ let primitive = kind in ("rect", "square", "circle", "ellipse", "line", "polygon", "curve")
36
+ let decoration = kind in (
37
+ "stack", "rotate", "scale", "move", "skew", "block", "box", "pad",
38
+ "place", "align", "sequence", "styled", "text", "space", "linebreak", "strong", "emph", "h", "v",
39
+ )
40
+ if not (primitive or decoration) { return (valid: false, paints: false, placed: false) }
41
+ let fields = node.fields()
42
+ let children = fields.at("children", default: ())
43
+ let body = fields.at(if kind == "styled" { "child" } else { "body" }, default: none)
44
+ if type(body) == content { children.push(body) }
45
+ let details = children.filter(it => type(it) == content).map(tw-drawing-info)
46
+ (
47
+ valid: details.all(it => it.valid),
48
+ paints: primitive or details.any(it => it.paints),
49
+ placed: kind == "place" or details.any(it => it.placed),
50
+ )
51
+ }
52
+ #let tw-composition(it) = {
53
+ let diagram = tw-drawing-info(it)
54
+ if diagram.valid and diagram.paints { tw-picture(it) } else { it }
55
+ }
56
+ """
57
+
58
+ _CANVAS_RULE = """
59
+ #let tw-fixed-length(value) = (
60
+ type(value) == length or (type(value) == relative and value.ratio == 0%)
61
+ )
62
+ #show block: it => context {
63
+ let fields = it.fields()
64
+ let fixed-canvas = (
65
+ tw-fixed-length(fields.at("width", default: auto)) and
66
+ tw-fixed-length(fields.at("height", default: auto))
67
+ )
68
+ if target() == "html" and fixed-canvas {
69
+ let diagram = tw-drawing-info(it)
70
+ if diagram.valid and diagram.paints and diagram.placed {
71
+ // Unhandled placed children leave an empty div in the original HTML.
72
+ html.elem("div", tw-picture(it))
73
+ } else { it }
74
+ } else { it }
75
+ }
76
+ """
77
+
78
+
79
+ def drawing_rules(names):
80
+ rules = [_PICTURE_RULE]
81
+ canvas = any(name in CANVAS_TRIGGERS for name in names)
82
+ if canvas or any(name in COMPOSITIONS for name in names):
83
+ rules.append(_COMPOSITION_RULES)
84
+ rules.extend(
85
+ "#show line: it => if tw-horizontal-rule(it) { it } else { tw-picture(it) }"
86
+ if name == "line"
87
+ else f"#show {name}: tw-picture"
88
+ for name in names
89
+ if name in PRIMITIVES
90
+ )
91
+ rules.extend(f"#show {name}: tw-composition" for name in names if name in COMPOSITIONS)
92
+ if canvas:
93
+ rules.append(_CANVAS_RULE)
94
+ return "\n".join(rules) + "\n"
95
+
96
+
97
+ def unwrap_drawing_images(tree):
98
+ """Expose a sole figure image to Pandoc without changing inline prose."""
99
+ for marker in tree.xpath(DRAWING_XPATH):
100
+ if len(marker) != 1 or marker[0].get("data-tw-inline-svg") != "1":
101
+ continue
102
+ image = marker[0]
103
+ wrapper = marker
104
+ while (
105
+ (parent := wrapper.getparent()).tag in ("div", "p")
106
+ and not parent.attrib
107
+ and len(parent) == 1
108
+ and not (parent.text or "").strip()
109
+ and not (wrapper.tail or "").strip()
110
+ ):
111
+ wrapper = parent
112
+ if (
113
+ parent.tag == "figure"
114
+ and not (marker.text or "").strip()
115
+ and not (image.tail or "").strip()
116
+ ):
117
+ image.tail = wrapper.tail
118
+ parent.replace(wrapper, image)
119
+ else:
120
+ marker.drop_tag()
121
+
122
+
123
+ def _trim_paragraphs(tree):
124
+ for paragraph in tree.xpath("//p[not(ancestor::pre)]"):
125
+ if paragraph.text:
126
+ paragraph.text = paragraph.text.lstrip(" \t\r\n") or None
127
+ if not len(paragraph) and paragraph.text:
128
+ paragraph.text = paragraph.text.rstrip(" \t\r\n") or None
129
+ if len(paragraph) and paragraph[-1].tail:
130
+ paragraph[-1].tail = paragraph[-1].tail.rstrip(" \t\r\n") or None
131
+
132
+
133
+ def _comparison_html(tree):
134
+ _trim_paragraphs(tree)
135
+ discard_unused_math_styles(tree)
136
+ return html.tostring(tree)
137
+
138
+
139
+ def _remove_empty_paragraph(paragraph):
140
+ if not paragraph.attrib and not len(paragraph) and not (paragraph.text or "").strip():
141
+ paragraph.drop_tree()
142
+
143
+
144
+ def _unpaint(tree, split_inline):
145
+ for marker in tree.xpath(DRAWING_XPATH):
146
+ paragraph = marker.getparent()
147
+ if (
148
+ split_inline
149
+ and paragraph.tag == "li"
150
+ and paragraph.xpath('parent::ol/parent::section[@role="doc-endnotes"]')
151
+ ):
152
+ # A single-paragraph Typst footnote omits its <p> wrapper in HTML.
153
+ note = paragraph
154
+ paragraph = html.Element("p")
155
+ paragraph.text, note.text = note.text, None
156
+ paragraph.extend(list(note))
157
+ note.append(paragraph)
158
+ if paragraph.tag != "p":
159
+ marker.drop_tree()
160
+ continue
161
+ if not split_inline:
162
+ marker.drop_tree()
163
+ else:
164
+ after = html.Element("p")
165
+ after.text = marker.tail
166
+ for node in list(marker.itersiblings()):
167
+ after.append(node)
168
+ marker.getparent().remove(marker)
169
+ paragraph.addnext(after)
170
+ _remove_empty_paragraph(after)
171
+ _remove_empty_paragraph(paragraph)
172
+ return _comparison_html(tree)
173
+
174
+
175
+ def drawing_replay_matches(original, replay):
176
+ """Compare layouts after removing artifacts introduced by inserted drawing frames."""
177
+ baseline = _comparison_html(copy.deepcopy(original))
178
+ return any(_unpaint(copy.deepcopy(replay), split) == baseline for split in (False, True))
tydo/_equations.py ADDED
@@ -0,0 +1,197 @@
1
+ """Transfer equation numbering and references around Pandoc's OMML output."""
2
+
3
+ import copy
4
+ import re
5
+
6
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
7
+ from docx.oxml.ns import qn
8
+ from docx.shared import Mm, Pt
9
+ from lxml import html
10
+
11
+ from ._xml import element as el
12
+ from ._xml import field
13
+ from ._xml import text_run as run
14
+
15
+
16
+ def prepare_equations(tree, source_equations, warnings):
17
+ # Preserve block-equation anchors; Pandoc's HTML math reader discards math IDs.
18
+ equations = {}
19
+ equation_markers = {}
20
+ equation_parens = {}
21
+ static_equations = {}
22
+ math_nodes = tree.xpath('//math[@display="block"]')
23
+ if len(math_nodes) != len(source_equations):
24
+ raise ValueError("HTML and Typst display-equation counts differ")
25
+ for index, (m, meta) in enumerate(zip(math_nodes, source_equations), 1):
26
+ if not meta["numbered"] and "id" not in m.attrib:
27
+ continue
28
+ ident = m.attrib.pop("id", f"eq_auto_{index}").replace("-", "_")
29
+ wrapper = html.Element("div", id=ident)
30
+ m.addprevious(wrapper)
31
+ wrapper.append(m)
32
+ if not meta["numbered"]:
33
+ continue
34
+ if meta["decimal"]:
35
+ equations[ident] = meta["number"]
36
+ equation_parens[ident] = meta["parens"]
37
+ elif meta["display"] is None:
38
+ warnings.append(
39
+ f"{ident}: equation numbering returned non-text content; number omitted."
40
+ )
41
+ continue
42
+ else:
43
+ static_equations[ident] = meta["display"]
44
+ marker = html.Element("p")
45
+ marker.text = f"TWEQUATION{index:05}"
46
+ wrapper.addprevious(marker)
47
+ equation_markers[marker.text] = ident
48
+ return equations, equation_markers, equation_parens, static_equations
49
+
50
+
51
+ def locate_equations(body, equation_markers):
52
+ mathparas = {}
53
+ for marker in body.xpath(".//w:p"):
54
+ ident = equation_markers.get("".join(marker.xpath(".//w:t/text()")))
55
+ if ident is None:
56
+ continue
57
+ equation = next((s for s in marker.itersiblings() if s.tag == qn("w:p")), None)
58
+ if equation is None or equation.find(".//" + qn("m:oMathPara")) is None:
59
+ raise ValueError(f"{ident}: could not find native Word math after its marker")
60
+ mathparas["_" + ident] = equation
61
+ marker.getparent().remove(marker)
62
+ return mathparas
63
+
64
+
65
+ def restore_equations(
66
+ doc,
67
+ body,
68
+ equations,
69
+ static_equations,
70
+ equation_parens,
71
+ mathparas,
72
+ wide_nodes,
73
+ full_mm,
74
+ column_mm,
75
+ section_sizes,
76
+ ):
77
+ # Restore each display equation's visible number as a Word SEQ field.
78
+ if mathparas.keys() != equations.keys() | static_equations.keys():
79
+ raise ValueError("One or more numbered display equations were dropped by Pandoc.")
80
+ previous_number = 0
81
+ next_math_bookmark = (
82
+ max([int(b.get(qn("w:id"))) for b in body.xpath(".//w:bookmarkStart")] + [0]) + 1
83
+ )
84
+ equation_tables = set()
85
+ for ident, old in mathparas.items():
86
+ n = equations.get(ident)
87
+ static_label = static_equations.get(ident)
88
+ # Remove Pandoc's empty anchor, then anchor the actual sequence number.
89
+ for start in body.xpath(".//w:bookmarkStart"):
90
+ if start.get(qn("w:name")) == ident:
91
+ bid = start.get(qn("w:id"))
92
+ for end in body.xpath(".//w:bookmarkEnd"):
93
+ if end.get(qn("w:id")) == bid:
94
+ end.getparent().remove(end)
95
+ start.getparent().remove(start)
96
+
97
+ number_paragraph = el("w:p")
98
+ number_props = el("w:pPr")
99
+ number_props.append(el("w:jc", val="right"))
100
+ number_paragraph.append(number_props)
101
+ bookmark_id = next_math_bookmark
102
+ next_math_bookmark += 1
103
+ if equation_parens.get(ident):
104
+ number_paragraph.append(run("("))
105
+ number_paragraph.append(el("w:bookmarkStart", id=bookmark_id, name=ident))
106
+ if static_label is not None:
107
+ number_paragraph.append(run(static_label))
108
+ else:
109
+ reset = f" \\r {n}" if n != previous_number + 1 else ""
110
+ number_paragraph.append(field(" SEQ Equation \\* ARABIC" + reset + " ", n))
111
+ previous_number = n
112
+ number_paragraph.append(el("w:bookmarkEnd", id=bookmark_id))
113
+ if equation_parens.get(ident):
114
+ number_paragraph.append(run(")"))
115
+ if old.getparent() is not body:
116
+ old.addnext(number_paragraph)
117
+ continue
118
+
119
+ tab = doc.add_table(rows=1, cols=2)
120
+ tab.autofit = False
121
+ equation_tables.add(tab._tbl)
122
+ eq_width = full_mm if old in wide_nodes else column_mm
123
+ if old in section_sizes:
124
+ eq_width = section_sizes[old][0]
125
+ label_width = len(static_label) * 2 if static_label is not None else 0
126
+ num_width = min(max(9.5, label_width), eq_width * 0.4)
127
+ tab.columns[0].width = Mm(eq_width - num_width)
128
+ tab.columns[1].width = Mm(num_width)
129
+ tab.cell(0, 0).width = Mm(eq_width - num_width)
130
+ tab.cell(0, 1).width = Mm(num_width)
131
+ pr = tab._tbl.tblPr
132
+ width = pr.find(qn("w:tblW"))
133
+ width.set(qn("w:type"), "dxa")
134
+ width.set(qn("w:w"), str(round(eq_width * 1440 / 25.4)))
135
+ borders = el("w:tblBorders")
136
+ for edge in ["top", "left", "bottom", "right", "insideH", "insideV"]:
137
+ borders.append(el("w:" + edge, val="nil"))
138
+ pr.append(borders)
139
+ cell_margins = el("w:tblCellMar")
140
+ for edge in ["top", "left", "bottom", "right"]:
141
+ cell_margins.append(el("w:" + edge, w="0", type="dxa"))
142
+ pr.append(cell_margins)
143
+ for cell in tab.rows[0].cells:
144
+ p = cell.paragraphs[0]
145
+ p.paragraph_format.first_line_indent = Pt(0)
146
+ p.paragraph_format.space_before = Pt(4)
147
+ p.paragraph_format.space_after = Pt(5)
148
+ cell.vertical_alignment = 1
149
+ eqp = tab.cell(0, 0).paragraphs[0]
150
+ eqp.alignment = WD_ALIGN_PARAGRAPH.CENTER
151
+ om = copy.deepcopy(old.find(".//" + qn("m:oMathPara")))
152
+ eqp._p.append(om)
153
+ nump = tab.cell(0, 1).paragraphs[0]
154
+ nump.alignment = WD_ALIGN_PARAGRAPH.RIGHT
155
+ nump._p.extend(list(number_paragraph)[1:])
156
+ tab.rows[0]._tr.get_or_add_trPr().append(el("w:cantSplit"))
157
+ old.addprevious(tab._tbl)
158
+ old.getparent().remove(old)
159
+ if old in wide_nodes:
160
+ wide_nodes.remove(old)
161
+ wide_nodes.add(tab._tbl)
162
+
163
+ # Formula references become updateable REF fields; other links remain clickable.
164
+ ref_count = 0
165
+ for link in list(body.xpath(".//w:hyperlink")):
166
+ ident = link.get(qn("w:anchor"))
167
+ if ident not in equations:
168
+ continue
169
+ text = "".join(link.xpath(".//w:t/text()"))
170
+ prefix = re.sub(r"\d+\s*$", "", text)
171
+ if prefix:
172
+ link.addprevious(run(prefix))
173
+ link.addprevious(field(f" REF {ident} \\h ", equations[ident]))
174
+ link.getparent().remove(link)
175
+ ref_count += 1
176
+ return equation_tables, ref_count
177
+
178
+
179
+ def configure_math_font(body):
180
+ # Pin math font size, including inline fractions, to the paper's text size.
181
+ for mr in body.xpath(".//m:r"):
182
+ pr = mr.find(qn("w:rPr"))
183
+ if pr is None:
184
+ pr = el("w:rPr")
185
+ mpr = mr.find(qn("m:rPr"))
186
+ mr.insert(1 if mpr is not None else 0, pr)
187
+ fonts = pr.find(qn("w:rFonts"))
188
+ if fonts is None:
189
+ fonts = el("w:rFonts")
190
+ pr.insert(0, fonts)
191
+ for key in ["ascii", "hAnsi", "eastAsia", "cs"]:
192
+ fonts.set(qn("w:" + key), "Cambria Math")
193
+ size = pr.find(qn("w:sz"))
194
+ if size is None:
195
+ pr.append(el("w:sz", val="20"))
196
+ else:
197
+ size.set(qn("w:val"), "20")