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.
@@ -0,0 +1,1732 @@
1
+ """Conversion engine: drives pandoc (which embeds texmath) through its JSON AST.
2
+
3
+ Every equation is normalised to pandoc's own representation, a ``Math`` inline
4
+ holding TeX plus an inline/display flag. Reading a format means asking pandoc
5
+ to parse a tiny document and collecting the ``Math`` nodes; writing means
6
+ feeding a one-paragraph JSON document to the relevant pandoc writer and cutting
7
+ the equation back out of its output.
8
+
9
+ Supported formats: read latex | mathml | omml
10
+ write mathml | omml | eqn | typst (LaTeX output is handled
11
+ in :mod:`latex_wrap` because the TeX is already in hand).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import collections
16
+ import copy
17
+ import html.entities
18
+ import io
19
+ import json
20
+ import os
21
+ import re
22
+ import subprocess
23
+ import sys
24
+ import unicodedata
25
+ import uuid
26
+ import zipfile
27
+ import xml.etree.ElementTree as ET
28
+ from dataclasses import dataclass
29
+ from typing import List, Optional
30
+
31
+ from . import tidy as _tidy
32
+
33
+ MATHML_NS = "http://www.w3.org/1998/Math/MathML"
34
+ OMML_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"
35
+ WML_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
36
+ MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"
37
+
38
+ ET.register_namespace("", MATHML_NS)
39
+ ET.register_namespace("m", OMML_NS)
40
+ ET.register_namespace("w", WML_NS)
41
+
42
+ READ_FORMATS = ("latex", "mathml", "omml")
43
+ WRITE_FORMATS = ("latex", "mathml", "omml", "eqn", "typst")
44
+
45
+ _CREATE_NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0
46
+ _EXE = "pandoc.exe" if sys.platform == "win32" else "pandoc"
47
+ INSTALL_HINT = {"darwin": "brew install pandoc", "win32": "winget install JohnMacFarlane.Pandoc"}.get(
48
+ sys.platform, "your system's package manager")
49
+ _DOWNLOAD_HINT = "Click Download in the MathShuttle window or run mathshuttle get-pandoc."
50
+ # An app started from the Finder or the Dock gets launchd's PATH (/usr/bin:/bin:/usr/sbin:/sbin), not
51
+ # the shell's: Homebrew's bin (Apple silicon, Intel) is searched too, and is where pandoc's own
52
+ # installer puts it (/usr/local/bin).
53
+ _MACOS_DIRS = ("/opt/homebrew/bin", "/usr/local/bin")
54
+
55
+
56
+ class PandocNotFound(RuntimeError):
57
+ pass
58
+
59
+
60
+ class ConversionError(ValueError):
61
+ """The input could not be converted; the message is meant for the user."""
62
+
63
+
64
+ @dataclass
65
+ class Equation:
66
+ tex: str
67
+ display: bool = True
68
+
69
+
70
+ # --- locating / running pandoc ------------------------------------------------------
71
+ _pandoc_path: Optional[str] = None
72
+ _pandoc_version: Optional[str] = None
73
+ _texmath_version: Optional[str] = None
74
+ _api_version: Optional[list] = None
75
+ _mathml_flag: Optional[str] = None
76
+
77
+
78
+ def reset_pandoc() -> None:
79
+ """Look up the executable, its versions and supported options again on next use."""
80
+ global _pandoc_path, _pandoc_version, _texmath_version, _api_version, _mathml_flag
81
+ _pandoc_path = _pandoc_version = _texmath_version = None
82
+ _api_version = _mathml_flag = None
83
+
84
+
85
+ def _env_pandoc() -> "tuple[str, Optional[str]]":
86
+ """(variable, value) of MATHSHUTTLE_PANDOC, or of EQUATION_TOOL_PANDOC (the tool's former name)."""
87
+ for name in ("MATHSHUTTLE_PANDOC", "EQUATION_TOOL_PANDOC"):
88
+ if os.environ.get(name):
89
+ return name, os.environ[name]
90
+ return "MATHSHUTTLE_PANDOC", None
91
+
92
+
93
+ def _candidate_paths():
94
+ env = _env_pandoc()[1]
95
+ if env:
96
+ yield env
97
+ # next to the frozen executable / this package (lets a copy of pandoc.exe be bundled)
98
+ base = os.path.dirname(sys.executable) if getattr(sys, "frozen", False) else os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
99
+ yield os.path.join(base, _EXE)
100
+ yield os.path.join(base, "pandoc", _EXE)
101
+ # PATH, but not the current directory: on Windows shutil.which() looks there first, which
102
+ # would run a pandoc.exe lying in whatever folder the CLI is started from.
103
+ for d in os.environ.get("PATH", "").split(os.pathsep):
104
+ d = d.strip().strip('"')
105
+ if os.path.isabs(d):
106
+ yield os.path.join(d, _EXE)
107
+ for root in (os.environ.get("LOCALAPPDATA"), os.environ.get("ProgramFiles"), os.environ.get("ProgramFiles(x86)")):
108
+ if root:
109
+ yield os.path.join(root, "Pandoc", "pandoc.exe")
110
+ if sys.platform == "darwin":
111
+ for d in _MACOS_DIRS:
112
+ yield os.path.join(d, "pandoc")
113
+ from .pandoc_fetch import installed_pandoc
114
+ installed = installed_pandoc()
115
+ if installed:
116
+ yield installed
117
+
118
+
119
+ def find_pandoc() -> str:
120
+ global _pandoc_path
121
+ if _pandoc_path is None:
122
+ name, env = _env_pandoc()
123
+ if env and not os.path.isfile(env): # a typo must not silently select some other pandoc
124
+ raise PandocNotFound(f"{name} is set to {env!r}, which is not an existing file. "
125
+ f"Correct it, or unset {name} so that MathShuttle looks for pandoc itself.")
126
+ for p in _candidate_paths():
127
+ if p and os.path.isfile(p):
128
+ _pandoc_path = p
129
+ break
130
+ else:
131
+ raise PandocNotFound(
132
+ f"{_EXE} was not found. {_DOWNLOAD_HINT}\n"
133
+ f"You can also install it with {INSTALL_HINT} or set MATHSHUTTLE_PANDOC to the full path of {_EXE}.")
134
+ return _pandoc_path
135
+
136
+
137
+ def _shim_target(path: str) -> Optional[str]:
138
+ """The executable behind a Scoop shim: ``<name>.exe`` is a generic launcher and the
139
+ ``<name>.shim`` file next to it holds ``path = "<real exe>"`` (unquoted in older Scoop)."""
140
+ try:
141
+ with open(os.path.splitext(path)[0] + ".shim", encoding="utf-8-sig") as f:
142
+ for line in f:
143
+ key, sep, value = line.partition("=")
144
+ if sep and key.strip() == "path":
145
+ target = value.strip().strip('"')
146
+ return target if os.path.isfile(target) else None
147
+ except OSError:
148
+ pass
149
+ return None
150
+
151
+
152
+ def pandoc_binary() -> str:
153
+ """The pandoc executable itself; `find_pandoc()` (what gets *run*) may be a launcher."""
154
+ path = find_pandoc()
155
+ return _shim_target(path) or path
156
+
157
+
158
+ def pandoc_version() -> str:
159
+ global _pandoc_version
160
+ if _pandoc_version is None:
161
+ out, _ = _run(["--version"], b"")
162
+ _pandoc_version = out.decode("utf-8", "replace").splitlines()[0]
163
+ return _pandoc_version
164
+
165
+
166
+ def _scan_texmath_version(path: str) -> Optional[str]:
167
+ """The ``texmath-<version>`` Haskell package id embedded in a (statically linked) pandoc. Cabal
168
+ shortens the ids on macOS (vowels dropped, as in ``pndc-cl-3.14-..``): Homebrew's pandoc carries
169
+ ``txmth-<version>``."""
170
+ import mmap
171
+ try:
172
+ with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
173
+ m = re.search(rb"(?:texmath|txmth)-(\d+(?:\.\d+)+)", mm)
174
+ return m.group(1).decode() if m else None # the match reads the mmap: decode before it closes
175
+ except (OSError, ValueError): # unreadable or empty file
176
+ return None
177
+
178
+
179
+ def texmath_version() -> Optional[str]:
180
+ """Version of the texmath library linked into pandoc (pandoc --version does not report it).
181
+
182
+ pandoc is statically linked, so the package id is embedded in the executable; a newer
183
+ texmath only arrives with a newer pandoc. None when the executable carries no package
184
+ id (a launcher we do not know how to follow, or an unusual build).
185
+ """
186
+ global _texmath_version
187
+ if _texmath_version is None:
188
+ _texmath_version = _scan_texmath_version(pandoc_binary()) or ""
189
+ return _texmath_version or None
190
+
191
+
192
+ def engine_description() -> str:
193
+ """One line for the status bar: ``pandoc 3.11 (texmath 0.13.2.2)``."""
194
+ return "%s (texmath %s)" % (pandoc_version(), texmath_version() or "version unknown")
195
+
196
+
197
+ def engine_report() -> str:
198
+ """`engine_description()` plus the executable in use (and the binary behind a shim)."""
199
+ from .pandoc_fetch import installed_pandoc
200
+ command, binary = find_pandoc(), pandoc_binary()
201
+ lines = [engine_description(), command if binary == command else "%s -> %s" % (command, binary)]
202
+ installed = installed_pandoc()
203
+ if installed and os.path.normcase(os.path.realpath(binary)) == os.path.normcase(os.path.realpath(installed)):
204
+ lines.append("Installed by MathShuttle.")
205
+ if not texmath_version():
206
+ lines.append("texmath version unknown: %s carries no texmath package id (a launcher?). "
207
+ "Set MATHSHUTTLE_PANDOC to the real %s to inspect it." % (os.path.basename(binary), _EXE))
208
+ return "\n".join(lines)
209
+
210
+
211
+ def _run(args: List[str], stdin: bytes, timeout: float = 60, cwd: Optional[str] = None) -> "tuple[bytes, str]":
212
+ """Run pandoc; `cwd`: where relative paths (\\input{...} in a .tex file) are found."""
213
+ try:
214
+ proc = subprocess.run([find_pandoc(), *args], input=stdin, capture_output=True,
215
+ timeout=timeout, creationflags=_CREATE_NO_WINDOW, cwd=cwd)
216
+ except subprocess.TimeoutExpired:
217
+ raise ConversionError("pandoc did not finish within %d s" % timeout)
218
+ except OSError as e: # e.g. pandoc.exe removed or replaced (winget upgrade) while the app runs
219
+ raise ConversionError("Could not run %s: %s" % (find_pandoc(), e))
220
+ err = proc.stderr.decode("utf-8", "replace").replace("\r\n", "\n")
221
+ if proc.returncode != 0:
222
+ raise ConversionError("pandoc failed (exit %d):\n%s" % (proc.returncode, err.strip()))
223
+ return proc.stdout, err
224
+
225
+
226
+ def _api():
227
+ global _api_version
228
+ if _api_version is None:
229
+ out, _ = _run(["-f", "markdown", "-t", "json"], b"")
230
+ _api_version = json.loads(out)["pandoc-api-version"]
231
+ return _api_version
232
+
233
+
234
+ def _mathml_flags() -> List[str]:
235
+ global _mathml_flag
236
+ if _mathml_flag is None:
237
+ try:
238
+ _run(["-f", "markdown", "-t", "html", "--math-method=mathml"], b"")
239
+ _mathml_flag = "--math-method=mathml"
240
+ except ConversionError:
241
+ _mathml_flag = "--mathml" # pandoc < 3.7 (deprecated spelling)
242
+ return [_mathml_flag]
243
+
244
+
245
+ # The TeX in the message keeps its line breaks (continuation lines indented by two spaces),
246
+ # so the part before ", rendering as TeX:" may span several lines.
247
+ _TEXMATH_WARNING = re.compile(r"\[WARNING\] Could not convert TeX math [\s\S]*?, rendering as TeX:\n((?: .*\n?)*)")
248
+
249
+ # for writers with text output: pandoc writes CRLF on Windows by default
250
+ _LF = "--eol=lf"
251
+
252
+
253
+ def _check_texmath_warning(stderr: str) -> None:
254
+ """Raise if texmath rejected the TeX (pandoc then writes the TeX source as text instead)."""
255
+ m = _TEXMATH_WARNING.search(stderr)
256
+ if m:
257
+ detail = "\n".join(line[2:] for line in m.group(1).rstrip("\n").splitlines())
258
+ raise ConversionError("texmath could not parse this LaTeX:\n" + detail)
259
+ if "Could not convert TeX math" in stderr: # message layout changed in some pandoc release
260
+ raise ConversionError("texmath could not parse this LaTeX:\n" + stderr.strip())
261
+
262
+
263
+ # --- reading --------------------------------------------------------------------------
264
+ def strip_tex(tex: str) -> str:
265
+ """`tex` without surrounding white space - and without a control space ``\\ `` left dangling at the
266
+ end (texmath ends ``\\left\\{ ... \\right.\\ ``): stripping its space would leave a lone backslash,
267
+ which escapes whatever delimiter is written after it (``\\right.\\$``). A backslash the input ends
268
+ with (no space after it) is kept: that is the user's unfinished TeX, which texmath reports."""
269
+ out = tex.lstrip()
270
+ while True:
271
+ stripped = out.rstrip()
272
+ if stripped == out:
273
+ return out
274
+ out = stripped
275
+ if not (out.endswith("\\") and (len(out) - len(out.rstrip("\\"))) % 2):
276
+ return out
277
+ out = out[:-1] # the backslash of a control space whose space was just stripped
278
+
279
+
280
+ def _collect_math(node, out: List[Equation]) -> None:
281
+ if isinstance(node, dict):
282
+ if node.get("t") == "Math":
283
+ kind, tex = node["c"]
284
+ out.append(Equation(strip_tex(tex), kind["t"] == "DisplayMath"))
285
+ return
286
+ for v in node.values():
287
+ _collect_math(v, out)
288
+ elif isinstance(node, list):
289
+ for v in node:
290
+ _collect_math(v, out)
291
+
292
+
293
+ def _read_json(fmt: str, source: bytes) -> List[Equation]:
294
+ out, _ = _run(["-f", fmt, "-t", "json"], source)
295
+ eqs: List[Equation] = []
296
+ _collect_math(json.loads(out)["blocks"], eqs)
297
+ return eqs
298
+
299
+
300
+ # environments that pandoc's LaTeX reader turns into maths (checked against pandoc 3.11)
301
+ _PANDOC_MATH_ENVS = frozenset(
302
+ "equation equation* displaymath math align align* alignat alignat* flalign flalign* eqnarray eqnarray* "
303
+ "gather gather* multline multline* dmath dmath* dgroup dgroup* darray darray* subequations".split())
304
+ # mathtools' cases with a text column (compat.py rewrites them for texmath)
305
+ _STARRED_CASES = frozenset(("cases*", "dcases*", "rcases*", "drcases*"))
306
+ # spaces and comments, which LaTeX skips between a command and its argument
307
+ _TEX_GAP = r"(?:\s|%[^\n]*\n)*"
308
+ # (\verb|...| and \url{...} hold their text verbatim: a % in them is no comment)
309
+ _LATEX_TOKEN = re.compile(r"\\begin" + _TEX_GAP + r"\{([^{}]*)\}|\\verb\*?([^\sa-zA-Z*])[^\n]*?\2"
310
+ r"|\\(?:url|href)\s*\{[^{}]*\}|\\[a-zA-Z@]+|\\.|%[^\n]*|[{}$]", re.S)
311
+ # commands whose argument is text even inside maths, so that it may hold nested $...$
312
+ _TEXT_IN_MATH = frozenset(
313
+ "\\text \\mbox \\hbox \\makebox \\fbox \\framebox \\raisebox \\parbox \\textrm \\textit \\textbf \\textsf "
314
+ "\\texttt \\textnormal \\textup \\textsl \\textsc \\textmd \\textcolor \\colorbox \\fcolorbox".split())
315
+ # what may stand between a command and its next argument: spaces, [options], TeX's "to 3cm"
316
+ _ARG_GAP = re.compile(r"\s*(?:\[[^\[\]{}]*\]\s*)*(?:(?:to|spread)\b[^{}\\$%\[\]]*)?")
317
+
318
+
319
+ _MACRO_DEF = re.compile(r"\\(?:(?:re|provide)?newcommand|DeclareRobustCommand)\*?" + _TEX_GAP +
320
+ r"(?:\{\s*(\\[a-zA-Z@]+)\s*\}|(\\[a-zA-Z@]+))|\\[gex]?def\s*(\\[a-zA-Z@]+)")
321
+
322
+
323
+ def _text_macros(text: str) -> frozenset:
324
+ """`_TEXT_IN_MATH` plus the macros that `text` defines with a body using one of them
325
+ (``\\newcommand{\\note}[1]{\\mbox{#1}}``)."""
326
+ bodies = {}
327
+ for m in _MACRO_DEF.finditer(text):
328
+ start = text.find("{", m.end()) # after [n] [default] or \def's parameter text
329
+ if start < 0:
330
+ continue
331
+ depth, i = 0, start
332
+ for i in range(start, len(text)):
333
+ depth += {"{": 1, "}": -1}.get(text[i], 0) if text[i - 1:i] != "\\" else 0
334
+ if not depth:
335
+ break
336
+ bodies[m.group(1) or m.group(2) or m.group(3)] = set(re.findall(r"\\[a-zA-Z@]+", text[start:i + 1]))
337
+ commands = set(_TEXT_IN_MATH)
338
+ while True: # a macro built from another text macro is one too
339
+ more = {name for name, used in bodies.items() if name not in commands and used & commands}
340
+ if not more:
341
+ return frozenset(commands)
342
+ commands |= more
343
+
344
+
345
+ def _has_math_delimiters(text: str) -> bool:
346
+ """True if `text` has $, \\(, \\[ or a maths environment outside every text-command argument.
347
+
348
+ In math-mode TeX those can only occur inside the argument of \\text, \\mbox, ... (text in
349
+ the formula), while prose with equations always has one elsewhere - at the top level, or
350
+ in a group such as ``\\emph{for $n$}`` / ``{\\bf ... $x$ ...}``. So input without them is a
351
+ single bare equation, even when pandoc would find maths nested in it (``\\mbox{for all $n$}``).
352
+ """
353
+ text_commands = _text_macros(text)
354
+ owners: List[Optional[str]] = [] # per open brace group: the command it is an argument of
355
+ in_text = 0 # open groups that are text-command arguments
356
+ owner, end = None, 0 # command whose argument may start next, end of the previous token
357
+ skip_to = 0
358
+ for m in _LATEX_TOKEN.finditer(text):
359
+ if m.start() < skip_to:
360
+ continue
361
+ tok = m.group()
362
+ if owner is not None and not _ARG_GAP.fullmatch(text, end, m.start()):
363
+ owner = None # something else came between the command and this token
364
+ end = m.end()
365
+ if tok == "{":
366
+ owners.append(owner)
367
+ in_text += owner in text_commands
368
+ owner = None
369
+ elif tok == "}":
370
+ if owners:
371
+ owner = owners.pop() # \raisebox{1pt}{$x$}: the next group is the same command's
372
+ in_text -= owner in text_commands
373
+ elif tok.startswith("%"):
374
+ pass
375
+ elif m.group(1) in _STARRED_CASES:
376
+ # mathtools' starred cases: their text column holds $...$, which is maths inside text
377
+ close = re.compile(r"\\end" + _TEX_GAP + r"\{%s\}" % re.escape(m.group(1))).search(text, m.end())
378
+ if close:
379
+ skip_to = end = close.end()
380
+ owner = None
381
+ elif not in_text and (tok in ("$", "\\(", "\\[") or m.group(1) in _PANDOC_MATH_ENVS):
382
+ return True
383
+ else:
384
+ owner = tok if tok.startswith("\\") and tok[1:2].isalpha() else None
385
+ return False
386
+
387
+
388
+ def read_latex(text: str, default_display: bool = True) -> List[Equation]:
389
+ """Extract every equation from LaTeX source (:func:`read_latex_text`)."""
390
+ return read_latex_text(text, default_display)[0]
391
+
392
+
393
+ def read_latex_text(text: str, default_display: bool = True) -> "tuple[List[Equation], bool]":
394
+ """Every equation of LaTeX source, or of Markdown text with LaTeX maths in it (a chat answer, notes),
395
+ and whether it was read as Markdown.
396
+
397
+ Delimited maths ($...$, \\(...\\), $$...$$, \\[...\\], equation/align/gather/
398
+ multline/eqnarray/... environments, several of them, with prose in between)
399
+ are recognised by pandoc's LaTeX reader; \\newcommand definitions in the
400
+ input are expanded. Input with no delimiters at all is taken as one bare
401
+ equation in the `default_display` mode (texmath handles its macros itself).
402
+
403
+ Text that looks like Markdown (:func:`looks_like_markdown`: "50% of", "$5 and", `code`, **bold**),
404
+ and text that pandoc's LaTeX reader cannot read at all, is read as Markdown too, where % is a
405
+ percent sign and $ next to a number is money. The Markdown reading is taken unless the LaTeX
406
+ reading found maths that it lost (`$ a + b $` with spaces, which Markdown does not take as maths,
407
+ or an equation after a "1% comment"): then the text was LaTeX after all.
408
+ """
409
+ if not text.strip():
410
+ raise ConversionError("The input is empty.")
411
+ latex: Optional[List[Equation]] = None # None: no delimiters (a bare equation)
412
+ failed: Optional[ConversionError] = None
413
+ if _has_math_delimiters(text):
414
+ try:
415
+ latex = _read_json("latex", text.encode("utf-8"))
416
+ except ConversionError as e:
417
+ failed = e
418
+ signs = looks_like_markdown(text)
419
+ prose = _without_code(text)
420
+ if (failed is not None or signs) and not _LATEX_DOCUMENT.search(prose):
421
+ markdown = read_markdown(text)
422
+ # what the LaTeX reader finds outside Markdown's code (a chat answer's `$x$` example is none),
423
+ # a bare equation counting as one
424
+ compared = latex
425
+ if prose != text:
426
+ try:
427
+ compared = _read_json("latex", prose.encode("utf-8")) if _has_math_delimiters(prose) else None
428
+ except ConversionError:
429
+ compared = []
430
+ if compared is None:
431
+ # a bare equation, unless a % hid the $ of the maths ("20% of $x$"): a bare equation has $
432
+ # only inside \text and the like
433
+ hidden = re.search(r"(?<!\\)\$", _TEXT_ARGUMENT.sub("", prose))
434
+ compared = [] if hidden else [Equation(strip_tex(prose), default_display)]
435
+ if markdown and (failed is not None or not _lost(compared, markdown, text)):
436
+ return (latex, False) if markdown == latex else (markdown, True)
437
+ if not markdown and signs and not any(_mathy(e.tex) and not _price(e.tex, text) for e in compared):
438
+ # Markdown without maths ("$5 and $10 per month"): no equation, not a made-up one
439
+ raise ConversionError("No equation found: this reads as Markdown text (a chat answer, notes) "
440
+ "without $...$, $$...$$, \\(...\\) or \\[...\\].")
441
+ if failed is not None:
442
+ raise failed
443
+ if latex:
444
+ return latex, False
445
+ return [Equation(strip_tex(text), default_display)], False
446
+
447
+
448
+ # what LaTeX maths has and prose does not
449
+ _MATH_SIGN = re.compile(r"\\[a-zA-Z]+|[\^_=<>+|]")
450
+ _TEXT_ARGUMENT = re.compile(r"\\(?:text\w*|math(?:rm|it|bf|sf|tt|cal|bb|frak)|operatorname\*?|mbox|begin|end)"
451
+ r"\s*\{[^{}]*\}")
452
+
453
+
454
+ def _mathy(tex: str) -> bool:
455
+ """Whether what the LaTeX reader took for an equation looks like maths, not like prose that "$5 and
456
+ $10" put between dollars: a command or an operator, or a lone variable (x, x1), and no word of three
457
+ letters or more outside \\text and the like."""
458
+ tex = re.sub(r"(?<!\\)((?:\\\\)*)%[^\n]*", r"\1", tex) # without TeX comments (x = 1 % initial value)
459
+ bare = _TEXT_ARGUMENT.sub("", tex)
460
+ if re.search(r"(?<![\\A-Za-z])[A-Za-z]{3,}", bare):
461
+ return False
462
+ pairs = re.findall(r"(?<![\\A-Za-z])[A-Za-z]{2}(?![A-Za-z])", bare) # xy, nm (not "to", "of")
463
+ return bool(_MATH_SIGN.search(tex) or re.fullmatch(r"\s*\d*[A-Za-z]\d*\s*", tex) # x, x1, 2x
464
+ or re.fullmatch(r"\s*-?\d[\d.,;:\s+\-*/]*\d\s*|\s*\d\s*", tex) # 42, 1/2, 0, 1, 10 - 3
465
+ or re.search(r"(?<![\\A-Za-z0-9])[A-Za-z](?![A-Za-z])", bare) # 2 x (not 5M)
466
+ or any(p.lower() not in _SHORT_WORDS for p in pairs))
467
+
468
+
469
+ # two-letter English words: prose between two prices ("$5M to $10M"), not a product like xy
470
+ _SHORT_WORDS = frozenset("to of in on or is at by as an if it be we so no up do my me us he am per".split())
471
+
472
+
473
+ def _price(tex: str, text: str) -> bool:
474
+ """Whether the LaTeX reader's "equation" `tex` is what lies between two prices in `text`: its
475
+ closing $ is the start of an amount ("$5 + $10")."""
476
+ if re.fullmatch(r"\s*\d[\d.,]*\s*\|.*", tex, re.S): # "$10 | $y$ |": a price in a Markdown table
477
+ return True
478
+ if "|" in tex and _TABLE_RULE.search(text): # "| | B |": what lies between two cells' dollars
479
+ return True
480
+ pattern = r"\$\s*" + r"\s*".join(re.escape(t) for t in tex.split()) + r"\s*\$\d"
481
+ return bool(tex.split()) and bool(re.search(pattern, text))
482
+
483
+
484
+ def _lost(latex: List[Equation], markdown: List[Equation], text: str) -> bool:
485
+ """Whether the Markdown reading lost an equation of the LaTeX reading (`text`'s) that looks like
486
+ maths; each occurrence counts ($x$ twice is two)."""
487
+ left = collections.Counter(" ".join(e.tex.split()) for e in markdown)
488
+ for e in latex:
489
+ # (the LaTeX reader keeps the > of a Markdown quote or Obsidian callout in display maths)
490
+ key = " ".join(re.sub(r"(?m)^[ \t]*>[ \t]?", "", e.tex).split())
491
+ if left[key]:
492
+ left[key] -= 1
493
+ elif _mathy(e.tex) and not _price(e.tex, text):
494
+ return True
495
+ return False
496
+
497
+
498
+ # Markdown, as chat answers and notes write it: $...$ and $$...$$, and \(...\) / \[...\] (MathJax's)
499
+ MARKDOWN = "markdown+tex_math_single_backslash"
500
+ _LATEX_DOCUMENT = re.compile(r"\\documentclass\b|\\begin\s*\{document\}")
501
+ _MARKDOWN_SIGNS = re.compile(
502
+ # 50% of, 50 % of, (in %): a percent sign, not a comment (nor %20 in a URL)
503
+ r"(?<![\\\w.={])\d+(?:[.,]\d+)?[ \t]?%(?![0-9A-Fa-f]{2})[ \t]*[^\s%]|\((?:in[ \t]+)?%\)"
504
+ r"|(?:(?<![\\\w])[A-Za-z]|\))%[ \t]+[A-Za-z]{2,}" # p% confidence, (100-p)% of
505
+ r"|\b[A-Z]{1,3}\$\d" # US$5 (other money: _money)
506
+ # `code`, ``code``; not TeX's quotes (`inner' and `outer', ``fast'' and ``slow'')
507
+ r"|(?<![`\\])`(?![^`\n]*\w'['\s,.;:)!?])[^`\n]+(?<!\\)`(?!`)|(?<!`)``[^`'\n]+``(?!`)"
508
+ r"|^[ \t]*\|?[ \t]*:?-{3,}:?[ \t]*\|[ \t]*:?-{3,}" # a table's | --- | --- |
509
+ r"|^[ \t]*(?:>[ \t]?)*(?:```[^`\n]*|~~~[\w+.-]*[ \t]*(?:\{[^}\n]*\})?[ \t]*)\r?$" # a code fence
510
+ r"|^#{1,6}[ \t]+\S" # # a heading
511
+ r"|(?<![\w\\^_{*])\*\*[^\s*$\\][^*\n]*?\*\*", # **bold**
512
+ re.M)
513
+ _COMMENT_LINE = re.compile(r"^[ \t]*%.*$", re.M)
514
+ _TABLE_RULE = re.compile(r"^[ \t]*\|?[ \t]*:?-{3,}:?[ \t]*\|[ \t]*:?-{3,}", re.M)
515
+
516
+
517
+ # LaTeX's verbatim text, where a % or # is no sign of anything
518
+ _VERBATIM = re.compile(r"\\verb\*?([^\sa-zA-Z*])[^\n]*?\1|\\(?:url|href)\s*\{[^{}]*\}"
519
+ r"|\\begin\s*\{(verbatim\*?|lstlisting|minted)\}.*?\\end\s*\{\2\}", re.S)
520
+
521
+
522
+ # Markdown's code: a fenced block (``` or ~~~ to the same fence) and `inline code`
523
+ _FENCE = re.compile(r"^[ \t]*(?:>[ \t]?)*(`{3,}|~{3,})(?:(?<=`)[^`\n]*|(?<=~)[^\n]*)\n.*?"
524
+ r"^[ \t]*(?:>[ \t]?)*\1[`~]*[ \t]*\r?$", re.M | re.S) # (also in a > quote)
525
+ _INLINE_CODE = re.compile(r"(?<![`\\])(`+)(?!`)(?![^`\n]*\w'['\s,.;:)!?])[^\n]+?(?<!`)\1(?!`)")
526
+
527
+
528
+ def _without_code(text: str) -> str:
529
+ """The text without Markdown code: a LaTeX example in a chat answer's code block is no LaTeX input."""
530
+ return _INLINE_CODE.sub(" ", _FENCE.sub(" ", text))
531
+
532
+
533
+ def looks_like_markdown(text: str) -> bool:
534
+ """Whether pasted text may be Markdown rather than LaTeX: outside LaTeX comment lines and verbatim
535
+ text it has what LaTeX source rarely does (a percent sign after a number, money, `code`, a code
536
+ fence, a # heading, **bold**); a line that is a LaTeX comment, or a LaTeX document, outside
537
+ Markdown's code says LaTeX."""
538
+ prose = _without_code(text)
539
+ if _COMMENT_LINE.search(_OBSIDIAN_COMMENT.sub(" ", prose)) or _LATEX_DOCUMENT.search(prose):
540
+ return False
541
+ plain = _without_tex_comments(_VERBATIM.sub(" ", text))
542
+ return bool(_MARKDOWN_SIGNS.search(plain)) or _money(plain)
543
+
544
+
545
+ _MONEY = re.compile(r"(?<![\\$\w])\$(\d[\d.,]*)")
546
+
547
+
548
+ def _money(text: str) -> bool:
549
+ """Whether the text has a dollar amount, which LaTeX would take for the start of maths: a $ and a
550
+ number whose next $ does not close it as Markdown maths would (that $ comes after a space, or
551
+ before a digit: "$5 and $10", "$5M to $10M", "$5-$10"; or there is none), or that a unit or a
552
+ bracket with maths follows ("$5/mo", "$5/1M tokens", "$5.00 ($p$"); not $2 n$, $10 nm$, $42$,
553
+ $1/2$, $2(x+1)$, $2k+1$."""
554
+ for m in _MONEY.finditer(text):
555
+ after = text[m.end():]
556
+ if re.match(r"/(?:[A-Za-z]|\d+[kKmMbB]\b)|[ \t]+\(\s*\$", after):
557
+ return True
558
+ close = re.search(r"(?<!\\)\$", after)
559
+ if close is None or (close.start() and after[close.start() - 1].isspace()) \
560
+ or after[close.end():close.end() + 1].isdigit():
561
+ return True
562
+ return False
563
+
564
+
565
+ # Obsidian's comments (%% ... %%), not shown
566
+ _OBSIDIAN_COMMENT = re.compile(r"(?<!\\)%%.*?%%", re.S)
567
+
568
+
569
+ def _without_tex_comments(text: str) -> str:
570
+ """The text without what can only be a TeX comment: an unescaped % after something that a percent
571
+ sign does not follow ("$x=1$% old", "a word % note", "\\\\ % row"); a % after a number ("50%",
572
+ "50 %"), after a lone letter or a ")" ("p%", "(100-p)%") or before ")" ("(in %)") stays."""
573
+ lines = []
574
+ for line in text.split("\n"):
575
+ at = 0
576
+ while True:
577
+ j = line.find("%", at)
578
+ if j < 0:
579
+ break
580
+ slashes = len(line[:j]) - len(line[:j].rstrip("\\"))
581
+ before = line[:j].rstrip()
582
+ spaced = len(before) < j
583
+ percent = (slashes % 2 == 1 or line[j + 1:j + 2] == ")" or before[-1:].isdigit()
584
+ or (not spaced and (before.endswith(")") or re.search(r"(?<![A-Za-z\\])[A-Za-z]$", before))))
585
+ if not percent:
586
+ line = line[:j] # a comment: the rest of the line
587
+ break
588
+ at = j + 1
589
+ lines.append(line)
590
+ return "\n".join(lines)
591
+
592
+
593
+ # environments that only occur inside maths (an LLM writes them into Markdown without $$ at times)
594
+ _INNER_MATH_ENV = re.compile(r"\s*\\begin\s*\{(?:aligned|alignedat|gathered|split|cases|dcases|rcases|array|"
595
+ r"[pbBvV]?matrix|smallmatrix)\}")
596
+
597
+
598
+ # maths in raw TeX: in Markdown that is TeX of a document (\textbf{Use $x$}), not a lone equation
599
+ _RAW_MATH = re.compile(r"\$|\\\(|\\\[|\\begin\s*\{(?:%s)\}" % "|".join(re.escape(e) for e in sorted(_PANDOC_MATH_ENVS)))
600
+
601
+
602
+ def markdown_maths(node, out: List[Equation], definitions: Optional[List[str]] = None,
603
+ cwd: Optional[str] = None) -> None:
604
+ """The equations of pandoc JSON read from Markdown, in order: its Math, and the maths of raw TeX in it
605
+ (a \\begin{align} ... \\end{align} written straight into the text), read by the LaTeX reader (in
606
+ `cwd`, where \\input finds its files) after the definitions (\\newcommand ...) of the raw TeX
607
+ before it; `definitions` collects those as the walk goes."""
608
+ definitions = [] if definitions is None else definitions
609
+ if isinstance(node, dict):
610
+ if node.get("t") == "Math":
611
+ kind, tex = node["c"]
612
+ if tex.strip(): # not the \[ \] of a task list
613
+ out.append(Equation(strip_tex(tex), kind["t"] == "DisplayMath"))
614
+ return
615
+ if node.get("t") in ("RawBlock", "RawInline") and node["c"][0] in ("tex", "latex"):
616
+ raw = node["c"][1]
617
+ if _INNER_MATH_ENV.match(raw):
618
+ raw = "\\[" + raw + "\\]" # \begin{aligned} ... written without $$: display maths
619
+ includes = re.search(r"\\(?:input|include)(?![a-zA-Z@])", raw)
620
+ if _RAW_MATH.search(raw) or includes:
621
+ try:
622
+ # after the definitions so far; their own maths (an \input file's) was found already
623
+ before = len(_latex_maths("\n".join(definitions), cwd)) if definitions else 0
624
+ out.extend(_latex_maths("\n".join(definitions + [raw]), cwd)[before:])
625
+ except ConversionError:
626
+ pass # raw TeX that is not maths after all
627
+ if includes or _MACRO_DEF.search(raw) or re.search(r"\\(?:DeclareMathOperator|let)(?![a-zA-Z@])", raw):
628
+ definitions.append(raw) # for the raw TeX after it
629
+ return
630
+ for v in node.values():
631
+ markdown_maths(v, out, definitions, cwd)
632
+ elif isinstance(node, list):
633
+ for v in node:
634
+ markdown_maths(v, out, definitions, cwd)
635
+
636
+
637
+ _LATEX_MATHS_CACHE: dict = {}
638
+
639
+
640
+ def _latex_maths(source: str, cwd: Optional[str]) -> List[Equation]:
641
+ """The equations pandoc's LaTeX reader finds in `source` (run in `cwd`); remembered for the walk."""
642
+ key = (source, cwd)
643
+ if key not in _LATEX_MATHS_CACHE:
644
+ if len(_LATEX_MATHS_CACHE) > 64:
645
+ _LATEX_MATHS_CACHE.clear()
646
+ found: List[Equation] = []
647
+ _collect_math(json.loads(_run(["-f", "latex", "-t", "json"], source.encode("utf-8"), cwd=cwd)[0])["blocks"],
648
+ found)
649
+ _LATEX_MATHS_CACHE[key] = found
650
+ return list(_LATEX_MATHS_CACHE[key])
651
+
652
+
653
+ def _money_math(tex: str) -> bool:
654
+ """Whether what pandoc's Markdown reader took for inline maths is money: "$5.00 ($p$ after tax)"
655
+ gives "5.00 (", a number up to an opening bracket, or a number and prose; $42$, $1/2$, $2 x$,
656
+ $10 nm$ are maths."""
657
+ tex = tex.strip()
658
+ return bool(re.match(r"\d", tex)) and (tex.endswith(("(", "[")) or bool(
659
+ re.search(r"(?<![\\A-Za-z])[A-Za-z]{3,}", _TEXT_ARGUMENT.sub("", tex))))
660
+
661
+
662
+ def _money_dollar(text: str, tex: str) -> Optional[int]:
663
+ """Where in `text` the inline "equation" `tex` that is money starts: a $ that is no \\$ nor part of
664
+ $$, followed by `tex` and a $."""
665
+ pattern = r"(?<![\\$])\$\s*" + r"\s*".join(re.escape(t) for t in tex.split()) + r"\s*\$(?!\$)"
666
+ found = re.search(pattern, text)
667
+ return found.start() if found else None
668
+
669
+
670
+ def _without_obsidian_comments(text: str) -> str:
671
+ """Markdown without Obsidian's %% comments %% (outside code), which a note does not show."""
672
+ if "%%" not in text:
673
+ return text
674
+ spans = [(m.start(), m.end()) for m in _FENCE.finditer(text)] + \
675
+ [(m.start(), m.end()) for m in _INLINE_CODE.finditer(text)]
676
+
677
+ def drop(m):
678
+ return m.group(0) if any(a <= m.start() < b for a, b in spans) else " "
679
+ return _OBSIDIAN_COMMENT.sub(drop, text)
680
+
681
+
682
+ def markdown_blocks(text: str, fmt: str = MARKDOWN, cwd: Optional[str] = None,
683
+ meta: Optional[dict] = None) -> "tuple[list, str]":
684
+ """pandoc's JSON blocks of Markdown text and its warnings (`meta`, if given, gets its metadata: the
685
+ title and authors of its YAML header). An inline "equation" that is money (a number, then prose:
686
+ "$5.00 ($p$ after tax)" gives "5.00 (") is read again with its $ escaped, so that the dollar it took
687
+ as its end starts the equation it belongs to."""
688
+ _LATEX_MATHS_CACHE.clear() # (an \input file may have changed since the last reading)
689
+ text = _without_obsidian_comments(text)
690
+ rounds = 8
691
+ while True:
692
+ out, err = _run(["-f", fmt, "-t", "json"], text.encode("utf-8"), cwd=cwd)
693
+ document = json.loads(out)
694
+ blocks = document["blocks"]
695
+ if meta is not None:
696
+ meta.clear()
697
+ meta.update(document.get("meta") or {})
698
+ maths: List[Equation] = []
699
+ _collect_math(blocks, maths)
700
+ escaped = text
701
+ for e in maths:
702
+ if not e.display and _money_math(e.tex):
703
+ at = _money_dollar(escaped, e.tex)
704
+ if at is not None:
705
+ escaped = escaped[:at] + "\\" + escaped[at:]
706
+ if escaped == text or not rounds:
707
+ return blocks, err # (the reading of the text as it is now)
708
+ text, rounds = escaped, rounds - 1
709
+
710
+
711
+ def read_markdown(text: str) -> List[Equation]:
712
+ """The equations of Markdown text (:data:`MARKDOWN`), in order (:func:`markdown_blocks`)."""
713
+ eqs: List[Equation] = []
714
+ markdown_maths(markdown_blocks(text)[0], eqs)
715
+ return eqs
716
+
717
+
718
+ _XML_ENTITIES = ("lt", "gt", "amp", "quot", "apos")
719
+ _NAMED_ENTITY = re.compile(r"&([A-Za-z][A-Za-z0-9]*);")
720
+ # CDATA sections and comments: literal text that the markup clean-ups below must not touch
721
+ _XML_LITERAL = re.compile(r"(<!\[CDATA\[[\s\S]*?\]\]>|<!--[\s\S]*?-->)")
722
+ # group 1: a literal (kept); otherwise an XML declaration or a DOCTYPE, whose internal subset
723
+ # [...] may hold comments and quoted strings with any characters
724
+ _XML_PROLOG = re.compile(_XML_LITERAL.pattern + r"|<\?xml\s[^>]*\?>"
725
+ r"|<!DOCTYPE[^\[>]*(?:\[(?:<!--[\s\S]*?-->|\"[^\"]*\"|'[^']*'|[^\]\"'])*\]\s*)?>", re.I)
726
+
727
+
728
+ def _outside_literals(text: str, fix) -> str:
729
+ """Apply `fix` to the markup of `text`, leaving CDATA sections and comments alone."""
730
+ parts = _XML_LITERAL.split(text)
731
+ return "".join(part if i % 2 else fix(part) for i, part in enumerate(parts))
732
+
733
+
734
+ def _strip_xml_prolog(text: str) -> str:
735
+ """Drop a BOM and every XML declaration / DOCTYPE: several pasted documents carry one
736
+ each, and inside the wrapper element we parse them in, any of them is a syntax error."""
737
+ return _XML_PROLOG.sub(lambda m: m.group(1) or "", text.lstrip("\ufeff"))
738
+
739
+
740
+ def _named_entities_to_numeric(text: str) -> str:
741
+ """``&InvisibleTimes;``, ``&nbsp;``... (MathML / HTML names, common in exported MathML)
742
+ as numeric references, which a plain XML parser understands."""
743
+ def numeric(m):
744
+ value = None if m.group(1) in _XML_ENTITIES else html.entities.html5.get(m.group(1) + ";")
745
+ return "".join("&#x%X;" % ord(c) for c in value) if value else m.group(0)
746
+ return _outside_literals(text, lambda s: _NAMED_ENTITY.sub(numeric, s))
747
+
748
+
749
+ def _local(name: str) -> str:
750
+ """``{namespace}tag`` -> ``tag``."""
751
+ return name.rsplit("}", 1)[-1]
752
+
753
+
754
+ def _outermost(root: ET.Element, match) -> List[ET.Element]:
755
+ """Descendants of `root` satisfying `match`, in document order, not descending into a match."""
756
+ found: List[ET.Element] = []
757
+
758
+ def walk(el):
759
+ for child in el:
760
+ if match(child):
761
+ found.append(child)
762
+ else:
763
+ walk(child)
764
+
765
+ walk(root)
766
+ return found
767
+
768
+
769
+ # characters that make up relation symbols (used to spot an equation array's alignment column):
770
+ # arrows, and the relations among the mathematical operators (not ∪ ⊕ ⊗ ... between them)
771
+ _RELATION_CHARS = frozenset("=<>:∈∉∊∋∌∍∝∣∤∥∦⋈⋔").union(map(chr, (
772
+ *range(0x2190, 0x2200), *range(0x27F0, 0x2800), *range(0x2900, 0x2980), # arrows
773
+ *range(0x2236, 0x223E), *range(0x2241, 0x228C), *range(0x228F, 0x2293), # ∶ ∼, ≁ ... ⊋, ⊏ ... ⊒
774
+ *range(0x22A2, 0x22B9), *range(0x22D0, 0x22D2), *range(0x22D6, 0x22EE), # ⊢ ... ⊸, ⋐ ⋑, ⋖ ... ⋭
775
+ *range(0x22F2, 0x2300), *range(0x2A66, 0x2AFB)))).difference( # ⋲ ... ⋿, ⩦ ... ⫺
776
+ "⊤∸∺⩱⩲⫵⫶") # an ordinary symbol and binary operators inside those ranges
777
+
778
+
779
+ def _leading_mo(el: ET.Element, ns: str) -> Optional[ET.Element]:
780
+ """The <mo> an element starts with: itself, or the base of an over/under-decorated operator
781
+ (``\\overset{!}{=}`` is an <mover> over <mo>=</mo>)."""
782
+ while el.tag in (ns + "mover", ns + "munder", ns + "munderover") and len(el):
783
+ el = el[0]
784
+ return el if el.tag == ns + "mo" else None
785
+
786
+
787
+ def _is_relation(mo: ET.Element) -> bool:
788
+ text = (mo.text or "").strip()
789
+ return bool(text) and set(text) <= _RELATION_CHARS
790
+
791
+
792
+ def _is_empty(el: ET.Element) -> bool:
793
+ """No text and nothing but <mrow>s: an empty table cell (not ``\\sqrt{}``, not spacing)."""
794
+ return not "".join(el.itertext()).strip() and all(_local(e.tag) in ("mtd", "mrow") for e in el.iter())
795
+
796
+
797
+ def _cell_start(cell: ET.Element, ns: str) -> Optional[str]:
798
+ """How the right-hand cell of an aligned block starts: "empty", "relation" (``&= b``), "operator"
799
+ (a continuation line, ``&+ c``), "space" (spacing followed by anything else, ``&\\quad x``), or
800
+ None for anything else (a table of values). Spacing before an operator is looked past
801
+ (``&\\quad = b``; Word exports ``&\\quad + c`` as ``<mo> </mo><mo>+</mo>``)."""
802
+ if _is_empty(cell):
803
+ return "empty"
804
+ spaced = False
805
+ for child in cell:
806
+ if child.tag == ns + "mspace" or _is_empty(child) or (child.tag == ns + "mo" and not (child.text or "").strip()):
807
+ spaced = True
808
+ continue
809
+ mo = _leading_mo(child, ns)
810
+ if mo is not None:
811
+ return "relation" if _is_relation(mo) else "operator"
812
+ break
813
+ return "space" if spaced else None
814
+
815
+
816
+ def _mark_equation_array_alignment(math: ET.Element) -> bool:
817
+ """Older Word / PowerPoint (and other programs) export an equation array as an <mtable> without
818
+ any alignment attributes, which texmath turns into ``\\begin{matrix}``. (Word 16.0.20527 writes
819
+ columnalign right / left on each cell itself.) When the table has the shape of an aligned block,
820
+ add ``columnalign`` so that texmath emits ``\\begin{aligned}``: every row has the same even number
821
+ of cells, read as right / left pairs (``a &= b & c &= d``), and in each pair the left-aligned cell
822
+ of every row is empty or starts with an operator or a space (a continuation line such as ``&+ c``)
823
+ and in at least one row with a relation. Returns True if changed."""
824
+ ns = math.tag[:math.tag.index("}") + 1] if math.tag.startswith("{") else ""
825
+ node = math
826
+ while len(node) == 1 and node[0].tag in (ns + "mrow", ns + "semantics", ns + "mstyle"):
827
+ node = node[0]
828
+ tables = [c for c in node if c.tag == ns + "mtable"]
829
+ if len(node) != 1 or not tables:
830
+ return False
831
+ table = tables[0]
832
+ # a table that says how it looks (its alignment, a frame, ruled lines) is laid out as it says
833
+ ruled = any(set((table.get(a) or "none").split()) - {"none"} for a in ("frame", "columnlines", "rowlines"))
834
+ if ruled or table.get("columnalign") or any(r.get("columnalign") for r in table if r.tag == ns + "mtr"):
835
+ return False
836
+ rows = [[c for c in r if c.tag == ns + "mtd"] for r in table if r.tag == ns + "mtr"]
837
+ if not rows:
838
+ return False
839
+ width = len(rows[0])
840
+ if width < 2 or width % 2 or any(len(cells) != width or any(c.get("columnalign") for c in cells)
841
+ for cells in rows):
842
+ return False
843
+ for left in range(1, width, 2): # each right / left pair: its left-aligned cells
844
+ starts = [_cell_start(cells[left], ns) for cells in rows]
845
+ if None in starts or "relation" not in starts:
846
+ return False
847
+ for cells in rows:
848
+ for i, cell in enumerate(cells):
849
+ cell.set("columnalign", "left" if i % 2 else "right")
850
+ return True
851
+
852
+
853
+ def _strip_namespaces(el: ET.Element) -> None:
854
+ for e in el.iter():
855
+ if isinstance(e.tag, str):
856
+ e.tag = _local(e.tag)
857
+ for key in [k for k in e.attrib if k.startswith("{")]:
858
+ e.attrib[_local(key)] = e.attrib.pop(key)
859
+
860
+
861
+ def _serialize_math(math: ET.Element) -> bytes:
862
+ math.tail = None # tostring() would include the text that follows the element
863
+ return ET.tostring(math, encoding="unicode").encode("utf-8")
864
+
865
+
866
+ def _converts(tex: str, display: bool) -> bool:
867
+ try:
868
+ write_mathml(Equation(tex, display))
869
+ return True
870
+ except ConversionError:
871
+ return False
872
+
873
+
874
+ def parse_mathml(text: str) -> List[ET.Element]:
875
+ """The outermost <math> elements of MathML input (prefixes and namespaces stripped, as pandoc
876
+ wants them; named entities as numeric ones)."""
877
+ body = _named_entities_to_numeric(_strip_xml_prolog(text))
878
+ try:
879
+ # the mml prefix is declared so that a pasted <mml:math> fragment parses without its declaration
880
+ root = ET.fromstring('<r xmlns:mml="%s">%s</r>' % (MATHML_NS, body))
881
+ except ET.ParseError as e:
882
+ raise ConversionError("The MathML is not well-formed XML: %s" % e)
883
+ maths = _outermost(root, lambda el: isinstance(el.tag, str) and _local(el.tag) == "math")
884
+ if not maths:
885
+ raise ConversionError("No <math> element found in the MathML input.")
886
+ for math in maths:
887
+ _strip_namespaces(math) # pandoc only recognises a bare <math>, not <mml:math>
888
+ return maths
889
+
890
+
891
+ def drop_annotations(math: ET.Element) -> Optional[str]:
892
+ """Remove the annotations of a parsed <math> (:func:`parse_mathml`); its TeX annotation, if any."""
893
+ return _drop_annotations(math)
894
+
895
+
896
+ def read_mathml(text: str, fix_office_alignment: bool = True, tidy: bool = True) -> List[Equation]:
897
+ """Equations in MathML. With `tidy`, identifiers that texmath would misread (upright names,
898
+ function names, bold italic symbols, binomials) come back as the LaTeX an author writes
899
+ (:mod:`tidy`); an equation for which that does not give valid TeX is read as texmath reads it."""
900
+ if not text.strip():
901
+ raise ConversionError("The input is empty.")
902
+ maths = parse_mathml(text)
903
+ annotations: List[Optional[str]] = []
904
+ for math in maths:
905
+ annotations.append(_drop_annotations(math))
906
+ _unicode_spaces(math)
907
+ if fix_office_alignment:
908
+ _mark_equation_array_alignment(math)
909
+ raw = [_serialize_math(m) for m in maths]
910
+ mappings: List[dict] = [{} for _ in maths]
911
+ count = 0
912
+ for math, mapping in zip(maths, mappings):
913
+ # placeholders must not occur in the equation - nor appear once texmath joins its identifiers
914
+ # (<mi>Q</mi><mi>Q</mi>...); checked per equation, each with its own placeholders
915
+ if tidy and _tidy.can_mark(_serialize_math(math).decode("utf-8") + "".join(math.itertext())):
916
+ _tidy.mark_identifiers(math, mapping, count)
917
+ count += len(mapping)
918
+ marked = [_serialize_math(m) for m in maths] if tidy else raw # also when only a fraction or a bar changed
919
+ eqs = _read_json("html", b"".join(marked))
920
+ if len(eqs) < len(maths): # pandoc turns a <math> that texmath rejects into plain text, silently
921
+ eqs, mappings = _read_one_by_one(marked, raw, annotations, mappings)
922
+ for i, (eq, mapping) in enumerate(zip(eqs, mappings)):
923
+ if not mapping:
924
+ continue
925
+ tex = _tidy.restore(eq.tex, mapping)
926
+ if tex is None or not _converts(tex, eq.display):
927
+ plain = _read_json("html", raw[i]) # this equation as texmath reads it
928
+ if plain:
929
+ tex = plain[0].tex
930
+ elif annotations[i]:
931
+ tex = strip_tex(annotations[i])
932
+ else:
933
+ raise ConversionError("texmath could not interpret <math> element %d of the input." % (i + 1))
934
+ eqs[i] = Equation(tex, eq.display)
935
+ _check_not_empty(eqs, "MathML")
936
+ return eqs
937
+
938
+
939
+ def _drop_annotations(math: ET.Element) -> Optional[str]:
940
+ """Read what the MathML shows, not a TeX annotation that texmath would prefer: it may be stale, or
941
+ use macros texmath does not know (the user's, kept by "TeX annotation"). Returns the TeX annotation
942
+ of the whole equation, if any: the fallback when the presentation cannot be read (Content MathML)."""
943
+ tex = None
944
+ for parent in [math] + list(math.iter()):
945
+ for child in list(parent):
946
+ if child.tag == "semantics":
947
+ shown = [c for c in child if c.tag not in ("annotation", "annotation-xml")]
948
+ if parent is math and tex is None:
949
+ for ann in child.findall("annotation"): # the whole equation's, not a part's
950
+ if (ann.get("encoding") or "").lower() in ("application/x-tex", "tex", "latex") and ann.text:
951
+ tex = ann.text
952
+ break
953
+ index = list(parent).index(child)
954
+ parent.remove(child)
955
+ if shown:
956
+ shown[0].tail = child.tail
957
+ parent.insert(index, shown[0])
958
+ return tex
959
+
960
+
961
+ def _read_one_by_one(marked: List[bytes], raw: List[bytes], annotations: List[Optional[str]],
962
+ mappings: List[dict]) -> "tuple[List[Equation], List[dict]]":
963
+ """The equations of several <math> elements when texmath rejected one: each read on its own; one that
964
+ texmath cannot read comes from its TeX annotation, else that is an error."""
965
+ eqs: List[Equation] = []
966
+ bad = []
967
+ for i, (m, r, ann) in enumerate(zip(marked, raw, annotations)):
968
+ found = _read_json("html", m) or _read_json("html", r)
969
+ if found:
970
+ if not _read_json("html", m):
971
+ mappings[i] = {} # read without placeholders
972
+ eqs.append(found[0])
973
+ elif ann is not None:
974
+ display = b'display="block"' in r
975
+ eqs.append(Equation(strip_tex(ann), display))
976
+ mappings[i] = {}
977
+ else:
978
+ bad.append(str(i + 1))
979
+ if bad:
980
+ if len(raw) == 1:
981
+ raise ConversionError("texmath could not interpret this MathML (unsupported or malformed elements).")
982
+ raise ConversionError("texmath could not interpret <math> element %s of the %d in the input "
983
+ "(unsupported or malformed elements)." % (", ".join(bad), len(raw)))
984
+ return eqs, mappings
985
+
986
+
987
+ _DOCX_CONTENT_TYPES = (
988
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
989
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
990
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
991
+ '<Default Extension="xml" ContentType="application/xml"/>'
992
+ '<Override PartName="/word/document.xml" '
993
+ 'ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
994
+ '</Types>')
995
+ _DOCX_RELS = (
996
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
997
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
998
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" '
999
+ 'Target="word/document.xml"/></Relationships>')
1000
+
1001
+
1002
+ def _alignment_mark(math: ET.Element) -> "Optional[tuple[ET.Element, ET.Element]]":
1003
+ """(element, its m:aln) of the first alignment mark that is on, directly in `math`: on a run
1004
+ (m:rPr/m:aln) or on an operator box (m:boxPr/m:aln, Word's "operator emulator"); None if none.
1005
+ A line has one alignment point in Word; a mark with m:val 0 / off / false is off."""
1006
+ q = lambda n: "{%s}%s" % (OMML_NS, n) # noqa: E731
1007
+ for child in math:
1008
+ props = {q("r"): q("rPr"), q("box"): q("boxPr")}.get(child.tag)
1009
+ mark = child.find("%s/%s" % (props, q("aln"))) if props else None
1010
+ if mark is not None and mark.get(q("val"), "on").strip().lower() not in ("0", "off", "false"):
1011
+ return child, mark
1012
+ return None
1013
+
1014
+
1015
+ def _q(name: str) -> str:
1016
+ return "{%s}%s" % (OMML_NS, name)
1017
+
1018
+
1019
+ def _separator() -> ET.Element:
1020
+ """A run "&" of its own: outside \\text, whatever the style of the run it goes before."""
1021
+ run = ET.Element(_q("r"))
1022
+ ET.SubElement(run, _q("t")).text = "&"
1023
+ return run
1024
+
1025
+
1026
+ def _without_line_breaks(line: List[ET.Element]) -> List[ET.Element]:
1027
+ """The line without Word's line breaks (<w:br/> in a run: the end of a line of a math paragraph): a
1028
+ run that held only the break goes, from a run with more in it only the break."""
1029
+ out = []
1030
+ for el in line:
1031
+ if el.tag == _q("r"):
1032
+ breaks = [c for c in el if c.tag == "{%s}br" % WML_NS]
1033
+ if breaks:
1034
+ for br in breaks:
1035
+ el.remove(br)
1036
+ if not "".join(el.itertext()).strip():
1037
+ continue
1038
+ out.append(el)
1039
+ return out
1040
+
1041
+
1042
+ def _take(el: ET.Element, holder: str, name: str) -> Optional[ET.Element]:
1043
+ """Remove and return the property `name` (m:brk, m:aln) from el's `holder` (m:rPr, m:boxPr), dropping
1044
+ the holder when nothing is left in it; None if it has none."""
1045
+ props = el.find(_q(holder))
1046
+ found = props.find(_q(name)) if props is not None else None
1047
+ if found is not None:
1048
+ props.remove(found)
1049
+ if not len(props) and not props.attrib:
1050
+ el.remove(props)
1051
+ return found
1052
+
1053
+
1054
+ def _line_break_of(el: ET.Element) -> Optional[ET.Element]:
1055
+ """The manual line break (m:brk, Word's "Insert Manual Break") with which el starts a new line, taken
1056
+ out of its run (m:rPr) or operator box (m:boxPr)."""
1057
+ if el.tag == _q("r"):
1058
+ return _take(el, "rPr", "brk")
1059
+ if el.tag == _q("box"):
1060
+ return _take(el, "boxPr", "brk")
1061
+ return None
1062
+
1063
+
1064
+ class _Line:
1065
+ """A line of an equation: its elements (copies), and the m:alnAt of the manual break it starts with,
1066
+ if any (the number of the operator of the equation's first line it aligns to)."""
1067
+
1068
+ def __init__(self, broken: bool = False, aln_at: Optional[int] = None):
1069
+ self.elements: List[ET.Element] = []
1070
+ self.broken = broken
1071
+ self.aln_at = aln_at
1072
+
1073
+
1074
+ def _lines(math: ET.Element) -> List[_Line]:
1075
+ """The lines of one m:oMath, split at its manual line breaks (m:brk directly in it)."""
1076
+ lines = [_Line()]
1077
+ for child in math:
1078
+ child = copy.deepcopy(child)
1079
+ brk = _line_break_of(child)
1080
+ if brk is not None:
1081
+ try:
1082
+ aln_at = int(brk.get(_q("alnAt"), "")) or None
1083
+ except ValueError:
1084
+ aln_at = None
1085
+ lines.append(_Line(True, aln_at))
1086
+ lines[-1].elements.append(child)
1087
+ return lines
1088
+
1089
+
1090
+ def _is_operator(ch: str) -> bool:
1091
+ return unicodedata.category(ch) == "Sm" or ch in "-/*!·" # Word's MathML: <mo>·</mo>
1092
+
1093
+
1094
+ def _is_on(el: ET.Element, path: str) -> bool:
1095
+ """Whether the OMML property at `path` (m:rPr/m:nor, m:boxPr/m:opEmu) is there and on (m:val absent,
1096
+ or not 0 / off / false)."""
1097
+ found = el.find(path)
1098
+ return found is not None and found.get(_q("val"), "on").strip().lower() not in ("0", "off", "false")
1099
+
1100
+
1101
+ def _split_run(run: ET.Element, text: ET.Element, pos: int) -> "tuple[ET.Element, ET.Element]":
1102
+ """A run cut before character `pos` of its m:t `text`: what comes before (with the run's
1103
+ properties) and what follows (with a copy of them); each piece of text in one of them only."""
1104
+ first, second = ET.Element(run.tag, run.attrib), ET.Element(run.tag, run.attrib)
1105
+ props = run.find(_q("rPr"))
1106
+ if props is not None:
1107
+ second.append(copy.deepcopy(props))
1108
+ target = first
1109
+ for child in run:
1110
+ if child is text:
1111
+ head, tail = copy.deepcopy(child), copy.deepcopy(child)
1112
+ head.text, tail.text = (child.text or "")[:pos], (child.text or "")[pos:]
1113
+ if head.text:
1114
+ first.append(head)
1115
+ second.append(tail)
1116
+ target = second
1117
+ else:
1118
+ target.append(child)
1119
+ return first, second
1120
+
1121
+
1122
+ def _before_operator(line: List[ET.Element], n: int) -> bool:
1123
+ """Put "&" before the n-th operator of the line: an operator character in a run of maths (not one of
1124
+ upright text, m:nor), or an operator box (m:opEmu) as one; a run "a=b" is cut at its "="."""
1125
+ count = 0
1126
+ texts = (_q("t"), "{%s}t" % WML_NS)
1127
+ for index, child in enumerate(line):
1128
+ if child.tag == _q("box") and _is_on(child, "%s/%s" % (_q("boxPr"), _q("opEmu"))):
1129
+ count += 1
1130
+ if count == n:
1131
+ line.insert(index, _separator())
1132
+ return True
1133
+ continue
1134
+ if child.tag != _q("r") or _is_on(child, "%s/%s" % (_q("rPr"), _q("nor"))):
1135
+ continue
1136
+ before = False # text of this run before the operator
1137
+ for text in [c for c in child if c.tag in texts]: # m:t, and w:t that Word also reads
1138
+ for pos, ch in enumerate(text.text or ""):
1139
+ if not _is_operator(ch):
1140
+ before = True
1141
+ continue
1142
+ count += 1
1143
+ if count != n:
1144
+ before = True
1145
+ continue
1146
+ if before or pos:
1147
+ first, second = _split_run(child, text, pos)
1148
+ line[index:index + 1] = [first, _separator(), second]
1149
+ else:
1150
+ line.insert(index, _separator())
1151
+ return True
1152
+ return False
1153
+
1154
+
1155
+ def _aligned_block(equations: List[List[_Line]]) -> ET.Element:
1156
+ """The lines of one or more equations (each m:oMath's, see _lines) as one m:oMath holding an
1157
+ m:eqArr whose rows have a run "&" at the alignment point: texmath reads that as an aligned block.
1158
+ A row's point is its m:aln mark (Word: "Align at ="). Rows without one: a line that a manual break
1159
+ started begins at the point; an equation's first line has it before the operator its first break
1160
+ names (m:alnAt), else at its start when no line has a mark."""
1161
+ math = ET.Element(_q("oMath"))
1162
+ arr = ET.SubElement(math, _q("eqArr"))
1163
+ marked = any(_alignment_mark(line.elements) is not None for lines in equations for line in lines)
1164
+ for lines in equations:
1165
+ target = next((line.aln_at for line in lines if line.broken), None) # for this equation's line 1
1166
+ for number, line in enumerate(lines):
1167
+ row = _without_line_breaks(line.elements)
1168
+ found = _alignment_mark(row)
1169
+ if found is not None:
1170
+ element, mark = found
1171
+ props = next(p for p in element if mark in list(p))
1172
+ props.remove(mark)
1173
+ if not len(props) and not props.attrib:
1174
+ element.remove(props)
1175
+ row.insert(row.index(element), _separator())
1176
+ elif line.broken:
1177
+ row.insert(0, _separator())
1178
+ elif number == 0 and not (target and _before_operator(row, target)) and not marked:
1179
+ row.insert(0, _separator())
1180
+ ET.SubElement(arr, _q("e")).extend(row)
1181
+ return math
1182
+
1183
+
1184
+ def split_math_paragraph(el: ET.Element) -> List[ET.Element]:
1185
+ """Word's math paragraphs and line breaks, as texmath can read them:
1186
+ * an m:oMathPara holding several m:oMath (the lines of Shift+Enter) whose lines are aligned at marks
1187
+ (m:aln, "Align at =") as one aligned block; without marks, as one m:oMathPara per equation
1188
+ (texmath would read them as one product, x y);
1189
+ * an equation with manual line breaks (m:brk, "Insert Manual Break") as an aligned block, display
1190
+ or inline as it was;
1191
+ * anything else as it is.
1192
+ Lines with an "&" of their own are left as they are: in an equation array texmath would take it
1193
+ for an alignment point."""
1194
+ para, math, props = _q("oMathPara"), _q("oMath"), _q("oMathParaPr")
1195
+ maths = [c for c in el if c.tag == math] if el.tag == para else ([el] if el.tag == math else [])
1196
+ if not maths:
1197
+ return [el]
1198
+
1199
+ def own_amp(*ms: ET.Element) -> bool:
1200
+ return any("&" in (t.text or "") for m in ms for t in m.iter(_q("t")))
1201
+
1202
+ def in_para(*children: ET.Element) -> ET.Element:
1203
+ piece = ET.Element(para)
1204
+ piece.extend(copy.deepcopy(c) for c in el if c.tag == props)
1205
+ piece.extend(children)
1206
+ return piece
1207
+
1208
+ if el.tag == para and len(maths) > 1 and any(_alignment_mark(m) is not None for m in maths) \
1209
+ and not own_amp(*maths):
1210
+ return [in_para(_aligned_block([_lines(m) for m in maths]))]
1211
+ out = []
1212
+ changed = False
1213
+ for m in maths:
1214
+ lines = _lines(m)
1215
+ if len(lines) > 1 and not own_amp(m):
1216
+ block = _aligned_block([lines])
1217
+ changed = True
1218
+ out.append(in_para(block) if el.tag == para else block)
1219
+ else:
1220
+ out.append(in_para(m) if el.tag == para else m)
1221
+ if not changed and len(maths) == 1:
1222
+ return [el]
1223
+ return out
1224
+
1225
+
1226
+ def _parse_omml_fragments(text: str) -> List[ET.Element]:
1227
+ """Return the top-level <m:oMathPara>/<m:oMath> elements found in arbitrary OMML-ish XML."""
1228
+ body = _strip_xml_prolog(text)
1229
+ # Wrap so that undeclared m:/w: prefixes (common when OMML is pasted from a snippet) resolve.
1230
+ wrapped = ('<r xmlns:m="%s" xmlns:w="%s" xmlns:mc="%s" '
1231
+ 'xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" '
1232
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">%s</r>') % (
1233
+ OMML_NS, WML_NS, MC_NS, body)
1234
+ try:
1235
+ root = ET.fromstring(wrapped)
1236
+ except ET.ParseError as e:
1237
+ raise ConversionError("The OMML is not well-formed XML: %s" % e)
1238
+ tags = ("{%s}oMathPara" % OMML_NS, "{%s}oMath" % OMML_NS)
1239
+ alternatives, choice = "{%s}AlternateContent" % MC_NS, "{%s}Choice" % MC_NS
1240
+ found: List[ET.Element] = []
1241
+
1242
+ def walk(el):
1243
+ for child in el:
1244
+ if child.tag in tags:
1245
+ found.append(child) # an oMath inside an oMathPara belongs to it
1246
+ elif child.tag == alternatives:
1247
+ # the same content once per branch (e.g. an equation in a text box: DrawingML choice +
1248
+ # VML fallback, possibly several choices): read the first choice, else the fallback
1249
+ branches = list(child)
1250
+ branch = next((b for b in branches if b.tag == choice), branches[0] if branches else None)
1251
+ if branch is not None:
1252
+ walk(branch)
1253
+ else:
1254
+ walk(child)
1255
+
1256
+ walk(root)
1257
+ if not found:
1258
+ raise ConversionError("No <m:oMath> or <m:oMathPara> element found in the OMML input.")
1259
+ return [piece for f in found for piece in split_math_paragraph(f)]
1260
+
1261
+
1262
+ def _check_not_empty(eqs: List[Equation], what: str) -> None:
1263
+ """texmath skips elements it does not know (OMML) and yields an empty equation for an empty one:
1264
+ report that instead of converting it to an empty result."""
1265
+ empty = [str(i) for i, e in enumerate(eqs, 1) if not e.tex]
1266
+ if empty:
1267
+ where = "this %s" % what if len(eqs) == 1 else "%s equation %s of the %d in the input" % (
1268
+ what, ", ".join(empty), len(eqs))
1269
+ raise ConversionError("texmath could not interpret %s: it is empty or holds only elements "
1270
+ "texmath does not support." % where)
1271
+
1272
+
1273
+ def _omml_docx(paras: List[str]) -> bytes:
1274
+ """A minimal .docx holding one paragraph per OMML fragment (pandoc reads OMML only inside a docx)."""
1275
+ document = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
1276
+ '<w:document xmlns:w="%s" xmlns:m="%s"><w:body>%s</w:body></w:document>') % (
1277
+ WML_NS, OMML_NS, "".join("<w:p>%s</w:p>" % p for p in paras))
1278
+ buf = io.BytesIO()
1279
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
1280
+ z.writestr("[Content_Types].xml", _DOCX_CONTENT_TYPES)
1281
+ z.writestr("_rels/.rels", _DOCX_RELS)
1282
+ z.writestr("word/document.xml", document)
1283
+ return buf.getvalue()
1284
+
1285
+
1286
+ def read_omml(text: str, tidy: bool = True) -> List[Equation]:
1287
+ """Equations in OMML; `tidy` as for :func:`read_mathml` (upright runs, function names, bold italic)."""
1288
+ if not text.strip():
1289
+ raise ConversionError("The input is empty.")
1290
+ fragments = _parse_omml_fragments(text)
1291
+ for f in fragments:
1292
+ f.tail = None # tostring() would copy the text that follows the element into the paragraph
1293
+ raw = [ET.tostring(f, encoding="unicode") for f in fragments]
1294
+ mappings: List[dict] = [{} for _ in fragments]
1295
+ paras = raw
1296
+ if tidy and _tidy.can_mark(text + "".join("".join(f.itertext()) for f in fragments)):
1297
+ count = 0
1298
+ for f, mapping in zip(fragments, mappings):
1299
+ _tidy.mark_omml(f, mapping, OMML_NS, count)
1300
+ count += len(mapping)
1301
+ paras = [ET.tostring(f, encoding="unicode") for f in fragments] # runs may have been split
1302
+ eqs = _read_json("docx", _omml_docx(paras))
1303
+ if not eqs:
1304
+ raise ConversionError("texmath could not interpret this OMML.")
1305
+ if any(mappings) and len(eqs) != len(fragments):
1306
+ eqs = _read_json("docx", _omml_docx(raw)) # equations and fragments cannot be paired: texmath's reading
1307
+ elif any(mappings):
1308
+ plain: Optional[List[Equation]] = None
1309
+ for i, (eq, mapping) in enumerate(zip(eqs, mappings)):
1310
+ if not mapping:
1311
+ continue
1312
+ tex = _tidy.restore(eq.tex, mapping)
1313
+ if tex is None or not _converts(tex, eq.display):
1314
+ if plain is None:
1315
+ plain = _read_json("docx", _omml_docx(raw))
1316
+ if len(plain) != len(eqs):
1317
+ eqs = plain # cannot be paired: texmath's own reading for all
1318
+ break
1319
+ tex = plain[i].tex
1320
+ eqs[i] = Equation(tex, eq.display)
1321
+ _check_not_empty(eqs, "OMML")
1322
+ return eqs
1323
+
1324
+
1325
+ def read_equations(text: str, fmt: str, default_display: bool = True, tidy: bool = True) -> List[Equation]:
1326
+ if fmt == "latex":
1327
+ return read_latex(text, default_display)
1328
+ if fmt == "mathml":
1329
+ return read_mathml(text, tidy=tidy)
1330
+ if fmt == "omml":
1331
+ return read_omml(text, tidy=tidy)
1332
+ raise ValueError("unknown input format %r" % fmt)
1333
+
1334
+
1335
+ # --- writing --------------------------------------------------------------------------
1336
+ def _math_para(eq: Equation) -> dict:
1337
+ mode = "DisplayMath" if eq.display else "InlineMath"
1338
+ return {"t": "Para", "c": [{"t": "Math", "c": [{"t": mode}, eq.tex]}]}
1339
+
1340
+
1341
+ def _doc_json(eq: Equation) -> bytes:
1342
+ doc = {"pandoc-api-version": _api(), "meta": {}, "blocks": [_math_para(eq)]}
1343
+ return json.dumps(doc).encode("utf-8")
1344
+
1345
+
1346
+ def _batch_json(eqs: List[Equation], boundary: Optional[dict] = None) -> bytes:
1347
+ blocks = []
1348
+ for i, eq in enumerate(eqs):
1349
+ body = [_math_para(eq)] if boundary is None else [boundary, _math_para(eq), boundary]
1350
+ blocks.append({"t": "Div", "c": [["mseq%d" % i, [], []], body]})
1351
+ doc = {"pandoc-api-version": _api(), "meta": {}, "blocks": blocks}
1352
+ return json.dumps(doc).encode("utf-8")
1353
+
1354
+
1355
+ def _pretty(el: ET.Element) -> str:
1356
+ if hasattr(ET, "indent"):
1357
+ ET.indent(el, space=" ")
1358
+ return ET.tostring(el, encoding="unicode")
1359
+
1360
+
1361
+ _MATH_RE = re.compile(r"<math[\s>][\s\S]*?</math>")
1362
+
1363
+
1364
+ _PAIRS = ("right", "left")
1365
+ _EQNARRAY = ["right", "center", "left"]
1366
+
1367
+
1368
+ def _table_shape(rows: List[ET.Element]) -> Optional[str]:
1369
+ """"pairs" for right/left cell pairs (align, aligned, split, alignat), "eqnarray" for eqnarray's
1370
+ right/center/left, None for anything else (matrix, cases, gather...). Rows may be short (a
1371
+ trailing \\\\, a line without &): only the cells they have must fit the pattern."""
1372
+ aligns = [[c.get("columnalign") for c in r] for r in rows]
1373
+ width = max(map(len, aligns))
1374
+ if width >= 2 and all(a == _PAIRS[i % 2] for row in aligns for i, a in enumerate(row)):
1375
+ return "pairs"
1376
+ if width == 3 and all(row == _EQNARRAY[:len(row)] for row in aligns):
1377
+ return "eqnarray"
1378
+ return None
1379
+
1380
+
1381
+ def _reads_as_alignment(rows: List[ET.Element], shape: str, ns: str) -> bool:
1382
+ """For a table that comes from `array`: True if its cells read like an aligned block - every
1383
+ right-hand cell (pairs) empty or starting with an operator or a space, every middle cell
1384
+ (eqnarray) empty or a relation, and at least one relation - rather than a table of values."""
1385
+ relations = 0
1386
+ for row in rows:
1387
+ cells = list(row)
1388
+ for cell in (cells[1::2] if shape == "pairs" else cells[1:2]):
1389
+ start = _cell_start(cell, ns)
1390
+ if start is None or (shape == "eqnarray" and start not in ("empty", "relation")):
1391
+ return False
1392
+ relations += start == "relation"
1393
+ return relations > 0
1394
+
1395
+
1396
+ def _office_equation_arrays(root: ET.Element, arrays: Optional[set] = frozenset()) -> None:
1397
+ """Mark aligned blocks so that Word / PowerPoint paste them as an equation array.
1398
+
1399
+ Office turns a pasted <mtable> into a matrix with centred columns - the = signs no longer line
1400
+ up - unless it has ``columnspacing="0em"``: that is how Word itself exports an equation array
1401
+ (right/left cell pairs, as texmath writes them, in a table without column gaps), and such a
1402
+ table becomes an <m:eqArr> aligned at the & points. Checked with Word / PowerPoint 16.
1403
+ Short rows are padded to the table's width and a trailing empty row (a final \\\\) is dropped.
1404
+ eqnarray's relation column is merged into the right-hand side (``a & = b``): as a third cell it
1405
+ would open a new alignment column.
1406
+
1407
+ `arrays` holds the indices (document order) of the tables that come from an `array`
1408
+ environment, None if unknown: such a table is marked only if it reads like an alignment.
1409
+ """
1410
+ ns = "{%s}" % MATHML_NS
1411
+ for index, table in enumerate(list(root.iter(ns + "mtable"))):
1412
+ if any(table.get(a, "none") != "none" for a in ("frame", "rowlines", "columnlines")):
1413
+ continue # an array with rules is not an alignment (texmath 0.13 writes none of these)
1414
+ rows = list(table)
1415
+ if not rows or any(r.tag != ns + "mtr" or any(c.tag != ns + "mtd" for c in r) for r in rows):
1416
+ continue # labelled rows (mlabeledtr) or other content
1417
+ shape = _table_shape(rows)
1418
+ if shape is None:
1419
+ continue
1420
+ if (arrays is None or index in arrays) and not _reads_as_alignment(rows, shape, ns):
1421
+ continue
1422
+ while len(rows) > 1 and all(_is_empty(c) for c in rows[-1]):
1423
+ table.remove(rows.pop())
1424
+ pattern = _EQNARRAY if shape == "eqnarray" else _PAIRS * ((max(len(r) for r in rows) + 1) // 2)
1425
+ for row in rows:
1426
+ for align in pattern[len(row):]:
1427
+ ET.SubElement(row, ns + "mtd", columnalign=align)
1428
+ if shape == "eqnarray":
1429
+ _, relation, rhs = list(row)
1430
+ rhs[:0] = list(relation)
1431
+ row.remove(relation)
1432
+ table.set("columnspacing", "0em")
1433
+
1434
+
1435
+ _ARRAY_BEGIN = re.compile(r"\\begin%s\{(?:array|subarray|darray)\}%s(?:\[[^\[\]]*\]%s)?\{" % ((_TEX_GAP,) * 3))
1436
+
1437
+
1438
+ def _centre_array_columns(tex: str) -> str:
1439
+ """`tex` with the l / r columns of every array environment made c (control words such as
1440
+ \\linewidth in the column spec are left alone)."""
1441
+ out, last = [], 0
1442
+ for m in _ARRAY_BEGIN.finditer(tex):
1443
+ depth, i = 1, m.end()
1444
+ while i < len(tex) and depth:
1445
+ depth += {"{": 1, "}": -1}.get(tex[i], 0)
1446
+ i += 1
1447
+ spec = re.sub(r"\\[a-zA-Z@]+|[lr]", lambda t: "c" if len(t.group()) == 1 else t.group(), tex[m.end():i])
1448
+ out.append(tex[last:m.end()] + spec)
1449
+ last = i
1450
+ return "".join(out) + tex[last:]
1451
+
1452
+
1453
+ def _array_tables(eq: Equation, root: ET.Element) -> Optional[set]:
1454
+ """Indices (document order) of the <mtable>s of `root` (texmath's MathML for `eq`) that come from
1455
+ an array environment, which texmath renders exactly like aligned: the TeX is converted once more
1456
+ with the arrays' columns centred, and the tables whose alignment changed are the arrays.
1457
+ None when that cannot be told."""
1458
+ if not _ARRAY_BEGIN.search(eq.tex):
1459
+ return set()
1460
+ try:
1461
+ centred = ET.fromstring(write_mathml(Equation(_centre_array_columns(eq.tex), eq.display)))
1462
+ except (ConversionError, ET.ParseError):
1463
+ return None
1464
+
1465
+ def alignments(tree):
1466
+ return [[[c.get("columnalign") for c in r] for r in t] for t in tree.iter("{%s}mtable" % MATHML_NS)]
1467
+
1468
+ before, after = alignments(root), alignments(centred)
1469
+ if len(before) != len(after):
1470
+ return None
1471
+ return {i for i, (a, b) in enumerate(zip(before, after)) if a != b}
1472
+
1473
+
1474
+ def write_mathml(eq: Equation, annotate: bool = False, for_office: bool = False,
1475
+ source: Optional[str] = None) -> str:
1476
+ """MathML for the equation. With `annotate`, the TeX source is kept in a <semantics>/<annotation>
1477
+ (`source` when given: the user's TeX, if `eq` holds a rewritten version of it); `for_office` shapes
1478
+ aligned blocks for Word / PowerPoint (see `_office_equation_arrays`)."""
1479
+ out, err = _run(["-f", "json", "-t", "html", _LF, *_mathml_flags()], _doc_json(eq))
1480
+ _check_texmath_warning(err)
1481
+ m = _MATH_RE.search(out.decode("utf-8"))
1482
+ if not m:
1483
+ raise ConversionError("pandoc produced no MathML:\n" + err.strip())
1484
+ root = ET.fromstring(m.group(0))
1485
+ return _format_mathml(root, eq, annotate, for_office, source)
1486
+
1487
+
1488
+ def _format_mathml(root: ET.Element, eq: Equation, annotate: bool = False, for_office: bool = False,
1489
+ source: Optional[str] = None) -> str:
1490
+ sem = root.find("{%s}semantics" % MATHML_NS)
1491
+ if sem is not None and not annotate:
1492
+ root.remove(sem)
1493
+ for child in list(sem):
1494
+ if child.tag != "{%s}annotation" % MATHML_NS:
1495
+ root.append(child)
1496
+ elif sem is not None and source is not None:
1497
+ for ann in sem.findall("{%s}annotation" % MATHML_NS):
1498
+ ann.text = source
1499
+ if for_office:
1500
+ _office_equation_arrays(root, _array_tables(eq, root))
1501
+ _office_spaces(root)
1502
+ _office_commas(root)
1503
+ return _pretty(root)
1504
+
1505
+
1506
+ # Word's MathML import makes a comma or semicolon between brackets a separator of one delimiter with one
1507
+ # separator character, and gets nested ones wrong: max(cos(a,b),0) came out max(cos,(a,b)0) and
1508
+ # q(x;mu,sigma) as q(x;mu;sigma) (Word 16.0.20527). It follows separator="false", and the content stays.
1509
+ def _office_commas(root: ET.Element) -> None:
1510
+ for el in root.iter("{%s}mo" % MATHML_NS):
1511
+ if (el.text or "").strip() in (",", ";") and el.get("separator") is None:
1512
+ el.set("separator", "false")
1513
+
1514
+
1515
+ # Word's MathML import turns every <mspace> into one no-break space (\quad as narrow as \,), but keeps the
1516
+ # Unicode spaces Office's own \thinsp, \medsp, \thicksp, \emsp give; read back by width (_unicode_spaces)
1517
+ _SPACE_CHARS = [(1.0, " "), (0.5, " "), (0.333, " "), (0.278, " "), (0.222, " "),
1518
+ (0.167, " ")]
1519
+ _SPACE_WIDTHS = {" ": 1.0, " ": 0.5, " ": 0.333, " ": 0.278, " ": 0.222,
1520
+ " ": 0.167, " ": 0.167}
1521
+
1522
+
1523
+ # elements whose children are arguments in place (base, script...): a child is never just removed
1524
+ _FIXED_ARITY = frozenset("msub msup msubsup munder mover munderover mfrac mroot mmultiscripts".split())
1525
+
1526
+
1527
+ def _office_spaces(root: ET.Element) -> None:
1528
+ """<mspace width="1.0em"/> -> <mo>U+2003</mo> (and so on) for Word / PowerPoint; a negative space,
1529
+ which Office cannot show, is left out (Word would make it a positive one): an empty <mrow/> where it
1530
+ is an argument (\\!^{-x} is a script on the space: e\\!^{-x})."""
1531
+ for parent in list(root.iter()):
1532
+ for child in list(parent):
1533
+ if child.tag != "{%s}mspace" % MATHML_NS:
1534
+ continue
1535
+ m = re.fullmatch(r"\s*(-?\d*\.?\d+)\s*em\s*", child.get("width") or "")
1536
+ if not m:
1537
+ continue
1538
+ width, chars = float(m.group(1)), ""
1539
+ if width > 0:
1540
+ chars = " " * int(width + 0.02)
1541
+ rest = width - int(width + 0.02)
1542
+ if rest > 0.08:
1543
+ chars += min(_SPACE_CHARS, key=lambda wc: abs(wc[0] - rest))[1]
1544
+ if not chars:
1545
+ if _local(parent.tag) in _FIXED_ARITY:
1546
+ empty = ET.Element("{%s}mrow" % MATHML_NS)
1547
+ empty.tail = child.tail
1548
+ parent[list(parent).index(child)] = empty
1549
+ else:
1550
+ parent.remove(child)
1551
+ continue
1552
+ mo = ET.Element("{%s}mo" % MATHML_NS)
1553
+ mo.text, mo.tail = chars, child.tail
1554
+ parent[list(parent).index(child)] = mo
1555
+
1556
+
1557
+ def _unicode_spaces(math: ET.Element) -> None:
1558
+ """<mo> / <mtext> holding only Unicode spaces (what Office keeps, see _office_spaces) -> <mspace> of
1559
+ their width, which texmath reads as \\, \\; \\quad \\qquad... (namespaces already stripped)."""
1560
+ converted = set()
1561
+ for el in math.iter():
1562
+ if el.tag in ("mo", "mtext") and el.text and len(el) == 0 and all(c in _SPACE_WIDTHS for c in el.text):
1563
+ width = sum(_SPACE_WIDTHS[c] for c in el.text)
1564
+ el.tag, el.text = "mspace", None
1565
+ el.attrib.clear()
1566
+ el.set("width", ("%.3f" % width).rstrip("0").rstrip(".") + "em")
1567
+ converted.add(el)
1568
+ # Word writes \qquad's two em spaces as two elements: one space of their width (\qquad, not \quad\quad);
1569
+ # only em spaces in a row of a sequence (spaces MathML writes itself, \ \ for instance, stay as they
1570
+ # are, and so do a \quad\, and the arguments of a fraction or script, each a space of its own)
1571
+ for parent in math.iter():
1572
+ if parent.tag in _FIXED_ARITY:
1573
+ continue
1574
+ children = list(parent)
1575
+ for a, b in zip(children, children[1:]):
1576
+ if a in converted and b in converted and a in list(parent):
1577
+ wa = re.fullmatch(r"(\d+)em", a.get("width") or "")
1578
+ if wa and int(wa.group(1)) >= 1 and b.get("width") == "1em":
1579
+ b.set("width", "%dem" % (int(wa.group(1)) + 1))
1580
+ parent.remove(a)
1581
+
1582
+
1583
+ def _batch_mathml(eqs: List[Equation]) -> List[Optional[ET.Element]]:
1584
+ if not eqs:
1585
+ return []
1586
+ out, _ = _run(["-f", "json", "-t", "html", _LF, *_mathml_flags()], _batch_json(eqs))
1587
+ results: List[Optional[ET.Element]] = [None] * len(eqs)
1588
+ for div in re.finditer(r'<div id="mseq(\d+)">(.*?)</div>', out.decode("utf-8"), re.S):
1589
+ i, found = int(div.group(1)), _MATH_RE.search(div.group(2))
1590
+ if found and i < len(eqs):
1591
+ try:
1592
+ results[i] = ET.fromstring(found.group(0))
1593
+ except ET.ParseError:
1594
+ pass
1595
+ return results
1596
+
1597
+
1598
+ def mathml_elements(eqs: List[Equation]) -> List[Optional[ET.Element]]:
1599
+ """Each equation as a parsed <math> (texmath's MathML, namespaces stripped), in one pandoc run; None
1600
+ for an equation texmath cannot write. For comparing renderings (convert.annotation_notes)."""
1601
+ results = _batch_mathml(eqs)
1602
+ for root in results:
1603
+ if root is not None:
1604
+ _strip_namespaces(root)
1605
+ _drop_annotations(root)
1606
+ return results
1607
+
1608
+
1609
+ def readable_mathml(maths: List[ET.Element]) -> List[bool]:
1610
+ """Whether texmath can read each parsed <math> (:func:`parse_mathml`, annotations dropped): one
1611
+ pandoc run when it reads them all, else one each (pandoc turns a <math> it rejects into text)."""
1612
+ raw = [_serialize_math(copy.deepcopy(m)) for m in maths]
1613
+ if not raw:
1614
+ return []
1615
+ if len(_read_json("html", b"".join(raw))) == len(raw):
1616
+ return [True] * len(raw)
1617
+ return [bool(_read_json("html", r)) for r in raw]
1618
+
1619
+
1620
+ def write_omml(eq: Equation) -> str:
1621
+ out, err = _run(["-f", "json", "-t", "docx", "-o", "-"], _doc_json(eq))
1622
+ _check_texmath_warning(err)
1623
+ text = _omml_body(_word_document(out))
1624
+ if text is not None:
1625
+ return text
1626
+ raise ConversionError("pandoc produced no OMML:\n" + err.strip())
1627
+
1628
+
1629
+ def _word_document(out: bytes) -> ET.Element:
1630
+ with zipfile.ZipFile(io.BytesIO(out)) as z:
1631
+ return ET.fromstring(z.read("word/document.xml"))
1632
+
1633
+
1634
+ def _omml_body(paragraph: ET.Element) -> Optional[str]:
1635
+ for el in paragraph.iter():
1636
+ if el.tag in ("{%s}oMathPara" % OMML_NS, "{%s}oMath" % OMML_NS):
1637
+ return _pretty(el)
1638
+ return None
1639
+
1640
+
1641
+ def write_eqn(eq: Equation) -> str:
1642
+ """groff eqn source (body only, without the .EQ/.EN macros)."""
1643
+ out, err = _run(["-f", "json", "-t", "ms", _LF], _doc_json(eq))
1644
+ _check_texmath_warning(err)
1645
+ body = _eqn_body(out.decode("utf-8"), eq.display)
1646
+ if body is None:
1647
+ raise ConversionError("pandoc produced no eqn output:\n" + err.strip())
1648
+ return body
1649
+
1650
+
1651
+ def _eqn_body(text: str, display: bool) -> Optional[str]:
1652
+ if display:
1653
+ m = re.search(r"^\.EQ\n([\s\S]*?)\n\.EN", text, re.M)
1654
+ if m:
1655
+ return m.group(1)
1656
+ lines = [ln for ln in text.splitlines() if not ln.startswith(".")]
1657
+ body = "\n".join(lines).strip()
1658
+ if body.startswith("@") and body.endswith("@"):
1659
+ body = body[1:-1]
1660
+ return body or None
1661
+
1662
+
1663
+ # pandoc writes a \label as a Typst label after the closing $: $ x = 1 $<eq:a>, or, when the name is not
1664
+ # valid label syntax (eq/loss, eq(1), a space...): $ x = 1 $#label("eq/loss")
1665
+ _TYPST_MATH = re.compile(r'^\$([\s\S]*)\$\s*(?:<[^<>\s]+>|#label\("(?:[^"\\]|\\.)*"\))?$')
1666
+
1667
+
1668
+ def write_typst(eq: Equation) -> str:
1669
+ """Typst math (body only, without the $ delimiters or a trailing <label>)."""
1670
+ out, err = _run(["-f", "json", "-t", "typst", _LF], _doc_json(eq))
1671
+ _check_texmath_warning(err)
1672
+ text = _typst_body(out.decode("utf-8"))
1673
+ if not text:
1674
+ raise ConversionError("pandoc produced no Typst output:\n" + err.strip())
1675
+ return text
1676
+
1677
+
1678
+ def _typst_body(text: str) -> str:
1679
+ text = text.strip()
1680
+ m = _TYPST_MATH.match(text)
1681
+ if m:
1682
+ text = m.group(1).strip()
1683
+ return text
1684
+
1685
+
1686
+ def write_equations(eqs: List[Equation], fmt: str) -> List[Optional[str]]:
1687
+ """Write a batch of prepared equations. A missing result needs the single-equation diagnostic."""
1688
+ if not eqs:
1689
+ return []
1690
+ if fmt == "mathml":
1691
+ return [_format_mathml(root, eq) if root is not None else None
1692
+ for eq, root in zip(eqs, _batch_mathml(eqs))]
1693
+ if fmt == "omml":
1694
+ out, _ = _run(["-f", "json", "-t", "docx", "-o", "-"], _batch_json(eqs))
1695
+ # Each Div contains exactly one paragraph, including when pandoc writes fallback TeX.
1696
+ paragraphs = _word_document(out).findall("w:body/w:p", {"w": WML_NS})
1697
+ if len(paragraphs) != len(eqs):
1698
+ return [None] * len(eqs)
1699
+ return [_omml_body(p) for p in paragraphs]
1700
+ writer = {"typst": "typst", "eqn": "ms"}[fmt]
1701
+ # ms drops Div identifiers, and Typst adds its own #block wrapper. Raw blocks delimit the
1702
+ # exact writer output for the paragraph, including embedded newlines and labels.
1703
+ marker = "MathShuttle" + uuid.uuid4().hex
1704
+ doc = _batch_json(eqs, {"t": "RawBlock", "c": [writer, marker]})
1705
+ out, _ = _run(["-f", "json", "-t", writer, _LF], doc)
1706
+ parts = out.decode("utf-8").split(marker)
1707
+ if len(parts) != 2 * len(eqs) + 1:
1708
+ return [None] * len(eqs)
1709
+ results = []
1710
+ for eq, text in zip(eqs, parts[1::2]):
1711
+ if fmt == "typst":
1712
+ # A rejected equation begins with an escaped dollar sign, a converted one with $.
1713
+ body = (_typst_body(text) or None) if text.lstrip().startswith("$") else None
1714
+ else:
1715
+ # Fallback TeX uses dollar signs here too. Converted maths uses .EQ or @...@.
1716
+ math = re.match(r"\s*(?:\.(?:LP|PP)\n)?(?:\.EQ\n|@)", text)
1717
+ body = _eqn_body(text, eq.display) if math else None
1718
+ results.append(body)
1719
+ return results
1720
+
1721
+
1722
+ def write_equation(eq: Equation, fmt: str, **opts) -> str:
1723
+ if fmt == "mathml":
1724
+ return write_mathml(eq, annotate=opts.get("annotate", False), for_office=opts.get("for_office", False),
1725
+ source=opts.get("source"))
1726
+ if fmt == "omml":
1727
+ return write_omml(eq)
1728
+ if fmt == "eqn":
1729
+ return write_eqn(eq)
1730
+ if fmt == "typst":
1731
+ return write_typst(eq)
1732
+ raise ValueError("unknown output format %r" % fmt)