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/compat.py ADDED
@@ -0,0 +1,1537 @@
1
+ """LaTeX that texmath does not take, rewritten into LaTeX it does - for conversions *out of* LaTeX.
2
+
3
+ texmath (inside pandoc) implements amsmath and a few packages, but real papers also use
4
+ plain-TeX font switches (``{\\rm OOD}``, ``\\cal L``), commands from other packages
5
+ (``\\notag``, ``\\mathbbm``, ``\\smash``, ``dcases``...) and their own macros. :func:`for_texmath`
6
+
7
+ 1. expands the macros an equation uses - its own definitions and those from the user's macro
8
+ files (:class:`Macros`) - with pandoc's LaTeX reader, which implements ``\\def`` (also with
9
+ delimited parameters), ``\\let``, ``\\newcommand`` with defaults and ``\\DeclareMathOperator``
10
+ like TeX does; ``\\DeclarePairedDelimiter`` is expanded here (pandoc does not know it);
11
+ 2. rewrites what is left into constructs texmath parses.
12
+
13
+ LaTeX output can write out the macros alone, with :func:`expand_macros`.
14
+ Rewrites that lose something (a colour, a strut) are reported as notes.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import re
20
+ from dataclasses import dataclass
21
+ from typing import AbstractSet, Dict, List, Optional, Sequence, Tuple
22
+
23
+ # a control word, a control symbol, a comment, a brace, &, $; \begin / \end with their argument
24
+ _TOKEN = re.compile(r"\\(?P<be>begin|end)\s*\{(?P<env>[^{}]*)\}|\\[a-zA-Z@]+|\\.|%[^\n]*|[{}&$]", re.S)
25
+ _CS = r"(?![a-zA-Z@])" # end of a control word
26
+ _GAP = re.compile(r"(?:\s|%[^\n]*(?:\n|$))*") # what TeX skips before an argument: spaces and comments
27
+
28
+ # commands whose argument is text: nothing is rewritten inside it (but in maths nested in it)
29
+ _TEXT_ARG = frozenset(
30
+ "\\text \\mbox \\hbox \\makebox \\fbox \\framebox \\textrm \\textit \\textbf \\textsf \\texttt \\textnormal "
31
+ "\\textup \\textsl \\textsc \\textmd \\emph \\label \\tag \\ref \\eqref \\operatorname \\DeclareMathOperator".split())
32
+ _VERBATIM_ARG = frozenset("\\label \\tag \\ref \\eqref \\operatorname \\DeclareMathOperator".split())
33
+
34
+ # plain-TeX font switches (scope: the rest of the group) -> the LaTeX command taking an argument
35
+ _SWITCHES = {"\\rm": "\\mathrm", "\\bf": "\\mathbf", "\\it": "\\mathit", "\\sl": "\\mathit", "\\sf": "\\mathsf",
36
+ "\\tt": "\\mathtt", "\\cal": "\\mathcal"}
37
+ # where the scope of a switch ends at the current group level ($: the end of maths nested in text)
38
+ _SCOPE_ENDS = frozenset(("&", "\\\\", "\\cr", "\\right", "\\middle", "$", "\\)"))
39
+
40
+ # exact or near-exact equivalents (renamed in place)
41
+ _RENAMES = {"\\notag": "\\nonumber", "\\mathbbm": "\\mathbb", "\\mathbbmss": "\\mathbb", "\\Bbb": "\\mathbb",
42
+ "\\frak": "\\mathfrak", "\\textup": "\\textrm", "\\textsc": "\\textrm", "\\hbox": "\\mbox",
43
+ "\\hphantom": "\\phantom"}
44
+ # symbols texmath 0.13 writes as the wrong character: \| as U+2225 PARALLEL TO (not U+2016, a norm),
45
+ # \setminus and \backslash swapped (a backslash and U+2216), \varnothing as U+2300 DIAMETER SIGN.
46
+ # One pass: \backslash -> \setminus is not renamed again.
47
+ _SYMBOLS = {"\\|": "\\Vert", "\\setminus": "\\smallsetminus", "\\backslash": "\\setminus",
48
+ "\\varnothing": "\\emptyset"}
49
+ # texmath reads these Unicode operators correctly but emits different glyphs for their commands.
50
+ _OFFICE_SYMBOLS = {
51
+ "\\leqslant": "⩽", "\\geqslant": "⩾", "\\amalg": "⨿",
52
+ "\\longleftarrow": "⟵", "\\longrightarrow": "⟶", "\\longleftrightarrow": "⟷",
53
+ "\\Longleftarrow": "⟸", "\\Longrightarrow": "⟹", "\\Longleftrightarrow": "⟺",
54
+ "\\longmapsto": "⟼", "\\iff": "⟺",
55
+ # Unsized norm bars also need the right character, with their original opening / closing class.
56
+ "\\lVert": "\\mathopen{\\Vert}", "\\rVert": "\\mathclose{\\Vert}",
57
+ }
58
+ # same maths, different size: renamed, with a note
59
+ _RESIZED = {"\\tbinom": "\\binom", "\\dbinom": "\\binom", "\\nicefrac": "\\tfrac"}
60
+ # commands that only adjust the layout: \cmd[opt]{x} -> {x}; value: how many [options] the command takes
61
+ _UNWRAP = {"\\smash": 1, "\\mathclap": 0, "\\mathllap": 0, "\\mathrlap": 0, "\\clap": 0, "\\llap": 0, "\\rlap": 0}
62
+ # struts: dropped with their argument (an empty group stays, so that \sin\vphantom{x}h is no \sinh)
63
+ _DROP_WITH_ARG = ("\\vphantom",)
64
+ _DROP = ("\\mathstrut", "\\strut")
65
+ # environments: name -> (texmath environment, opening extra, closing extra)
66
+ _ENVS = {"dcases": ("cases", "", ""), "rcases": ("array}{ll", "\\left.", "\\right\\}"),
67
+ "drcases": ("array}{ll", "\\left.", "\\right\\}"),
68
+ "matrix*": ("matrix", "", ""), "pmatrix*": ("pmatrix", "", ""), "bmatrix*": ("bmatrix", "", ""),
69
+ "Bmatrix*": ("Bmatrix", "", ""), "vmatrix*": ("vmatrix", "", ""), "Vmatrix*": ("Vmatrix", "", ""),
70
+ "smallmatrix*": ("smallmatrix", "", "")}
71
+ # mathtools' starred cases: the second column is text (with $...$ for maths)
72
+ _STARRED_CASES = {"cases*": ("cases", "", ""), "dcases*": ("cases", "", ""),
73
+ "rcases*": ("array}{ll", "\\left.", "\\right\\}"), "drcases*": ("array}{ll", "\\left.", "\\right\\}")}
74
+ STARRED_CASES = frozenset(_STARRED_CASES)
75
+
76
+
77
+ def _group_end(tex: str, start: int) -> int:
78
+ """Index just after the brace group opening at `start` (``tex[start] == "{"``); -1 if it is not closed."""
79
+ depth = 0
80
+ for m in _TOKEN.finditer(tex, start):
81
+ tok = m.group()
82
+ if tok == "{":
83
+ depth += 1
84
+ elif tok == "}":
85
+ depth -= 1
86
+ if not depth:
87
+ return m.end()
88
+ return -1
89
+
90
+
91
+ def _bracket_end(tex: str, start: int) -> int:
92
+ """Index just after the [option] opening at `start`; braces protect brackets (``[{[x]}]``). -1 if open."""
93
+ depth = 0
94
+ i = start + 1
95
+ while i < len(tex):
96
+ ch = tex[i]
97
+ if ch == "\\":
98
+ i += 2
99
+ continue
100
+ if ch == "{":
101
+ depth += 1
102
+ elif ch == "}":
103
+ depth -= 1
104
+ elif ch == "]" and depth <= 0:
105
+ return i + 1
106
+ i += 1
107
+ return -1
108
+
109
+
110
+ def _argument(tex: str, pos: int) -> Tuple[int, int]:
111
+ """(start, end) of the TeX argument at `pos` (after spaces and comments): a brace group, a control
112
+ sequence or one character. (pos, pos) if there is none."""
113
+ i = _GAP.match(tex, pos).end()
114
+ if i >= len(tex) or tex[i] == "}":
115
+ return pos, pos
116
+ if tex[i] == "{":
117
+ end = _group_end(tex, i)
118
+ return i, end if end > 0 else len(tex)
119
+ t = _TOKEN.match(tex, i)
120
+ return i, t.end() if t and t.start() == i else i + 1
121
+
122
+
123
+ def _optional(tex: str, pos: int, count: int = 1) -> int:
124
+ """End of at most `count` [options] at `pos` (after spaces and comments), or `pos`."""
125
+ end = pos
126
+ for _ in range(count):
127
+ i = _GAP.match(tex, end).end()
128
+ if tex[i:i + 1] != "[":
129
+ break
130
+ j = _bracket_end(tex, i)
131
+ if j < 0:
132
+ break
133
+ end = j
134
+ return end
135
+
136
+
137
+ def _unbrace(arg: str) -> str:
138
+ """An argument without its one outer brace pair: ``{\\{}`` -> ``\\{``."""
139
+ arg = arg.strip()
140
+ return arg[1:-1] if arg.startswith("{") and _group_end(arg, 0) == len(arg) else arg
141
+
142
+
143
+ def _maths_in(text: str, start: int, end: int) -> List[Tuple[int, int]]:
144
+ """$...$ and \\(...\\) inside the text tex[start:end] (maths nested in a \\text argument)."""
145
+ spans = []
146
+ for m in re.finditer(r"(?<!\\)\$(?:\\.|[^$\\])*\$|\\\((?:\\.|[^\\])*?\\\)", text[start:end]):
147
+ spans.append((start + m.start(), start + m.end()))
148
+ return spans
149
+
150
+
151
+ def _text_spans(tex: str) -> List[Tuple[int, int]]:
152
+ """The text parts of the arguments of text commands (\\text{..}, \\label{..}...), where nothing is
153
+ rewritten - without maths nested in them (``\\text{for $\\rm x$}``)."""
154
+ spans = []
155
+ for m in _TOKEN.finditer(tex):
156
+ if m.group() in _TEXT_ARG:
157
+ start, end = _argument(tex, _optional(tex, m.end(), 3))
158
+ if end <= start:
159
+ continue
160
+ maths = [] if m.group() in _VERBATIM_ARG else _maths_in(tex, start, end)
161
+ last = start
162
+ for a, b in maths:
163
+ spans.append((last, a))
164
+ last = b
165
+ spans.append((last, end))
166
+ return spans
167
+
168
+
169
+ def _in(spans: List[Tuple[int, int]], pos: int) -> bool:
170
+ return any(a <= pos < b for a, b in spans)
171
+
172
+
173
+ def _find(tex: str, pattern: "re.Pattern", start: int = 0):
174
+ """The first match of `pattern` at a token boundary, outside comments and text."""
175
+ spans = _text_spans(tex)
176
+ for m in _TOKEN.finditer(tex, start):
177
+ if m.group().startswith("%") or _in(spans, m.start()):
178
+ continue
179
+ hit = pattern.match(tex, m.start())
180
+ if hit:
181
+ return hit
182
+ return None
183
+
184
+
185
+ def _scope_end(tex: str, pos: int) -> int:
186
+ """Where the scope of a font switch ending at `pos` ends: the close of the current group,
187
+ the next & or \\\\ of the current level, \\right, \\end{...}, the end of nested maths, or the end."""
188
+ depth = 0
189
+ for m in _TOKEN.finditer(tex, pos):
190
+ tok = m.group()
191
+ if tok.startswith("%"):
192
+ continue
193
+ if tok == "{" or m.group("be") == "begin" or tok == "\\left":
194
+ depth += 1
195
+ elif tok == "}" or m.group("be") == "end" or tok == "\\right":
196
+ if not depth:
197
+ return m.start()
198
+ depth -= 1
199
+ elif not depth and tok in _SCOPE_ENDS:
200
+ return m.start()
201
+ return len(tex)
202
+
203
+
204
+ _SWITCH_RE = re.compile(r"(%s)%s" % ("|".join(re.escape(s) for s in _SWITCHES), _CS))
205
+
206
+
207
+ def _switches_in_text(tex: str) -> str:
208
+ """Inside text (``\\text{for {\\rm all}}``) a switch is a text font change that texmath does not
209
+ parse: dropped (Office shows that text upright anyway)."""
210
+ spans = _text_spans(tex)
211
+ if not spans:
212
+ return tex
213
+ out, last = [], 0
214
+ for m in _SWITCH_RE.finditer(tex):
215
+ if _in(spans, m.start()):
216
+ out.append(tex[last:m.start()])
217
+ last = m.end()
218
+ if tex[last:last + 1] == " ":
219
+ last += 1
220
+ return "".join(out) + tex[last:]
221
+
222
+
223
+ def _font_switches(tex: str) -> str:
224
+ """``{\\rm OOD}`` -> ``{\\mathrm{OOD}}``, ``\\rm{x}`` -> ``\\mathrm{x}``, ``\\cal L`` -> ``\\mathcal{L}``."""
225
+ tex = _switches_in_text(tex)
226
+ pos = 0
227
+ while True:
228
+ m = _find(tex, _SWITCH_RE, pos)
229
+ if not m:
230
+ return tex
231
+ end = _scope_end(tex, m.end())
232
+ scope = tex[m.end():end]
233
+ # a comment in the scope would swallow the closing brace: TeX ignores it anyway
234
+ body = re.sub(r"(?<!\\)%[^\n]*", "", scope).strip()
235
+ if body.startswith("{") and _group_end(body, 0) == len(body):
236
+ body = body[1:-1] # \rm{OOD}: the group is the whole scope
237
+ new = "%s{%s}" % (_SWITCHES[m.group(1)], body) + scope[len(scope.rstrip()):] if body else ""
238
+ tex = tex[:m.start()] + new + tex[end:]
239
+ pos = m.start() + (len(_SWITCHES[m.group(1)]) + 1 if new else 0) # nested switches inside the new group
240
+
241
+
242
+ def _bold_upright(tex: str) -> str:
243
+ """``\\mathbf{x}`` -> 𝐱: texmath 0.13 writes \\mathbf on a Latin letter as bold *italic* MathML /
244
+ OMML, while LaTeX sets it upright; given the bold character itself it writes ``<mi>𝐱</mi>``,
245
+ which is also what Word exports for a bold upright letter. Only for an argument of letters, digits
246
+ and operators (``\\mathbf{x+y}``: as in LaTeX, the operators stay as they are)."""
247
+ pattern = re.compile(r"\\mathbf" + _CS)
248
+ pos = 0
249
+ while True:
250
+ m = _find(tex, pattern, pos)
251
+ if not m:
252
+ return tex
253
+ start, end = _argument(tex, m.end())
254
+ inner = _unbrace(tex[start:end])
255
+ if not re.fullmatch(r"[A-Za-z0-9 +\-=<>,.;:!?'()\[\]/|*]*", inner) or not re.search(r"[A-Za-z0-9]", inner):
256
+ pos = m.end()
257
+ continue
258
+ bold = "".join(_BOLD.get(ch, ch) for ch in inner)
259
+ tex = tex[:m.start()] + "{%s}" % bold + tex[end:]
260
+ pos = m.start() + len(bold) + 2
261
+
262
+
263
+ _BOLD = {**{chr(ord("A") + i): chr(0x1D400 + i) for i in range(26)},
264
+ **{chr(ord("a") + i): chr(0x1D41A + i) for i in range(26)},
265
+ **{chr(ord("0") + i): chr(0x1D7CE + i) for i in range(10)}}
266
+
267
+
268
+ def _rename(tex: str, table: Dict[str, str], hits: List[str]) -> str:
269
+ # a control word ends at a non-letter; a control symbol (\|) at once
270
+ pattern = re.compile(r"(%s)" % "|".join(re.escape(k) + (_CS if k[1:].isalpha() else "") for k in table))
271
+ pos = 0
272
+ while True:
273
+ m = _find(tex, pattern, pos)
274
+ if not m:
275
+ return tex
276
+ hits.append(m.group(1))
277
+ new = table[m.group(1)]
278
+ if new[-1:].isalpha() and re.match(r"[a-zA-Z@#]", tex[m.end():m.end() + 1]):
279
+ new += " " # \|g -> \Vert g, \|#1 -> \Vert #1: not the control words \Vertg, \Vert#1...
280
+ tex = tex[:m.start()] + new + tex[m.end():]
281
+ pos = m.start() + len(new)
282
+
283
+
284
+ _SIZED_NORM = re.compile(r"(\\(?:left|right|middle|[bB]igg?[lrm]?)" + _CS + _GAP.pattern + r")\\[lr]Vert" + _CS)
285
+
286
+
287
+ def _sized_norms(tex: str) -> str:
288
+ """texmath 0.13 writes a sized \\lVert / \\rVert (\\left\\lVert, \\middle\\lVert, \\bigr\\rVert...) as
289
+ U+2225 PARALLEL TO, not the norm bar U+2016 that it writes for \\Vert there.
290
+ With \\bigl and the like, texmath then writes the bars as plain symbols rather than a delimiter pair,
291
+ as it already did for \\bigl\\| (the size is fixed there anyway)."""
292
+ pos = 0
293
+ while True:
294
+ m = _find(tex, _SIZED_NORM, pos)
295
+ if not m:
296
+ return tex
297
+ new = m.group(1) + "\\Vert"
298
+ tex = tex[:m.start()] + new + tex[m.end():]
299
+ pos = m.start() + len(new)
300
+
301
+
302
+ def _commands(tex: str, names, how: str, hits: List[str]) -> str:
303
+ """`how`: "unwrap" (\\cmd[opt]{x} -> {x}; `names` maps each to its number of options), "drop_arg"
304
+ (\\cmd{x} -> {}), "drop" (\\cmd -> {}). The empty group keeps the atoms around apart."""
305
+ pattern = re.compile(r"(%s)%s" % ("|".join(re.escape(k) for k in names), _CS))
306
+ pos = 0
307
+ while True:
308
+ m = _find(tex, pattern, pos)
309
+ if not m:
310
+ return tex
311
+ hits.append(m.group(1))
312
+ if how == "drop":
313
+ new, end = "{}", m.end()
314
+ else:
315
+ options = names[m.group(1)] if isinstance(names, dict) else 0
316
+ start, end = _argument(tex, _optional(tex, m.end(), options))
317
+ new = "{}" if how == "drop_arg" else "{%s}" % _unbrace(tex[start:end])
318
+ tex = tex[:m.start()] + new + tex[end:]
319
+ pos = m.start() + (2 if how != "unwrap" else 0)
320
+
321
+
322
+ def _textcolor(tex: str, hits: List[str]) -> str:
323
+ """\\textcolor[model]{c}{x} -> {\\color{c}x} (texmath reads \\color and drops the colour)."""
324
+ pattern = re.compile(r"\\textcolor" + _CS)
325
+ while True:
326
+ m = _find(tex, pattern)
327
+ if not m:
328
+ return tex
329
+ hits.append("\\textcolor")
330
+ c0, c1 = _argument(tex, _optional(tex, m.end(), 1))
331
+ a0, a1 = _argument(tex, c1)
332
+ tex = tex[:m.start()] + "{\\color{%s} %s}" % (_unbrace(tex[c0:c1]), tex[a0:a1]) + tex[a1:]
333
+
334
+
335
+ def _env_end(tex: str, pos: int, env: str) -> Tuple[int, int]:
336
+ depth = 1
337
+ for m in _TOKEN.finditer(tex, pos):
338
+ if m.group("be") and m.group("env") == env:
339
+ depth += 1 if m.group("be") == "begin" else -1
340
+ if not depth:
341
+ return m.start(), m.end()
342
+ return -1, -1
343
+
344
+
345
+ def _split_top(body: str, separators: Tuple[str, ...]) -> List[str]:
346
+ """`body` split at its own (not nested) separators: & / \\\\."""
347
+ parts, start, depth = [], 0, 0
348
+ for m in _TOKEN.finditer(body):
349
+ tok = m.group()
350
+ if tok == "{" or m.group("be") == "begin":
351
+ depth += 1
352
+ elif tok == "}" or m.group("be") == "end":
353
+ depth -= 1
354
+ elif not depth and tok in separators:
355
+ parts.append(body[start:m.start()])
356
+ start = m.end()
357
+ parts.append(body[start:])
358
+ return parts
359
+
360
+
361
+ def _text_cell(cell: str) -> str:
362
+ """A text column cell of starred cases (``if $x>0$``) as maths: ``\\text{if }{x>0}``. Only the $ of
363
+ the cell itself switch to maths (not those inside ``\\textbf{if $x$}``); comments are dropped."""
364
+ cell = re.sub(r"(?<!\\)%[^\n]*\n?", "", cell)
365
+ stripped = cell.strip()
366
+ m = re.match(r"\\(?:text[a-z]*|mbox|emph)\s*\{", stripped)
367
+ if m and _group_end(stripped, m.end() - 1) == len(stripped):
368
+ return stripped # one text command already: texmath reads it with the maths inside
369
+ cuts, depth = [], 0
370
+ for t in _TOKEN.finditer(cell):
371
+ tok = t.group()
372
+ if tok == "{":
373
+ depth += 1
374
+ elif tok == "}":
375
+ depth -= 1
376
+ elif tok == "$" and not depth:
377
+ cuts.append(t.start())
378
+ if len(cuts) % 2:
379
+ cuts.pop() # an unmatched $ stays text
380
+ out, last = [], 0
381
+ for i in range(0, len(cuts), 2):
382
+ if cell[last:cuts[i]]:
383
+ out.append("\\text{%s}" % cell[last:cuts[i]])
384
+ out.append("{%s}" % cell[cuts[i] + 1:cuts[i + 1]]) # a group: $\alpha$ $b$ is no \alphab
385
+ last = cuts[i + 1] + 1
386
+ if cell[last:].strip() or not out:
387
+ out.append("\\text{%s}" % (cell[last:] if out else cell.strip()))
388
+ return "".join(out)
389
+
390
+
391
+ def _environments(tex: str, hits: List[str]) -> str:
392
+ # starred cases: rewrite their text column first
393
+ for env, (name, before, after) in _STARRED_CASES.items():
394
+ while True:
395
+ m = re.search(r"\\begin\s*\{%s\}" % re.escape(env), tex)
396
+ if not m:
397
+ break
398
+ end, end2 = _env_end(tex, m.end(), env)
399
+ if end < 0:
400
+ break
401
+ hits.append(env)
402
+ rows = []
403
+ for row in _split_top(tex[m.end():end], ("\\\\", "\\cr")):
404
+ cells = _split_top(row, ("&",))
405
+ if len(cells) > 1:
406
+ cells[1] = _text_cell(cells[1])
407
+ rows.append("&".join(cells))
408
+ tex = (tex[:m.start()] + before + "\\begin{%s}" % name + "\\\\".join(rows) +
409
+ "\\end{%s}" % name.split("}")[0] + after + tex[end2:])
410
+
411
+ def begin(m):
412
+ env = m.group(1)
413
+ hits.append(env)
414
+ name, before, _ = _ENVS[env]
415
+ return before + "\\begin{%s}" % name
416
+
417
+ def end(m):
418
+ name, _, after = _ENVS[m.group(1)]
419
+ return "\\end{%s}" % name.split("}")[0] + after
420
+
421
+ names = "|".join(re.escape(e) for e in sorted(_ENVS, key=len, reverse=True))
422
+ # matrix* takes an optional column alignment [r], which texmath would read as maths; nothing else does
423
+ tex = re.sub(r"\\begin\s*\{([a-zA-Z]*matrix\*)\}\s*\[[^\[\]{}]*\]", lambda m: "\\begin{%s}" % m.group(1), tex)
424
+ tex = re.sub(r"\\begin\s*\{(%s)\}" % names, begin, tex)
425
+ return re.sub(r"\\end\s*\{(%s)\}" % names, end, tex)
426
+
427
+
428
+ # ---- definitions ----------------------------------------------------------------------------------
429
+ _DEF_START = re.compile(
430
+ r"\\(?P<cmd>(?:re)?newcommand\*?|providecommand\*?|DeclareRobustCommand\*?|DeclareMathOperator\*?"
431
+ r"|[gex]?def|let|DeclarePairedDelimiterX|DeclarePairedDelimiter"
432
+ r"|(?:New|Renew|Provide|Declare)DocumentCommand)%s" % _CS)
433
+
434
+
435
+ @dataclass
436
+ class Definition:
437
+ name: str # \foo
438
+ source: str # the definition as written; pandoc expands it
439
+ uses: frozenset # control words in it
440
+ paired: Optional[Tuple[str, str]] = None # \DeclarePairedDelimiter: the left and right delimiter
441
+ span: Tuple[int, int] = (0, 0) # where it is in the text it was read from
442
+ paired_x: Optional[Tuple[int, str]] = None # \DeclarePairedDelimiterX: its arguments and body
443
+ loop: bool = False # made by a \foreach alphabet loop (pandoc cannot run it)
444
+
445
+
446
+ def _control_words(tex: str) -> set:
447
+ """Control words, and control symbols, which can be macros too (``\\newcommand{\\1}{\\mathbf 1}``)."""
448
+ return set(re.findall(r"\\(?:[a-zA-Z@]+|[^a-zA-Z@\s])", tex))
449
+
450
+
451
+ # the name being defined: a control word, or a control symbol other than the ones TeX syntax needs
452
+ _NAME = r"(\\[a-zA-Z@]+|\\[^a-zA-Z@\s{}\\%#])"
453
+
454
+
455
+ def _in_comment(text: str, pos: int) -> bool:
456
+ line = text[text.rfind("\n", 0, pos) + 1:pos]
457
+ return bool(re.search(r"(?<!\\)(?:\\\\)*%", line))
458
+
459
+
460
+ def _parse_definition(text: str, m) -> Optional[Definition]:
461
+ cmd = m.group("cmd")
462
+ pos = m.end()
463
+ gap = _GAP.pattern # spaces and comments, as TeX skips them
464
+ if cmd == "let":
465
+ lm = re.compile(gap + _NAME + gap + r"=?\s*(\\[a-zA-Z@]+|\\.|[^\s\\])").match(text, pos)
466
+ if not lm:
467
+ return None
468
+ return Definition(lm.group(1), text[m.start():lm.end()], frozenset({lm.group(2)}), span=(m.start(), lm.end()))
469
+ nm = re.compile(gap + r"(?:\{" + gap + _NAME + gap + r"\}|" + _NAME + ")").match(text, pos)
470
+ if not nm:
471
+ return None
472
+ name = nm.group(1) or nm.group(2)
473
+ pos = nm.end()
474
+ if cmd.endswith("def"): # \def\foo#1#2{..}, \def\foo #1.{..}: parameter text up to the body
475
+ brace = text.find("{", pos)
476
+ if brace < 0 or "}" in text[pos:brace]:
477
+ return None
478
+ end = _group_end(text, brace)
479
+ elif cmd == "DeclarePairedDelimiter":
480
+ l0, l1 = _argument(text, pos)
481
+ r0, r1 = _argument(text, l1)
482
+ if r1 <= r0 or text[r0:r1] == "" or (text[r0] == "{" and _group_end(text, r0) < 0):
483
+ return None
484
+ left, right = _unbrace(text[l0:l1]), _unbrace(text[r0:r1])
485
+ return Definition(name, text[m.start():r1], frozenset(_control_words(left + right)), (left, right),
486
+ (m.start(), r1))
487
+ elif cmd == "DeclarePairedDelimiterX": # \DeclarePairedDelimiterX{\set}[1]{\{}{\}}{#1}
488
+ count = 0
489
+ cm = re.compile(_GAP.pattern + r"\[\s*(\d)\s*\]").match(text, pos)
490
+ if cm:
491
+ count, pos = int(cm.group(1)), cm.end()
492
+ l0, l1 = _argument(text, pos)
493
+ r0, r1 = _argument(text, l1)
494
+ b0 = _GAP.match(text, r1).end()
495
+ if text[b0:b0 + 1] != "{" or _group_end(text, b0) < 0 or r1 <= r0:
496
+ return None
497
+ end = _group_end(text, b0)
498
+ left, right, body = _unbrace(text[l0:l1]), _unbrace(text[r0:r1]), text[b0 + 1:end - 1]
499
+ return Definition(name, text[m.start():end], frozenset(_control_words(left + right + body) - {name}),
500
+ (left, right), (m.start(), end), paired_x=(count, body))
501
+ elif cmd.endswith("DocumentCommand"): # xparse: \NewDocumentCommand{\foo}{O{1} m m}{body}
502
+ # pandoc's reader implements xparse (o, O{}, \IfNoValueTF, \RenewDocumentCommand): kept as written
503
+ s0 = _GAP.match(text, pos).end()
504
+ if text[s0:s0 + 1] != "{" or _group_end(text, s0) < 0:
505
+ return None
506
+ s1 = _group_end(text, s0)
507
+ b0 = _GAP.match(text, s1).end()
508
+ if text[b0:b0 + 1] != "{" or _group_end(text, b0) < 0:
509
+ return None
510
+ end = _group_end(text, b0)
511
+ body = text[b0 + 1:end - 1]
512
+ return Definition(name, text[m.start():end], frozenset(_control_words(body) - {name}), span=(m.start(), end))
513
+ else: # \newcommand{\foo}[n][default]{body}, \DeclareMathOperator*{\foo}{text}
514
+ if not cmd.startswith("DeclareMathOperator"):
515
+ pos = _optional(text, pos, 2)
516
+ b0 = _GAP.match(text, pos).end()
517
+ if text[b0:b0 + 1] != "{":
518
+ return None
519
+ end = _group_end(text, b0)
520
+ if end < 0: # the body is never closed
521
+ return None
522
+ source = text[m.start():end]
523
+ uses = frozenset(_control_words(source[len(m.group()):]) - {name})
524
+ if cmd.startswith("DeclareMathOperator"):
525
+ # pandoc expands \DeclareMathOperator* to \mathop{\mathrm{..}}, which loses the limits of the
526
+ # starred form; texmath knows \operatorname(*) itself
527
+ source = "\\newcommand{%s}{\\operatorname%s{%s}}" % (name, "*" if cmd.endswith("*") else "",
528
+ text[b0 + 1:end - 1])
529
+ return Definition(name, source, uses, span=(m.start(), end))
530
+
531
+
532
+ _LOOP = re.compile(r"\\foreach\s*(\\[a-zA-Z]+)\s*in\s*\{([^{}]*)\}|\\@for\s*(\\[a-zA-Z]+)\s*:=\s*([^{}\\]*?)\s*\\do")
533
+ _LOOP_DEF = r"\\csname\s*([A-Za-z]*)\s*%s\s*\\endcsname"
534
+
535
+
536
+ def _letters(items: str) -> List[str]:
537
+ """A pgffor / \\@for list of letters: "A,B,...,Z,a,b,...,z" -> A..Z a..z."""
538
+ parts = [p.strip() for p in items.split(",") if p.strip()]
539
+ out: List[str] = []
540
+ for i, p in enumerate(parts):
541
+ if p == "..." and out and i + 1 < len(parts) and len(parts[i + 1]) == 1 and parts[i + 1].isalpha() \
542
+ and out[-1].isupper() == parts[i + 1].isupper():
543
+ out += [chr(c) for c in range(ord(out[-1]) + 1, ord(parts[i + 1]))]
544
+ elif len(p) == 1 and p.isalpha():
545
+ out.append(p)
546
+ else:
547
+ return [] # not a list of letters
548
+ return out
549
+
550
+
551
+ def _letter_loops(text: str) -> "Tuple[List[Definition], List[Tuple[int, int]]]":
552
+ """The alphabet idiom: ``\\foreach \\x in {A,...,Z}{\\expandafter\\xdef\\csname cal\\x\\endcsname
553
+ {\\noexpand\\mathcal{\\x}}}`` (also with \\@for and \\newcommand) defines \\calA ... \\calZ; pandoc
554
+ cannot run the loop. Returns the definitions and the spans of the loops."""
555
+ defs: List[Definition] = []
556
+ spans: List[Tuple[int, int]] = []
557
+ for m in _LOOP.finditer(text):
558
+ if _in_comment(text, m.start()):
559
+ continue
560
+ var, items = (m.group(1), m.group(2)) if m.group(1) else (m.group(3), m.group(4))
561
+ b0 = _GAP.match(text, m.end()).end()
562
+ if text[b0:b0 + 1] != "{" or _group_end(text, b0) < 0:
563
+ continue
564
+ end = _group_end(text, b0)
565
+ letters = _letters(items)
566
+ body = text[b0 + 1:end - 1]
567
+ found = False
568
+ for d in re.finditer(_LOOP_DEF % re.escape(var) + r"(?![a-zA-Z@])", body):
569
+ g0 = _GAP.match(body, d.end()).end()
570
+ if body[g0:g0 + 1] != "{" or _group_end(body, g0) < 0:
571
+ continue
572
+ template = body[g0 + 1:_group_end(body, g0) - 1].replace("\\noexpand", "")
573
+ for letter in letters:
574
+ value = re.sub(re.escape(var) + r"(?![a-zA-Z@])", lambda _m: letter, template)
575
+ name = "\\" + d.group(1) + letter
576
+ defs.append(Definition(name, "\\newcommand{%s}{%s}" % (name, value),
577
+ frozenset(_control_words(value) - {name}), span=(m.start(), end), loop=True))
578
+ found = True
579
+ if found:
580
+ spans.append((m.start(), end))
581
+ return defs, spans
582
+
583
+
584
+ def parse_definitions(text: str, document: bool = False) -> "Tuple[List[Definition], List[str]]":
585
+ """The macro definitions in LaTeX source (a preamble, a macro file, an equation), and the names
586
+ of those that cannot be used (malformed, never closed). `document`: a whole document or a style
587
+ file, whose internal definitions (names or bodies with @) are left out."""
588
+ defs, loops = _letter_loops(text) if "\\foreach" in text or "\\@for" in text else ([], [])
589
+ skipped: List[str] = []
590
+ pos = 0
591
+ while True:
592
+ m = _DEF_START.search(text, pos)
593
+ if not m:
594
+ if document:
595
+ defs = [d for d in defs if "@" not in d.name and "@" not in d.source]
596
+ defs.sort(key=lambda d: d.span[0]) # the loops' definitions where the loops are (stable)
597
+ return defs, skipped
598
+ if _in_comment(text, m.start()) or _in(loops, m.start()):
599
+ pos = m.end()
600
+ continue
601
+ d = _parse_definition(text, m)
602
+ if d is None:
603
+ nm = re.compile(r"\s*\{?\s*(\\[a-zA-Z@]+)").match(text, m.end())
604
+ skipped.append(nm.group(1) if nm else "\\" + m.group("cmd"))
605
+ pos = m.end()
606
+ continue
607
+ defs.append(d)
608
+ pos = d.span[1]
609
+
610
+
611
+ _USEPACKAGE = re.compile(r"\\(?:usepackage|RequirePackage)\s*(?:\[[^\]]*\])?\s*\{([^{}]*)\}")
612
+
613
+
614
+ def packages_in(text: str) -> set:
615
+ """The packages that LaTeX source loads (\\usepackage{a,b})."""
616
+ names: set = set()
617
+ for m in _USEPACKAGE.finditer(text):
618
+ if not _in_comment(text, m.start()):
619
+ names.update(p.strip() for p in m.group(1).split(",") if p.strip())
620
+ return names
621
+
622
+
623
+ _VERBATIM = re.compile(r"\\begin\s*\{(verbatim\*?|Verbatim\*?|lstlisting|minted|comment|BVerbatim|LVerbatim)\}"
624
+ r"[\s\S]*?\\end\s*\{\1\}|\\(?:verb|lstinline)\*?([^\sa-zA-Z{])[^\n]*?\2")
625
+
626
+
627
+ def without_verbatim(text: str) -> str:
628
+ """LaTeX source with its verbatim parts blanked out (a LaTeX example in a tutorial is no
629
+ definition), keeping every other character where it was (offsets into it hold for `text`)."""
630
+ return _VERBATIM.sub(lambda m: re.sub(r"[^\n]", " ", m.group()), text)
631
+
632
+
633
+ _HOOKS = re.compile(r"\\(?:AtBeginDocument" + _CS + r"|AddToHook\s*\{\s*begindocument(?:/before|/end)?\s*\}"
634
+ r"(?:\s*\[[^\]]*\])?)")
635
+ # a hook whose definitions depend on something (\@ifpackageloaded{physics}{..}{}): not taken
636
+ _CONDITIONAL = re.compile(r"\\(?:@?if[a-zA-Z@]*|If[A-Za-z]*TF?|IfPackageLoaded[A-Za-z]*)(?![a-zA-Z@])")
637
+
638
+
639
+ def _hook_spans(text: str) -> List[Tuple[int, int]]:
640
+ """The arguments of \\AtBeginDocument{..} and \\AddToHook{begindocument}[label]{..} without a condition
641
+ in them: definitions there hold for the whole body, but pandoc's reader does not run the hook."""
642
+ spans = []
643
+ for m in _HOOKS.finditer(text):
644
+ if _in_comment(text, m.start()):
645
+ continue
646
+ a0, a1 = _argument(text, m.end())
647
+ if a1 > a0 and text[a0] == "{" and not _CONDITIONAL.search(text, a0, a1):
648
+ spans.append((a0, a1))
649
+ return spans
650
+
651
+
652
+ def pandoc_leftovers(text: str) -> str:
653
+ """The definitions in LaTeX source that pandoc's reader does not apply (\\DeclarePairedDelimiter(X),
654
+ the \\foreach alphabet loop, those in \\AtBeginDocument), with what they use and the source's
655
+ \\usepackage lines: what a document or a pasted preamble adds to the macros of its equations,
656
+ which pandoc already expanded otherwise. Only those: re-applying all definitions would also
657
+ apply one that holds in a group elsewhere."""
658
+ text = without_verbatim(text)
659
+ if not any(k in text for k in ("\\DeclarePairedDelimiter", "\\foreach", "\\@for", "usepackage", "RequirePackage",
660
+ "\\AtBeginDocument", "\\AddToHook")):
661
+ return ""
662
+ defs, _ = parse_definitions(text, document=True)
663
+ hooks = _hook_spans(text)
664
+ wanted = [d for d in defs if d.paired or d.loop or _in(hooks, d.span[0])]
665
+ # with the definitions those use (\DeclarePairedDelimiter{\pr}{\myL}{\myR} and \myL's \newcommand)
666
+ names = {n for d in wanted for n in d.uses}
667
+ while True:
668
+ more = {n for d in defs if d.name in names for n in d.uses} - names
669
+ if not more:
670
+ break
671
+ names |= more
672
+ keep = [d.source for d in defs if d.paired or d.loop or d.name in names or _in(hooks, d.span[0])]
673
+ keep += ["\\usepackage{%s}" % p for p in sorted(packages_in(text))]
674
+ return "\n".join(keep)
675
+
676
+
677
+ class Macros:
678
+ """Macro definitions from the user's files and text, applied to every LaTeX input. A document's own
679
+ definitions (its preamble, files it \\input s: :func:`documents.read_text_document`) come as
680
+ `document`, after the user's files and text, so that they win; `labels` then maps its \\label s to
681
+ the numbers LaTeX gave them (from the .aux file), for \\eqref."""
682
+
683
+ def __init__(self, files: Sequence[str] = (), text: str = "", document: str = "",
684
+ labels: Optional[Dict[str, str]] = None):
685
+ self.files = list(files)
686
+ self.text = text
687
+ self.document = document
688
+ self.definitions: Dict[str, Definition] = {}
689
+ self.order: List[Definition] = [] # every definition, in file order (\let takes a snapshot)
690
+ self.skipped: List[str] = []
691
+ self.errors: List[str] = []
692
+ self.packages: set = set()
693
+ self.labels: Dict[str, str] = dict(labels or {})
694
+ for path in self.files:
695
+ try:
696
+ with open(path, "rb") as f:
697
+ data = f.read()
698
+ except OSError as e:
699
+ self.errors.append("cannot read %s: %s" % (path, e.strerror or e))
700
+ continue
701
+ self._add(data.decode("utf-8-sig", "replace"))
702
+ self._add(text)
703
+ if document:
704
+ self._add(document, document=True)
705
+
706
+ def _add(self, text: str, document: bool = False) -> None:
707
+ defs, skipped = parse_definitions(text, document)
708
+ for d in defs:
709
+ self.definitions[d.name] = d # a later definition wins, as in LaTeX with \renewcommand
710
+ self.order.append(d)
711
+ if not document: # (a document's own skipped definitions are pandoc's business)
712
+ self.skipped += skipped
713
+ self.packages |= packages_in(text)
714
+
715
+ def __len__(self) -> int:
716
+ return len(self.definitions)
717
+
718
+ def needed(self, tex: str) -> List[Definition]:
719
+ """The definitions `tex` uses, directly or through other definitions, in file order (so that
720
+ \\let and redefinitions behave as in the file); not those that `tex` defines itself."""
721
+ own = {d.name for d in parse_definitions(tex)[0]}
722
+ names: set = set()
723
+ todo = [n for n in _control_words(tex) if n not in own]
724
+ while todo:
725
+ name = todo.pop()
726
+ if name in names or name not in self.definitions:
727
+ continue
728
+ names.add(name)
729
+ for d in self.order:
730
+ if d.name == name:
731
+ todo.extend(d.uses)
732
+ return [d for d in self.order if d.name in names]
733
+
734
+
735
+ _MACRO_CACHE: Dict[tuple, Macros] = {}
736
+
737
+
738
+ def file_stamps(files: Sequence[str]) -> tuple:
739
+ stamps = []
740
+ for f in files:
741
+ try:
742
+ st = os.stat(f)
743
+ stamps.append((f, st.st_mtime_ns, st.st_size))
744
+ except OSError:
745
+ stamps.append((f, None, None))
746
+ return tuple(stamps)
747
+
748
+
749
+ def load_macros(files: Sequence[str] = (), text: str = "", document: str = "",
750
+ labels: Optional[Dict[str, str]] = None, *, preamble: str = "") -> Optional[Macros]:
751
+ """A Macros object for these files and text (None for neither), re-read only when a file changes;
752
+ `document` and `labels`: a document's own definitions and label numbers (see :class:`Macros`)."""
753
+ files = [f for f in files if f]
754
+ if not files and not text.strip() and not document.strip() and not labels and not preamble:
755
+ return None
756
+ key = (file_stamps(files), text, document, tuple(sorted((labels or {}).items())), preamble)
757
+ if key not in _MACRO_CACHE:
758
+ if len(_MACRO_CACHE) > 16:
759
+ _MACRO_CACHE.clear()
760
+ loaded = Macros(files, text, document, labels)
761
+ if preamble:
762
+ loaded._add(preamble) # pasted definitions take precedence, just as they do in bare equations
763
+ _MACRO_CACHE[key] = loaded
764
+ return _MACRO_CACHE[key]
765
+
766
+
767
+ def with_document(macros: Optional[Macros], document: str, labels: Optional[Dict[str, str]] = None,
768
+ *, preamble: str = "") -> Optional[Macros]:
769
+ """The user's macros plus a document's own definitions and label numbers (which win)."""
770
+ if not document.strip() and not labels and not preamble:
771
+ return macros
772
+ return load_macros(macros.files if macros is not None else (), macros.text if macros is not None else "",
773
+ document, labels, preamble=preamble)
774
+
775
+
776
+ def before_equations(text: str, masked: Optional[str] = None, defer: bool = True) -> Tuple[str, str]:
777
+ """Prepare a LaTeX read. Defer preamble macros and keep the limits of operator declarations."""
778
+ from .pandoc_engine import _has_math_delimiters
779
+ plain = without_verbatim(masked if masked is not None else text)
780
+ definitions, _ = parse_definitions(plain)
781
+ keep, out = [], []
782
+ end = previous = 0
783
+ for d in definitions:
784
+ start, stop = d.span
785
+ if defer and _has_math_delimiters(plain[previous:start]):
786
+ defer = False
787
+ previous = stop
788
+ if defer and not _depth(plain, start):
789
+ keep.append(d.source)
790
+ if start >= end: # an alphabet loop yields several definitions from one span
791
+ out.append(text[end:start])
792
+ end = stop
793
+ elif plain.startswith("\\DeclareMathOperator", start):
794
+ out.extend((text[end:start], d.source))
795
+ end = stop
796
+ return "".join(out) + text[end:], "\n".join(keep)
797
+
798
+
799
+ # ---- expansion ----------------------------------------------------------------------------------------
800
+ def _paired(tex: str, paired: Dict[str, Tuple[str, str]]) -> str:
801
+ """Uses of \\DeclarePairedDelimiter macros: ``\\abs{x}`` -> ``\\lvert x\\rvert``, ``\\abs*{x}`` ->
802
+ ``\\left\\lvert x\\right\\rvert``, ``\\abs[\\big]{x}`` -> ``\\bigl\\lvert x\\bigr\\rvert``."""
803
+ if not paired:
804
+ return tex
805
+ # (a control symbol, \DeclarePairedDelimiter{\1}..., may be followed by a letter: \1x)
806
+ pattern = re.compile(r"(%s)" % "|".join(re.escape(k) + (_CS if re.match(r"\\[a-zA-Z@]", k) else "")
807
+ for k in paired))
808
+ pos = 0
809
+ while True:
810
+ m = _find(tex, pattern, pos)
811
+ if not m:
812
+ return tex
813
+ left, right, x = paired[m.group(1)]
814
+ i = _GAP.match(tex, m.end()).end()
815
+ size = ""
816
+ if tex[i:i + 1] == "*":
817
+ opening, closing, middle, i = "\\left", "\\right", "\\middle", i + 1
818
+ else:
819
+ j = _optional(tex, i, 1)
820
+ if j > i:
821
+ size = tex[i:j].strip()[1:-1].strip()
822
+ i = j
823
+ opening, closing = (size + "l", size + "r") if size else ("", "")
824
+ middle = size
825
+ count, body = x if x else (1, "#1")
826
+ args = []
827
+ for _ in range(count):
828
+ a0, a1 = _argument(tex, i)
829
+ if a1 <= a0:
830
+ from .pandoc_engine import ConversionError
831
+ raise ConversionError("%s needs an argument (it was declared with \\DeclarePairedDelimiter)"
832
+ % m.group(1))
833
+ args.append(_unbrace(tex[a0:a1]))
834
+ i = a1
835
+ inner = re.sub(r"#(\d)", lambda d: "{%s}" % args[int(d.group(1)) - 1] if 0 < int(d.group(1)) <= count
836
+ else d.group(), body)
837
+ # \delimsize (in an X body: \delimsize\vert) takes the size of the pair, or \middle for *
838
+ inner = re.sub(r"\\delimsize" + _CS + r"\s*", lambda _d: middle + " " if middle else "", inner)
839
+ # one group: \abs{x}^2 puts the whole |x| under the exponent; the argument keeps its own scope
840
+ new = "{%s%s {%s}%s%s}" % (opening, left, inner if x else "%s" % args[0], closing, right)
841
+ tex = tex[:m.start()] + new + tex[i:]
842
+ pos = m.start() # nested uses inside the argument
843
+
844
+
845
+ _PANDOC_MATH_ENVS = frozenset(
846
+ "equation equation* displaymath math align align* alignat alignat* flalign flalign* eqnarray eqnarray* "
847
+ "gather gather* multline multline*".split())
848
+
849
+
850
+ def _expand(body: str, sources: List[str], keep_layout: bool = False) -> Optional[str]:
851
+ """`body` with the macros of `sources` (definitions as written) expanded by pandoc's LaTeX reader;
852
+ None if pandoc does not give back exactly one equation."""
853
+ from .pandoc_engine import ConversionError, _read_json
854
+ env = re.fullmatch(r"\s*\\begin\s*\{([a-zA-Z]+\*?)\}[\s\S]*\\end\s*\{\1\}\s*", body)
855
+ # Inside \[...\] pandoc preserves the layout of an align environment as well.
856
+ wrapped = body if not keep_layout and env and env.group(1) in _PANDOC_MATH_ENVS else "\\[" + body + "\n\\]"
857
+ try:
858
+ eqs = _read_json("latex", ("\n".join(sources) + "\n" + wrapped).encode("utf-8"))
859
+ except ConversionError:
860
+ return None
861
+ if len(eqs) != 1:
862
+ return None
863
+ if keep_layout:
864
+ return body[:len(body) - len(body.lstrip())] + eqs[0].tex + body[len(body.rstrip()):]
865
+ return eqs[0].tex
866
+
867
+
868
+ def _fraction_arguments(tex: str, names: AbstractSet[str]) -> str:
869
+ """Keep a macro used as a single fraction argument together when its body has several tokens (also
870
+ the second argument of \\overset and its kind: \\overset\\K\\K)."""
871
+ fractions = {r"\frac", r"\dfrac", r"\tfrac", r"\cfrac", r"\binom", r"\dbinom", r"\tbinom", r"\overset",
872
+ r"\underset", r"\stackrel"} - names
873
+ out, last = [], 0
874
+ for m in _TOKEN.finditer(tex):
875
+ if m.group() in fractions:
876
+ end = m.end()
877
+ for _ in range(2):
878
+ start, end = _argument(tex, end)
879
+ if start >= last and tex[start:end] in names:
880
+ out.extend((tex[last:start], "{", tex[start:end], "}"))
881
+ last = end
882
+ return "".join(out) + tex[last:]
883
+
884
+
885
+ _SIMPLE_DEF = re.compile(r"\s*\\(?:(?:re)?newcommand\*?|providecommand\*?|g?def)\s*\{?\s*(\\[a-zA-Z]+)\s*\}?"
886
+ r"\s*\{([\s\S]*)\}\s*")
887
+ # a body that needs TeX itself (a mode test, a look ahead, expansion control): pandoc expands those
888
+ _NOT_LITERAL = re.compile(r"\\(?:if[a-zA-Z]*|else|fi|xspace|expandafter|noexpand|csname|protect|futurelet|"
889
+ r"let|relax|ensuremath|@ifnextchar|ifx)(?![a-zA-Z@])")
890
+
891
+
892
+ _TAKES_ARGUMENT = frozenset(("\\" + n) for n in """
893
+ frac dfrac tfrac cfrac binom dbinom tbinom sqrt mathbb mathbf mathcal mathrm mathit mathsf mathtt mathfrak mathscr
894
+ mathnormal boldsymbol bm pmb operatorname text textrm textbf textit textsf texttt textup textnormal mbox emph hat
895
+ widehat tilde widetilde bar overline underline vec dot ddot dddot check breve acute grave mathring overbrace
896
+ underbrace overset underset stackrel xrightarrow xleftarrow left right middle big Big bigg Bigg bigl bigr Bigl
897
+ Bigr biggl biggr Biggl Biggr bigm Bigm not color textcolor boxed cancel bcancel xcancel phantom hphantom vphantom
898
+ smash mathop mathrel mathbin mathord mathopen mathclose mathpunct mathinner hspace mspace label tag ref eqref
899
+ overleftarrow overrightarrow underleftarrow underrightarrow sideset substack
900
+ """.split())
901
+
902
+
903
+ _NO_ARGUMENT: List[frozenset] = []
904
+
905
+
906
+ def _no_argument() -> frozenset:
907
+ """Commands that take no argument (symbols, operators, Greek letters): diagnose's list without those
908
+ that take one."""
909
+ if not _NO_ARGUMENT:
910
+ from .diagnose import _KNOWN
911
+ _NO_ARGUMENT.append(frozenset(_KNOWN) - _TAKES_ARGUMENT)
912
+ return _NO_ARGUMENT[0]
913
+
914
+
915
+ def _simple_expansion(tex: str, definitions: List[Definition], keep_layout: bool = False) -> Optional[str]:
916
+ """`tex` with its macros expanded here, when every definition it needs is a macro without arguments
917
+ (``\\newcommand{\\calR}{\\mathcal{R}}``: the \\foreach alphabet, \\R for \\mathbb{R}): as TeX replaces
918
+ them, without a pandoc run per equation. None when one is anything else (pandoc expands those)."""
919
+ bodies: Dict[str, str] = {}
920
+ for d in definitions:
921
+ m = _SIMPLE_DEF.fullmatch(d.source)
922
+ if not m or m.group(1) != d.name or "#" in m.group(2) or "@" in d.source or _NOT_LITERAL.search(m.group(2)):
923
+ return None
924
+ if d.source.lstrip().startswith("\\providecommand") and d.name in bodies:
925
+ continue # \providecommand defines only what is not defined yet
926
+ bodies[d.name] = m.group(2)
927
+ if not bodies:
928
+ return tex
929
+ for _ in range(20):
930
+ if keep_layout:
931
+ tex = _fraction_arguments(tex, bodies.keys())
932
+ out, last = [], 0
933
+ for t in _TOKEN.finditer(tex): # (whole control words; a comment is one token)
934
+ if t.group() not in bodies:
935
+ continue
936
+ body = bodies[t.group()]
937
+ before = tex[last:t.start()]
938
+ # right after a command that takes an argument (\mathbb\RR, \frac\mass{V}, \left\bar) TeX hands
939
+ # the whole macro over, which plain text in its place would not do: pandoc decides. After one
940
+ # that takes none (\in \calR, \sum\subk, \cdot\vx) the text goes in where the macro was.
941
+ prev = re.search(r"(\\[a-zA-Z@]+)\s*$", before or (out[-1] if out else ""))
942
+ if prev and (prev.group(1) in _TAKES_ARGUMENT or prev.group(1) not in _no_argument()):
943
+ return None
944
+ if keep_layout and prev and not prev.group()[-1].isspace() and re.match(r"[a-zA-Z@]", body):
945
+ body = " " + body # \le\res with \res defined as R: keep \le and R apart
946
+ end = t.end()
947
+ if t.group()[1:].isalpha(): # TeX skips the spaces after a control word (\text{\prefix Hz})
948
+ end = re.compile(r"[ \t]*\n?[ \t]*").match(tex, end).end()
949
+ if re.search(r"\\[a-zA-Z@]+$", body) and re.match(r"[a-zA-Z@]", tex[end:end + 1]):
950
+ body += " " # \bb R -> \mathbb R, not \mathbbR
951
+ out += [before, body]
952
+ last = end
953
+ if not out:
954
+ return tex
955
+ tex = "".join(out) + tex[last:]
956
+ return None # a macro that keeps expanding into itself: pandoc decides
957
+
958
+
959
+ def _depth(tex: str, pos: int) -> int:
960
+ """How many brace groups are open at `pos`."""
961
+ depth = 0
962
+ for m in _TOKEN.finditer(tex, 0, pos):
963
+ depth += {"{": 1, "}": -1}.get(m.group(), 0)
964
+ return depth
965
+
966
+
967
+ def _without(text: str, spans: List[Tuple[int, int]]) -> str:
968
+ out, last = [], 0
969
+ for a, b in sorted(spans):
970
+ out.append(text[last:a])
971
+ last = b
972
+ return "".join(out) + text[last:]
973
+
974
+
975
+ # ---- standard LaTeX that texmath 0.13 rejects ------------------------------------------------------------
976
+ # amsmath / LaTeX commands written with what texmath has (renamed in place, no note)
977
+ _STANDARD = {"\\varlimsup": "\\overline{\\lim}", "\\varliminf": "\\underline{\\lim}",
978
+ "\\varinjlim": "\\underset{\\rightarrow}{\\lim}", "\\varprojlim": "\\underset{\\leftarrow}{\\lim}",
979
+ "\\injlim": "\\operatorname*{inj\\,lim}", "\\projlim": "\\operatorname*{proj\\,lim}",
980
+ "\\idotsint": "\\int\\cdots\\int", "\\operatornamewithlimits": "\\operatorname*",
981
+ "\\bigm": "\\big", "\\Bigm": "\\Big", "\\biggm": "\\bigg", "\\Biggm": "\\Bigg",
982
+ "\\cfrac": "\\dfrac"}
983
+ # no-ops in maths: font sizes, page-break hints, \qedhere
984
+ _SIZES = ("\\tiny", "\\scriptsize", "\\footnotesize", "\\small", "\\normalsize", "\\large", "\\Large", "\\LARGE",
985
+ "\\huge", "\\Huge")
986
+ _NO_OPS = _SIZES + ("\\qedhere", "\\nobreak", "\\allowdisplaybreaks", "\\hfill", "\\hfil", "\\hss")
987
+ _COUNTERS = {"\\addtocounter": 2, "\\setcounter": 2, "\\stepcounter": 1, "\\refstepcounter": 1,
988
+ "\\@namedef": 2} # (what a document's redefined \label leaves: \global\@namedef{..}{..})
989
+ _GROUPING = {"\\begingroup": "{", "\\endgroup": "}", "\\bgroup": "{", "\\egroup": "}"}
990
+ _RULES = re.compile(r"\\(?:toprule|midrule|bottomrule)(?:\s*\[[^\]]*\])?|\\cmidrule\s*(?:\([^)]*\))?\s*\{[^{}]*\}")
991
+ # text commands: texmath reads none of them inside another (\text{a \textbf{b}})
992
+ _TEXT_STYLES = ("\\text", "\\textrm", "\\textit", "\\textbf", "\\textsf", "\\texttt", "\\textup", "\\textsl",
993
+ "\\textmd", "\\emph", "\\mbox")
994
+ # lengths texmath takes in \hspace: pt, em, cm, in; the rest in those
995
+ _LENGTHS = {"mm": (0.1, "cm"), "bp": (1.00375, "pt"), "pc": (12.0, "pt"), "dd": (1.07, "pt"), "cc": (12.84, "pt"),
996
+ "sp": (1 / 65536, "pt"), "ex": (0.43, "em"), "mu": (1 / 18, "em"), "pt": (1, "pt"), "em": (1, "em"),
997
+ "cm": (1, "cm"), "in": (1, "in")}
998
+ _DIMEN = r"(-?\s*(?:\d+\.?\d*|\.\d+))\s*(mm|cm|in|pt|bp|pc|dd|cc|sp|em|ex|mu)"
999
+ _GLUE = r"(?:\s*plus\s*-?[\d.]+\s*(?:fil+|[a-z]{2}))?(?:\s*minus\s*-?[\d.]+\s*(?:fil+|[a-z]{2}))?"
1000
+ _SPACING = re.compile(r"\\hspace\*?\s*\{\s*%s\s*\}|\\(?:kern|hskip)\s*%s%s|\\m(?:kern|skip)\s*%s%s"
1001
+ % (_DIMEN, _DIMEN, _GLUE, _DIMEN, _GLUE))
1002
+ _FILL = re.compile(r"\\hspace\*?\s*\{\s*\\(?:h?fill|stretch\s*\{[^{}]*\})\s*\}")
1003
+ _REFS = re.compile(r"\\(eqref|ref|cref|Cref|autoref|pageref|nameref|cite|citep|citet|Citep|Citet)\*?" + _CS)
1004
+ _ACCENT_FONT = re.compile(
1005
+ r"(\\(?:hat|tilde|widehat|widetilde|bar|overline|underline|vec|dot|ddot|check|breve|acute|grave|mathring|"
1006
+ r"overrightarrow|overleftarrow))\s*(\\(?:mathcal|mathbf|mathbb|mathrm|mathit|mathsf|mathtt|mathfrak|mathscr|"
1007
+ r"boldsymbol|bm))" + _CS)
1008
+ _ENV_POSITION = re.compile(r"(\\begin\s*\{(?:aligned|alignedat|gathered|array|split|subarray)\})\s*\[\s*[tbc]\s*\]")
1009
+
1010
+
1011
+ # keys of a labels mapping (Macros.labels, a document's .aux numbers) that say how the document prints
1012
+ # references and citations: "cleveref" / "hyperref", "authoryear" / "numeric" (see documents)
1013
+ REF_STYLE, CITE_STYLE = "\x00ref-style", "\x00cite-style"
1014
+ # cleveref's default names (singular, plural; capitalised for \Cref), hyperref's \autoref names
1015
+ _CREF_NAMES = {"equation": ("eq.", "eqs."), "figure": ("fig.", "figs."), "subfigure": ("fig.", "figs."),
1016
+ "table": ("table", "tables"), "subtable": ("table", "tables"), "section": ("section", "sections"),
1017
+ "subsection": ("section", "sections"), "subsubsection": ("section", "sections"),
1018
+ "chapter": ("chapter", "chapters"), "appendix": ("appendix", "appendices"),
1019
+ "theorem": ("theorem", "theorems"), "lemma": ("lemma", "lemmas"),
1020
+ "corollary": ("corollary", "corollaries"), "proposition": ("proposition", "propositions"),
1021
+ "definition": ("definition", "definitions"), "remark": ("remark", "remarks"),
1022
+ "example": ("example", "examples"), "assumption": ("assumption", "assumptions"),
1023
+ "algorithm": ("algorithm", "algorithms"), "line": ("line", "lines"), "footnote": ("footnote", "footnotes"),
1024
+ "enumi": ("item", "items"), "item": ("item", "items"), "page": ("page", "pages")}
1025
+ _AUTOREF_NAMES = {"equation": "Equation", "figure": "Figure", "table": "Table", "part": "Part", "appendix": "Appendix",
1026
+ "chapter": "chapter", "section": "section", "subsection": "subsection",
1027
+ "subsubsection": "subsubsection", "paragraph": "paragraph", "theorem": "Theorem",
1028
+ "footnote": "footnote", "Item": "item", "item": "item", "page": "page"}
1029
+
1030
+
1031
+ def _listed(items: List[str]) -> str:
1032
+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
1033
+
1034
+
1035
+ def reference_text(command: str, keys: List[str], labels: Dict[str, str]) -> Optional[str]:
1036
+ """What \\eqref / \\ref / \\cref / \\Cref / \\autoref (pandoc: ref+label, ref+Label) of `keys` print,
1037
+ from the .aux numbers in `labels`; None when one of them has no number."""
1038
+ numbers = [labels.get(k) for k in keys]
1039
+ if not keys or any(n is None for n in numbers):
1040
+ return None
1041
+ if command == "eqref":
1042
+ return "(%s)" % ", ".join(numbers)
1043
+ if command not in ("cref", "Cref", "autoref", "ref+label", "ref+Label"):
1044
+ return ", ".join(numbers)
1045
+ types = [labels.get("type:" + k) for k in keys]
1046
+ style = ("hyperref" if command == "autoref" else "cleveref" if command in ("cref", "Cref")
1047
+ else labels.get(REF_STYLE, "hyperref"))
1048
+ kind = types[0] if len(set(types)) == 1 else None
1049
+ if style == "cleveref": # one name for each run of one type: "fig. 1 and eqs. (2) and (3)"
1050
+ groups: List[Tuple[Optional[Tuple[str, str]], List[str]]] = [] # (a section and a subsection: one name)
1051
+ for n, t in zip(numbers, types):
1052
+ shown = "(%s)" % n if t == "equation" else n
1053
+ names = _CREF_NAMES.get(t or "")
1054
+ if groups and groups[-1][0] == names:
1055
+ groups[-1][1].append(shown)
1056
+ else:
1057
+ groups.append((names, [shown]))
1058
+ parts = []
1059
+ for names, shown in groups:
1060
+ name = (names[0] if len(shown) == 1 else names[1]) if names else ""
1061
+ if name and command in ("Cref", "ref+Label"):
1062
+ name = name[:1].upper() + name[1:]
1063
+ parts.append(("%s %s" % (name, _listed(shown))) if name else _listed(shown))
1064
+ return _listed(parts)
1065
+ name = _AUTOREF_NAMES.get(kind or "")
1066
+ return "%s %s" % (name, _listed(numbers)) if name else _listed(numbers)
1067
+
1068
+
1069
+ def citation_text(command: str, cites: List[Tuple[str, str, str]], labels: Dict[str, str]) -> Tuple[str, bool]:
1070
+ """What \\cite, \\citep, \\citet, \\citeauthor ... (`command`, without the backslash) of `cites`
1071
+ ((key, prefix, suffix)) print, from the .aux (numbers; natbib's authors and years for an author-year
1072
+ document); and whether every key was found there."""
1073
+ command = command.rstrip("*").lower()
1074
+ found = all(("cite:" + k) in labels or ("citeauthor:" + k) in labels for k, _, _ in cites)
1075
+ year = {k: labels.get("citeyear:" + k) for k, _, _ in cites}
1076
+ author = {k: labels.get("citeauthor:" + k) for k, _, _ in cites}
1077
+ if command == "citeauthor":
1078
+ return "; ".join(author[k] or k for k, _, _ in cites), found
1079
+ if command in ("citeyear", "citeyearpar"):
1080
+ years = "; ".join(year[k] or k for k, _, _ in cites)
1081
+ return ("(%s)" % years if command == "citeyearpar" else years), found
1082
+ prefix, suffix = cites[0][1], cites[-1][2]
1083
+ if labels.get(CITE_STYLE) == "authoryear" and all(author[k] and year[k] for k, _, _ in cites):
1084
+ if command in ("citep", "citealp"):
1085
+ body = "; ".join("%s, %s" % (author[k], year[k]) for k, _, _ in cites)
1086
+ body = (prefix + " " if prefix else "") + body + (", " + suffix if suffix else "")
1087
+ return ("(%s)" % body if command == "citep" else body), found
1088
+ if command == "citealt":
1089
+ return "; ".join("%s %s" % (author[k], year[k]) for k, _, _ in cites), found
1090
+ # \citet, and \cite, which natbib prints as \citet in an author-year document
1091
+ parts = ["%s (%s)" % (author[k], year[k]) for k, _, _ in cites]
1092
+ if suffix:
1093
+ parts[-1] = parts[-1][:-1] + ", " + suffix + ")"
1094
+ return "; ".join(parts), found
1095
+ if command in ("citet", "citealt") and all(author[k] for k, _, _ in cites): # numeric \citet: Smith [7]
1096
+ parts = ["%s [%s]" % (author[k], labels.get("cite:" + k, k)) for k, _, _ in cites]
1097
+ if suffix:
1098
+ parts[-1] = parts[-1][:-1] + ", " + suffix + "]"
1099
+ return ", ".join(parts), found
1100
+ body = ", ".join(labels.get("cite:" + k, k) for k, _, _ in cites)
1101
+ body = (prefix + " " if prefix else "") + body + (", " + suffix if suffix else "")
1102
+ return "[%s]" % body, found
1103
+
1104
+
1105
+ def _refs(tex: str, labels: Dict[str, str]) -> str:
1106
+ """\\eqref{eq:x} -> (2.1) with the number from the document's .aux file (or the label itself),
1107
+ \\ref -> 2.1, \\cite{key} -> [key]: as text in maths, as letters inside text."""
1108
+ pos = 0
1109
+ while True:
1110
+ m = _REFS.search(tex, pos)
1111
+ if not m:
1112
+ return tex
1113
+ if _in_comment(tex, m.start()):
1114
+ pos = m.end()
1115
+ continue
1116
+ i = _optional(tex, m.end(), 2)
1117
+ a0, a1 = _argument(tex, i)
1118
+ if a1 <= a0 or tex[a0] != "{":
1119
+ pos = m.end()
1120
+ continue
1121
+ keys = [k.strip() for k in _unbrace(tex[a0:a1]).split(",") if k.strip()]
1122
+ if m.group(1).lower().startswith("cite"):
1123
+ shown = citation_text(m.group(1), [(k, "", "") for k in keys], labels)[0]
1124
+ elif m.group(1) in ("pageref", "nameref"): # (the .aux holds a label's page and title too)
1125
+ field = {"pageref": "page:", "nameref": "title:"}[m.group(1)]
1126
+ shown = ", ".join(labels.get(field + k, k) for k in keys)
1127
+ else:
1128
+ shown = reference_text(m.group(1), keys, labels)
1129
+ if shown is None: # no number: the label itself, as LaTeX's ?? would not say which
1130
+ shown = ", ".join(labels.get(k, k) for k in keys)
1131
+ shown = "(%s)" % shown if m.group(1) == "eqref" else shown
1132
+ in_text = _in(_text_spans(tex), m.start())
1133
+ new = shown if in_text else "\\text{%s}" % shown.replace("_", "\\_")
1134
+ tex = tex[:m.start()] + new + tex[a1:]
1135
+ pos = m.start() + len(new)
1136
+
1137
+
1138
+ def _intertext(tex: str, layout: List[str]) -> str:
1139
+ """\\intertext{and so} in an align: a row of its own with the text (texmath has no \\intertext)."""
1140
+ pattern = re.compile(r"\\(?:short)?intertext" + _CS)
1141
+ while True:
1142
+ m = _find(tex, pattern)
1143
+ if not m:
1144
+ return tex
1145
+ a0, a1 = _argument(tex, m.end())
1146
+ layout.append("intertext")
1147
+ tex = tex[:m.start()] + "\\text{%s}\\\\" % _unbrace(tex[a0:a1]) + tex[a1:]
1148
+
1149
+
1150
+ def _nested_text(tex: str) -> str:
1151
+ """\\text{a \\textbf{b} c} -> \\text{a }\\textbf{b}\\text{ c}; size switches inside text dropped."""
1152
+ names = "|".join(re.escape(n) for n in _TEXT_STYLES)
1153
+ outer = re.compile(r"(%s)%s" % (names, _CS))
1154
+ inner = re.compile(r"(%s|%s)%s" % (names, "|".join(re.escape(n) for n in _SIZES), _CS))
1155
+ pos = 0
1156
+ while True:
1157
+ m = outer.search(tex, pos)
1158
+ if not m:
1159
+ return tex
1160
+ a0, a1 = _argument(tex, m.end())
1161
+ if a1 <= a0 or tex[a0] != "{" or _in_comment(tex, m.start()):
1162
+ pos = m.end()
1163
+ continue
1164
+ body = tex[a0 + 1:a1 - 1]
1165
+ pieces, last, depth, changed, maths = [], 0, 0, False, False
1166
+ for t in _TOKEN.finditer(body):
1167
+ tok = t.group()
1168
+ if tok == "{":
1169
+ depth += 1
1170
+ elif tok == "}":
1171
+ depth -= 1
1172
+ elif tok in ("$", "\\(", "\\)") and not depth:
1173
+ maths = tok == "\\(" or (tok == "$" and not maths) # maths in the text: not split there
1174
+ elif not depth and not maths and inner.fullmatch(tok):
1175
+ changed = True
1176
+ if tok in _SIZES: # dropped (with the space after it)
1177
+ pieces.append("%s{%s}" % (m.group(1), body[last:t.start()]))
1178
+ last = t.end() + (1 if body[t.end():t.end() + 1] == " " else 0)
1179
+ continue
1180
+ b0, b1 = _argument(body, t.end())
1181
+ pieces.append("%s{%s}" % (m.group(1), body[last:t.start()]))
1182
+ pieces.append("%s{%s}" % (tok, _unbrace(body[b0:b1])))
1183
+ last = b1
1184
+ if not changed:
1185
+ pos = m.end()
1186
+ continue
1187
+ pieces.append("%s{%s}" % (m.group(1), body[last:]))
1188
+ pieces = [p for p in pieces if not p.endswith("{}")]
1189
+ # one group, as the \text was one argument (x_\text{a \textbf{b}}: all of it in the subscript)
1190
+ new = pieces[0] if len(pieces) == 1 else "{%s}" % "".join(pieces)
1191
+ tex = tex[:m.start()] + new + tex[a1:]
1192
+ pos = m.start() # the pieces may hold more nesting
1193
+
1194
+
1195
+ def _spacing(tex: str) -> str:
1196
+ """\\hspace{10mm}, \\kern3pt, \\hskip 1em plus 1fil, \\mkern3mu: in units texmath reads (it takes pt,
1197
+ em, cm and in, and \\mspace); \\hspace{\\fill} and its kind are left out."""
1198
+ tex = _at_tokens(tex, _FILL, lambda _m: "{}")
1199
+
1200
+ def length(value: str, unit: str) -> str:
1201
+ factor, base = _LENGTHS[unit]
1202
+ number = float(re.sub(r"\s+", "", value)) * factor # (a line break between - and the number)
1203
+ return "%s%s" % (("%.3f" % number).rstrip("0").rstrip(".") or "0", base)
1204
+
1205
+ def sub(m):
1206
+ if m.group(1): # \hspace
1207
+ return "\\hspace{%s}" % length(m.group(1), m.group(2))
1208
+ if m.group(3): # \kern / \hskip
1209
+ return "\\hspace{%s}" % length(m.group(3), m.group(4))
1210
+ if m.group(6) == "mu" and re.fullmatch(r"\d+", re.sub(r"\s+", "", m.group(5))):
1211
+ return "\\mspace{%smu}" % re.sub(r"\s+", "", m.group(5)) # \mkern 3mu (texmath: whole mu only)
1212
+ return "\\hspace{%s}" % length(m.group(5), m.group(6))
1213
+ return _at_tokens(tex, _SPACING, sub)
1214
+
1215
+
1216
+ def _drop_arguments(tex: str, names: Dict[str, int]) -> str:
1217
+ """\\addtocounter{equation}{1} and its kind: left out with their arguments."""
1218
+ pattern = re.compile(r"(%s)%s" % ("|".join(re.escape(n) for n in names), _CS))
1219
+ while True:
1220
+ m = _find(tex, pattern)
1221
+ if not m:
1222
+ return tex
1223
+ end = m.end()
1224
+ for _ in range(names[m.group(1)]):
1225
+ end = _argument(tex, end)[1]
1226
+ tex = tex[:m.start()] + "{}" + tex[end:]
1227
+
1228
+
1229
+ def _sideset(tex: str) -> str:
1230
+ """\\sideset{_a^b}{_c^d}\\sum -> {}_a^b\\sum_c^d (the scripts beside the operator); limits after it
1231
+ (\\sideset{}{'}\\sum_{i=1}^n) stay under and over the operator, the side scripts beside them."""
1232
+ pattern = re.compile(r"\\sideset" + _CS)
1233
+ while True:
1234
+ m = _find(tex, pattern)
1235
+ if not m:
1236
+ return tex
1237
+ l0, l1 = _argument(tex, m.end())
1238
+ r0, r1 = _argument(tex, l1)
1239
+ o0, o1 = _argument(tex, r1)
1240
+ left, right = _unbrace(tex[l0:l1]), _unbrace(tex[r0:r1])
1241
+ operator, end, limits = tex[o0:o1], o1, {}
1242
+ while True: # _{..} and ^{..} right after the operator: its limits
1243
+ s = re.compile(_GAP.pattern + r"(\\limits" + _CS + r")?" + _GAP.pattern + r"([_^])").match(tex, end)
1244
+ if not s or s.group(2) in limits:
1245
+ break
1246
+ a0, a1 = _argument(tex, s.end())
1247
+ if a1 <= a0:
1248
+ break
1249
+ limits[s.group(2)] = _unbrace(tex[a0:a1])
1250
+ end = a1
1251
+ if limits:
1252
+ if "^" in limits:
1253
+ operator = "\\overset{%s}{%s}" % (limits["^"], operator)
1254
+ if "_" in limits:
1255
+ operator = "\\underset{%s}{%s}" % (limits["_"], operator)
1256
+ new = "{}%s{%s}%s" % (left, operator, "{}" + right if right and limits else right)
1257
+ tex = tex[:m.start()] + new + tex[end:]
1258
+
1259
+
1260
+ def _accent_fonts(tex: str) -> str:
1261
+ """\\widetilde\\mathcal K -> \\widetilde{\\mathcal{K}}: LaTeX takes it, texmath wants the group."""
1262
+ pos = 0
1263
+ while True:
1264
+ m = _find(tex, _ACCENT_FONT, pos)
1265
+ if not m:
1266
+ return tex
1267
+ a0, a1 = _argument(tex, m.end())
1268
+ new = "%s{%s{%s}}" % (m.group(1), m.group(2), _unbrace(tex[a0:a1]))
1269
+ tex = tex[:m.start()] + new + tex[a1:]
1270
+ pos = m.start() + len(m.group(1))
1271
+
1272
+
1273
+ def merge_notes(notes: List[str]) -> List[str]:
1274
+ """Merge the macro notes from several equations, counting each name once."""
1275
+ prefix = _NOTES["packs"].split("%s")[0]
1276
+ by_package: Dict[str, List[str]] = {}
1277
+ written: List[str] = []
1278
+ macro_prefix = _NOTES["written"].split("%s")[0]
1279
+ out: List[str] = []
1280
+ for note in notes:
1281
+ if note.startswith(macro_prefix):
1282
+ if not written:
1283
+ out.append(macro_prefix)
1284
+ written.extend(n for n in note[len(macro_prefix):].split(", ") if n not in written)
1285
+ continue
1286
+ if not note.startswith(prefix):
1287
+ if note not in out:
1288
+ out.append(note)
1289
+ continue
1290
+ if not by_package:
1291
+ out.append(prefix) # where the merged note goes
1292
+ for part in note[len(prefix):].split("; "):
1293
+ m = re.fullmatch(r"(.*) \((\S+)\)", part)
1294
+ if m:
1295
+ names = by_package.setdefault(m.group(2), [])
1296
+ names += [n for n in m.group(1).split(", ") if n not in names]
1297
+ if written:
1298
+ out[out.index(macro_prefix)] = (_NOTES["written"] % ", ".join(written) if len(written) <= 5
1299
+ else "%d distinct macros written out" % len(written))
1300
+ if by_package:
1301
+ merged = _NOTES["packs"] % "; ".join("%s (%s)" % (", ".join(names), package)
1302
+ for package, names in by_package.items())
1303
+ out[out.index(prefix)] = merged
1304
+ return out
1305
+
1306
+
1307
+ def _at_tokens(tex: str, pattern: "re.Pattern", repl) -> str:
1308
+ """pattern.sub, but only where a token starts and outside comments: in ``a \\\\global`` the word
1309
+ after a row break \\\\ is no \\global."""
1310
+ out, last = [], 0
1311
+ for t in _TOKEN.finditer(tex):
1312
+ if t.start() < last or t.group().startswith("%"):
1313
+ continue
1314
+ m = pattern.match(tex, t.start())
1315
+ if m:
1316
+ out += [tex[last:m.start()], repl(m) if callable(repl) else m.expand(repl)]
1317
+ last = m.end()
1318
+ return "".join(out) + tex[last:]
1319
+
1320
+
1321
+ def _standard(tex: str, layout: List[str]) -> str:
1322
+ """Standard LaTeX that texmath 0.13 rejects, written with what it has."""
1323
+ tex = _at_tokens(tex, _ENV_POSITION, r"\1") # \begin{aligned}[t]: texmath would show the [t]
1324
+ tex = _at_tokens(tex, re.compile(r"\\cfrac\s*\[\s*[lcr]\s*\]"), lambda _m: "\\cfrac")
1325
+ tex = _at_tokens(tex, re.compile(r"\\textnormal" + _CS), lambda _m: "\\textrm") # also inside text
1326
+ tex = _rename(tex, _STANDARD, [])
1327
+ tex = _intertext(tex, layout)
1328
+ tex = _nested_text(tex)
1329
+ tex = _commands(tex, {"\\mathnormal": 0}, "unwrap", [])
1330
+ tex = _at_tokens(tex, re.compile(r"\\displaybreak(?:\s*\[\s*\d\s*\])?"), lambda _m: "{}")
1331
+ tex = _at_tokens(tex, _RULES, lambda _m: "\\hline") # booktabs rules in an array
1332
+ tex = _rename(tex, _GROUPING, [])
1333
+ tex = _at_tokens(tex, re.compile(r"\\global" + _CS + r"\s*"), lambda _m: "")
1334
+ tex = _commands(tex, _NO_OPS, "drop", [])
1335
+ tex = _drop_arguments(tex, _COUNTERS)
1336
+ tex = _spacing(tex)
1337
+ tex = _sideset(tex)
1338
+ return _accent_fonts(tex)
1339
+
1340
+
1341
+ # ---- the whole rewrite -------------------------------------------------------------------------------
1342
+ _NOTES = {
1343
+ "colour": "colours were dropped (texmath has no colour)",
1344
+ "resized": "%s: written as the plain-size version",
1345
+ "layout": "%s: layout-only commands were left out",
1346
+ "unexpanded": "the macros could not be expanded together with this equation; texmath was given the "
1347
+ "definitions instead",
1348
+ "kept": "the macros could not be expanded, so the equation was kept as written",
1349
+ "written": "macros written out: %s",
1350
+ "machinery": "kept as written (they are made of LaTeX's internal commands): %s",
1351
+ "packs": "written as their packages define them (built in): %s",
1352
+ "intertext": "\\intertext: written as a row of text in the equation",
1353
+ }
1354
+
1355
+
1356
+ def _expand_definitions(tex: str, own: List[Definition], used: List[Definition],
1357
+ for_writer: bool) -> Tuple[str, bool]:
1358
+ """Expand the equation's definitions and the file definitions it needs. Report whether it worked."""
1359
+ for d in own:
1360
+ if _depth(tex, d.span[0]):
1361
+ from .pandoc_engine import ConversionError
1362
+ raise ConversionError("%s is defined inside a group: a definition that only holds there cannot be "
1363
+ "expanded here - define it at the start of the equation or in Macros..." % d.name)
1364
+ definitions = used + own
1365
+ # a name defined twice (two macro files, a file and the equation) has its last definition: a
1366
+ # \newcommand{\abs} after a \DeclarePairedDelimiter{\abs} (or before it) is not both
1367
+ last = {d.name: d for d in definitions}
1368
+ paired = {name: d.paired + (d.paired_x,) for name, d in last.items() if d.paired}
1369
+ # \let\myabs\abs of a paired delimiter: the same pair
1370
+ for d in definitions:
1371
+ aliased = next(iter(d.uses), None) if d.source.lstrip().startswith("\\let") else None
1372
+ if last[d.name] is d and aliased in paired:
1373
+ paired[d.name] = paired[aliased]
1374
+ # paired delimiters first, in the equation and in the definitions that use them: then pandoc expands
1375
+ # the macros their delimiters may be made of (\DeclarePairedDelimiter{\abs}{\ld}{\rangle})
1376
+ plain: List[str] = []
1377
+ seen: set = set()
1378
+ for d in definitions:
1379
+ if d.paired or last[d.name].paired or d.name in paired:
1380
+ continue
1381
+ source = d.source
1382
+ if d.name in seen: # pandoc keeps a name's first \newcommand: a later one must win, as \renewcommand
1383
+ source = re.sub(r"^(\s*)\\(?:newcommand|DeclareRobustCommand)(?![a-zA-Z@])", r"\1\\renewcommand", source)
1384
+ seen.add(d.name)
1385
+ try:
1386
+ plain.append(_paired(source, paired))
1387
+ except Exception: # noqa: BLE001 - \newcommand{\foo}{\abs}: the pair is used where \foo is
1388
+ plain.append(source)
1389
+ out = _paired(_without(tex, [d.span for d in own]) if own else tex, paired)
1390
+ simple = _simple_expansion(out, [d for d in definitions if not d.paired and d.name not in paired],
1391
+ keep_layout=not for_writer)
1392
+ if simple is not None: # 0-argument \newcommand only (the \foreach alphabet): no pandoc run per equation
1393
+ out, plain = _paired(simple, paired), []
1394
+ if for_writer or own:
1395
+ out = out.strip()
1396
+ if plain:
1397
+ if not for_writer:
1398
+ bare = {n for n, d in last.items() if not _takes_arguments(d)} # (\frac1\norm{x}: not {\norm}{x})
1399
+ out = _fraction_arguments(out, bare)
1400
+ plain = [_fraction_arguments(s, bare) for s in plain]
1401
+ expanded = _expand(out, plain, not for_writer)
1402
+ if expanded is None and for_writer:
1403
+ # a style file's machinery (\let to internals, \expandafter, \csname...) can stop pandoc:
1404
+ # once more with the plain definitions alone
1405
+ simple = [s for s in plain if not re.search(r"\\(?:let|expandafter|csname|if[a-z]*|@)" + _CS + "|@", s)]
1406
+ expanded = _expand(out, simple) if simple and len(simple) < len(plain) else None
1407
+ if expanded is None:
1408
+ return ("\n".join(plain) + "\n" + out if for_writer else tex), False
1409
+ out = _paired(expanded, paired)
1410
+ return out, True
1411
+
1412
+
1413
+ def _expand_packs(out: str, tex: str, macros: Optional[Macros], own: List[Definition],
1414
+ pack_hits: List[str], for_latex: bool = False) -> str:
1415
+ # (a Macros with no definitions is falsy: it may still hold packages and labels)
1416
+ from . import packs
1417
+ defined = set(macros.definitions if macros is not None else ()) | {d.name for d in own}
1418
+ packages = (macros.packages if macros is not None else set()) | packages_in(tex)
1419
+ return packs.apply(out, defined, packages, pack_hits, for_latex)
1420
+
1421
+
1422
+ # a definition made of LaTeX's machinery (\@namedef, \global, \expandafter...): written out into an
1423
+ # equation, where there is no \makeatletter, it would break; such a macro is kept as written
1424
+ _MACHINERY = re.compile(r"\\[a-zA-Z]*@[a-zA-Z@]*|\\(?:global|gdef|xdef|edef|expandafter|csname|noexpand|"
1425
+ r"futurelet|afterassignment|aftergroup)(?![a-zA-Z@])")
1426
+ # commands that take the next token as a delimiter, not an argument in braces
1427
+ _DELIMITER_SIZES = frozenset("\\" + n for n in "left right middle big Big bigg Bigg bigl bigr Bigl Bigr biggl "
1428
+ "biggr Biggl Biggr bigm Bigm biggm Biggm".split())
1429
+
1430
+
1431
+ def _braced_arguments(tex: str, names: AbstractSet[str]) -> str:
1432
+ """A macro of `names` written as a bare argument (``\\widetilde\\K``, ``x^\\R``) gets braces, so that
1433
+ what it stands for stays one argument (``\\widetilde{\\mathcal K}``), as TeX hands the macro itself over."""
1434
+ out, last = [], 0
1435
+ for t in _TOKEN.finditer(tex):
1436
+ if t.group() not in names:
1437
+ continue
1438
+ # after ^ or _, or a command that takes an argument (also after its [option]: \sqrt[3]\K)
1439
+ prev = re.search(r"(?:(\\[a-zA-Z@]+)\s*(?:\[[^\[\]{}]*\]\s*)?|([\^_])\s*)$", tex[last:t.start()])
1440
+ if prev and (prev.group(2) or (prev.group(1) in _TAKES_ARGUMENT
1441
+ and prev.group(1) not in _DELIMITER_SIZES)):
1442
+ out += [tex[last:t.start()], "{", t.group(), "}"]
1443
+ last = t.end()
1444
+ return "".join(out) + tex[last:]
1445
+
1446
+
1447
+ def _takes_arguments(d: Definition) -> bool:
1448
+ """\\newcommand{\\f}[1]..., \\def\\f#1..., a paired delimiter: a macro that takes arguments."""
1449
+ return bool(d.paired) or "#" in d.source
1450
+
1451
+
1452
+ def _after_name(d: Definition) -> str:
1453
+ """The definition without its head (\\gdef\\R, \\newcommand{\\R}): what the macro stands for."""
1454
+ i = d.source.find(d.name)
1455
+ return d.source[i + len(d.name):] if i >= 0 else d.source
1456
+
1457
+
1458
+ def expand_macros(tex: str, macros: Optional[Macros] = None) -> Tuple[str, List[str]]:
1459
+ """Write out the macros of an equation for LaTeX output and say which ones were used."""
1460
+ from .pandoc_engine import ConversionError
1461
+ from .diagnose import _KNOWN
1462
+ source = tex
1463
+ comments = [m.span() for m in _TOKEN.finditer(tex) if m.group().startswith("%")]
1464
+ used = macros.needed(_without(tex, comments)) if macros else []
1465
+ effective = {d.name: d for d in used} # (a later definition of a name wins, as in LaTeX)
1466
+ machinery = {name for name, d in effective.items() if "@" in name or _MACHINERY.search(_after_name(d))}
1467
+ used = [d for d in used if d.name not in machinery]
1468
+ own, _ = parse_definitions(tex)
1469
+ effective.update({d.name: d for d in own})
1470
+ # braces for a macro written as a bare argument, if it takes no arguments itself (\hat\K, not \hat\abs{x})
1471
+ tex = _braced_arguments(tex, {n for n, d in effective.items() if n not in machinery and not _takes_arguments(d)})
1472
+ own, skipped = parse_definitions(tex)
1473
+ body = _without(tex, [d.span for d in own]) if own else tex
1474
+ names = {m.group() for m in _TOKEN.finditer(body)}
1475
+ defined = {d.name for d in used + own}
1476
+ tex_kept = (source, [_NOTES["kept"]])
1477
+ kept = sorted(names & machinery)
1478
+ try:
1479
+ out, ok = _expand_definitions(tex, own, used, for_writer=False)
1480
+ # a defined name still there means a macro that did not expand, unless it is a standard command
1481
+ # that a definition gives back (\let\oldhat\hat \renewcommand{\hat}[1]{\oldhat{...}}, \phi and
1482
+ # \varphi swapped with \let)
1483
+ left = {m.group() for m in _TOKEN.finditer(out)} & defined
1484
+ if skipped or not ok or left - set(_KNOWN):
1485
+ return tex_kept
1486
+ hits: List[str] = []
1487
+ out = _expand_packs(out, tex, macros, own, hits, for_latex=True)
1488
+ except ConversionError:
1489
+ return tex_kept
1490
+ written = sorted((names & defined) | {h.split(": ", 1)[1] for h in hits})
1491
+ notes = [_NOTES["written"] % ", ".join(written)] if written else []
1492
+ return out, notes + ([_NOTES["machinery"] % ", ".join(kept)] if kept else [])
1493
+
1494
+
1495
+ def for_texmath(tex: str, macros: Optional[Macros] = None, target: str = "mathml") -> "Tuple[str, List[str]]":
1496
+ """Rewrite `tex` for texmath, with notes on what was approximated."""
1497
+ own, _ = parse_definitions(tex)
1498
+ out, ok = _expand_definitions(tex, own, macros.needed(tex) if macros else [], for_writer=True)
1499
+ notes = [] if ok else [_NOTES["unexpanded"]]
1500
+ out = _refs(out, macros.labels if macros is not None else {})
1501
+ pack_hits: List[str] = []
1502
+ out = _expand_packs(out, tex, macros, own, pack_hits)
1503
+ hits: List[str] = []
1504
+ resized: List[str] = []
1505
+ layout: List[str] = []
1506
+ rows: List[str] = []
1507
+ out = _standard(out, rows)
1508
+ if rows:
1509
+ notes.append(_NOTES["intertext"])
1510
+ out = _environments(out, hits)
1511
+ out = _font_switches(out)
1512
+ out = _rename(out, _RENAMES, hits)
1513
+ out = _rename(out, _SYMBOLS, [])
1514
+ out = _sized_norms(out)
1515
+ if target in ("mathml", "omml"):
1516
+ out = _rename(out, _OFFICE_SYMBOLS, [])
1517
+ out = _bold_upright(out)
1518
+ out = _rename(out, _RESIZED, resized)
1519
+ out = _textcolor(out, hits)
1520
+ out = _commands(out, _UNWRAP, "unwrap", layout)
1521
+ out = _commands(out, _DROP_WITH_ARG, "drop_arg", layout)
1522
+ out = _commands(out, _DROP, "drop", layout)
1523
+ if "\\textcolor" in hits or re.search(r"\\color" + _CS, out):
1524
+ notes.append(_NOTES["colour"])
1525
+ if resized:
1526
+ notes.append(_NOTES["resized"] % ", ".join(sorted(set(resized))))
1527
+ if layout:
1528
+ notes.append(_NOTES["layout"] % ", ".join(sorted(set(layout))))
1529
+ if pack_hits:
1530
+ by_package: Dict[str, List[str]] = {}
1531
+ for hit in pack_hits:
1532
+ package, name = hit.split(": ", 1)
1533
+ if name not in by_package.setdefault(package, []):
1534
+ by_package[package].append(name)
1535
+ notes.append(_NOTES["packs"] % "; ".join("%s (%s)" % (", ".join(names), package)
1536
+ for package, names in by_package.items()))
1537
+ return out, notes