mathshuttle 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,903 @@
1
+ """Equations in whole documents: .docx, .pptx (OMML), .tex, .md - with where each one is.
2
+
3
+ Office files are read here, not by pandoc's docx / pptx readers, so that their equations go through
4
+ :func:`pandoc_engine.read_omml` like a pasted one (Tidy LaTeX included) and keep their location
5
+ (the heading above them, the slide and its title, the footnote). What a reader of the final document
6
+ sees is read: tracked deletions are skipped, one of a markup-compatibility block's alternatives is
7
+ read. Equation objects of the old Equation Editor 3.0 and MathType (OLE objects, no OMML inside)
8
+ cannot be read; they are counted so that the user knows.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import posixpath
15
+ import re
16
+ import tempfile
17
+ import time
18
+ import zipfile
19
+ import xml.etree.ElementTree as ET
20
+ from dataclasses import dataclass, field
21
+ from typing import Callable, Dict, List, Optional, Tuple
22
+
23
+ from . import compat
24
+ from .pandoc_engine import (MC_NS, OMML_NS, WML_NS, ConversionError, Equation, _api, _collect_math, _run,
25
+ markdown_blocks, markdown_maths, read_omml, split_math_paragraph)
26
+
27
+ P_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"
28
+ A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
29
+ R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
30
+ REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
31
+ # Strict Open XML (ISO 29500 strict) names the same vocabularies differently
32
+ _STRICT = {
33
+ "http://purl.oclc.org/ooxml/officeDocument/math": OMML_NS,
34
+ "http://purl.oclc.org/ooxml/wordprocessingml/main": WML_NS,
35
+ "http://purl.oclc.org/ooxml/presentationml/main": P_NS,
36
+ "http://purl.oclc.org/ooxml/drawingml/main": A_NS,
37
+ "http://purl.oclc.org/ooxml/officeDocument/relationships": R_NS,
38
+ }
39
+
40
+ READABLE = {".docx": "Word document", ".pptx": "PowerPoint presentation", ".tex": "LaTeX file",
41
+ ".md": "Markdown file"}
42
+ FILE_TYPES = [("Documents with equations", "*.docx *.pptx *.tex *.md"), ("Word", "*.docx"),
43
+ ("PowerPoint", "*.pptx"), ("LaTeX", "*.tex"), ("Markdown", "*.md")]
44
+ MARK = "\u25a1" # where the equation is, in its context
45
+ _LEGACY = re.compile(r"Equation\.(?:3|DSMT\d*)|MathType", re.I)
46
+
47
+
48
+ @dataclass
49
+ class Found:
50
+ equation: Equation
51
+ where: str # "Method", "slide 2: Update rule", "footnote 3", "Bounds [eq:bound]"
52
+ context: str = "" # the text around it, shortened, with MARK for the equation
53
+
54
+ def numbered_location(self, labels: Dict[str, str]) -> str:
55
+ if labels and r"\label" in self.equation.tex:
56
+ # Skip commented labels and escaped backslashes. TeX permits whitespace before the key.
57
+ for m in re.finditer(r"%[^\n]*|\\label(?:\s|%[^\n]*\n)*\{([^{}]+)\}|\\.", self.equation.tex):
58
+ key = m[1]
59
+ if key in labels:
60
+ heading = re.sub(r" \[[^{}]*\]$", "", self.where)
61
+ return f"{heading} [{key}] ({labels[key]})"
62
+ return self.where
63
+
64
+
65
+ @dataclass
66
+ class EquationRow:
67
+ number: int # original position in the document, starting at 1
68
+ found: Found
69
+ where: str # location including the number from LaTeX, when available
70
+ count: int = 0 # occurrence count when grouped
71
+
72
+ @property
73
+ def location(self) -> str:
74
+ return f"{self.where} ({self.count}x)" if self.count else self.where
75
+
76
+
77
+ @dataclass
78
+ class DocumentEquations:
79
+ path: str
80
+ source: str # "latex" when the equations are the document's own LaTeX, else "office"
81
+ found: List[Found] = field(default_factory=list)
82
+ notes: List[str] = field(default_factory=list)
83
+ # a .tex file: its own source and that of the local files it reads, for the definitions pandoc does
84
+ # not apply (\DeclarePairedDelimiter, the \foreach alphabet idiom...); its \label numbers (.aux)
85
+ definitions: str = ""
86
+ labels: Dict[str, str] = field(default_factory=dict)
87
+ # read for Expand macros: the preamble's definitions with an @ in them too (\text{a@b}; an \eqlabel made
88
+ # of \@namedef, which is then kept as written with a note), which `definitions` leaves out
89
+ expansion_definitions: str = ""
90
+
91
+ def rows(self, display: bool = False, unique: bool = False, match: str = "") -> List[EquationRow]:
92
+ """Matching occurrences in source order. Group equal LaTeX after applying both filters."""
93
+ rows: List[EquationRow] = []
94
+ first: Dict[str, EquationRow] = {}
95
+ needle = match.casefold()
96
+ for number, found in enumerate(self.found, 1):
97
+ eq = found.equation
98
+ if display and not eq.display:
99
+ continue
100
+ where = found.numbered_location(self.labels)
101
+ if needle and needle not in eq.tex.casefold() and needle not in where.casefold():
102
+ continue
103
+ if unique and eq.tex in first:
104
+ first[eq.tex].count += 1
105
+ continue
106
+ row = EquationRow(number, found, where, 1 if unique else 0)
107
+ rows.append(row)
108
+ if unique:
109
+ first[eq.tex] = row
110
+ return rows
111
+
112
+ def macros(self, user: Optional[compat.Macros]) -> Optional[compat.Macros]:
113
+ """The macros for this document's equations: the user's files apply to a document's own LaTeX
114
+ (with its own definitions, which win), not to equations read from Office."""
115
+ if self.source != "latex":
116
+ return None
117
+ return compat.with_document(user, self.definitions, self.labels, preamble=self.expansion_definitions)
118
+
119
+
120
+ def _q(ns: str, tag: str) -> str:
121
+ return "{%s}%s" % (ns, tag)
122
+
123
+
124
+ _MATH_TAGS = (_q(OMML_NS, "oMathPara"), _q(OMML_NS, "oMath"))
125
+ # tracked changes: what the final document no longer holds
126
+ _DELETED = (_q(WML_NS, "del"), _q(WML_NS, "moveFrom"))
127
+
128
+
129
+ def decode_text(data: bytes) -> str:
130
+ """Text with a UTF-16 / UTF-8 byte-order mark, or UTF-8."""
131
+ if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
132
+ return data.decode("utf-16")
133
+ return data.decode("utf-8-sig")
134
+
135
+
136
+ def _parse(data: bytes) -> ET.Element:
137
+ """An Office XML part (UTF-8 or UTF-16, Transitional or Strict) as Transitional XML."""
138
+ if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
139
+ text = data.decode("utf-16")
140
+ elif data[1:2] == b"\0": # UTF-16 without a byte-order mark: "<" then a zero byte
141
+ text = data.decode("utf-16-le")
142
+ elif data[:1] == b"\0":
143
+ text = data.decode("utf-16-be")
144
+ else:
145
+ text = data.decode("utf-8-sig")
146
+ text = re.sub(r"^\s*<\?xml[^>]*\?>", "", text) # the declaration names the bytes' encoding, not the text's
147
+ for strict, transitional in _STRICT.items():
148
+ text = text.replace(strict, transitional)
149
+ return ET.fromstring(text)
150
+
151
+
152
+ def _walk(el: ET.Element, visit: Callable[[ET.Element], bool], leave: Optional[Callable[[ET.Element], None]] = None) -> None:
153
+ """Depth-first, in document order; of a markup-compatibility block only the first Choice (the
154
+ Fallback repeats the same content, e.g. as a picture), nothing of a tracked deletion. `visit`
155
+ returns False to skip the children; `leave` is called after the children of a visited element."""
156
+ for child in el:
157
+ if child.tag == _q(MC_NS, "AlternateContent"):
158
+ branches = list(child)
159
+ branch = next((b for b in branches if b.tag == _q(MC_NS, "Choice")), branches[0] if branches else None)
160
+ if branch is not None:
161
+ _walk(branch, visit, leave)
162
+ continue
163
+ if child.tag in _DELETED:
164
+ continue
165
+ if visit(child):
166
+ _walk(child, visit, leave)
167
+ if leave:
168
+ leave(child)
169
+
170
+
171
+ def _shorten(text: str, limit: int = 90) -> str:
172
+ text = " ".join(text.split())
173
+ return text if len(text) <= limit else text[:limit - 1] + "\u2026"
174
+
175
+
176
+ def _context(para: Optional[ET.Element], ns: str, math: ET.Element) -> str:
177
+ """The text of the paragraph holding `math`, with MARK where it is (other equations: …)."""
178
+ if para is None:
179
+ return ""
180
+ parts: List[str] = []
181
+
182
+ def visit(el):
183
+ if el.tag in _MATH_TAGS:
184
+ parts.append(MARK if el is math or math in el.iter() else "\u2026")
185
+ return False
186
+ if el.tag == _q(ns, "p") and el is not para:
187
+ return False # a paragraph nested in this one (a text box) has its own context
188
+ if el.tag == _q(ns, "t") and el.text:
189
+ parts.append(el.text)
190
+ return True
191
+
192
+ _walk(para, visit)
193
+ text = "".join(parts).strip()
194
+ return "" if text == MARK else _shorten(text)
195
+
196
+
197
+ def _is_legacy_object(el: ET.Element) -> bool:
198
+ """An Equation Editor 3.0 / MathType OLE object (Word: o:OLEObject ProgID, PowerPoint: p:oleObj progId)."""
199
+ return bool(_LEGACY.match(el.get("ProgID") or el.get("progId") or ""))
200
+
201
+
202
+ class _Collector:
203
+ """Equations found while walking the parts of a document, with where they are."""
204
+
205
+ def __init__(self) -> None:
206
+ self.fragments: List[ET.Element] = []
207
+ self.places: List[Tuple[str, str]] = []
208
+ self.display: List[bool] = []
209
+ self.legacy = 0
210
+
211
+ def add(self, math: ET.Element, where: str, context: str, display: bool = False) -> None:
212
+ for piece in split_math_paragraph(math): # several equations in one math paragraph
213
+ self.fragments.append(piece)
214
+ self.places.append((where, context))
215
+ self.display.append(display or piece.tag == _q(OMML_NS, "oMathPara"))
216
+
217
+ def result(self, path: str) -> DocumentEquations:
218
+ from .convert import tidied, _UNICODE_NOTE
219
+
220
+ result = DocumentEquations(path, "office")
221
+ for eq, (where, context), display in zip(_read_fragments(self.fragments), self.places, self.display):
222
+ if eq is None:
223
+ result.notes.append("an equation in %s could not be read" % where)
224
+ continue
225
+ # A standalone equation on a slide is display maths even in a bare m:oMath.
226
+ eq = tidied(Equation(eq.tex, eq.display or display))
227
+ result.found.append(Found(eq, where, context))
228
+ if not eq.tex.isascii() and _UNICODE_NOTE not in result.notes:
229
+ result.notes.append(_UNICODE_NOTE)
230
+ if self.legacy:
231
+ result.notes.append("%d Equation Editor 3.0 / MathType object(s) cannot be read (no OMML inside)"
232
+ % self.legacy)
233
+ return result
234
+
235
+
236
+ def _read_fragments(fragments: List[ET.Element]) -> List[Optional[Equation]]:
237
+ """The equations of OMML fragments, one per fragment: all in one pandoc
238
+ run, or one by one if the counts do not match (a fragment texmath skips: None)."""
239
+ if not fragments:
240
+ return []
241
+ xml = "".join(ET.tostring(f, encoding="unicode") for f in fragments)
242
+ try:
243
+ eqs: List[Optional[Equation]] = list(read_omml(xml))
244
+ if len(eqs) != len(fragments):
245
+ raise ConversionError("counts differ")
246
+ except ConversionError:
247
+ eqs = []
248
+ for f in fragments:
249
+ try:
250
+ eqs.append(read_omml(ET.tostring(f, encoding="unicode"))[0])
251
+ except ConversionError:
252
+ eqs.append(None)
253
+ return eqs
254
+
255
+
256
+ # ---- Word ----------------------------------------------------------------------------------------
257
+ def _heading_styles(z: zipfile.ZipFile) -> set:
258
+ """Style ids of headings and titles (localised Office versions use ids such as "1", "2")."""
259
+ try:
260
+ styles = _parse(z.read("word/styles.xml"))
261
+ except KeyError:
262
+ return set()
263
+ ids = set()
264
+ for st in styles.iter(_q(WML_NS, "style")):
265
+ name = st.find(_q(WML_NS, "name"))
266
+ value = ((name.get(_q(WML_NS, "val")) if name is not None else "") or "").lower()
267
+ if re.match(r"(heading \d|title)$", value) or _outline_level(st) is not None:
268
+ ids.add(st.get(_q(WML_NS, "styleId")))
269
+ return ids
270
+
271
+
272
+ def _outline_level(el: ET.Element) -> Optional[int]:
273
+ """The outline level 0-8 of a paragraph or style (9 is body text), or None."""
274
+ outline = el.find("%s/%s" % (_q(WML_NS, "pPr"), _q(WML_NS, "outlineLvl")))
275
+ try:
276
+ level = int(outline.get(_q(WML_NS, "val"))) if outline is not None else None
277
+ except (TypeError, ValueError):
278
+ return None
279
+ return level if level is not None and 0 <= level <= 8 else None
280
+
281
+
282
+ def _walk_word_part(root: ET.Element, headings: set, collector: _Collector, where: Optional[str] = None) -> None:
283
+ """The equations of a Word part; `where`: a fixed location (a footnote), else the heading above."""
284
+ state = {"heading": "", "paras": []}
285
+
286
+ def visit(el):
287
+ if el.tag == _q(WML_NS, "p"):
288
+ style = el.find("%s/%s" % (_q(WML_NS, "pPr"), _q(WML_NS, "pStyle")))
289
+ if where is None and ((style is not None and style.get(_q(WML_NS, "val")) in headings)
290
+ or _outline_level(el) is not None):
291
+ state["heading"] = _shorten("".join(t.text or "" for t in el.iter(_q(WML_NS, "t"))), 60)
292
+ state["paras"].append(el)
293
+ return True
294
+ if _is_legacy_object(el):
295
+ collector.legacy += 1
296
+ if el.tag in _MATH_TAGS:
297
+ para = state["paras"][-1] if state["paras"] else None
298
+ collector.add(el, where or state["heading"] or "(before the first heading)", _context(para, WML_NS, el))
299
+ return False
300
+ return True
301
+
302
+ def leave(el):
303
+ if el.tag == _q(WML_NS, "p") and state["paras"]:
304
+ state["paras"].pop() # back to the paragraph around a text box
305
+
306
+ _walk(root, visit, leave)
307
+
308
+
309
+ def read_docx(path: str) -> DocumentEquations:
310
+ collector = _Collector()
311
+ with zipfile.ZipFile(path) as z:
312
+ names = set(z.namelist())
313
+ headings = _heading_styles(z)
314
+ _walk_word_part(_parse(z.read("word/document.xml")), headings, collector)
315
+ for part, kind in (("word/footnotes.xml", "footnote"), ("word/endnotes.xml", "endnote")):
316
+ if part not in names:
317
+ continue
318
+ for note in _parse(z.read(part)):
319
+ if note.get(_q(WML_NS, "type")) in ("separator", "continuationSeparator", "continuationNotice"):
320
+ continue
321
+ _walk_word_part(note, headings, collector, "%s %s" % (kind, note.get(_q(WML_NS, "id"), "?")))
322
+ return collector.result(path)
323
+
324
+
325
+ # ---- PowerPoint ----------------------------------------------------------------------------------
326
+ def _targets(z: zipfile.ZipFile, part: str) -> List[Tuple[str, str, str]]:
327
+ """(id, type, part name) of the relationships of `part`."""
328
+ folder, name = posixpath.split(part)
329
+ rels = posixpath.join(folder, "_rels", name + ".rels")
330
+ if rels not in z.namelist():
331
+ return []
332
+ out = []
333
+ for r in _parse(z.read(rels)).iter(_q(REL_NS, "Relationship")):
334
+ target = r.get("Target") or ""
335
+ resolved = target.lstrip("/") if target.startswith("/") else posixpath.normpath(posixpath.join(folder, target))
336
+ out.append((r.get("Id"), r.get("Type") or "", resolved))
337
+ return out
338
+
339
+
340
+ def _slide_paths(z: zipfile.ZipFile) -> List[str]:
341
+ """The slide parts in presentation order (the file names need not follow it)."""
342
+ targets = {rid: target for rid, _, target in _targets(z, "ppt/presentation.xml")}
343
+ pres = _parse(z.read("ppt/presentation.xml"))
344
+ return [targets[s.get(_q(R_NS, "id"))] for s in pres.iter(_q(P_NS, "sldId")) if s.get(_q(R_NS, "id")) in targets]
345
+
346
+
347
+ def _walk_slide_part(root: ET.Element, where: str, collector: _Collector, notes: bool = False) -> None:
348
+ state = {"paras": []}
349
+
350
+ def visit(el):
351
+ if el.tag == _q(P_NS, "sp") and notes:
352
+ ph = el.find(".//" + _q(P_NS, "ph"))
353
+ if ph is None or ph.get("type") != "body":
354
+ return False # a notes page also holds the slide picture and a page number
355
+ if el.tag == _q(A_NS, "p"):
356
+ state["paras"].append(el)
357
+ return True
358
+ if _is_legacy_object(el):
359
+ collector.legacy += 1
360
+ if el.tag in _MATH_TAGS:
361
+ para = state["paras"][-1] if state["paras"] else None
362
+ context = _context(para, A_NS, el)
363
+ # PowerPoint keeps every equation inline (m:oMath); one alone in its paragraph shows as display
364
+ collector.add(el, where, context, display=not context)
365
+ return False
366
+ return True
367
+
368
+ def leave(el):
369
+ if el.tag == _q(A_NS, "p") and state["paras"]:
370
+ state["paras"].pop()
371
+
372
+ _walk(root, visit, leave)
373
+
374
+
375
+ def read_pptx(path: str) -> DocumentEquations:
376
+ collector = _Collector()
377
+ with zipfile.ZipFile(path) as z:
378
+ names = set(z.namelist())
379
+ for number, slide in enumerate(_slide_paths(z), 1):
380
+ if slide not in names:
381
+ continue
382
+ root = _parse(z.read(slide))
383
+ title = ""
384
+ for sp in root.iter(_q(P_NS, "sp")):
385
+ ph = sp.find(".//" + _q(P_NS, "ph"))
386
+ if ph is not None and ph.get("type") in ("title", "ctrTitle"):
387
+ title = _shorten("".join(t.text or "" for t in sp.iter(_q(A_NS, "t"))), 50)
388
+ break
389
+ where = "slide %d" % number + (": " + title if title else "")
390
+ _walk_slide_part(root, where, collector)
391
+ for _, kind, target in _targets(z, slide):
392
+ if kind.endswith("/notesSlide") and target in names:
393
+ _walk_slide_part(_parse(z.read(target)), "slide %d notes" % number, collector, notes=True)
394
+ return collector.result(path)
395
+
396
+
397
+ # ---- LaTeX and Markdown --------------------------------------------------------------------------
398
+ def _inline_text(node, words: List[str]) -> None:
399
+ if isinstance(node, dict):
400
+ t = node.get("t")
401
+ if t == "Str":
402
+ words.append(node["c"])
403
+ elif t in ("Space", "SoftBreak"):
404
+ words.append(" ")
405
+ elif t == "Math":
406
+ words.append("$%s$" % node["c"][1])
407
+ else:
408
+ _inline_text(node.get("c"), words)
409
+ elif isinstance(node, list):
410
+ for n in node:
411
+ _inline_text(n, words)
412
+
413
+
414
+ _READS = re.compile(r"\\(input|include|subfile|usepackage|RequirePackage)\s*(?:\[[^\]]*\])?\s*\{([^{}]+)\}")
415
+ # \newlabel{key}{{number}{page}{title}{anchor}{}} (hyperref); without hyperref only {number}{page};
416
+ # cleveref adds \newlabel{key@cref}{{[equation][7][]7}{[1][1][]1}}
417
+ _NEWLABEL_START = re.compile(r"\\newlabel\{([^{}]+)\}\s*\{")
418
+ _AUX_INPUT = re.compile(r"\\@input\{([^{}]+)\}")
419
+ # \bibcite{key}{12}, or natbib's \bibcite{key}{{12}{2020}{{Smith et~al.}}{{Smith, Jones, and Lee}}} (its
420
+ # argument read by brace depth: a name holds {\"o})
421
+ _BIBCITE = re.compile(r"\\bibcite\{([^{}]+)\}\s*\{")
422
+ _TEX_ACCENTS = {'"': "\u0308", "'": "\u0301", "`": "\u0300", "^": "\u0302", "~": "\u0303", "=": "\u0304",
423
+ ".": "\u0307", "c": "\u0327", "v": "\u030c", "u": "\u0306", "H": "\u030b", "r": "\u030a", "k": "\u0328"}
424
+ _TEX_LETTERS = {"ss": "ß", "o": "ø", "O": "Ø", "ae": "æ", "AE": "Æ", "oe": "œ", "OE": "Œ", "aa": "å", "AA": "Å",
425
+ "l": "ł", "L": "Ł", "i": "ı", "j": "ȷ"}
426
+ _ACCENTED = re.compile(r"\\([\"'`^~=.])\s*(?:\{\s*(\\?[A-Za-z]+)\s*\}|(\\[A-Za-z]+|[A-Za-z]))"
427
+ r"|\\([cvuHrk])(?:\s*\{\s*(\\?[A-Za-z]+)\s*\}|\s+([A-Za-z]))")
428
+
429
+
430
+ def _group_end(text: str, start: int) -> int:
431
+ """Index after the {...} group whose { is at `start` (-1 if it does not close)."""
432
+ depth, i = 0, start
433
+ while i < len(text):
434
+ ch = text[i]
435
+ if ch == "\\":
436
+ i += 2
437
+ continue
438
+ depth += {"{": 1, "}": -1}.get(ch, 0)
439
+ i += 1
440
+ if not depth:
441
+ return i
442
+ return -1
443
+
444
+
445
+ def _groups(text: str) -> List[str]:
446
+ """The contents of the top-level {...} groups of `text`, in order."""
447
+ groups, depth, start = [], 0, 0
448
+ for i, ch in enumerate(text):
449
+ if ch == "{":
450
+ depth += 1
451
+ if depth == 1:
452
+ start = i + 1
453
+ elif ch == "}" and depth:
454
+ depth -= 1
455
+ if not depth:
456
+ groups.append(text[start:i])
457
+ return groups
458
+
459
+
460
+ def _aux_text(value: str) -> str:
461
+ """Text from an .aux field as it prints: accents ({\\"o} as ö), \\ss and the like, ~, \\&, no braces."""
462
+ import unicodedata
463
+
464
+ def accent(m: "re.Match") -> str:
465
+ mark = _TEX_ACCENTS[m.group(1) or m.group(4)]
466
+ base = next(g for g in (m.group(2), m.group(3), m.group(5), m.group(6)) if g)
467
+ base = {"\\i": "i", "\\j": "j"}.get(base, base.lstrip("\\"))
468
+ return unicodedata.normalize("NFC", base[:1] + mark + base[1:])
469
+ value = _ACCENTED.sub(accent, value)
470
+ value = re.sub(r"\\(ss|ae|AE|oe|OE|aa|AA|o|O|l|L|i|j)(?![A-Za-z])\s*", lambda m: _TEX_LETTERS[m.group(1)], value)
471
+ value = value.replace("~", " ").replace("\\&", "&").replace("\\ ", " ")
472
+ return " ".join(value.replace("{", "").replace("}", "").split())
473
+
474
+
475
+ def _source_text(data: bytes) -> str:
476
+ """A source file's text: as decode_text, but a style file in Latin-1 (an old author's é in a comment)
477
+ is read all the same."""
478
+ try:
479
+ return decode_text(data)
480
+ except UnicodeDecodeError:
481
+ return data.decode("latin-1")
482
+
483
+
484
+ def _local_sources(path: str, text: str) -> str:
485
+ """The document's text with the local files it reads (\\input, \\include, \\subfile, and a
486
+ \\usepackage'd .sty next to it) put in where they are read (so that definitions after an \\input
487
+ win over the file's), without comments and verbatim parts, for its definitions. At most 300
488
+ files of up to 4 MB."""
489
+ folder = os.path.dirname(os.path.abspath(path))
490
+ cache: Dict[str, Optional[str]] = {}
491
+ size = [0] # characters put in (a file \input twice is put in twice, as LaTeX reads it twice)
492
+
493
+ def read(full: str) -> Optional[str]:
494
+ if full not in cache:
495
+ try:
496
+ if os.path.getsize(full) > 4 << 20:
497
+ cache[full] = None
498
+ else:
499
+ with open(full, "rb") as f:
500
+ cache[full] = _source_text(f.read())
501
+ except OSError:
502
+ cache[full] = None
503
+ return cache[full]
504
+
505
+ def expand(current: str, active: Tuple[str, ...]) -> str:
506
+ current = compat.without_verbatim(re.sub(r"(?<!\\)((?:\\\\)*)%[^\n]*", r"\1", current))
507
+ out, last = [], 0
508
+ for m in _READS.finditer(current):
509
+ package = m.group(1) in ("usepackage", "RequirePackage")
510
+ inserted = []
511
+ for name in m.group(2).split(","):
512
+ name = name.strip()
513
+ for candidate in ([name + ".sty"] if package else [name, name + ".tex"]) if name else []:
514
+ full = os.path.normcase(os.path.abspath(os.path.join(folder, candidate)))
515
+ if not os.path.isfile(full):
516
+ continue
517
+ # a file that includes itself (directly or not) once; a package once, as LaTeX loads it;
518
+ # at most 300 different files and 40 million characters in all
519
+ if full in active or (package and full in cache) or (full not in cache and len(cache) >= 300):
520
+ break
521
+ data = read(full)
522
+ if data is not None and size[0] + len(data) <= 40_000_000:
523
+ size[0] += len(data)
524
+ inserted.append(expand(data, active + (full,)))
525
+ break
526
+ out.append(current[last:m.end()])
527
+ out += ["\n" + part + "\n" for part in inserted]
528
+ last = m.end()
529
+ return "".join(out) + current[last:]
530
+ return expand(text, (os.path.normcase(os.path.abspath(path)),))
531
+
532
+
533
+ def _document_bounds(text: str) -> Tuple[Optional[int], Optional[int]]:
534
+ """Where the body starts and ends (after \\begin{document}, at \\end{document}), not counting
535
+ those in comments or verbatim parts."""
536
+ plain = compat.without_verbatim(text)
537
+ begin = end = None
538
+ for m in re.finditer(r"\\(begin|end)\s*\{document\}", plain):
539
+ if compat._in_comment(plain, m.start()):
540
+ continue
541
+ if m.group(1) == "begin" and begin is None:
542
+ begin = m.end()
543
+ elif m.group(1) == "end" and begin is not None and end is None:
544
+ end = m.start()
545
+ return begin, end
546
+
547
+
548
+ def _aux_labels(path: str) -> Dict[str, str]:
549
+ """\\label -> number from the .aux file LaTeX wrote next to the document (and the .aux files of its
550
+ \\include s), plus "page:key" and "title:key" for \\pageref and \\nameref; empty without one."""
551
+ labels: Dict[str, str] = {}
552
+ folder = os.path.dirname(os.path.abspath(path))
553
+ todo, seen = [os.path.splitext(os.path.abspath(path))[0] + ".aux"], set()
554
+ while todo and len(seen) < 300:
555
+ aux = todo.pop(0)
556
+ if aux in seen or not os.path.isfile(aux):
557
+ continue
558
+ seen.add(aux)
559
+ try:
560
+ with open(aux, "rb") as f:
561
+ data = f.read().decode("utf-8", "replace")
562
+ except OSError:
563
+ continue
564
+ for m in _NEWLABEL_START.finditer(data): # (its fields read by brace depth: a title holds $L^{2}$)
565
+ end = _group_end(data, m.end() - 1)
566
+ if end < 0:
567
+ continue
568
+ fields = _groups(data[m.end():end - 1]) + ["", "", "", ""]
569
+ key, number = m.group(1), fields[0].strip()
570
+ if key.endswith("@cref"): # what the label is a number of (cleveref): "type:key"
571
+ kind = re.match(r"\[([A-Za-z]+)\]", number)
572
+ if kind:
573
+ labels["type:" + key[:-len("@cref")]] = kind.group(1)
574
+ continue
575
+ if number.startswith("{") and number.endswith("}") and len(_groups(number)) == 1:
576
+ number = number[1:-1].strip() # a \tag{T}'s label: {T}
577
+ if "@cref" in key or not number or number.startswith("\\"):
578
+ continue
579
+ labels.setdefault(key, number)
580
+ for field, value in (("page:", fields[1]), ("title:", fields[2])):
581
+ value = (value or "").strip()
582
+ if value and "\\" not in value:
583
+ labels.setdefault(field + key, value)
584
+ anchor = re.match(r"([A-Za-z]+)\.", (fields[3] or "").strip()) # hyperref's equation.2.1
585
+ if anchor:
586
+ labels.setdefault("type:" + key, anchor.group(1))
587
+ for m in _BIBCITE.finditer(data): # a citation's number ("cite:key"); natbib's author and year too
588
+ end = _group_end(data, m.end() - 1)
589
+ if end < 0:
590
+ continue
591
+ key, value = m.group(1), data[m.end():end - 1].strip()
592
+ fields = _groups(value) if value.startswith("{") else [value]
593
+ number = fields[0].strip() if fields else ""
594
+ if re.fullmatch(r"[\w.\-]{1,12}", number):
595
+ labels.setdefault("cite:" + key, number)
596
+ if len(fields) >= 3 and _aux_text(fields[1]) and _aux_text(fields[2]):
597
+ labels.setdefault("citeyear:" + key, _aux_text(fields[1]))
598
+ labels.setdefault("citeauthor:" + key, _aux_text(fields[2]))
599
+ todo += [os.path.join(folder, n) for n in _AUX_INPUT.findall(data)]
600
+ return labels
601
+
602
+
603
+ def _read_latex_blocks(text: str, folder: str, notes: List[str], raw: bool = False,
604
+ meta: Optional[dict] = None) -> Tuple[list, str, Optional[str]]:
605
+ """pandoc's reading of a .tex file; if pandoc cannot read the file (a style file it trips over:
606
+ "unexpected \\@ ... \\maketitle"), the body alone, whose macros then come from the preamble.
607
+ Returns the blocks, pandoc's warnings, and the preamble when the body was read alone. `raw`: keep
608
+ what the reader does not know as raw TeX (it drops it otherwise, without a word). `meta`, if given,
609
+ gets pandoc's metadata (title, authors, date, abstract)."""
610
+ fmt = "latex+raw_tex" if raw else "latex"
611
+ try:
612
+ out, err = _run(["-f", fmt, "-t", "json"], text.encode("utf-8"), cwd=folder)
613
+ document = json.loads(out)
614
+ if meta is not None:
615
+ meta.update(document.get("meta") or {})
616
+ return document["blocks"], err, None
617
+ except ConversionError as e:
618
+ begin, end = _document_bounds(text)
619
+ if begin is None:
620
+ raise
621
+ body = text[begin:end if end is not None else len(text)]
622
+ out, err = _run(["-f", fmt, "-t", "json"], body.encode("utf-8"), cwd=folder)
623
+ reason = next((line.strip() for line in str(e).splitlines() if line.strip() and "WARNING" not in line), "")
624
+ notes.append("pandoc could not read the preamble (%s): the body was read alone, with the preamble's "
625
+ "definitions." % _shorten(reason, 120))
626
+ document = json.loads(out)
627
+ if meta is not None:
628
+ meta.update(document.get("meta") or {})
629
+ front = _front_matter(text[:begin])
630
+ if front: # the title, authors and date of the preamble pandoc could not read, read alone
631
+ try:
632
+ meta.update(json.loads(_run(["-f", "latex", "-t", "json"], (
633
+ front + "\n\\begin{document}\\end{document}").encode("utf-8"), cwd=folder)[0]).get("meta") or {})
634
+ except (ConversionError, ValueError):
635
+ pass
636
+ return document["blocks"], err, text[:begin]
637
+
638
+
639
+ _FRONT = re.compile(r"\\(title|author|date)\s*(?:\[[^\]]*\])?\s*\{")
640
+
641
+
642
+ def _front_matter(preamble: str) -> str:
643
+ """The \\title{...}, \\author{...} and \\date{...} commands of a preamble (comments out)."""
644
+ preamble = re.sub(r"(?<!\\)%[^\n]*", "", preamble)
645
+ found = []
646
+ for m in _FRONT.finditer(preamble):
647
+ depth, i = 1, m.end()
648
+ while i < len(preamble) and depth:
649
+ if preamble[i] == "\\":
650
+ i += 2
651
+ continue
652
+ depth += {"{": 1, "}": -1}.get(preamble[i], 0)
653
+ i += 1
654
+ if not depth:
655
+ found.append("\\%s{%s}" % (m.group(1), preamble[m.end():i - 1]))
656
+ return "\n".join(found)
657
+
658
+
659
+ def read_text_document(path: str, fmt: str, expand_macros: bool = False) -> DocumentEquations:
660
+ """A .tex file (\\input and \\include found next to it) or a .md file, read by pandoc: each
661
+ equation as LaTeX, with the heading above it and its \\label; pandoc's warnings (a file that
662
+ \\input names but that is not there) become notes. A .tex file also gets its own definitions and
663
+ \\label numbers (see :class:`DocumentEquations`)."""
664
+ folder = os.path.dirname(os.path.abspath(path))
665
+ with open(path, "rb") as f:
666
+ text = _source_text(f.read()) # (an old paper in Latin-1 too)
667
+ result = DocumentEquations(path, "latex")
668
+ # a .md file: pandoc's Markdown, where \[1\] is an escaped bracket (pandoc writes [1] so), not maths
669
+ # as in pasted chat text (MARKDOWN); raw TeX environments in it are read all the same
670
+ markdown = fmt == "markdown"
671
+ raw_equations: List[Equation] = []
672
+ if markdown: # (with money before maths read right: "$5.00 ($p$ after tax)")
673
+ blocks, err = markdown_blocks(text, "markdown", folder)
674
+ # what pandoc's Markdown reader does not apply either (\DeclarePairedDelimiter...), not from code
675
+ from .pandoc_engine import _without_code
676
+ result.definitions = compat.pandoc_leftovers(_without_code(text))
677
+ else:
678
+ read_text = text
679
+ if expand_macros and "\\DeclareMathOperator" in text:
680
+ read_text, _ = compat.before_equations(text, defer=False)
681
+ blocks, err, preamble = _read_latex_blocks(read_text, folder, result.notes)
682
+ # what pandoc did not apply (\DeclarePairedDelimiter...); with the body read alone, also the whole
683
+ # preamble's definitions, which pandoc did not see
684
+ result.definitions = compat.pandoc_leftovers(_local_sources(path, text))
685
+ if preamble is not None:
686
+ result.definitions = _local_sources(path, preamble) + "\n" + result.definitions
687
+ if expand_macros and preamble is None:
688
+ begin, end = _document_bounds(text)
689
+ body, leading = compat.before_equations(text[begin:end])
690
+ if begin is not None:
691
+ local = _local_sources(path, text[:begin])
692
+ # also those with an @ in what they stand for (\text{a@b}, or \eqlabel made of \@namedef,
693
+ # which expand_macros then keeps as written, with a note); not internal names (\@foo)
694
+ top = [d.source for d in compat.parse_definitions(local)[0]
695
+ if "@" not in d.name and not compat._depth(local, d.span[0])]
696
+ leading = "\n".join(top + [leading])
697
+ result.expansion_definitions = "\n".join(s for s in top if "@" in s)
698
+ if leading.strip():
699
+ # Keep the raw macro calls for the LaTeX writer. Some macros produce whole
700
+ # equations in prose, so use the full reading if the body alone loses any.
701
+ result.definitions = leading + "\n" + result.definitions
702
+ try:
703
+ raw_blocks, _, _ = _read_latex_blocks(body, folder, [])
704
+ except ConversionError:
705
+ pass
706
+ else:
707
+ original: List[Equation] = []
708
+ raw: List[Equation] = []
709
+ _collect_math(blocks, original)
710
+ _collect_math(raw_blocks, raw)
711
+ raw_equations = _matched(original, raw)
712
+ result.labels = _aux_labels(path)
713
+ result.notes += [" ".join(line.replace("[WARNING]", "").split()) for line in err.splitlines()
714
+ if line.startswith("[WARNING]")]
715
+ definitions: List[str] = [] # the raw TeX definitions so far (a .md file)
716
+ heading = ""
717
+ for block in blocks:
718
+ context = ""
719
+ if isinstance(block, dict) and block.get("t") == "Header":
720
+ words: List[str] = []
721
+ _inline_text(block["c"][2], words)
722
+ heading = _shorten("".join(words), 60)
723
+ elif isinstance(block, dict) and block.get("t") in ("Para", "Plain"):
724
+ words = []
725
+ _inline_text(block["c"], words)
726
+ context = _shorten("".join(words))
727
+ eqs: List[Equation] = []
728
+ if markdown: # with the maths of raw TeX in the text (\begin{align} ... without $$)
729
+ markdown_maths(block, eqs, definitions, folder)
730
+ else:
731
+ _collect_math(block, eqs) # also the maths of a heading
732
+ for eq in eqs:
733
+ label = re.search(r"\\label\{([^{}]*)\}", eq.tex)
734
+ where = (heading or "(before the first heading)") + (" [%s]" % label.group(1) if label else "")
735
+ if len(result.found) < len(raw_equations) and raw_equations[len(result.found)] is not None:
736
+ eq = raw_equations[len(result.found)]
737
+ result.found.append(Found(eq, where, "" if eq.display else context))
738
+ return result
739
+
740
+
741
+ def _shape(eq: Equation) -> tuple:
742
+ """An equation as a macro leaves it: inline or display, its environment, and what it shows apart from
743
+ commands (letters and digits), which tells two equations of the same kind apart."""
744
+ env = re.match(r"\s*\\begin\s*\{([^{}]*)\}", eq.tex)
745
+ return eq.display, env.group(1) if env else "", _skeleton(eq.tex)
746
+
747
+
748
+ def _skeleton(tex: str) -> str:
749
+ return re.sub(r"[^A-Za-z0-9]", "", re.sub(r"\\(?:[a-zA-Z@]+|.)", "", tex))
750
+
751
+
752
+ def _matched(expanded: List[Equation], raw: List[Equation]) -> "List[Optional[Equation]]":
753
+ """For each equation of pandoc's reading (macros expanded), the same equation as written, from the
754
+ reading without the preamble (macros kept), or None where the two do not line up: a macro in the
755
+ prose that makes an equation of its own is in the first reading only. Equations that differ only
756
+ where macros were expanded pair up when they are of the same kind and mostly show the same."""
757
+ import difflib
758
+ out: "List[Optional[Equation]]" = [None] * len(expanded)
759
+ a, b = [_shape(e) for e in expanded], [_shape(e) for e in raw]
760
+ matcher = difflib.SequenceMatcher(None, a, b, autojunk=False)
761
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
762
+ if tag == "equal":
763
+ pairs = zip(range(i1, i2), range(j1, j2))
764
+ elif tag == "replace" and i2 - i1 == j2 - j1:
765
+ pairs = ((i, j) for i, j in zip(range(i1, i2), range(j1, j2))
766
+ if a[i][:2] == b[j][:2]
767
+ and difflib.SequenceMatcher(None, a[i][2], b[j][2], autojunk=False).ratio() >= 0.5)
768
+ else:
769
+ continue
770
+ for i, j in pairs:
771
+ out[i] = raw[j]
772
+ return out
773
+
774
+
775
+ def read_document(path: str, *, expand_macros: bool = False) -> DocumentEquations:
776
+ """Every equation in document order. For expanded LaTeX, retain preamble macros for the writer."""
777
+ ext = os.path.splitext(path)[1].lower()
778
+ if ext not in READABLE:
779
+ raise ConversionError("Cannot read %s files (only %s)." % (ext or "these", ", ".join(READABLE)))
780
+ try:
781
+ if ext == ".docx":
782
+ return read_docx(path)
783
+ if ext == ".pptx":
784
+ return read_pptx(path)
785
+ return read_text_document(path, "latex" if ext == ".tex" else "markdown", expand_macros)
786
+ except OSError as e:
787
+ raise ConversionError("Cannot read %s: %s" % (path, e.strerror or e))
788
+ except (zipfile.BadZipFile, KeyError, ET.ParseError, UnicodeDecodeError) as e:
789
+ raise ConversionError("%s is not a readable %s (%s)" % (os.path.basename(path), READABLE[ext], e))
790
+
791
+
792
+ def _inlines(text: str) -> list:
793
+ """Plain text as pandoc JSON inlines."""
794
+ out: list = []
795
+ for word in text.split():
796
+ if out:
797
+ out.append({"t": "Space"})
798
+ out.append({"t": "Str", "c": word})
799
+ return out
800
+
801
+
802
+ # the TeX keeps its line breaks (continuation lines indented by two spaces), then texmath's message
803
+ _UNCONVERTED = re.compile(r"\[WARNING\] Could not convert TeX math ([\s\S]*?), rendering as TeX:\n((?: .*\n?)*)")
804
+
805
+
806
+ def _unconverted(err: str, prepared: List[str]) -> Dict[int, str]:
807
+ """Which equations (1-based) pandoc wrote as TeX text, with texmath's reason, from its warnings
808
+ ("[WARNING] Could not convert TeX math <tex>, rendering as TeX:" then texmath's message)."""
809
+ by_text: Dict[str, str] = {}
810
+ for m in _UNCONVERTED.finditer(err.replace("\r\n", "\n")):
811
+ lines = [ln.strip() for ln in m.group(2).split("\n") if ln.strip()]
812
+ reason = next((b for a, b in zip(lines, lines[1:]) if a.startswith("^") and not b.startswith("^")), "")
813
+ by_text.setdefault(" ".join(m.group(1).split()), reason)
814
+ out: Dict[int, str] = {}
815
+ for i, tex in enumerate(prepared, 1):
816
+ key = " ".join(tex.split())
817
+ if key in by_text:
818
+ out[i] = by_text[key] or "texmath could not read it"
819
+ return out
820
+
821
+
822
+ def write_docx(doc: DocumentEquations, path: str, macros: Optional[compat.Macros] = None,
823
+ rows: Optional[List[EquationRow]] = None) -> List[str]:
824
+ """The document's equations (`rows`, all of them by default) as a Word document (`path`), each a
825
+ native equation under a line that says where it was, as the list shows it ("[3] Method [eq:x]
826
+ (2.1)": its place in the document, its LaTeX number), in one pandoc run; for a collaborator who
827
+ edits them in Word. Macros apply to a document's own LaTeX. Returns notes: equations that texmath
828
+ cannot write are in the file as LaTeX text. The file is written next to `path` first and then put
829
+ in its place, so a failed export leaves an older file as it was. An equation that texmath cannot
830
+ write is in the file as LaTeX text, under its line with the reason."""
831
+ own = doc.source == "latex"
832
+ used = doc.macros(macros)
833
+ rows = doc.rows() if rows is None else rows
834
+ notes: List[str] = []
835
+ tags = False
836
+ prepared: List[str] = []
837
+ for found in [row.found for row in rows]:
838
+ try:
839
+ tex, new = compat.for_texmath(found.equation.tex, used, "omml")
840
+ except ConversionError: # (a definition compat cannot use): as it is, pandoc writes it as text
841
+ tex, new = found.equation.tex, []
842
+ if own: # what was approximated (a colour, a resized fraction...); LaTeX from Office has none
843
+ notes += [n for n in new if n not in notes]
844
+ # (a % after an even number of backslashes starts a comment: \\% \tag{old} is one)
845
+ active = re.sub(r"(?<!\\)((?:\\\\)*)%[^\n]*", r"\1", tex)
846
+ tags |= bool(re.search(r"\\tag(?![a-zA-Z@])", active))
847
+ prepared.append(tex)
848
+
849
+ def source(reasons: Dict[int, str]) -> bytes:
850
+ blocks: list = [{"t": "Header", "c": [1, ["", [], []],
851
+ _inlines("Equations of " + os.path.basename(doc.path))]}]
852
+ for i, (row, tex) in enumerate(zip(rows, prepared), 1):
853
+ kind = "DisplayMath" if row.found.equation.display else "InlineMath"
854
+ line = [{"t": "Emph", "c": _inlines("[%d] %s" % (row.number, row.location))}]
855
+ if i in reasons:
856
+ line += [{"t": "Space"}, {"t": "Strong", "c": _inlines(
857
+ "(not converted: %s; it is here as LaTeX text)" % reasons[i])}]
858
+ blocks.append({"t": "Para", "c": line})
859
+ blocks.append({"t": "Para", "c": [{"t": "Math", "c": [{"t": kind}, tex]}]})
860
+ return json.dumps({"pandoc-api-version": _api(), "meta": {}, "blocks": blocks}).encode("utf-8")
861
+
862
+ target = os.path.abspath(path)
863
+ try: # a name of its own next to the target (two exports at once do not meet)
864
+ handle, part = tempfile.mkstemp(dir=os.path.dirname(target), prefix="." + os.path.basename(target) + ".",
865
+ suffix=".part")
866
+ os.close(handle)
867
+ except OSError as e:
868
+ raise ConversionError("Could not write %s: %s" % (path, e.strerror or e))
869
+ try:
870
+ _, err = _run(["-f", "json", "-t", "docx", "-o", part], source({}))
871
+ reasons = _unconverted(err, prepared)
872
+ from . import diagnose
873
+ for i in sorted(reasons)[:50]: # in plain words (a probe each: not for hundreds of them)
874
+ words = diagnose.explain(rows[i - 1].found.equation.tex, prepared[i - 1], reasons[i], short=True)
875
+ reasons[i] = words[0] if words else reasons[i]
876
+ if reasons: # once more, with the reason above each equation that stays LaTeX text
877
+ _, err = _run(["-f", "json", "-t", "docx", "-o", part], source(reasons))
878
+ for attempt in range(5):
879
+ try:
880
+ os.replace(part, target)
881
+ break
882
+ except PermissionError: # another export replacing it this moment, or open in Word
883
+ if attempt == 4:
884
+ raise
885
+ time.sleep(0.1)
886
+ except OSError as e: # e.g. the file is open in Word
887
+ raise ConversionError("Could not write %s: %s" % (path, e.strerror or e))
888
+ finally:
889
+ try:
890
+ os.remove(part)
891
+ except OSError:
892
+ pass # moved into place, or held for a moment by a virus scanner
893
+ failed = len(re.findall(r"^\[WARNING\] Could not convert TeX math", err, re.M))
894
+ if failed:
895
+ notes.append("%d equation%s could not be converted; %s in the file as LaTeX text, under %s line with "
896
+ "the reason.%s"
897
+ % (failed, "" if failed == 1 else "s", "it is" if failed == 1 else "they are",
898
+ "its" if failed == 1 else "their",
899
+ " Definitions from a file that the document does not read itself can be given as a "
900
+ "macro file (Macros..., --macros)." if own else ""))
901
+ if tags:
902
+ notes.append("\\tag numbers are not carried over: number the equations in Word if they need numbers.")
903
+ return compat.merge_notes(notes)