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/convert.py ADDED
@@ -0,0 +1,496 @@
1
+ """High-level conversion API used by the GUI and the command line."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ import unicodedata
6
+ from dataclasses import dataclass, field
7
+ from typing import List, Optional, Tuple
8
+
9
+ from . import compat, diagnose as _diagnose, latex_wrap, tidy as _tidy
10
+ from .pandoc_engine import (READ_FORMATS, WRITE_FORMATS, ConversionError, Equation, # noqa: F401
11
+ _has_math_delimiters, drop_annotations, looks_like_markdown, mathml_elements, parse_mathml,
12
+ read_equations, read_latex_text, readable_mathml, strip_tex, write_equation, write_equations,
13
+ write_mathml)
14
+
15
+ FORMAT_LABELS = {
16
+ "latex": "LaTeX",
17
+ "mathml": "MathML",
18
+ "omml": "OMML (Office Math)",
19
+ "eqn": "eqn (groff)",
20
+ "typst": "Typst",
21
+ }
22
+
23
+ MODES = [("auto", "Auto"), ("display", "Display"), ("inline", "Inline")]
24
+
25
+ _TAG_NOTE = "\\tag numbers are not carried over (Word / PowerPoint number equations themselves)."
26
+ _UNICODE_NOTE = "The LaTeX contains a Unicode character that pdfLaTeX may reject."
27
+
28
+
29
+ @dataclass
30
+ class Result:
31
+ equations: List[Equation]
32
+ outputs: List[str]
33
+ notes: List[str] = field(default_factory=list)
34
+
35
+ @property
36
+ def text(self) -> str:
37
+ return latex_wrap.join_outputs(self.outputs)
38
+
39
+
40
+ def apply_mode(eqs: List[Equation], mode: str) -> List[Equation]:
41
+ if mode == "display":
42
+ return [Equation(e.tex, True) for e in eqs]
43
+ if mode == "inline":
44
+ return [Equation(e.tex, False) for e in eqs]
45
+ return eqs
46
+
47
+
48
+ def _add(notes: List[str], new: List[str]) -> None:
49
+ for n in new:
50
+ if n not in notes:
51
+ notes.append(n)
52
+
53
+
54
+ def macro_notes(macros: Optional[compat.Macros]) -> List[str]:
55
+ """What went wrong while loading the macro files."""
56
+ if macros is None:
57
+ return []
58
+ notes = list(macros.errors)
59
+ if macros.skipped:
60
+ notes.append("macros not usable (delimited \\def parameters or malformed): " +
61
+ ", ".join(sorted(set(macros.skipped))))
62
+ return notes
63
+
64
+
65
+ def tidied(eq: Equation, display: Optional[bool] = None) -> Equation:
66
+ """An equation read from MathML / OMML with texmath's TeX cleaned up (:func:`tidy.tidy_tex`) for
67
+ output in `display` mode (default: the equation's); if the cleaned TeX no longer converts, texmath's."""
68
+ tex = _tidy.tidy_tex(eq.tex, eq.display if display is None else display)
69
+ if tex != eq.tex:
70
+ try:
71
+ write_mathml(Equation(compat.for_texmath(tex)[0], eq.display))
72
+ except ConversionError:
73
+ tex = eq.tex
74
+ return Equation(tex, eq.display)
75
+
76
+
77
+ def for_texmath(eq: Equation, src: str, macros: Optional[compat.Macros],
78
+ target: str = "mathml") -> "tuple[Equation, List[str]]":
79
+ """The equation as texmath gets it, through :func:`compat.for_texmath` (plain-TeX font switches,
80
+ \\notag, macros, texmath's symbol bugs...). The user's macros apply to LaTeX input only; LaTeX
81
+ read from MathML / OMML (texmath's or tidied) still needs the symbol and bold corrections."""
82
+ tex, notes = compat.for_texmath(eq.tex, macros if src == "latex" else None, target)
83
+ return Equation(tex, eq.display), notes if src == "latex" else []
84
+
85
+
86
+ def _write(prepared: Equation, dst: str, eq: Equation, which: str = "", **kw) -> str:
87
+ """write_equation, with texmath's parse error of LaTeX input explained in plain words first."""
88
+ try:
89
+ return write_equation(prepared, dst, **kw)
90
+ except ConversionError as e:
91
+ raise _diagnose.explained(e, eq.tex, prepared.tex, which) from None
92
+
93
+
94
+ # Markdown code: a fence, an indented block (after a blank line), `inline code`
95
+ _MARKDOWN_CODE = re.compile(r"^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1[^\n]*$|(?:(?<=\n\n)|^)(?:(?: {4}|\t)[^\n]*(?:\n|$))+"
96
+ r"|(`+)[\s\S]*?\2", re.M)
97
+
98
+
99
+ def input_macros(macros: Optional[compat.Macros], text: str, src: str,
100
+ as_markdown: bool = False, preamble: Optional[str] = None) -> Optional[compat.Macros]:
101
+ """The macros plus what LaTeX input defines outside its equations that pandoc's reader drops
102
+ (\\DeclarePairedDelimiter above $\\abs{x}$, as Open file's Use writes it) and the packages it loads;
103
+ in text read as Markdown (a chat answer), not from its code."""
104
+ if src != "latex":
105
+ return macros
106
+ # (also when both readings agreed and the LaTeX one was kept: the code is still no preamble)
107
+ markdown = as_markdown or ("\\" in text and looks_like_markdown(text))
108
+ leftovers = compat.pandoc_leftovers(_MARKDOWN_CODE.sub(" ", text) if markdown else text)
109
+ if preamble is None:
110
+ return compat.with_document(macros, leftovers)
111
+ document = [macros.document] if macros is not None else []
112
+ document.append(leftovers)
113
+ return compat.with_document(macros, "\n".join(part for part in document if part),
114
+ macros.labels if macros is not None else None, preamble=preamble)
115
+
116
+
117
+ def _read(text: str, src: str, mode: str, tidy: bool) -> List[Equation]:
118
+ return _read_text(text, src, mode, tidy)[0]
119
+
120
+
121
+ def _read_text(text: str, src: str, mode: str, tidy: bool) -> "tuple[List[Equation], bool]":
122
+ """The equations of the input, and whether LaTeX input was read as Markdown (a chat answer)."""
123
+ if src == "latex":
124
+ eqs, as_markdown = read_latex_text(text, default_display=(mode != "inline"))
125
+ return apply_mode(eqs, mode), as_markdown
126
+ return apply_mode(read_equations(text, src, default_display=(mode != "inline"), tidy=tidy), mode), False
127
+
128
+
129
+ _MARKDOWN_NOTE = ("Read as Markdown text (a chat answer, notes): % is a percent sign there and $5 is money; "
130
+ "the equations are those in $...$, $$...$$, \\(...\\) and \\[...\\].")
131
+
132
+
133
+ def _read_for_expansion(text: str, mode: str,
134
+ macros: Optional[compat.Macros]) -> Tuple[List[Equation], bool, Optional[compat.Macros]]:
135
+ """Keep preamble macro calls in the equations so the LaTeX writer can expand and report them."""
136
+ masked = None
137
+ if looks_like_markdown(text):
138
+ masked = _MARKDOWN_CODE.sub(lambda m: re.sub(r"[^\n]", " ", m.group()), text)
139
+ body, preamble = compat.before_equations(text, masked)
140
+ if preamble and not _has_math_delimiters(body):
141
+ body, preamble = text, "" # a bare equation keeps its own definitions
142
+ equations, markdown = read_latex_text(body, default_display=(mode != "inline"))
143
+ if preamble:
144
+ # A macro in the prose may make an equation of its own ($x$ or \ensuremath{M}): the reading with
145
+ # the macros applied finds it, and each equation of it is taken as written where the two line up.
146
+ full, _ = compat.before_equations(text, masked, defer=False)
147
+ try:
148
+ complete, as_markdown = read_latex_text(full, default_display=(mode != "inline"))
149
+ except ConversionError:
150
+ pass # expand each recovered equation separately
151
+ else:
152
+ if len(complete) != len(equations) or any(a.display != b.display for a, b in zip(complete, equations)):
153
+ from .documents import _matched
154
+ equations = [raw or eq for raw, eq in zip(_matched(complete, equations), complete)]
155
+ markdown = as_markdown
156
+ return apply_mode(equations, mode), markdown, input_macros(macros, body, "latex", markdown, preamble)
157
+
158
+
159
+ def convert(text: str, src: str, dst: str, mode: str = "auto", wrapper: str = "auto",
160
+ annotate: bool = False, macros: Optional[compat.Macros] = None, tidy: bool = True, *,
161
+ expand_macros: bool = False) -> Result:
162
+ """Convert `text` from format `src` to format `dst`.
163
+
164
+ mode "auto" (as detected from the input; bare LaTeX counts as display),
165
+ "display" or "inline" - the mode used for the *output*.
166
+ wrapper how LaTeX output is delimited (see latex_wrap.WRAPPERS); ignored otherwise.
167
+ annotate keep the TeX source as an <annotation> inside MathML output.
168
+ macros definitions applied to LaTeX input (:class:`compat.Macros`).
169
+ expand_macros also write out the macros when converting LaTeX to LaTeX.
170
+ tidy write LaTeX from MathML / OMML input as an author would (:mod:`tidy`).
171
+ """
172
+ if src not in READ_FORMATS:
173
+ raise ValueError("cannot read format %r" % src)
174
+ if dst not in WRITE_FORMATS:
175
+ raise ValueError("cannot write format %r" % dst)
176
+
177
+ expand = expand_macros and src == dst == "latex"
178
+ if expand:
179
+ eqs, as_markdown, macros = _read_for_expansion(text, mode, macros)
180
+ else:
181
+ eqs, as_markdown = _read_text(text, src, mode, tidy)
182
+ macros = input_macros(macros, text, src, as_markdown)
183
+ notes: List[str] = [_MARKDOWN_NOTE] if as_markdown else []
184
+ if len(eqs) > 1:
185
+ notes.append("%d equations found in the input; each was converted separately." % len(eqs))
186
+
187
+ outputs: List[str] = []
188
+ numbering_conflict = False
189
+ for i, eq in enumerate(eqs):
190
+ if dst == "latex":
191
+ display = not latex_wrap.wrapper_is_inline(wrapper, eq.display)
192
+ if expand:
193
+ tex, new = compat.expand_macros(eq.tex, macros)
194
+ eq = Equation(tex, eq.display)
195
+ _add(notes, new)
196
+ if tidy and src != "latex":
197
+ # for the mode of the output (\limits stays in $...$); bare: the equation's own mode
198
+ eq = tidied(eq, eq.display if wrapper == "bare" else display)
199
+ if src != "latex" and not eq.tex.isascii():
200
+ _add(notes, [_UNICODE_NOTE])
201
+ outputs.append(latex_wrap.wrap(eq.tex, wrapper, display))
202
+ numbering_conflict |= latex_wrap.numbering_conflict(eq.tex, wrapper, display)
203
+ # the mode of the output, which the wrapper decides (Auto: a kept environment)
204
+ eqs[i] = Equation(eq.tex, latex_wrap.output_is_display(eq.tex, wrapper, display))
205
+ else:
206
+ # (tidy_tex makes LaTeX for a paper: \backslash -> \setminus...; MathML / OMML output keeps
207
+ # the symbols of the input - the identifiers were already read right, see read_mathml)
208
+ prepared, new = for_texmath(eq, src, macros, dst)
209
+ _add(notes, new)
210
+ which = "Equation %d of %d" % (i + 1, len(eqs)) if len(eqs) > 1 else ""
211
+ outputs.append(_write(prepared, dst, eq, which, annotate=annotate, source=eq.tex))
212
+ if src == "latex" and re.search(r"\\tag(?![a-zA-Z@])", eq.tex):
213
+ _add(notes, [_TAG_NOTE])
214
+ if numbering_conflict:
215
+ notes.append("\\tag / \\label commands were kept, but LaTeX allows no \\tag and at most one "
216
+ "\\label in this wrapper - edit them, or choose the align wrapper.")
217
+ if src == "latex" and (dst != "latex" or expand):
218
+ _add(notes, macro_notes(macros))
219
+ if src == "mathml" and "annotation" in text:
220
+ _add(notes, annotation_notes(text, macros))
221
+ return Result(eqs, outputs, compat.merge_notes(notes) if expand else notes)
222
+
223
+
224
+ # ---- a TeX annotation that does not show what its MathML shows -----------------------------------
225
+ # characters that renderers use for the same thing (applied after NFKC, which folds 𝑥 / x, ϕ / φ and
226
+ # makes "…" "..."); MathType writes angle brackets as < >; invisible operators and zero-width spaces go
227
+ _SAME_SYMBOL = {ord(a): b for a, b in (
228
+ ("⋅", "·"), ("∙", "·"), ("−", "-"), ("∗", "*"), ("∣", "|"), ("∥", "‖"), ("⋯", "..."), ("⩽", "≤"), ("⩾", "≥"),
229
+ ("⟨", "<"), ("〈", "<"), ("〈", "<"), ("⟩", ">"), ("〉", ">"), ("〉", ">"), ("≔", ":="), ("⟺", "⇔"), ("⟹", "⇒"),
230
+ ("⟸", "⇐"), ("⟷", "↔"), ("⟶", "→"), ("⟵", "←"), ("⟼", "↦"))}
231
+ _SAME_SYMBOL.update({cp: None for cp in (0x2061, 0x2062, 0x2063, 0x2064, 0x200B)})
232
+ # what renderers put over or under a symbol as an accent or a bar, brace or arrow, each in its own way
233
+ # (\hat: ^ ˆ U+0302; \overline: ‾ ¯ ―; \vec, \underleftarrow: arrows; ...)
234
+ _ACCENTS = frozenset("^ˆ~˜¯‾ˉ―_˘ˇ˙¨´`°˚‿⁀⏞⏟⏜⏝⎴⎵︷︸→←↔⟶⟵⟷⇀↼⃗" + "".join(map(chr, range(0x0300, 0x0370)))
235
+ + "".join(map(chr, range(0x20D0, 0x20F0))))
236
+ # names that take limits over and under them (\lim_{x\to 0}; Word writes "lim" as <mi>)
237
+ _LIMIT_NAMES = frozenset("lim limsup liminf max min sup inf det gcd Pr arg".split())
238
+ _SCRIPTS = {"msub": "_", "munder": "_", "msup": "^", "mover": "^", "msubsup": "_^", "munderover": "_^"}
239
+ _PRESENTATION_TOKENS = frozenset("mi mn mo mtext ms mfenced".split())
240
+ _OPEN, _CLOSE = "", "" # the bounds of a script's or fraction's argument (not a shown { })
241
+
242
+
243
+ def _local(el) -> str:
244
+ return el.tag.rsplit("}", 1)[-1] if isinstance(el.tag, str) else ""
245
+
246
+
247
+ def _is_accent(base, child) -> bool:
248
+ """Whether `child`, over or under `base`, is an accent (a bar, brace, arrow, hat...) rather than a
249
+ script or limit: an <mo> of accent characters over or under anything but an operator (∑, lim, =).
250
+ Decided by what is shown, not by the accent / accentunder attributes: renderers set them each in
251
+ their own way (Word's overline is accent="false", texmath's arrow under \\lim accent="true")."""
252
+ text = "".join(child.itertext()).strip()
253
+ if _local(child) != "mo" or not text or not all(ch in _ACCENTS for ch in text):
254
+ return False
255
+ shown = unicodedata.normalize("NFKC", "".join(base.itertext())).strip()
256
+ operator = _local(base) == "mo" or shown in _LIMIT_NAMES or (
257
+ len(shown) == 1 and unicodedata.category(shown) == "Sm")
258
+ return not operator
259
+
260
+
261
+ def _symbols(math) -> str:
262
+ """What a <math> shows, for comparing two renderings of an equation: its symbols in order, a script
263
+ (_{..} ^{..}), fraction ({..}/{..}) or root (√{..}) marked with its arguments' bounds, the fences of
264
+ <mfenced> written out, prescripts before their base; no spacing, no invisible operators, nothing
265
+ in <mphantom>, font variants folded (NFKC), accents left out (renderers write them with different
266
+ characters). Sub- and superscripts and limits under or over an operator are marked alike:
267
+ renderers choose between them by display mode."""
268
+ out: List[str] = []
269
+
270
+ def arg(el, mark: str = "") -> None:
271
+ """An argument within its bounds, after `mark` (_ ^); a script with nothing in it is left out."""
272
+ start = len(out)
273
+ out.extend((mark, _OPEN))
274
+ walk(el)
275
+ if mark and not "".join(out[start + 2:]).translate(_SAME_SYMBOL).strip():
276
+ del out[start:]
277
+ else:
278
+ out.append(_CLOSE)
279
+
280
+ def walk(el) -> None:
281
+ tag = _local(el)
282
+ kids = [k for k in el if _local(k) != "none"] if tag != "mmultiscripts" else list(el)
283
+ if tag == "mphantom":
284
+ return
285
+ if tag == "mfenced":
286
+ seps = [ch for ch in el.get("separators", ",") if not ch.isspace()]
287
+ out.append(el.get("open", "("))
288
+ for k, child in enumerate(kids):
289
+ if k and seps:
290
+ out.append(seps[min(k - 1, len(seps) - 1)])
291
+ walk(child)
292
+ out.append(el.get("close", ")"))
293
+ return
294
+ out.append(el.text or "")
295
+ if tag in _SCRIPTS and kids:
296
+ walk(kids[0])
297
+ for mark, child in zip(_SCRIPTS[tag], kids[1:]):
298
+ if tag in ("mover", "munder", "munderover") and _is_accent(kids[0], child):
299
+ continue
300
+ arg(child, mark)
301
+ return
302
+ if tag == "mmultiscripts" and kids: # base, (sub sup)*, <mprescripts/>, (sub sup)*
303
+ names = [_local(k) for k in kids]
304
+ split = names.index("mprescripts") if "mprescripts" in names else len(kids)
305
+ post, pre = kids[1:split], kids[split + 1:]
306
+ for scripts in (pre, None, post):
307
+ if scripts is None:
308
+ walk(kids[0])
309
+ continue
310
+ for k in range(0, len(scripts) - 1, 2):
311
+ for mark, child in (("_", scripts[k]), ("^", scripts[k + 1])):
312
+ if _local(child) != "none":
313
+ arg(child, mark)
314
+ return
315
+ if tag == "mfrac" and len(kids) == 2:
316
+ arg(kids[0])
317
+ out.append("/")
318
+ arg(kids[1])
319
+ return
320
+ if tag in ("msqrt", "mroot"):
321
+ out.append("√")
322
+ if tag == "mroot" and len(kids) == 2:
323
+ arg(kids[1])
324
+ kids = kids[:1]
325
+ out.append(_OPEN)
326
+ for child in kids:
327
+ walk(child)
328
+ out.append(_CLOSE)
329
+ return
330
+ k = 0
331
+ while k < len(kids):
332
+ # Word's linear fraction (\tfrac, a/b typed in Word): <mrow>a</mrow><mo>/</mo><mrow>b</mrow>
333
+ if k + 2 < len(kids) and _local(kids[k]) == _local(kids[k + 2]) == "mrow" \
334
+ and _local(kids[k + 1]) == "mo" and (kids[k + 1].text or "").strip() == "/":
335
+ arg(kids[k])
336
+ out.append("/")
337
+ arg(kids[k + 2])
338
+ k += 3
339
+ continue
340
+ walk(kids[k])
341
+ k += 1
342
+
343
+ walk(math)
344
+ text = unicodedata.normalize("NFKC", "".join(out)).translate(_SAME_SYMBOL)
345
+ return "".join(ch for ch in text if not ch.isspace())
346
+
347
+
348
+ def annotation_notes(text: str, macros: Optional[compat.Macros] = None) -> List[str]:
349
+ """MathML that carries its TeX source as an annotation (MathType, KaTeX / MathJax pages, the "TeX
350
+ annotation" option): a note for each <math> whose annotation shows something else than the MathML
351
+ itself, which the conversion follows - it was edited after the TeX was written. Not compared: an
352
+ annotation that cannot be read (macros not given), and an equation whose MathML texmath cannot read
353
+ (Content MathML, KaTeX's \\dddot): its LaTeX comes from the annotation. The annotations are drawn
354
+ by texmath in one pandoc run, in each equation's mode."""
355
+ try:
356
+ maths = parse_mathml(text)
357
+ except ConversionError:
358
+ return []
359
+ annotations = [drop_annotations(math) for math in maths] # what is left of each is what it shows
360
+ try:
361
+ readable = readable_mathml(maths)
362
+ except ConversionError:
363
+ return []
364
+ todo = [] # (number, math, annotation, the annotation as texmath gets it)
365
+ for i, (math, tex, ok) in enumerate(zip(maths, annotations, readable), 1):
366
+ if not ok or not tex or not tex.strip() or not any(_local(e) in _PRESENTATION_TOKENS for e in math.iter()):
367
+ continue
368
+ try:
369
+ prepared, _ = for_texmath(Equation(strip_tex(tex), math.get("display") == "block"), "latex", macros)
370
+ except ConversionError:
371
+ continue
372
+ todo.append((i, math, tex, prepared))
373
+ if not todo:
374
+ return []
375
+ try:
376
+ drawn = mathml_elements([t[3] for t in todo])
377
+ except ConversionError:
378
+ return []
379
+ notes: List[str] = []
380
+ for (i, math, tex, _), annotated in zip(todo, drawn):
381
+ if annotated is None or _symbols(math) == _symbols(annotated):
382
+ continue
383
+ short = " ".join(tex.split())
384
+ short = short if len(short) <= 60 else short[:57] + "..."
385
+ which = "" if len(maths) == 1 else " of equation %d" % i
386
+ notes.append("The TeX annotation%s (%s) does not show what the MathML shows: it may be out of date. "
387
+ "The LaTeX here is what the MathML shows." % (which, short))
388
+ return notes
389
+
390
+
391
+ def convert_equation(eq: Equation, dst: str, wrapper: str = "auto", macros: Optional[compat.Macros] = None,
392
+ annotate: bool = False, *, expand_macros: bool = False) -> "tuple[str, List[str]]":
393
+ """One equation given as LaTeX (a document's, or tidied from Office) in format `dst`, and notes."""
394
+ if dst == "latex":
395
+ display = not latex_wrap.wrapper_is_inline(wrapper, eq.display)
396
+ tex, notes = compat.expand_macros(eq.tex, macros) if expand_macros else (eq.tex, [])
397
+ return latex_wrap.wrap(tex, wrapper, display), notes
398
+ prepared, notes = for_texmath(eq, "latex", macros, dst)
399
+ return _write(prepared, dst, eq, annotate=annotate, source=eq.tex), notes
400
+
401
+
402
+ def convert_equations(eqs: List[Equation], dst: str, wrapper: str = "auto",
403
+ macros: Optional[compat.Macros] = None, *,
404
+ expand_macros: bool = False) -> list[tuple[str, List[str]] | ConversionError]:
405
+ """Document equations in order, with the same notes or error as converting each separately."""
406
+ if dst == "latex":
407
+ return [convert_equation(eq, dst, wrapper, macros, expand_macros=expand_macros) for eq in eqs]
408
+ keys = [(eq.tex, eq.display) for eq in eqs]
409
+ results = {}
410
+ pending = []
411
+ for key in dict.fromkeys(keys):
412
+ eq = Equation(*key)
413
+ try:
414
+ prepared, notes = for_texmath(eq, "latex", macros, dst)
415
+ except ConversionError as e:
416
+ results[key] = e
417
+ else:
418
+ pending.append((key, eq, prepared, notes))
419
+ try:
420
+ outputs = write_equations([prepared for _, _, prepared, _ in pending], dst)
421
+ except ConversionError: # e.g. timeout of the whole writer: recover individual results
422
+ outputs = [None] * len(pending)
423
+ for (key, eq, prepared, notes), output in zip(pending, outputs):
424
+ if output is None:
425
+ try:
426
+ output = _write(prepared, dst, eq)
427
+ except ConversionError as e:
428
+ results[key] = e
429
+ continue
430
+ results[key] = output, notes
431
+ return [results[key] for key in keys]
432
+
433
+
434
+ @dataclass
435
+ class OfficeCopy:
436
+ mathml: str # for the clipboard: Word / PowerPoint paste a native equation
437
+ latex: str # the same (first) equation as LaTeX. Not for the clipboard's plain-text
438
+ # format: Word pastes from that one (see clipboard.copy_mathml_for_office)
439
+ notes: List[str] = field(default_factory=list)
440
+ source: Optional[Equation] = None # the LaTeX it was made from, as written (for recall.remember)
441
+
442
+ def remember(self) -> None:
443
+ """Note it for Paste from Word/PowerPoint (recall): after it is on the clipboard."""
444
+ if self.source is not None:
445
+ from . import recall
446
+ recall.remember(self.mathml, self.source.tex, self.source.display)
447
+
448
+
449
+ class Equations(list):
450
+ """Equations of an input, and whether it was read as Markdown (a chat answer), for the note."""
451
+ as_markdown = False
452
+
453
+
454
+ def input_equations(text: str, src: str, mode: str = "auto", tidy: bool = True) -> List[Equation]:
455
+ """The equations of the input, in order: what "Copy for Word/PowerPoint" can copy (by index)."""
456
+ eqs, as_markdown = _read_text(text, src, mode, tidy)
457
+ found = Equations(eqs)
458
+ found.as_markdown = as_markdown
459
+ return found
460
+
461
+
462
+ def office_copy(text: str, src: str, mode: str = "auto", macros: Optional[compat.Macros] = None,
463
+ tidy: bool = True, index: int = 0, eqs: Optional[List[Equation]] = None) -> OfficeCopy:
464
+ """What "Copy for Word/PowerPoint" puts on the clipboard: equation `index` (0: the first) of the
465
+ input; Word and PowerPoint paste one equation at a time. `eqs`: the input's equations, when the
466
+ caller read them already (:func:`input_equations` with the same arguments)."""
467
+ as_markdown = getattr(eqs, "as_markdown", False) # (eqs from input_equations)
468
+ if eqs is None:
469
+ eqs, as_markdown = _read_text(text, src, mode, tidy)
470
+ if not 0 <= index < len(eqs):
471
+ raise ConversionError("There is no equation %d: the input has %d." % (index + 1, len(eqs)))
472
+ macros = input_macros(macros, text, src, as_markdown)
473
+ notes: List[str] = [_MARKDOWN_NOTE] if as_markdown else []
474
+ if len(eqs) > 1:
475
+ notes.append("Equation %d of the %d in the input was copied." % (index + 1, len(eqs)))
476
+ eq = eqs[index]
477
+ prepared, new = for_texmath(eq, src, macros)
478
+ _add(notes, new)
479
+ if src == "latex":
480
+ if re.search(r"\\tag(?![a-zA-Z@])", eq.tex):
481
+ _add(notes, [_TAG_NOTE])
482
+ _add(notes, macro_notes(macros))
483
+ which = "Equation %d of %d" % (index + 1, len(eqs)) if len(eqs) > 1 and src == "latex" else ""
484
+ mathml = _write(prepared, "mathml", eq, which, for_office=True)
485
+ latex = tidied(eq) if tidy and src != "latex" else eq
486
+ if src != "latex" and not latex.tex.isascii():
487
+ _add(notes, [_UNICODE_NOTE])
488
+ return OfficeCopy(mathml, latex_wrap.wrap(latex.tex, "auto", eq.display), notes,
489
+ source=eq if src == "latex" else None)
490
+
491
+
492
+ def mathml_for_office(text: str, src: str, mode: str = "auto",
493
+ macros: Optional[compat.Macros] = None) -> "tuple[str, Optional[str]]":
494
+ """MathML (first equation) to place on the clipboard for Word/PowerPoint, plus a note."""
495
+ copy = office_copy(text, src, mode, macros)
496
+ return copy.mathml, " ".join(copy.notes) or None