mathshuttle 0.8.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.
mathshuttle/tidy.py ADDED
@@ -0,0 +1,830 @@
1
+ """Paper-ready LaTeX from equations that come from Word / PowerPoint (MathML or OMML input).
2
+
3
+ texmath's TeX writer is faithful to the structure but not to what a LaTeX author would write,
4
+ and its MathML reader drops some of the meaning:
5
+
6
+ * ``<mi>OOD</mi>`` (upright, several letters) becomes ``OOD`` - italic in LaTeX; a function
7
+ name such as ``<mi>softmax</mi><mo>&#x2061;</mo>`` becomes ``{softmax}``, which reads
8
+ back as s*o*f*t*m*a*x;
9
+ * bold italic symbols (``\\boldsymbol{\\theta}``, ``\\bm{w}``) become ``\\mathbf{θ}`` / ``\\mathbf{w}``
10
+ (bold upright, and a raw θ that pdfLaTeX rejects);
11
+ * a binomial with ``linethickness="0"`` becomes ``\\left( \\frac{n}{k} \\right)``;
12
+ * a cell of an aligned block becomes ``a & {= b}``: the group loses the spacing of the relation;
13
+ * ``cases`` becomes ``\\left\\{ \\begin{matrix} ... \\end{matrix} \\right.``, sums carry
14
+ ``\\limits`` even in display maths, scripts may be empty (``x_{i}^{}``).
15
+
16
+ :func:`mark_identifiers` replaces the identifiers texmath would misread by placeholder names
17
+ before texmath runs and :func:`restore` puts the right LaTeX in their place; :func:`tidy_tex`
18
+ cleans the TeX texmath wrote. The caller checks that the result still converts.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import bisect
23
+ import copy
24
+ import itertools
25
+ import re
26
+ import unicodedata
27
+ import xml.etree.ElementTree as ET
28
+ from typing import Dict, List, Optional
29
+
30
+ # operator names texmath already writes as \log, \max, ...
31
+ _KNOWN_FUNCTIONS = frozenset(
32
+ "arccos arcsin arctan arg cos cosh cot coth csc deg det dim exp gcd hom inf ker lg lim liminf limsup "
33
+ "ln log max min Pr sec sin sinh sup tan tanh".split())
34
+ _GREEK = {
35
+ "α": "alpha", "β": "beta", "γ": "gamma", "δ": "delta", "ε": "varepsilon", "ϵ": "epsilon", "ζ": "zeta",
36
+ "η": "eta", "θ": "theta", "ϑ": "vartheta", "ι": "iota", "κ": "kappa", "ϰ": "varkappa", "λ": "lambda",
37
+ "μ": "mu", "ν": "nu", "ξ": "xi", "π": "pi", "ϖ": "varpi", "ρ": "rho", "ϱ": "varrho", "σ": "sigma",
38
+ "ς": "varsigma", "τ": "tau", "υ": "upsilon", "φ": "varphi", "ϕ": "phi", "χ": "chi", "ψ": "psi",
39
+ "ω": "omega", "Γ": "Gamma", "Δ": "Delta", "Θ": "Theta", "Λ": "Lambda", "Ξ": "Xi", "Π": "Pi",
40
+ "Σ": "Sigma", "Υ": "Upsilon", "Φ": "Phi", "Ψ": "Psi", "Ω": "Omega", "∇": "nabla", "∂": "partial"}
41
+ # Symbols texmath leaves as literal characters.
42
+ _RAW_SYMBOLS = {
43
+ **_GREEK, "ϝ": "digamma", "▫": "square", "▴": "blacktriangle", "▾": "blacktriangledown",
44
+ "⊏": "sqsubset", "⊐": "sqsupset", "≔": "coloneqq", "≕": "eqqcolon", "⤳": "leadsto",
45
+ "⌜": "ulcorner", "⌝": "urcorner", "⌞": "llcorner", "⌟": "lrcorner", "℧": "mho",
46
+ "✓": "checkmark", "✠": "maltese",
47
+ }
48
+ # Choose the conventional name for shared glyphs. texmath reads □ as \square, but its
49
+ # writer needs \Box to keep □ distinct from ▫ (\square). Apply these before _RAW_SYMBOLS.
50
+ _COMMAND_ALIASES = {
51
+ r"\hslash": r"\hbar", r"\preccurlyeq": r"\preceq", r"\succcurlyeq": r"\succeq",
52
+ r"\bigtriangleup": r"\triangle", r"\land": r"\wedge", r"\lor": r"\vee", r"\square": r"\Box",
53
+ r"\backslash": r"\setminus", r"\smallsetminus": r"\setminus", r"\varnothing": r"\emptyset",
54
+ }
55
+ # Placeholder identifiers: letters only (texmath keeps a multi-letter <mi> as one run of letters), with
56
+ # an index alphabet that cannot form the delimiters, so that adjacent placeholders split unambiguously.
57
+ _PLACEHOLDER = "QQXJ%sJXQQ"
58
+ _PLACEHOLDER_RE = re.compile(r"QQXJ[A-H]+?JXQQ")
59
+
60
+
61
+ def _letters(n: int) -> str:
62
+ s = ""
63
+ while True:
64
+ s = "ABCDEFGH"[n % 8] + s
65
+ n //= 8
66
+ if not n:
67
+ return s
68
+
69
+
70
+ def _base(ch: str) -> str:
71
+ """The plain character behind a mathematical alphanumeric (𝜽 -> θ, 𝐱 -> x), from its Unicode name:
72
+ NFKC would fold the Greek variants together (𝝓 PHI SYMBOL -> φ, but it is ϕ)."""
73
+ try:
74
+ name = unicodedata.name(ch)
75
+ except ValueError:
76
+ return ch
77
+ m = re.match(r"MATHEMATICAL (?:BOLD |ITALIC |SCRIPT |FRAKTUR |DOUBLE-STRUCK |SANS-SERIF |MONOSPACE )+(.*)$", name)
78
+ if not m:
79
+ return ch
80
+ rest = m.group(1)
81
+ for candidate in ("GREEK " + rest.replace("SMALL ", "SMALL LETTER ").replace("CAPITAL ", "CAPITAL LETTER "),
82
+ "GREEK " + rest, "GREEK LUNATE " + rest, rest.replace("SMALL ", "LATIN SMALL LETTER ")
83
+ .replace("CAPITAL ", "LATIN CAPITAL LETTER "), rest):
84
+ try:
85
+ return unicodedata.lookup(candidate)
86
+ except KeyError:
87
+ continue
88
+ return unicodedata.normalize("NFKC", ch)
89
+
90
+
91
+ def _style(ch: str) -> str:
92
+ """"bold-italic", "bold" or "" for a mathematical alphanumeric character."""
93
+ try:
94
+ name = unicodedata.name(ch)
95
+ except ValueError:
96
+ return ""
97
+ if name.startswith("MATHEMATICAL BOLD ITALIC "):
98
+ return "bold-italic"
99
+ if name.startswith("MATHEMATICAL BOLD "):
100
+ return "bold"
101
+ return ""
102
+
103
+
104
+ def _symbol_tex(ch: str) -> Optional[str]:
105
+ if "a" <= ch <= "z" or "A" <= ch <= "Z":
106
+ return ch
107
+ name = _GREEK.get(ch)
108
+ return "\\" + name if name else None
109
+
110
+
111
+ def _identifier_tex(mi: ET.Element, applied: bool) -> Optional[str]:
112
+ """The LaTeX for an <mi> that texmath would misread, or None to leave it to texmath."""
113
+ text = (mi.text or "").strip()
114
+ if len(mi) or not text:
115
+ return None
116
+ variant = mi.get("mathvariant")
117
+ if len(text) > 1:
118
+ if not re.fullmatch(r"[A-Za-z]+", text) or variant not in (None, "normal") or text in _KNOWN_FUNCTIONS:
119
+ return None
120
+ return "\\operatorname{%s}" % text if applied else "\\mathrm{%s}" % text
121
+ if variant == "normal" and re.fullmatch(r"[A-Za-z]", text):
122
+ return "\\mathrm{%s}" % text
123
+ style = _style(text) or (variant if variant in ("bold", "bold-italic") else "")
124
+ base = _base(text)
125
+ symbol = _symbol_tex(base)
126
+ if not style or symbol is None or len(base) != 1:
127
+ return None
128
+ if style == "bold-italic":
129
+ return "\\boldsymbol{%s}" % symbol
130
+ if base in _GREEK and not base.isupper(): # bold upright lowercase Greek does not exist in LaTeX
131
+ return "\\boldsymbol{%s}" % symbol
132
+ if base in _GREEK:
133
+ return "\\mathbf{%s}" % symbol
134
+ return None # bold upright Latin: texmath writes \mathbf{x} itself
135
+
136
+
137
+ def _is_mo(el: Optional[ET.Element], *texts: str) -> bool:
138
+ return el is not None and el.tag == "mo" and (el.text or "").strip() in texts
139
+
140
+
141
+ def _infix_operators(row: ET.Element) -> None:
142
+ """Arrows and bars in a row can inherit stretchy=true from the operator dictionary. texmath
143
+ then invents invisible fences. A delimiter, a middle in a fenced row and a label base keep
144
+ their stretchiness."""
145
+ if row.tag not in ("math", "mrow", "mtd", "mstyle", "mpadded", "msqrt") or len(row) < 3:
146
+ return
147
+ fenced = any(edge.get("stretchy") != "false" and _is_mo(edge, *chars)
148
+ for edge, chars in ((row[0], "([{⟨⌊⌈|‖"), (row[-1], ")]}⟩⌋⌉|‖")))
149
+ # bars that the MathML itself says stretch, in pairs (a |y/x| b): an absolute value or a norm
150
+ declared = [i for i in range(1, len(row) - 1) if row[i].tag == "mo" and row[i].get("stretchy") == "true"
151
+ and (row[i].text or "").strip() in ("|", "‖")]
152
+ paired = set(declared) if len(declared) >= 2 and len(declared) % 2 == 0 else set()
153
+ for i in range(1, len(row) - 1):
154
+ mo = row[i]
155
+ if mo.tag != "mo" or mo.get("stretchy") == "false" or mo.get("fence") == "true" or i in paired:
156
+ continue
157
+ ch = (mo.text or "").strip()
158
+ name = unicodedata.name(ch, "") if len(ch) == 1 else ""
159
+ if ch not in ("|", "‖", "∣", "∥") and "ARROW" not in name and "HARPOON" not in name:
160
+ continue
161
+ if mo.get("form") in ("prefix", "postfix"):
162
+ continue
163
+ if fenced and (ch in ("|", "‖") or mo.get("stretchy") == "true"):
164
+ continue
165
+ # With invisible outer fences, a declared \middle| can still stretch to a fraction or script.
166
+ if ch in ("|", "‖") and mo.get("form") == "infix" and mo.get("stretchy") == "true" and any(map(len, row)):
167
+ continue
168
+ # A bar next to another operator can open or close an absolute value (a + |x|).
169
+ if ch in ("|", "‖") and ((row[i - 1].tag == "mo" and row[i - 1].get("form") != "postfix")
170
+ or (row[i + 1].tag == "mo" and row[i + 1].get("form") != "prefix")):
171
+ continue
172
+ mo.set("stretchy", "false")
173
+
174
+
175
+ def mark_identifiers(math: ET.Element, mapping: Dict[str, str], start: int = 0) -> None:
176
+ """Replace the <mi>s texmath would misread by placeholder names (recorded in `mapping`, numbered
177
+ from `start` so that the keys of several equations differ), and fix two readings of texmath's:
178
+ a zero-thickness fraction between ( and ) is a binomial (texmath only knows ``0pt`` for that), and
179
+ U+2225 with form prefix / postfix is a norm bar (texmath writes \\| so; a relation has no form).
180
+ The element must have no namespace (tags ``mi``, ``mo``...)."""
181
+ for parent in math.iter():
182
+ _infix_operators(parent)
183
+ children = list(parent)
184
+ for i, child in enumerate(children):
185
+ if child.tag == "mfrac":
186
+ thickness = (child.get("linethickness") or "").strip()
187
+ if not (thickness and re.fullmatch(r"0*\.?0*(?:pt|px|em|ex|mm|cm|in)?", thickness)) or len(child) != 2:
188
+ continue
189
+ fenced = (0 < i < len(children) - 1 and _is_mo(children[i - 1], "(") and _is_mo(children[i + 1], ")"))
190
+ if fenced:
191
+ child.set("linethickness", "0pt")
192
+ else:
193
+ # a bar-less stack (Word's "stack", a \substack): texmath would read \frac (a bar) for
194
+ # "0" and \binom (parentheses) for "0pt" - two rows of a table keep what it shows
195
+ rows = [ET.Element("mtr") for _ in range(2)]
196
+ for row, part in zip(rows, list(child)):
197
+ cell = ET.SubElement(row, "mtd")
198
+ cell.append(part)
199
+ child.tag = "mtable"
200
+ child.attrib.clear()
201
+ child[:] = rows
202
+ elif child.tag == "mo" and (child.text or "").strip() == "\u2225" and (
203
+ child.get("form") in ("prefix", "postfix") or child.get("fence") == "true"):
204
+ child.text = "\u2016" # a norm bar, not the relation "parallel to"
205
+ elif i == 0 and parent.tag in ("mover", "munder", "munderover") and _is_mo(child, "→", "←") \
206
+ and child.get("stretchy") == "false":
207
+ # This label sits on a fixed arrow; keep it distinct from an extensible xarrow.
208
+ key = _PLACEHOLDER % _letters(start + len(mapping))
209
+ arrow = "rightarrow" if child.text.strip() == "→" else "leftarrow"
210
+ mapping[key] = "\\mathrel{\\%s}" % arrow
211
+ child.tag, child.text = "mi", key
212
+ elif child.tag == "mi":
213
+ nxt = children[i + 1] if i + 1 < len(children) else None
214
+ tex = _identifier_tex(child, _is_mo(nxt, "\u2061"))
215
+ if tex is None:
216
+ continue
217
+ key = _PLACEHOLDER % _letters(start + len(mapping))
218
+ mapping[key] = tex
219
+ child.text = key
220
+ child.attrib.pop("mathvariant", None)
221
+
222
+
223
+ def _run_tex(text: str, style: Optional[str], function_name: bool) -> Optional[str]:
224
+ """The LaTeX for an OMML run (`style`: its m:sty, p b i bi) that texmath would misread, or None."""
225
+ if len(text) > 1:
226
+ if not re.fullmatch(r"[A-Za-z]+", text) or text in _KNOWN_FUNCTIONS:
227
+ return None
228
+ if function_name:
229
+ return "\\operatorname{%s}" % text
230
+ return "\\mathrm{%s}" % text if style == "p" else None
231
+ symbol = _symbol_tex(text)
232
+ if symbol is None:
233
+ return None
234
+ if style == "p" and text.isascii():
235
+ return "\\mathrm{%s}" % text
236
+ if style == "bi" or (style == "b" and text in _GREEK and not text.isupper()):
237
+ return "\\boldsymbol{%s}" % symbol
238
+ return None
239
+
240
+
241
+ def _split_styled_runs(fragment: ET.Element, m: str) -> None:
242
+ """Word stores ``ℒ=`` as one run with a script style (m:scr) and the text "L="; texmath applies the
243
+ style to the whole run (``\\mathcal{L =}``). A style (m:scr, m:sty) only changes letters, so such
244
+ a run is split: the letters keep the style, the other characters get a run without it."""
245
+ parents = {child: parent for parent in fragment.iter() for child in parent}
246
+ for run in list(fragment.iter(m + "r")):
247
+ rpr = run.find(m + "rPr")
248
+ t = run.find(m + "t")
249
+ if rpr is None or t is None or not t.text or rpr.find(m + "nor") is not None:
250
+ continue
251
+ if not any(e.tag in (m + "scr", m + "sty") for e in rpr):
252
+ continue
253
+ pieces = ["".join(g) for _, g in itertools.groupby(t.text, key=str.isalnum)] # bold A1 stays bold
254
+ if len(pieces) < 2:
255
+ continue
256
+ parent = parents[run]
257
+ index = list(parent).index(run)
258
+ parent.remove(run)
259
+ for offset, piece in enumerate(pieces):
260
+ new = copy.deepcopy(run)
261
+ new.find(m + "t").text = piece
262
+ if not piece[0].isalnum():
263
+ new_rpr = new.find(m + "rPr")
264
+ for e in [e for e in new_rpr if e.tag in (m + "scr", m + "sty")]:
265
+ new_rpr.remove(e)
266
+ new.tail = run.tail if offset == len(pieces) - 1 else None
267
+ parent.insert(index + offset, new)
268
+
269
+
270
+ def mark_omml(fragment: ET.Element, mapping: Dict[str, str], ns: str, start: int = 0) -> None:
271
+ """:func:`mark_identifiers` for OMML: upright multi-letter runs, function names (m:fName),
272
+ upright single letters (``\\mathrm{d}``) and bold italic symbols get placeholders."""
273
+ m = "{%s}" % ns
274
+ _split_styled_runs(fragment, m)
275
+ names = {id(r) for f in fragment.iter(m + "fName") for r in f.iter(m + "r")}
276
+ # The OMML reader turns a limLow on max into \max_x even inline. A marked base keeps
277
+ # limLow/limUpp as an explicit underset/overset until the output style is known.
278
+ limits = {base[0] for tag in ("limLow", "limUpp") for lim in fragment.iter(m + tag)
279
+ for base in lim.findall(m + "e") if len(base) == 1}
280
+ for run in fragment.iter(m + "r"):
281
+ t = run.find(m + "t")
282
+ if t is None or not (t.text or "").strip():
283
+ continue
284
+ rpr = run.find(m + "rPr")
285
+ if rpr is not None and (rpr.find(m + "nor") is not None or rpr.find(m + "scr") is not None):
286
+ continue # normal text (\text{...}); script / fraktur / double-struck, which texmath reads itself
287
+ sty = rpr.find(m + "sty") if rpr is not None else None
288
+ word = t.text.strip()
289
+ style = sty.get(m + "val") if sty is not None else None
290
+ if run in limits and style in (None, "p") and (word in _NAMED_LIMITS or word == "arg"):
291
+ tex = "\\" + word
292
+ else:
293
+ tex = _run_tex(word, style, id(run) in names)
294
+ if tex is None:
295
+ continue
296
+ key = _PLACEHOLDER % _letters(start + len(mapping))
297
+ mapping[key] = tex
298
+ t.text = key
299
+ if sty is not None:
300
+ rpr.remove(sty)
301
+
302
+
303
+ def can_mark(text: str) -> bool:
304
+ """`text`: the input and the text of its identifiers (texmath joins adjacent ones)."""
305
+ return "QQXJ" not in text
306
+
307
+
308
+ # commands texmath writes with brace-group arguments; the second group of the two-argument ones
309
+ _ARG_COMMANDS = frozenset(
310
+ "sqrt frac dfrac tfrac cfrac binom dbinom tbinom genfrac overset underset stackrel overline underline hat "
311
+ "tilde bar vec dot ddot dddot breve check acute grave mathring widehat widetilde overbrace underbrace "
312
+ "overrightarrow overleftarrow overleftrightarrow underrightarrow underleftarrow xrightarrow xleftarrow "
313
+ "mathbf mathrm mathit mathcal mathbb mathfrak mathsf mathtt mathscr boldsymbol bm pmb operatorname text "
314
+ "textrm textit textbf mbox substack color phantom boxed cancel".split())
315
+ _TWO_ARG_COMMANDS = frozenset("frac dfrac tfrac cfrac binom dbinom tbinom genfrac overset underset stackrel".split())
316
+
317
+
318
+ def _is_argument(tex: str, start: int) -> bool:
319
+ """Whether the brace group opening at tex[start] is an argument (of a command, or a script)."""
320
+ before = tex[:start].rstrip()
321
+ if not before:
322
+ return False
323
+ if before[-1] in "_^":
324
+ return True
325
+ word = re.search(r"\\([a-zA-Z]+)\*?$", before)
326
+ if word:
327
+ return word.group(1) in _ARG_COMMANDS
328
+ if before[-1] == "}": # the second group of \frac{..}{..}?
329
+ depth, i = 0, len(before) - 1
330
+ while i >= 0:
331
+ if before[i] == "}" and (i == 0 or before[i - 1] != "\\"):
332
+ depth += 1
333
+ elif before[i] == "{" and (i == 0 or before[i - 1] != "\\"):
334
+ depth -= 1
335
+ if not depth:
336
+ break
337
+ i -= 1
338
+ word = re.search(r"\\([a-zA-Z]+)\s*$", before[:max(i, 0)])
339
+ return bool(word and word.group(1) in _TWO_ARG_COMMANDS)
340
+ return False
341
+
342
+
343
+ def restore(tex: str, mapping: Dict[str, str]) -> Optional[str]:
344
+ """`tex` with the placeholders replaced; None if one of them got lost or split."""
345
+ def unbraced(m):
346
+ # texmath groups a multi-letter identifier ({softmax}); the group goes where it is no argument
347
+ # (it stays in \sqrt{..}, x_{..}, the second group of \frac)
348
+ value = mapping.get(m.group(1), m.group(1))
349
+ return "{%s}" % value if _is_argument(tex, m.start()) else value
350
+ out = re.sub(r"\{(%s)\}" % _PLACEHOLDER_RE.pattern, unbraced, tex)
351
+ out = _PLACEHOLDER_RE.sub(lambda m: mapping.get(m.group(0), m.group(0)), out)
352
+ if "QQXJ" in out:
353
+ return None
354
+ # texmath's own MathML for \mathrm{OOD} has one <mi> per letter
355
+ return re.sub(r"(?:\\mathrm\{[A-Za-z]+\}){2,}",
356
+ lambda m: "\\mathrm{%s}" % "".join(re.findall(r"\{([A-Za-z]+)\}", m.group())), out)
357
+
358
+
359
+ # ---- the TeX written by texmath ------------------------------------------------------------------
360
+ _TOKEN = re.compile(r"\\(?P<be>begin|end)\s*\{(?P<env>[^{}]*)\}|\\[a-zA-Z@]+|\\.|%[^\n]*|[{}&_^]", re.S)
361
+ _CELL_ENVS = frozenset("matrix pmatrix bmatrix Bmatrix vmatrix Vmatrix smallmatrix aligned alignedat gathered "
362
+ "split cases array subarray align align* alignat alignat* gather gather* eqnarray "
363
+ "eqnarray* flalign flalign*".split())
364
+
365
+
366
+ def _group_end(tex: str, start: int) -> int:
367
+ depth = 0
368
+ for m in _TOKEN.finditer(tex, start):
369
+ if m.group() == "{":
370
+ depth += 1
371
+ elif m.group() == "}":
372
+ depth -= 1
373
+ if not depth:
374
+ return m.end()
375
+ return -1
376
+
377
+
378
+ def _env_end(tex: str, pos: int, env: str) -> "tuple[int, int]":
379
+ """(start, end) of the \\end{env} matching a \\begin{env} that ends at `pos`; (-1, -1) if none."""
380
+ depth = 1
381
+ for m in _TOKEN.finditer(tex, pos):
382
+ if m.group("be") and m.group("env") == env:
383
+ depth += 1 if m.group("be") == "begin" else -1
384
+ if not depth:
385
+ return m.start(), m.end()
386
+ return -1, -1
387
+
388
+
389
+ def _cells(body: str) -> "List[tuple[int, int]]":
390
+ """(start, end) of the cells of an environment body: split at its own & and \\\\."""
391
+ spans, start, depth = [], 0, 0
392
+ for m in _TOKEN.finditer(body):
393
+ tok = m.group()
394
+ if tok == "{" or m.group("be") == "begin":
395
+ depth += 1
396
+ elif tok == "}" or m.group("be") == "end":
397
+ depth -= 1
398
+ elif not depth and tok in ("&", "\\\\", "\\cr"):
399
+ spans.append((start, m.start()))
400
+ start = m.end()
401
+ spans.append((start, len(body)))
402
+ return spans
403
+
404
+
405
+ def _unwrap_cells(tex: str) -> str:
406
+ """``a & {= b + c}`` -> ``a & = b + c``: a cell is a group already, so braces around the
407
+ whole cell only take the spacing away from a relation at its start."""
408
+ changed = True
409
+ while changed:
410
+ changed = False
411
+ for m in _TOKEN.finditer(tex):
412
+ if m.group("be") != "begin" or m.group("env") not in _CELL_ENVS:
413
+ continue
414
+ open_end = m.end()
415
+ if m.group("env") in ("array", "subarray", "alignat", "alignat*", "alignedat"):
416
+ arg = re.compile(r"\s*(?:\[[^\[\]]*\]\s*)?\{").match(tex, open_end)
417
+ if arg:
418
+ open_end = _group_end(tex, arg.end() - 1)
419
+ if open_end < 0:
420
+ continue
421
+ end, _ = _env_end(tex, open_end, m.group("env"))
422
+ if end < 0:
423
+ continue
424
+ body = tex[open_end:end]
425
+ for a, b in reversed(_cells(body)):
426
+ cell = body[a:b]
427
+ inner = cell.strip()
428
+ if len(inner) > 2 and inner[0] == "{" and _group_end(inner, 0) == len(inner):
429
+ lead = cell[:len(cell) - len(cell.lstrip())]
430
+ trail = cell[len(cell.rstrip()):]
431
+ body = body[:a] + lead + inner[1:-1].strip() + trail + body[b:]
432
+ changed = True
433
+ if changed:
434
+ tex = tex[:open_end] + body + tex[end:]
435
+ break
436
+ return tex
437
+
438
+
439
+ _RELATION_START = re.compile(
440
+ r"\s*(?:\{\s*)*(?:[=<>:]|\\(?:leq?|geq?|neq?|ne|approx|equiv|sim|simeq|cong|propto|in|notin|ni|subset|subseteq|"
441
+ r"supset|supseteq|to|rightarrow|leftarrow|Rightarrow|Leftarrow|iff|implies|mapsto|coloneqq|triangleq|ll|gg|"
442
+ r"prec|succ|preceq|succeq|perp|mid|parallel|models|vdash)(?![a-zA-Z@]))")
443
+
444
+
445
+ def _cases(tex: str) -> str:
446
+ """``\\left\\{ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right.`` -> ``\\begin{cases}``."""
447
+ # only array has a column specification: in matrix / aligned a {ll} is the first cell's content
448
+ pattern = re.compile(r"\\left\s*\\\{\s*\\begin\{(?:(matrix|aligned)\}|(array)\}\s*\{l{1,2}\})")
449
+ pos = 0
450
+ while True:
451
+ m = pattern.search(tex, pos)
452
+ if not m:
453
+ return tex
454
+ env = m.group(1) or m.group(2)
455
+ end, end2 = _env_end(tex, m.end(), env)
456
+ close = re.compile(r"\s*\\right\s*\.").match(tex, end2) if end >= 0 else None
457
+ body = tex[m.end():end] if end >= 0 else ""
458
+ rows = [[body[a:b] for a, b in _cells(r)] for r in _rows(body)]
459
+ # a system of equations ({ x + y &= 1 \\ x - y &= 0) has relations at the start of its right-hand
460
+ # cells; the cells of cases are values and conditions
461
+ if (not close or any(len(r) > 2 for r in rows)
462
+ or any(len(r) == 2 and _RELATION_START.match(r[1]) for r in rows)):
463
+ pos = m.end()
464
+ continue
465
+ new = "\\begin{cases}" + body + "\\end{cases}"
466
+ tex = tex[:m.start()] + new + tex[close.end():]
467
+ pos = m.start() + len(new)
468
+
469
+
470
+ def _rows(body: str) -> List[str]:
471
+ """The rows of an environment body: split at its own \\\\."""
472
+ rows, start, depth = [], 0, 0
473
+ for m in _TOKEN.finditer(body):
474
+ tok = m.group()
475
+ if tok == "{" or m.group("be") == "begin":
476
+ depth += 1
477
+ elif tok == "}" or m.group("be") == "end":
478
+ depth -= 1
479
+ elif not depth and tok in ("\\\\", "\\cr"):
480
+ rows.append(body[start:m.start()])
481
+ start = m.end()
482
+ rows.append(body[start:])
483
+ return rows
484
+
485
+
486
+ _NAMED_LIMITS = frozenset("max min lim sup inf liminf limsup det gcd Pr".split())
487
+ _DISPLAY_LIMITS = {"\\" + name for name in _NAMED_LIMITS.union(
488
+ "sum prod coprod bigcup bigcap bigoplus bigotimes bigodot biguplus bigsqcup bigvee bigwedge".split())}
489
+
490
+
491
+ def _labelled_operators(tex: str) -> str:
492
+ """Recognise the two braced arguments that texmath writes for an over/underset. Work from
493
+ the inside out, so a second label on an arrow can become its optional argument."""
494
+ from .compat import _argument
495
+
496
+ placements = [m for m in _TOKEN.finditer(tex) if m.group() in (r"\overset", r"\underset")]
497
+ for m in reversed(placements):
498
+ a, b = _argument(tex, m.end())
499
+ c, d = _argument(tex, b)
500
+ if tex[a:a + 1] != "{" or tex[c:c + 1] != "{":
501
+ continue
502
+ label, base = tex[a:b], tex[c + 1:d - 1]
503
+ under = m.group() == r"\underset"
504
+ script = "_" if under else "^"
505
+ brace = r"\underbrace" if under else r"\overbrace"
506
+ if base.startswith(brace + "{") and _group_end(base, len(brace)) == len(base):
507
+ new = base + script + label
508
+ elif not under and base in (r"\rightarrow", r"\leftarrow"):
509
+ new = r"\x" + base[1:] + label
510
+ elif under and (arrow := re.match(r"\\x(?:right|left)arrow(?=\{)", base)) \
511
+ and _group_end(base, arrow.end()) == len(base):
512
+ lower = label[1:-1]
513
+ new = arrow.group() + "[" + (label if "]" in lower else lower) + "]" + base[arrow.end():]
514
+ elif base in _DISPLAY_LIMITS or base == r"\arg":
515
+ new = base + r"\limits" + script + label
516
+ elif (arg := re.fullmatch(r"\\mathrm\{arg(max|min)\}|\\?arg\\,\\?(max|min)", base)):
517
+ name = "arg" + (arg[1] or r"\," + arg[2])
518
+ new = r"\operatorname*{" + name + r"}\limits" + script + label
519
+ else:
520
+ continue
521
+ if tex[d:].lstrip().startswith(("_", "^", "'")):
522
+ new = "{" + new + "}" # the following script belongs to the entire annotated object
523
+ tex = tex[:m.start()] + new + tex[d:]
524
+ return tex
525
+
526
+
527
+ # commands whose arguments are set in a smaller style (\limits matters there)
528
+ _SMALL_ARGS = {"\\frac": 2, "\\tfrac": 2, "\\dfrac": 2, "\\cfrac": 2, "\\binom": 2, "\\dbinom": 2,
529
+ "\\tbinom": 2, "\\genfrac": 6,
530
+ "\\stackrel": 2, "\\overset": 2, "\\underset": 2}
531
+ # commands whose arguments keep the style
532
+ _SAME_STYLE_ARGS = {"\\sqrt": 1, "\\overline": 1, "\\underline": 1, "\\mathbf": 1, "\\mathrm": 1, "\\mathit": 1,
533
+ "\\mathcal": 1, "\\boldsymbol": 1, "\\operatorname": 1, "\\left": 0, "\\right": 0,
534
+ "\\widehat": 1, "\\widetilde": 1, "\\hat": 1, "\\tilde": 1, "\\bar": 1, "\\vec": 1,
535
+ "\\overbrace": 1, "\\underbrace": 1, "\\mathbb": 1}
536
+ _DISPLAY_ENVS = frozenset("aligned gathered split align align* gather gather* equation equation* multline "
537
+ "multline* flalign flalign* alignat alignat* alignedat eqnarray eqnarray*".split())
538
+
539
+
540
+ def _drop_display_limits(tex: str) -> str:
541
+ """``\\sum\\limits_{i}`` -> ``\\sum_{i}`` where the sum is in display style (its limits go
542
+ above and below anyway); kept inside fractions, scripts, matrices and unknown arguments."""
543
+ from .compat import _optional, _argument
544
+
545
+ out = []
546
+ last = 0
547
+ stack = [True] # display style at the top and inside each open group / environment
548
+ pending: Dict[int, List[bool]] = {} # per group level: styles of the next arguments of a command there
549
+ prev = ""
550
+ starred_ends = set() # \operatorname* has display limits; \operatorname and \arg do not
551
+ prev_end = 0
552
+ skip_to = 0
553
+ for m in _TOKEN.finditer(tex):
554
+ tok = m.group()
555
+ if m.start() < skip_to or tok.startswith("%"):
556
+ continue
557
+ level = len(stack)
558
+ if m.group("be") == "begin":
559
+ stack.append(m.group("env") in _DISPLAY_ENVS)
560
+ elif m.group("be") == "end":
561
+ if len(stack) > 1:
562
+ pending.pop(len(stack), None)
563
+ stack.pop()
564
+ elif tok == "{":
565
+ if pending.get(level):
566
+ stack.append(pending[level].pop(0))
567
+ elif prev in ("_", "^") or (prev.startswith("\\") and prev[1:2].isalpha()):
568
+ stack.append(False) # a script, or an argument of a command we do not know
569
+ else:
570
+ stack.append(True)
571
+ elif tok == "}":
572
+ if len(stack) > 1:
573
+ pending.pop(len(stack), None) # arguments pending inside the group that closes
574
+ stack.pop()
575
+ elif tok in (r"\xleftarrow", r"\xrightarrow"):
576
+ # Both labels are in script style, including the optional lower one.
577
+ _, skip_to = _argument(tex, _optional(tex, m.end()))
578
+ elif tok in _SMALL_ARGS:
579
+ pending[level] = [False] * _SMALL_ARGS[tok]
580
+ elif tok in _SAME_STYLE_ARGS:
581
+ pending[level] = [True] * _SAME_STYLE_ARGS[tok]
582
+ if tok == r"\sqrt":
583
+ skip_to = _optional(tex, m.end()) # the root index is in script style
584
+ elif tok == "\\operatorname" and (star := re.match(r"\s*\*\s*\{", tex[m.end():])):
585
+ starred_ends.add(_group_end(tex, m.end() + star.end() - 1))
586
+ elif tok in (r"\textstyle", r"\scriptstyle", r"\scriptscriptstyle"):
587
+ stack[-1] = False
588
+ elif tok == "\\limits" and (prev in _DISPLAY_LIMITS or prev_end in starred_ends) and all(stack):
589
+ out.append(tex[last:m.start()])
590
+ last = m.end()
591
+ prev, prev_end = tok, m.end()
592
+ out.append(tex[last:])
593
+ return "".join(out)
594
+
595
+
596
+ def _symbol_commands(tex: str) -> str:
597
+ """Raw symbols (including Greek inside \\mathbf) as control words; a bold
598
+ lowercase Greek letter becomes \\boldsymbol, since \\mathbf does not embolden it."""
599
+ from .compat import _text_spans # text arguments keep their characters
600
+
601
+ letters = "|".join(map(re.escape, _GREEK))
602
+
603
+ def bold(m):
604
+ ch = m.group(1)
605
+ return ("\\mathbf{\\%s}" if ch.isupper() else "\\boldsymbol{\\%s}") % _GREEK[ch]
606
+
607
+ def outside_text(pattern, repl, s):
608
+ spans = _text_spans(s)
609
+ return re.sub(pattern, lambda m: m.group(0) if any(a <= m.start() < b for a, b in spans) else repl(m), s)
610
+
611
+ tex = outside_text(r"\\[a-zA-Z@]+|\\.", lambda m: _COMMAND_ALIASES.get(m[0], m[0]), tex)
612
+ # The MathML reader joins a fixed infix arrow to its left operand (a\rightarrow b).
613
+ tex = outside_text(r"(?<=[a-zA-Z0-9)}\]])\\(?:[a-zA-Z]*(?:arrow|harpoon)[a-zA-Z]*|(?:long)?mapsto|leadsto)"
614
+ r"(?= )", lambda m: " " + m[0], tex)
615
+ tex = outside_text(r"\\mathbf\{(%s)\}" % letters, bold, tex)
616
+ tex = outside_text("[" + "".join(_RAW_SYMBOLS) + "]", lambda m: "\\" + _RAW_SYMBOLS[m.group()] +
617
+ (" " if re.match("[a-zA-Z@]", m.string[m.end():m.end() + 1]) else ""), tex)
618
+ # \mathbf leaves lowercase Greek (and \nabla, \partial) as it is
619
+ lower = "|".join(n for ch, n in _GREEK.items() if not ch.isupper())
620
+ tex = re.sub(r"\\mathbf\{\\(%s)\}" % lower, r"\\boldsymbol{\\\1}", tex)
621
+ # ℓ: texmath writes \mathcal{l}, but calligraphic letters are capitals only
622
+ tex = re.sub(r"\{\\mathcal\{l\}\}|\\mathcal\{l\}", r"\\ell", tex)
623
+ # Word's italic run around ∇ / ∂ (symbols \mathit does not change)
624
+ return re.sub(r"\\mathit\{\\(nabla|partial)\}", r"\\\1", tex)
625
+
626
+
627
+ _RELATION_IN = re.compile(r"[=<>]|\\(?:leq?|geq?|neq?|approx|equiv|sim|in|subset|to|rightarrow|Rightarrow|mapsto|"
628
+ r"parallel|perp|mid)(?![a-zA-Z@])|&|,|\\\\")
629
+
630
+
631
+ _OPERAND_END = re.compile(r"(?:[A-Za-z0-9)\]}!'|]|\\[a-zA-Z]+|\\[}|])\s*$")
632
+ _NOT_OPERANDS = re.compile(r"\\(?:left|right|big[lr]?|Big[lr]?|bigg[lr]?|Bigg[lr]?|cdot|times|cdots|ldots|quad|qquad|"
633
+ r"leq?|geq?|neq?|approx|equiv|sim|in|to|mapsto|rightarrow|Rightarrow|div|pm|mp|"
634
+ r"oplus|otimes|circ|odot|setminus|cup|cap|wedge|vee|land|lor|frac|sqrt)\s*$")
635
+
636
+
637
+ def _norm_bars(tex: str) -> str:
638
+ """``\\parallel x \\parallel`` -> ``\\| x \\|``: a norm written with U+2225 PARALLEL TO (texmath 0.13
639
+ writes \\| as that character, so equations pasted into Office by earlier versions hold it).
640
+ Only pairs at the same group level whose content has no relation, comma or alignment point, and
641
+ whose first bar does not follow an operand: ``a \\parallel b \\parallel c`` stays two relations."""
642
+ out, last = [], 0
643
+ opened: Dict[int, int] = {} # group level -> start of an unmatched opening \parallel
644
+ depth = 0
645
+ pairs = []
646
+ for m in _TOKEN.finditer(tex):
647
+ tok = m.group()
648
+ if tok == "{":
649
+ depth += 1
650
+ elif tok == "}":
651
+ opened.pop(depth, None)
652
+ depth -= 1
653
+ elif tok == "\\parallel":
654
+ if depth in opened:
655
+ start = opened.pop(depth)
656
+ if not _RELATION_IN.search(tex, start + len("\\parallel"), m.start()):
657
+ pairs.append((start, m.start()))
658
+ continue
659
+ before = tex[:m.start()]
660
+ if not _OPERAND_END.search(before) or _NOT_OPERANDS.search(before):
661
+ opened[depth] = m.start() # can open a norm: nothing, an operator or a bracket before it
662
+ for a, b in pairs:
663
+ out.append(tex[last:a] + "\\|")
664
+ out.append(tex[a + len("\\parallel"):b] + "\\|")
665
+ last = b + len("\\parallel")
666
+ out.append(tex[last:])
667
+ return re.sub(r"\\\|(?=[a-zA-Z])", r"\\| ", "".join(out))
668
+
669
+
670
+ def _bold_numbers(tex: str) -> str:
671
+ """``\\mathbf{2}\\mathbf{5}.\\mathbf{2}`` (texmath reading a bold <mn>) -> ``\\mathbf{25.2}``."""
672
+ def merge(m):
673
+ return "\\mathbf{%s}" % re.sub(r"\\mathbf\{([0-9]+)\}", r"\1", m.group())
674
+ return re.sub(r"\\mathbf\{[0-9]+\}(?:\.?\\mathbf\{[0-9]+\})+", merge, tex)
675
+
676
+
677
+ def tidy_tex(tex: str, display: bool) -> str:
678
+ """Clean up the TeX that texmath wrote for an equation read from MathML / OMML."""
679
+ out = _unwrap_cells(tex)
680
+ out = _cases(out)
681
+ out = re.sub(r"(?<!\\)[_^]\{\s*\}", "", out) # x_{i}^{} -> x_{i}
682
+ out = _edge_spaces(out) # before \lbrack -> [ below: a row may start with the bracket once its space is gone
683
+ out = _plain_brackets(out)
684
+ out = _labelled_operators(out)
685
+ if display:
686
+ out = _drop_display_limits(out)
687
+ out = _norm_bars(out)
688
+ out = _bold_numbers(out)
689
+ out = _symbol_commands(out)
690
+ return out
691
+
692
+
693
+ # TeX tokens for _edge_spaces: a control word, a control symbol (\\, "\ ", \~ ...; \.? : a lone \ at
694
+ # the end too), ~, white space, a brace, a bracket, a star, a run of other characters
695
+ _EDGE_TOKEN = re.compile(r"\\[a-zA-Z@]+|\\.?|~|\s+|[{}\[\]*]|[^\\~\s{}\[\]*]+", re.S)
696
+ _TYPED_SPACES = frozenset(["~", "\\ "]) # how texmath writes a space typed in Word
697
+ _SMALL_SPACES = frozenset(["\\,", "\\:", "\\;", "\\>"]) # removed with a typed space next to them
698
+ _ARGUMENT_ENVS = frozenset("array subarray alignat alignat* alignedat".split()) # \begin{array}{rl}
699
+ # environments that read a [...] right after \begin{env} as their option: amsmath's position option,
700
+ # array's, mathtools' starred matrices and multlined
701
+ _OPTION_ENVS = frozenset("aligned alignedat gathered array multlined matrix* pmatrix* bmatrix* Bmatrix* "
702
+ "vmatrix* Vmatrix* smallmatrix* psmallmatrix* bsmallmatrix* tabular".split())
703
+
704
+
705
+ def _plain_brackets(tex: str) -> str:
706
+ r"""A bracket after a symbol such as \in or \left is safe. Guard the commands and line starts
707
+ where LaTeX would consume it as an option."""
708
+ if r"\lbrack" not in tex and r"\rbrack" not in tex:
709
+ return tex
710
+ tokens = _EDGE_TOKEN.findall(tex)
711
+ starts, _ = _line_starts_and_ends(tokens)
712
+ guarded = set()
713
+ for i, kind in starts.items():
714
+ if kind:
715
+ while i < len(tokens) and tokens[i].isspace():
716
+ i += 1
717
+ guarded.add(i)
718
+ options = {r"\sqrt", r"\cfrac", r"\xleftarrow", r"\xrightarrow", r"\smash", r"\cr"}
719
+ prev = ""
720
+ option = False # inside an [option] (\sqrt[\lbrack n\rbrack]{x}): a plain ] there would end it
721
+ for i, token in enumerate(tokens):
722
+ if option:
723
+ option = token != "]"
724
+ prev = token if token.strip() else prev
725
+ continue
726
+ if token == "[" and prev in options:
727
+ option, prev = True, token
728
+ continue
729
+ if token == r"\rbrack" or (token == r"\lbrack" and i not in guarded and prev not in options):
730
+ tokens[i] = "[" if token == r"\lbrack" else "]"
731
+ if i + 1 < len(tokens):
732
+ tokens[i + 1] = tokens[i + 1].removeprefix(" ") # texmath's control-word terminator
733
+ if token.strip():
734
+ prev = token
735
+ return "".join(tokens)
736
+
737
+
738
+ def _line_starts_and_ends(tokens: List[str]) -> "tuple[dict, list]":
739
+ """({token index where a line starts: what a "[" or "*" there would turn into an option of, or ""},
740
+ sorted token indices where a line ends). A line starts at the equation's start, after a row break
741
+ \\\\ (and its \\\\*, \\\\[2pt]) and after \\begin{env} (and its [t], and the {rl} of an array); it
742
+ ends at the end, at a row break and at \\end."""
743
+ starts, ends = {0: ""}, [len(tokens)]
744
+
745
+ def skip_space(i: int) -> int:
746
+ while i < len(tokens) and tokens[i].isspace():
747
+ i += 1
748
+ return i
749
+
750
+ def group_end(i: int) -> int:
751
+ """Index after the {...} group that starts at tokens[i] (balanced), or -1."""
752
+ depth = 0
753
+ for j in range(i, len(tokens)):
754
+ depth += {"{": 1, "}": -1}.get(tokens[j], 0)
755
+ if not depth:
756
+ return j + 1
757
+ return -1
758
+
759
+ def option_end(i: int) -> int:
760
+ """Index after a [...] option at tokens[i] or after white space there (LaTeX looks past white
761
+ space for an option), or i if there is none."""
762
+ j = skip_space(i)
763
+ if j < len(tokens) and tokens[j] == "[":
764
+ close = next((k for k in range(j, len(tokens)) if tokens[k] == "]"), -1)
765
+ if close >= 0:
766
+ return close + 1
767
+ return i
768
+
769
+ for i, token in enumerate(tokens):
770
+ if token == "\\\\":
771
+ ends.append(i)
772
+ k = i + 1
773
+ star = skip_space(k)
774
+ if star < len(tokens) and tokens[star] == "*": # \\* (LaTeX looks past white space for it)
775
+ k = star + 1
776
+ after = option_end(k)
777
+ # after a bare \\ a "[" or "*" would be read as its option or star; after \\* a "["
778
+ starts[after] = "" if after != k else ("row" if k == i + 1 else "row*")
779
+ elif token == "\\end":
780
+ ends.append(i)
781
+ elif token == "\\begin":
782
+ j = skip_space(i + 1)
783
+ if j >= len(tokens) or tokens[j] != "{":
784
+ continue
785
+ k = group_end(j)
786
+ if k < 0:
787
+ continue
788
+ env = "".join(tokens[j + 1:k - 1]).strip()
789
+ after = option_end(k) if env in _OPTION_ENVS else k # \begin{aligned}[t]; matrix has none
790
+ if env in _ARGUMENT_ENVS:
791
+ after = skip_space(after)
792
+ if after < len(tokens) and tokens[after] == "{":
793
+ after = group_end(after)
794
+ if after < 0:
795
+ continue
796
+ starts[after] = "begin" if after == k and env in _OPTION_ENVS else ""
797
+ return starts, sorted(set(ends))
798
+
799
+
800
+ def _edge_spaces(tex: str) -> str:
801
+ """Drop a space typed at the very start or end of the equation, or of a line of an aligned block or
802
+ a matrix (texmath writes it "~" or "\\ "; with a thin space \\, next to it, that goes too): Word keeps
803
+ the space typed after the last symbol, a LaTeX author does not write it. Spaces inside a line are
804
+ left alone, and so is a line start where what follows would become an option: [x] after a row break
805
+ (\\\\[x]) or a \\begin{..} ([t]), * after a row break (\\\\*)."""
806
+ tokens = _EDGE_TOKEN.findall(tex)
807
+ starts, ends = _line_starts_and_ends(tokens)
808
+ start_list = sorted(starts)
809
+ drop = set()
810
+
811
+ def edge_run(indices) -> List[int]:
812
+ run = []
813
+ for i in indices:
814
+ if i in drop or not (tokens[i].isspace() or tokens[i] in _TYPED_SPACES or tokens[i] in _SMALL_SPACES):
815
+ break
816
+ run.append(i)
817
+ return [i for i in run if not tokens[i].isspace()] if any(tokens[i] in _TYPED_SPACES for i in run) else []
818
+
819
+ for start in start_list:
820
+ stop = ends[bisect.bisect_left(ends, start)] if start <= ends[-1] else len(tokens)
821
+ gone = edge_run(range(start, stop))
822
+ nxt = next((i for i in range(start, stop) if i not in gone and not tokens[i].isspace()), None)
823
+ guarded = {"row": ("[", "*"), "row*": ("[",), "begin": ("[",)}.get(starts[start], ())
824
+ if gone and not (nxt is not None and tokens[nxt].startswith(guarded) and guarded):
825
+ drop.update(gone)
826
+ for end in ends:
827
+ begin = start_list[bisect.bisect_right(start_list, end) - 1]
828
+ drop.update(edge_run(range(end - 1, begin - 1, -1)))
829
+ out = "".join(t for i, t in enumerate(tokens) if i not in drop)
830
+ return out if out.strip() else tex