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,887 @@
1
+ """A passage (the window's input: a chat answer, Markdown notes, LaTeX text) or a whole .tex / .md document
2
+ as a Word file: its title, authors, abstract, prose, headings, lists, tables and figures through pandoc's
3
+ docx writer, and each equation a native Word equation, prepared as Copy for Word/PowerPoint prepares it
4
+ (the user's macros, the document's own definitions, the built-in packs).
5
+
6
+ Numbers go at the right margin as Word numbers equations itself: ``#(2.1)`` at the end of a row of an
7
+ equation array with maximum distribution (checked with Word 16.0.20527). A row's number is its \\tag, or
8
+ the one LaTeX gives it: counted as LaTeX counts (equation and multline one number, align, gather,
9
+ eqnarray, flalign and alignat one per row; \\nonumber, \\notag, \\tag and starred environments
10
+ counted out; checked against a real LaTeX run) in a document that numbers equations (1), (2)... in
11
+ order, and checked against the .aux file LaTeX wrote next to it when there is one. A document that
12
+ numbers them by chapter or section, or sets the counter itself, gets the .aux numbers of its labelled
13
+ equations only. \\eqref, \\ref, \\cref, \\Cref, \\autoref and citations show what LaTeX prints for them.
14
+ An equation that texmath cannot write stays LaTeX text, with the reason after it.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ import tempfile
22
+ import time
23
+ import zipfile
24
+ from typing import Dict, List, Optional, Tuple
25
+
26
+ from . import compat
27
+ from .pandoc_engine import MARKDOWN, ConversionError, _api, _run, markdown_blocks
28
+
29
+ _SENTINEL = "QQMSN%dQQ"
30
+ _SENTINEL_RUN = re.compile(r"<m:r>(?:(?!</m:r>)[\s\S])*?QQMSN(\d+)QQ(?:(?!</m:r>)[\s\S])*?</m:r>")
31
+ _LABEL = re.compile(r"\\label\s*\{([^{}]*)\}")
32
+ _TAG_START = re.compile(r"\\tag(\*?)\s*\{")
33
+ _NO_NUMBER = re.compile(r"\\(?:nonumber|notag)(?![a-zA-Z@])")
34
+ _PER_ROW = frozenset("align flalign alignat xalignat xxalignat gather eqnarray".split())
35
+ _ONE_NUMBER = frozenset(("equation", "multline"))
36
+ _ENV = re.compile(r"(\s*\\begin\s*\{([a-zA-Z]+)(\*?)\}(?:\s*\{[^{}]*\})?)([\s\S]*?)(\\end\s*\{\2\3\}\s*)")
37
+ _REFERENCE_TYPES = ("eqref", "ref", "autoref", "cref", "Cref", "ref+label", "ref+Label")
38
+ REF_COMMANDS = "\x00ref-commands:" # + the keys of an \autoref / \cref: the commands, in source order
39
+ _RAW_TEX = ("tex", "latex")
40
+ _BLOCK_TYPES = frozenset("Para Plain Header CodeBlock BlockQuote OrderedList BulletList DefinitionList Table Div "
41
+ "HorizontalRule LineBlock RawBlock Figure".split())
42
+ # what makes a passage Markdown to Word, besides what makes its equations Markdown (looks_like_markdown)
43
+ _PROSE_SIGNS = re.compile(r"^[ \t]*(?:[-*+]|\d{1,3}[.)])[ \t]+\S|^[ \t]*>[ \t]?\S", re.M)
44
+ _OUTSIDE_MATHS = re.compile(r"\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|(?<![\\$])\$[^$\n]+\$"
45
+ r"|\\begin\s*\{([a-zA-Z]+\*?)\}[\s\S]*?\\end\s*\{\1\}")
46
+ _CHAPTER_CLASS = re.compile(r"\\documentclass\s*(?:\[[^\]]*\])?\s*\{\s*(?:report|book|memoir|scrbook|scrreprt|amsbook"
47
+ r"|[^{}]*thesis[^{}]*|siamart[^{}]*|siamonline[^{}]*)\s*\}")
48
+
49
+
50
+ # ---- the passage or document, as pandoc JSON ---------------------------------------------------------
51
+ def _prose(text: str) -> bool:
52
+ """Words, not an equation (for a passage without maths delimiters): no command, script, brace or
53
+ operator, and three words or a sentence ("sin x cos y" and "AB + CD" are equations)."""
54
+ if re.search(r"\\[A-Za-z]|[_^{}=+<>|*/]", text):
55
+ return False
56
+ words = len(re.findall(r"[A-Za-z]{2,}", text))
57
+ return words >= 3 or (words >= 2 and text.rstrip().endswith((".", "!", "?")))
58
+
59
+
60
+ # LaTeX text, not an equation: a passage without maths delimiters with these is read as LaTeX
61
+ _LATEX_TEXT = re.compile(r"\\(?:section|subsection|subsubsection|paragraph|chapter|item|textbf|textit|emph|"
62
+ r"citep?|citet|ref|eqref|footnote|begin\s*\{(?:itemize|enumerate|description|abstract|"
63
+ r"quote)\})(?![a-zA-Z@])")
64
+
65
+
66
+ def passage_blocks(text: str) -> Tuple[list, bool]:
67
+ """The window's input as pandoc blocks, and whether it was read as Markdown: a chat answer or notes
68
+ with Markdown in them (a heading, **bold**, a list, a table, `code`, money) as Markdown, prose as a
69
+ paragraph, a bare equation (no delimiters, no words) as one display equation, LaTeX text as LaTeX."""
70
+ from .convert import input_equations
71
+ from .pandoc_engine import (_COMMENT_LINE, _LATEX_DOCUMENT, _has_math_delimiters, _without_code,
72
+ looks_like_markdown, strip_tex)
73
+ prose = _without_code(text)
74
+ outside = _OUTSIDE_MATHS.sub(" ", prose) # (an align's continuation line "- c + d" is no list)
75
+ if not _LATEX_DOCUMENT.search(prose) and (looks_like_markdown(text) or (
76
+ _PROSE_SIGNS.search(outside) and not _COMMENT_LINE.search(prose))):
77
+ return markdown_blocks(text, MARKDOWN)[0], True
78
+ if not _has_math_delimiters(text):
79
+ if _LATEX_TEXT.search(text):
80
+ return json.loads(_run(["-f", "latex", "-t", "json"], text.encode("utf-8"))[0])["blocks"], False
81
+ if _prose(text) or not text.strip():
82
+ return markdown_blocks(text, MARKDOWN)[0], True
83
+ return [{"t": "Para", "c": [{"t": "Math", "c": [{"t": "DisplayMath"}, strip_tex(text)]}]}], False
84
+ try:
85
+ as_markdown = input_equations(text, "latex").as_markdown
86
+ except ConversionError: # no equation after all ($5 and $10): text
87
+ as_markdown = True
88
+ if as_markdown:
89
+ return markdown_blocks(text, MARKDOWN)[0], True
90
+ return json.loads(_run(["-f", "latex", "-t", "json"], text.encode("utf-8"))[0])["blocks"], False
91
+
92
+
93
+ def passage_to_word(text: str, path: str, macros: Optional[compat.Macros] = None) -> List[str]:
94
+ """The window's input (`text`, LaTeX or a chat answer / Markdown) as a Word document at `path`."""
95
+ from .convert import input_macros
96
+ blocks, as_markdown = passage_blocks(text)
97
+ return write_word(blocks, path, input_macros(macros, text, "latex", as_markdown), markdown=as_markdown)
98
+
99
+
100
+ def _local_class(source: str, text: str) -> str:
101
+ """The text of the document's own class file, when it sits next to it (\\documentclass{siamart})."""
102
+ from . import documents
103
+ m = re.search(r"\\documentclass\s*(?:\[[^\]]*\])?\s*\{\s*([^{}\s]+)\s*\}", text)
104
+ path = os.path.join(os.path.dirname(os.path.abspath(source)), m.group(1) + ".cls") if m else ""
105
+ try:
106
+ with open(path, "rb") as f:
107
+ return documents._source_text(f.read())
108
+ except OSError:
109
+ return ""
110
+
111
+
112
+ def _cite_style(sources: str) -> str:
113
+ """natbib without its numbers option prints author and year (as the ICLR and ICML styles load it)."""
114
+ natbib = re.findall(r"\\(?:usepackage|RequirePackage)\s*(?:\[([^\]]*)\])?\s*\{[^{}]*\bnatbib\b[^{}]*\}", sources)
115
+ if not natbib:
116
+ return "numeric"
117
+ numbers = any("numbers" in (options or "") for options in natbib) or re.search(
118
+ r"\\(?:setcitestyle|citestyle)\s*\{[^{}]*\b(?:numbers|super)\b"
119
+ r"|\\PassOptionsToPackage\s*\{[^{}]*\b(?:numbers|super)\b[^{}]*\}\s*\{\s*natbib\s*\}", sources)
120
+ return "numeric" if numbers else "authoryear"
121
+
122
+
123
+ def document_to_word(source: str, path: str, macros: Optional[compat.Macros] = None) -> List[str]:
124
+ """A whole .tex or .md file as a Word document at `path`; a .tex file with its own definitions, its
125
+ equation numbers and the numbers of its .aux file."""
126
+ from . import documents
127
+ ext = os.path.splitext(source)[1].lower()
128
+ if ext not in (".tex", ".md"):
129
+ raise ConversionError("Only a .tex or .md file can be written as a whole Word document "
130
+ "(a .docx / .pptx: use Export all as .docx... for its equations).")
131
+ folder = os.path.dirname(os.path.abspath(source))
132
+ try:
133
+ with open(source, "rb") as f:
134
+ text = documents._source_text(f.read()) # (an old paper in Latin-1 too)
135
+ except OSError as e:
136
+ raise ConversionError("Cannot read %s: %s" % (source, e.strerror or e))
137
+ notes: List[str] = []
138
+ meta: dict = {}
139
+ plans = None
140
+ if ext == ".md":
141
+ blocks, err = markdown_blocks(text, "markdown", folder, meta=meta)
142
+ own = macros
143
+ labels: Dict[str, str] = {}
144
+ else:
145
+ # (as pandoc reads it: with raw_tex, pandoc would no longer follow \input; a command it does not
146
+ # know is left out, as pandoc's own conversions do)
147
+ blocks, err, preamble = documents._read_latex_blocks(text, folder, notes, meta=meta)
148
+ sources = documents._local_sources(source, text)
149
+ definitions = compat.pandoc_leftovers(sources)
150
+ if preamble is not None:
151
+ definitions = documents._local_sources(source, preamble) + "\n" + definitions
152
+ labels = documents._aux_labels(source)
153
+ labels[compat.REF_STYLE] = "cleveref" if re.search(r"\bcleveref\b", sources) else "hyperref"
154
+ # pandoc reads \autoref and \cref alike (ref+label): which one each reference is, in source order
155
+ for m in re.finditer(r"\\(autoref|cref)\*?\s*\{([^{}]*)\}", sources):
156
+ key = REF_COMMANDS + ",".join(k.strip() for k in m.group(2).split(","))
157
+ labels[key] = (labels.get(key, "") + " " + m.group(1)).strip()
158
+ labels[compat.CITE_STYLE] = _cite_style(sources)
159
+ _split_grouped(blocks)
160
+ graphics = re.search(r"\\graphicspath\s*\{((?:\s*\{[^{}]*\})+)\s*\}", sources)
161
+ _find_figures(blocks, folder, re.findall(r"\{([^{}]*)\}", graphics.group(1)) if graphics else [])
162
+ plans, counted, more = _count_equations(blocks, labels, sources + "\n" + _local_class(source, text))
163
+ notes += more
164
+ labels.update(counted) # (the same as the .aux's when it has them; a \tag's as it prints)
165
+ for key in counted: # equations, for \cref and \autoref without an .aux
166
+ labels.setdefault("type:" + key, "equation")
167
+ own = compat.with_document(macros, definitions, labels)
168
+ notes += [" ".join(line.replace("[WARNING]", "").split()) for line in err.splitlines()
169
+ if line.startswith("[WARNING]") and "Could not convert TeX math" not in line]
170
+ return write_word(blocks, path, own, labels, notes, folder, markdown=ext == ".md", meta=meta, plans=plans)
171
+
172
+
173
+ _PICTURES = ("", ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tif", ".tiff", ".svg", ".emf", ".wmf")
174
+
175
+
176
+ def _find_figures(node, folder: str, dirs: List[str]) -> None:
177
+ """Each figure's file, found as LaTeX finds it: next to the document or in a \\graphicspath folder, with
178
+ the extension LaTeX adds (\\includegraphics{plot}); a picture Word can take before a .pdf or .eps of
179
+ the same name. In place."""
180
+ if isinstance(node, list):
181
+ for n in node:
182
+ _find_figures(n, folder, dirs)
183
+ elif isinstance(node, dict):
184
+ if node.get("t") == "Image" and isinstance(node.get("c"), list) and len(node["c"]) == 3:
185
+ target = node["c"][2][0]
186
+ if re.match(r"[a-z]+://", target):
187
+ return
188
+ stem, ext = os.path.splitext(target)
189
+ names = ([stem + e for e in _PICTURES[1:]] if ext.lower() in (".pdf", ".eps", ".ps") else []) + \
190
+ [target + e for e in _PICTURES]
191
+ for base in [""] + dirs:
192
+ found = next((p for p in (os.path.join(folder, base, n) for n in names) if os.path.isfile(p)), None)
193
+ if found:
194
+ node["c"][2][0] = found
195
+ return
196
+ return
197
+ _find_figures(node.get("c"), folder, dirs)
198
+
199
+
200
+ # ---- equation numbers ---------------------------------------------------------------------------------
201
+ def _without_comments(tex: str) -> str:
202
+ """TeX without its % comments (a \\% stays; a \\\\ before a % is a row break, not an escape)."""
203
+ out, i = [], 0
204
+ while i < len(tex):
205
+ ch = tex[i]
206
+ if ch == "\\" and i + 1 < len(tex):
207
+ out.append(tex[i:i + 2])
208
+ i += 2
209
+ continue
210
+ if ch == "%":
211
+ end = tex.find("\n", i)
212
+ if end < 0:
213
+ break
214
+ i = end # (the line break stays: what follows is on a line of its own)
215
+ continue
216
+ out.append(ch)
217
+ i += 1
218
+ return "".join(out)
219
+
220
+
221
+ _CONTROL = re.compile(r"\\(?:(begin|end)\s*\{[^{}]*\}|\\\*?(?:\s*\[[^\]]*\])?|[a-zA-Z@]+|.)", re.S)
222
+
223
+
224
+ def _top_rows(body: str) -> List[str]:
225
+ """`body` split at its own \\\\ (not those of a cases, aligned or matrix in it, nor inside braces):
226
+ [row, separator, row, ...]."""
227
+ parts, depth, start, i = [], 0, 0, 0
228
+ while i < len(body):
229
+ ch = body[i]
230
+ if ch == "\\":
231
+ m = _CONTROL.match(body, i)
232
+ if m.group(1) == "begin":
233
+ depth += 1
234
+ elif m.group(1) == "end":
235
+ depth -= 1
236
+ elif depth == 0 and m.group(0).startswith("\\\\"):
237
+ parts += [body[start:i], m.group(0)]
238
+ start = m.end()
239
+ i = m.end()
240
+ continue
241
+ if ch == "{":
242
+ depth += 1
243
+ elif ch == "}":
244
+ depth -= 1
245
+ i += 1
246
+ parts.append(body[start:])
247
+ return parts
248
+
249
+
250
+ def _tag(row: str) -> Optional[Tuple[int, int, bool, str]]:
251
+ """The row's \\tag: (start, end, starred, argument), its argument with braces in it."""
252
+ m = _TAG_START.search(row)
253
+ if not m:
254
+ return None
255
+ depth, i = 1, m.end()
256
+ while i < len(row) and depth:
257
+ if row[i] == "\\":
258
+ i += 2
259
+ continue
260
+ depth += {"{": 1, "}": -1}.get(row[i], 0)
261
+ i += 1
262
+ return (m.start(), i, bool(m.group(1)), row[m.end():i - 1]) if not depth else None
263
+
264
+
265
+ _TAG_TEXT: Dict[str, str] = {}
266
+
267
+
268
+ def _tag_text(argument: str, labels: Dict[str, str]) -> str:
269
+ """What a \\tag's argument prints: text, $\\dagger$ as †, \\text{Max} as Max, \\ref as the number."""
270
+ def ref(m: "re.Match") -> str:
271
+ keys = [k.strip() for k in m.group(2).split(",")]
272
+ return compat.reference_text(m.group(1), keys, labels) or ", ".join(keys)
273
+ argument = re.sub(r"\\(eqref|ref)\s*\{([^{}]*)\}", ref, argument)
274
+ if not re.search(r"[\\$^_{}]", argument):
275
+ return " ".join(argument.split())
276
+ if argument not in _TAG_TEXT:
277
+ try:
278
+ # (a tag's argument is text, with maths in $...$; \text and symbols read as maths)
279
+ out = _run(["-f", "latex", "-t", "plain", "--wrap=none"], (argument if "$" in argument else
280
+ "$%s$" % argument).encode("utf-8"))[0]
281
+ out = out.decode("utf-8")
282
+ _TAG_TEXT[argument] = " ".join(out.split()) or argument
283
+ except ConversionError:
284
+ _TAG_TEXT[argument] = argument
285
+ return _TAG_TEXT[argument]
286
+
287
+
288
+ def _row_kinds(tex: str) -> Tuple[str, List[str], str, list]:
289
+ """(head, rows, tail, kinds) of a display equation (comments out): its rows (rows[0::2]; one for an
290
+ equation, multline or a bare display), and for each None, "count" (LaTeX numbers it) or
291
+ ("tag", start, end, starred, argument)."""
292
+ env = _ENV.fullmatch(tex)
293
+ if env:
294
+ head, name, star, body, tail = env.group(1), env.group(2), env.group(3), env.group(4), env.group(5)
295
+ else:
296
+ head, name, star, body, tail = "", "", "", tex, ""
297
+ rows = _top_rows(body) if name in _PER_ROW else [body]
298
+ kinds: list = []
299
+ for row in rows[0::2]:
300
+ tag = _tag(row)
301
+ if tag:
302
+ kinds.append(("tag",) + tag)
303
+ elif name in _PER_ROW | _ONE_NUMBER and not star and not _NO_NUMBER.search(row):
304
+ kinds.append("count")
305
+ else:
306
+ kinds.append(None)
307
+ return head, rows, tail, kinds
308
+
309
+
310
+ def _display_maths(node, out: list) -> None:
311
+ if isinstance(node, list):
312
+ for n in node:
313
+ _display_maths(n, out)
314
+ elif isinstance(node, dict):
315
+ if node.get("t") == "Math":
316
+ if node["c"][0]["t"] == "DisplayMath":
317
+ out.append(node)
318
+ return
319
+ _display_maths(node.get("c"), out)
320
+
321
+
322
+ _TOP_ENV = re.compile(r"\\begin\s*\{([a-zA-Z]+\*?)\}")
323
+
324
+
325
+ def _environments(tex: str) -> Optional[List[str]]:
326
+ """The environments a display holds one after the other (pandoc gives a subequations group of
327
+ two equation environments as one display; and \\label{group} before them), or None."""
328
+ parts, i = [], 0
329
+ while True:
330
+ rest = re.match(r"(?:\s|\\label\s*\{[^{}]*\})*", tex[i:])
331
+ i += rest.end()
332
+ if i >= len(tex):
333
+ return parts
334
+ m = _TOP_ENV.match(tex, i)
335
+ if not m:
336
+ return None
337
+ name, depth, j = m.group(1), 0, i
338
+ pattern = re.compile(r"\\(begin|end)\s*\{%s\}" % re.escape(name))
339
+ for e in pattern.finditer(tex, i):
340
+ depth += 1 if e.group(1) == "begin" else -1
341
+ if not depth:
342
+ j = e.end()
343
+ break
344
+ if depth:
345
+ return None
346
+ parts.append(tex[i:j])
347
+ i = j
348
+
349
+
350
+ def _split_grouped(node) -> None:
351
+ """A display of several environments in a row (subequations) as one display each, in place."""
352
+ if isinstance(node, list):
353
+ k = 0
354
+ while k < len(node):
355
+ n = node[k]
356
+ if isinstance(n, dict) and n.get("t") == "Math" and n["c"][0]["t"] == "DisplayMath":
357
+ parts = _environments(_without_comments(n["c"][1])) # (% first condition between them)
358
+ if parts and (len(parts) > 1 or parts[0] != n["c"][1]):
359
+ node[k:k + 1] = [{"t": "Math", "c": [{"t": "DisplayMath"}, p]} for p in parts]
360
+ k += len(parts)
361
+ continue
362
+ else:
363
+ _split_grouped(n)
364
+ k += 1
365
+ elif isinstance(node, dict):
366
+ _split_grouped(node.get("c"))
367
+
368
+
369
+ def _count_equations(blocks: list, aux: Dict[str, str], sources: str
370
+ ) -> Tuple[Optional[Dict[int, List[Optional[str]]]], Dict[str, str], List[str]]:
371
+ """The numbers LaTeX gives the display equations of a document read by pandoc: (for each display's
372
+ id, its rows' numbers; the labels so numbered; notes), counted (1), (2)... as LaTeX does, unless the
373
+ document numbers equations otherwise (then None, and the .aux numbers of labelled equations are used)
374
+ or its .aux file says other numbers. The labels of \\tag rows refer to the tag as it prints, always."""
375
+ plans: Dict[int, List[Optional[str]]] = {}
376
+ counted: Dict[str, str] = {}
377
+ tagged: Dict[str, str] = {}
378
+ counter = 0
379
+ displays: list = []
380
+ _display_maths(blocks, displays)
381
+ for node in displays:
382
+ head, rows, tail, kinds = _row_kinds(_without_comments(node["c"][1]))
383
+ numbers: List[Optional[str]] = []
384
+ for k, kind in enumerate(kinds):
385
+ row = rows[2 * k]
386
+ if kind == "count":
387
+ counter += 1
388
+ numbers.append(str(counter))
389
+ for m in _LABEL.finditer(row):
390
+ counted.setdefault(m.group(1), str(counter))
391
+ else:
392
+ numbers.append(None)
393
+ # a \tag's label refers to the tag, as it prints (the .aux has its TeX: $\dagger $); not
394
+ # \numberthis's \tag{\theequation}, whose number only the .aux knows
395
+ if kind and "\\theequation" not in kind[4]:
396
+ for m in _LABEL.finditer(row):
397
+ tagged.setdefault(m.group(1), _tag_text(kind[4], aux))
398
+ if any(numbers):
399
+ plans[id(node)] = numbers
400
+ if not counter:
401
+ return None, tagged, []
402
+ have_aux = any(k in aux for k in counted)
403
+ if _numbering_changed(sources) or _CHAPTER_CLASS.search(sources):
404
+ unnumbered = sum(1 for numbers in plans.values() for n in numbers if n) - sum(
405
+ 1 for k in counted if k in aux)
406
+ if not have_aux:
407
+ return None, tagged, ["No equation numbers: the document numbers its equations by chapter or "
408
+ "section (or another counter shares theirs, or it sets the counter itself), "
409
+ "which only LaTeX's .aux file next to it tells (compile it once)."]
410
+ return None, tagged, ["Equations without a \\label have no number (%d): the document numbers equations "
411
+ "by chapter or section, or another way the .aux file tells only for labelled ones."
412
+ % unnumbered] if unnumbered > 0 else []
413
+ differ = [k for k, v in counted.items() if k in aux and aux[k] != v]
414
+ if differ:
415
+ return None, tagged, ["Only labelled equations have numbers: the .aux file's numbers are not (1), (2)... "
416
+ "in order (%s is %s there), so the others are not known (an .aux file older than "
417
+ "the document, or numbering the document sets itself)." % (differ[0], aux[differ[0]])]
418
+ notes = [] if have_aux else ["Equations numbered (1), (2)... in order, as LaTeX numbers them in this document "
419
+ "(not checked: no .aux file next to it holds their labels)."]
420
+ return plans, dict(counted, **tagged), notes
421
+
422
+
423
+ _COUNTER_CHANGE = re.compile(
424
+ r"\\(?:numberwithin|counterwithin\*?)\s*\{equation\}|\\@addtoreset\s*\{equation\}"
425
+ r"|\\(?:re|provide)?newcommand\*?\s*\{?\s*\\theequation(?![a-zA-Z@])|\\def\s*\\theequation(?![a-zA-Z@])"
426
+ r"|\\(?:setcounter|addtocounter|stepcounter|refstepcounter)\s*\{equation\}|\\begin\s*\{subequations\}"
427
+ r"|\\chapter(?![a-zA-Z@])|\\newtheorem\s*\{[^{}]*\}\s*\[\s*equation\s*\]|\\newaliascnt\s*\{[^{}]*\}\s*\{equation\}")
428
+ _DEFINITION = re.compile(r"\\(?:re|provide)?newcommand\*?\s*\{?\s*\\([a-zA-Z@]+)\s*\}?\s*(?:\[\d\])?\s*(?:\[[^\]]*\])?\s*\{"
429
+ r"|\\[gex]?def\s*\\([a-zA-Z@]+)[^{\n]*\{")
430
+
431
+
432
+ def _numbering_changed(sources: str) -> bool:
433
+ """Whether the document numbers equations otherwise than (1), (2)... in order: by chapter or section,
434
+ a theorem counter sharing theirs, subequations, or the counter set or stepped; a macro that steps it
435
+ (\\numberthis) only if the document uses it."""
436
+ stepping, spans = [], []
437
+ for m in _DEFINITION.finditer(sources):
438
+ depth, i = 1, m.end()
439
+ while i < len(sources) and depth:
440
+ if sources[i] == "\\":
441
+ i += 2
442
+ continue
443
+ depth += {"{": 1, "}": -1}.get(sources[i], 0)
444
+ i += 1
445
+ body = sources[m.end():i - 1]
446
+ name = m.group(1) or m.group(2)
447
+ if name != "theequation" and _COUNTER_CHANGE.search(body):
448
+ stepping.append(name)
449
+ spans.append((m.start(), i))
450
+ rest = sources
451
+ for start, end in reversed(spans):
452
+ rest = rest[:start] + rest[end:]
453
+ return bool(_COUNTER_CHANGE.search(rest)) or any(
454
+ re.search(r"\\%s(?![a-zA-Z@])" % re.escape(name), rest) for name in stepping)
455
+
456
+
457
+ # ---- preparing the blocks -----------------------------------------------------------------------------
458
+ class _Prepare:
459
+ """Walks pandoc JSON: raw TeX (in Markdown) read as LaTeX, each Math prepared for texmath with its
460
+ numbers marked by sentinels, references and citations replaced by what LaTeX prints."""
461
+
462
+ def __init__(self, macros: Optional[compat.Macros], labels: Dict[str, str], folder: Optional[str],
463
+ markdown: bool = False, plans: Optional[Dict[int, List[Optional[str]]]] = None):
464
+ self.macros, self.labels, self.folder = macros, labels, folder
465
+ self.base_macros = macros
466
+ self.ref_commands = {k[len(REF_COMMANDS):]: v.split() for k, v in labels.items() if k.startswith(REF_COMMANDS)}
467
+ # raw TeX in Markdown is read by the LaTeX reader; in a LaTeX document it is what that reader could
468
+ # not read (\gls{..}, a package's command): kept as code, not dropped as pandoc's docx writer would
469
+ self.markdown = markdown
470
+ self.plans = plans or {}
471
+ self.raw_kept = 0
472
+ self.raw_dropped: Dict[str, int] = {}
473
+ self.numbers: Dict[int, str] = {} # sentinel id -> "(2.1)"
474
+ self.maths: List[Tuple[dict, str, str]] = [] # (Math node, original TeX, prepared TeX)
475
+ self.notes: List[str] = []
476
+ self.definitions: List[str] = [] # raw TeX definitions so far (Markdown)
477
+ self.read: Dict[str, bytes] = {}
478
+ self.unresolved = 0
479
+
480
+ def blocks(self, blocks: list) -> list:
481
+ return self.node(blocks)
482
+
483
+ def dropped(self, raw: str) -> None:
484
+ """A LaTeX block pandoc does not know (tikzpicture, algorithm): left out, and said so."""
485
+ env = re.match(r"\s*\\begin\s*\{([^{}]*)\}", raw)
486
+ name = env.group(1) if env else (re.match(r"\s*(\\[A-Za-z@]+)", raw) or [None, "raw TeX"])[1]
487
+ self.raw_dropped[name] = self.raw_dropped.get(name, 0) + 1
488
+
489
+ def raw_block(self, raw: str) -> list:
490
+ """Raw TeX written into Markdown (\\begin{align} or \\begin{aligned} without $$, a \\newcommand,
491
+ an \\input): pandoc's docx writer would drop it; read by the LaTeX reader after the definitions
492
+ before it (what those give themselves left out)."""
493
+ from .pandoc_engine import _MACRO_DEF
494
+ try:
495
+ read = self.after_definitions(raw)
496
+ except ConversionError:
497
+ read = [{"t": "CodeBlock", "c": [["", [], []], raw]}]
498
+ if re.search(r"\\(?:input|include)(?![a-zA-Z@])", raw) or _MACRO_DEF.search(raw) or \
499
+ re.search(r"\\(?:DeclareMathOperator|let)(?![a-zA-Z@])", raw):
500
+ self.definitions.append(raw)
501
+ # for the Markdown maths after it too ($\R$), which pandoc expands only from definitions written
502
+ # into the Markdown itself, not from an \input file's
503
+ from . import documents
504
+ sources = documents._local_sources(os.path.join(self.folder or os.getcwd(), "notes.md"),
505
+ "\n".join(self.definitions))
506
+ self.macros = compat.with_document(self.base_macros, sources, self.labels)
507
+ return self.as_latex(read) if read and isinstance(read[0], dict) and read[0].get("t") != "CodeBlock" \
508
+ else read
509
+
510
+ def after_definitions(self, raw: str) -> list:
511
+ """The blocks of raw TeX read after the definitions so far, without those the definitions give
512
+ themselves (an equation of a raw block that also defines a macro); a blank line between them,
513
+ so that the two never share a paragraph."""
514
+ from .pandoc_engine import _INNER_MATH_ENV
515
+ source = "\\[" + raw + "\\]" if _INNER_MATH_ENV.match(raw) else raw
516
+ if not self.definitions:
517
+ return self.read_latex(source)
518
+ definitions = "\n\n".join(self.definitions)
519
+ return self.read_latex(definitions + "\n\n" + source)[len(self.read_latex(definitions)):]
520
+
521
+ def read_latex(self, source: str) -> list:
522
+ """pandoc's LaTeX reading of raw TeX (remembered: the definitions alone are read once)."""
523
+ if source not in self.read:
524
+ self.read[source] = _run(["-f", "latex", "-t", "json"], source.encode("utf-8"), cwd=self.folder)[0]
525
+ return json.loads(self.read[source])["blocks"]
526
+
527
+ def as_latex(self, nodes):
528
+ """Nodes the LaTeX reader gave (no second reading of the raw TeX it left)."""
529
+ markdown, self.markdown = self.markdown, False
530
+ try:
531
+ return self.node(nodes)
532
+ finally:
533
+ self.markdown = markdown
534
+
535
+ def node(self, node):
536
+ if isinstance(node, list):
537
+ out = []
538
+ for n in node:
539
+ if isinstance(n, dict) and n.get("t") == "RawBlock" and n["c"][0] in _RAW_TEX:
540
+ if self.markdown:
541
+ out += self.raw_block(n["c"][1])
542
+ else:
543
+ self.dropped(n["c"][1])
544
+ else:
545
+ out.append(self.node(n))
546
+ return out
547
+ if not isinstance(node, dict):
548
+ return node
549
+ t = node.get("t")
550
+ if t is None: # the metadata (title, abstract: its citations and maths as the text's), a MetaMap's
551
+ return {k: self.node(v) for k, v in node.items()}
552
+ if t == "Math":
553
+ self.math(node)
554
+ return node
555
+ if t == "Link":
556
+ attrs = dict(node["c"][0][2])
557
+ kind, key = attrs.get("reference-type"), attrs.get("reference", "")
558
+ if kind in _REFERENCE_TYPES:
559
+ keys = [k.strip() for k in key.split(",") if k.strip()]
560
+ if kind == "ref+label": # \autoref or \cref: the next of those the source has for these keys
561
+ queue = self.ref_commands.get(",".join(keys))
562
+ if queue:
563
+ kind = queue.pop(0)
564
+ shown = compat.reference_text(kind, keys, self.labels)
565
+ if shown is not None:
566
+ return {"t": "Str", "c": shown}
567
+ if _inline_text(node["c"][1]).strip() == "[%s]" % key: # pandoc's placeholder: no number
568
+ self.unresolved += 1
569
+ if t == "Cite":
570
+ return self.cite(node)
571
+ if t == "RawInline" and node["c"][0] in _RAW_TEX:
572
+ return self.raw_inline(node)
573
+ if "c" in node:
574
+ node = dict(node)
575
+ node["c"] = self.node(node["c"])
576
+ return node
577
+
578
+ def cite(self, node: dict):
579
+ """What LaTeX prints for a citation (pandoc's docx writer drops the raw \\cite in it): its number or
580
+ author and year from the .aux, else [key]; in Markdown, a key no .aux knows stays as written."""
581
+ raws = [n["c"][1] for n in node["c"][1] if isinstance(n, dict) and n.get("t") == "RawInline"]
582
+ command = re.match(r"\s*\\([A-Za-z]+)", raws[0]) if raws else None # \citep, \citet, \citeauthor...
583
+ cites = [(c["citationId"], _inline_text(c.get("citationPrefix") or []).strip(),
584
+ _inline_text(c.get("citationSuffix") or []).strip().lstrip(", ")) for c in node["c"][0]]
585
+ shown, found = compat.citation_text(command.group(1) if command else "cite", cites, self.labels)
586
+ if self.markdown and not found:
587
+ return {"t": "Span", "c": [["", [], []], self.node(node["c"][1])]}
588
+ return {"t": "Str", "c": shown}
589
+
590
+ def raw_inline(self, node: dict):
591
+ code = {"t": "Code", "c": [["", [], []], node["c"][1]]}
592
+ if not self.markdown:
593
+ self.raw_kept += 1
594
+ return code
595
+ try:
596
+ read = self.after_definitions(node["c"][1])
597
+ except ConversionError:
598
+ return code
599
+ if len(read) == 1 and read[0].get("t") in ("Para", "Plain"):
600
+ return {"t": "Span", "c": [["", [], []], self.as_latex(read[0]["c"])]}
601
+ return code
602
+
603
+ def math(self, node: dict) -> None:
604
+ kind, tex = node["c"]
605
+ marked = tex
606
+ if kind["t"] == "DisplayMath":
607
+ marked = self.mark_numbers(tex, self.plans.get(id(node)))
608
+ try:
609
+ prepared, notes = compat.for_texmath(marked, self.macros, "omml")
610
+ self.notes += [n for n in notes if n not in self.notes]
611
+ except ConversionError:
612
+ prepared = tex
613
+ node["c"] = [kind, prepared]
614
+ self.maths.append((node, tex, prepared))
615
+
616
+ def mark_numbers(self, tex: str, plan: Optional[List[Optional[str]]] = None) -> str:
617
+ """Each numbered row of a display with a sentinel at its end: its \\tag, its number counted as LaTeX
618
+ counts (`plan`), or the .aux number of its \\label."""
619
+ def sentinel(shown: str) -> str:
620
+ n = len(self.numbers) + 1
621
+ self.numbers[n] = shown
622
+ return "\\text{%s}" % (_SENTINEL % n)
623
+
624
+ tex = _without_comments(tex)
625
+ head, rows, tail, kinds = _row_kinds(tex)
626
+ for k, kind in enumerate(kinds):
627
+ i = 2 * k
628
+ row = rows[i]
629
+ if kind and kind != "count":
630
+ _, start, end, starred, argument = kind
631
+ if "\\theequation" in argument: # \numberthis: the number LaTeX stepped to, from the .aux
632
+ label = next((m for m in _LABEL.finditer(row) if m.group(1) in self.labels), None)
633
+ rows[i] = _LABEL.sub("", row[:start] + row[end:]) + (
634
+ sentinel("(%s)" % self.labels[label.group(1)]) if label else "")
635
+ continue
636
+ shown = _tag_text(argument, self.labels)
637
+ rows[i] = _LABEL.sub("", row[:start] + row[end:]) + sentinel(shown if starred else "(%s)" % shown)
638
+ elif kind == "count":
639
+ label = next((m for m in _LABEL.finditer(row) if m.group(1) in self.labels), None)
640
+ shown = plan[k] if plan and k < len(plan) and plan[k] else (
641
+ self.labels[label.group(1)] if label else None)
642
+ if shown is not None:
643
+ rows[i] = _LABEL.sub("", row) + sentinel("(%s)" % shown)
644
+ return head + "".join(rows) + tail
645
+
646
+
647
+ # ---- writing --------------------------------------------------------------------------------------------
648
+ def write_word(blocks: list, path: str, macros: Optional[compat.Macros] = None,
649
+ labels: Optional[Dict[str, str]] = None, notes: Optional[List[str]] = None,
650
+ folder: Optional[str] = None, markdown: bool = False, meta: Optional[dict] = None,
651
+ plans: Optional[Dict[int, List[Optional[str]]]] = None) -> List[str]:
652
+ """`blocks` (pandoc JSON; read from Markdown when `markdown`; `meta`: its title, authors, abstract) as a
653
+ Word document at `path`, written next to it first and then put in its place, with figures found from
654
+ `folder`. Returns notes (what was approximated, what could not be converted, numbers)."""
655
+ from . import diagnose, documents
656
+ prep = _Prepare(macros, labels or {}, folder, markdown, plans)
657
+ meta = prep.node(meta or {})
658
+ blocks = prep.blocks(blocks)
659
+ notes = list(notes or []) + prep.notes
660
+
661
+ def source() -> bytes:
662
+ return json.dumps({"pandoc-api-version": _api(), "meta": meta, "blocks": blocks}).encode("utf-8")
663
+
664
+ target = os.path.abspath(path)
665
+ try:
666
+ handle, part = tempfile.mkstemp(dir=os.path.dirname(target), prefix="." + os.path.basename(target) + ".",
667
+ suffix=".part")
668
+ os.close(handle)
669
+ except OSError as e:
670
+ raise ConversionError("Could not write %s: %s" % (path, e.strerror or e))
671
+ failed: Dict[int, str] = {}
672
+ try:
673
+ _, err = _run(["-f", "json", "-t", "docx", "-o", part], source(), cwd=folder)
674
+ failed = documents._unconverted(err, [p for _, _, p in prep.maths])
675
+ if failed: # again, each such equation as its LaTeX (without sentinels) and the reason after it
676
+ for count, i in enumerate(sorted(failed), 1):
677
+ node, original, prepared = prep.maths[i - 1]
678
+ words = diagnose.explain(original, prepared, failed[i], short=True) if count <= 50 else []
679
+ node["c"] = [node["c"][0], original]
680
+ node["reason"] = words[0] if words else failed[i]
681
+ meta = _with_reasons(meta)
682
+ blocks = _with_reasons(blocks)
683
+ _, err = _run(["-f", "json", "-t", "docx", "-o", part], source(), cwd=folder)
684
+ missing = sorted({m.group(1) for m in re.finditer(r"Could not fetch resource '?([^'\n]+?)'?(?::|\n|$)", err)})
685
+ numbered = _number_equations(part, prep.numbers)
686
+ for attempt in range(5):
687
+ try:
688
+ os.replace(part, target)
689
+ break
690
+ except PermissionError: # open in Word, or a scanner holds it for a moment
691
+ if attempt == 4:
692
+ raise
693
+ time.sleep(0.1)
694
+ except OSError as e:
695
+ raise ConversionError("Could not write %s: %s" % (path, e.strerror or e))
696
+ finally:
697
+ try:
698
+ os.remove(part)
699
+ except OSError:
700
+ pass
701
+ if failed:
702
+ notes.append("%d equation%s could not be converted; %s in the file as LaTeX text with the reason after "
703
+ "%s." % (len(failed), "" if len(failed) == 1 else "s", "it is" if len(failed) == 1 else "they are",
704
+ "it" if len(failed) == 1 else "them"))
705
+ if missing:
706
+ notes.append("Not found, so left out: %s." % ", ".join(missing[:5] + (["..."] if len(missing) > 5 else [])))
707
+ if numbered:
708
+ notes.append("%d equation number%s at the right margin, as Word numbers equations." % (
709
+ numbered, "" if numbered == 1 else "s"))
710
+ if prep.unresolved:
711
+ notes.append("%d reference%s without a number (no .aux file next to the document, or a label it does "
712
+ "not hold)." % (prep.unresolved, "" if prep.unresolved == 1 else "s"))
713
+ if prep.raw_kept:
714
+ notes.append("%d LaTeX command%s that pandoc does not know (a package's command) %s in the file "
715
+ "as code." % (prep.raw_kept, "" if prep.raw_kept == 1 else "s",
716
+ "is" if prep.raw_kept == 1 else "are"))
717
+ if prep.raw_dropped:
718
+ notes.append("Left out, as pandoc does not know them: %s." % ", ".join(
719
+ "%s (%d)" % (name, n) if n > 1 else name for name, n in sorted(prep.raw_dropped.items())))
720
+ return compat.merge_notes(notes)
721
+
722
+
723
+ def _inline_text(nodes) -> str:
724
+ """The plain text of pandoc inlines."""
725
+ words: List[str] = []
726
+
727
+ def walk(n):
728
+ if isinstance(n, list):
729
+ for v in n:
730
+ walk(v)
731
+ elif isinstance(n, dict):
732
+ if n.get("t") == "Str":
733
+ words.append(n["c"])
734
+ elif n.get("t") in ("Space", "SoftBreak"):
735
+ words.append(" ")
736
+ elif "c" in n:
737
+ walk(n["c"])
738
+ walk(nodes)
739
+ return "".join(words)
740
+
741
+
742
+ def _with_reasons(node):
743
+ """The failed Math nodes (marked with "reason") followed by their reason, in bold."""
744
+ if isinstance(node, list):
745
+ out = []
746
+ for n in node:
747
+ out.append(_with_reasons(n))
748
+ if isinstance(n, dict) and n.get("t") == "Math" and n.get("reason"):
749
+ out += [{"t": "Space"}, {"t": "Strong", "c": [{"t": "Str", "c": "[not converted: %s]" % n["reason"]}]}]
750
+ return out
751
+ if isinstance(node, dict):
752
+ clean = {k: v for k, v in node.items() if k != "reason"}
753
+ if "c" in clean:
754
+ clean["c"] = _with_reasons(clean["c"])
755
+ elif "t" not in clean: # the meta mapping
756
+ clean = {k: _with_reasons(v) for k, v in clean.items()}
757
+ return clean
758
+ return node
759
+
760
+
761
+ # ---- numbers in the written file -------------------------------------------------------------------------
762
+ _TAG_TOKEN = re.compile(r"<(/?)m:(\w+)\b[^>]*?(/?)>")
763
+ _MAX_DIST = '<m:maxDist m:val="1"/>'
764
+ _ALIGN = "<m:r><m:t>&amp;</m:t></m:r>"
765
+ _PARTS = ("word/document.xml", "word/footnotes.xml", "word/endnotes.xml")
766
+
767
+
768
+ def _number_equations(docx: str, numbers: Dict[int, str]) -> int:
769
+ """Replaces the sentinels in the written file (its text, footnotes and endnotes) by Word's own
770
+ equation numbers; how many there are."""
771
+ if not numbers:
772
+ return 0
773
+ with zipfile.ZipFile(docx) as z:
774
+ files = {info: z.read(info.filename) for info in z.infolist()}
775
+ names = {info.filename: info for info in files}
776
+ count = [0]
777
+
778
+ def omath(m: "re.Match") -> str:
779
+ body = m.group(1)
780
+ if "QQMSN" not in body:
781
+ return m.group(0)
782
+ return "<m:oMath>%s</m:oMath>" % _numbered(body, numbers, count)
783
+
784
+ for part in _PARTS:
785
+ if part in names:
786
+ xml = files[names[part]].decode("utf-8")
787
+ if "QQMSN" in xml:
788
+ files[names[part]] = re.sub(r"<m:oMath>([\s\S]*?)</m:oMath>", omath, xml).encode("utf-8")
789
+ with zipfile.ZipFile(docx, "w", zipfile.ZIP_DEFLATED) as z:
790
+ for info, data in files.items():
791
+ z.writestr(info, data)
792
+ return count[0]
793
+
794
+
795
+ def _number_run(shown: str) -> str:
796
+ """Word's number mark: # and the number, upright as Word sets its own numbers ((Q), not (𝑄))."""
797
+ return ('<m:r><m:rPr><m:sty m:val="p"/></m:rPr><m:t>#%s</m:t></m:r>'
798
+ % shown.replace("&", "&amp;").replace("<", "&lt;"))
799
+
800
+
801
+ def _as_array(matrix: str) -> Optional[str]:
802
+ """texmath's matrix for gather, eqnarray, flalign (and an align without &) as the equation array Word
803
+ numbers rows of: a row's cells joined at alignment points (eqnarray's at its middle column), a gather
804
+ row centred."""
805
+ first_row = matrix.find("<m:mr>")
806
+ jcs = re.findall(r'<m:mcJc m:val="(\w+)"\s*/>', matrix[:first_row] if first_row > 0 else "")
807
+ rows: List[List[str]] = []
808
+ depth, start = 0, None
809
+ for m in _TAG_TOKEN.finditer(matrix): # its own rows (depth 2) and cells (depth 3), not a nested matrix's
810
+ if m.group(3):
811
+ continue
812
+ if not m.group(1):
813
+ depth += 1
814
+ if depth == 2 and m.group(2) == "mr":
815
+ rows.append([])
816
+ elif depth == 3 and m.group(2) == "e" and rows:
817
+ start = m.end()
818
+ else:
819
+ if depth == 3 and m.group(2) == "e" and start is not None:
820
+ rows[-1].append(matrix[start:m.start()])
821
+ start = None
822
+ depth -= 1
823
+ out = []
824
+ for cells in rows:
825
+ if jcs == ["right", "center", "left"] and len(cells) == 3:
826
+ out.append(cells[0] + _ALIGN + cells[1] + cells[2])
827
+ else:
828
+ out.append(_ALIGN.join(cells))
829
+ return "<m:eqArr>%s</m:eqArr>" % "".join("<m:e>%s</m:e>" % r for r in out) if len(out) > 1 else None
830
+
831
+
832
+ def _numbered(body: str, numbers: Dict[int, str], count: List[int]) -> str:
833
+ """An equation's OMML (inside m:oMath) with its sentinels made Word numbers: in an equation array at
834
+ the end of their rows, else around the whole equation as a one-row array."""
835
+ stripped = body.strip()
836
+ if stripped.startswith("<m:m>") and _top_level_end(stripped, 0) == len(stripped):
837
+ stripped = _as_array(stripped) or stripped # rows numbered one by one (or the last, multline)
838
+ if stripped.startswith("<m:eqArr>") and _top_level_end(stripped, 0) == len(stripped):
839
+ rows = _rows(stripped)
840
+ out, last = [], 0
841
+ for start, end in rows: # end: where the row's </m:e> starts
842
+ row = stripped[start:end]
843
+ ids = [int(i) for i in re.findall(r"QQMSN(\d+)QQ", row)]
844
+ if ids:
845
+ row = _SENTINEL_RUN.sub("", row) + _number_run(numbers[ids[0]])
846
+ count[0] += 1
847
+ out += [stripped[last:start], row]
848
+ last = end
849
+ array = "".join(out) + stripped[last:]
850
+ if "<m:eqArrPr>" in array[:len("<m:eqArr><m:eqArrPr>")]:
851
+ return array.replace("<m:eqArrPr>", "<m:eqArrPr>" + _MAX_DIST, 1)
852
+ return array.replace("<m:eqArr>", "<m:eqArr><m:eqArrPr>%s</m:eqArrPr>" % _MAX_DIST, 1)
853
+ ids = [int(i) for i in re.findall(r"QQMSN(\d+)QQ", body)]
854
+ count[0] += 1
855
+ return ("<m:eqArr><m:eqArrPr>%s</m:eqArrPr><m:e>%s%s</m:e></m:eqArr>"
856
+ % (_MAX_DIST, _SENTINEL_RUN.sub("", body), _number_run(numbers[ids[0]])))
857
+
858
+
859
+ def _top_level_end(xml: str, start: int) -> int:
860
+ """Index after the element that starts at `start` (its closing tag at the same depth)."""
861
+ depth = 0
862
+ for m in _TAG_TOKEN.finditer(xml, start):
863
+ if m.group(3): # <m:x/>
864
+ continue
865
+ depth += -1 if m.group(1) else 1
866
+ if not depth:
867
+ return m.end()
868
+ return -1
869
+
870
+
871
+ def _rows(array: str) -> List[Tuple[int, int]]:
872
+ """(start of content, start of </m:e>) of each row (a direct m:e child) of the m:eqArr `array`."""
873
+ rows, depth, start = [], 0, None
874
+ for m in _TAG_TOKEN.finditer(array):
875
+ if m.group(3):
876
+ continue
877
+ closing, name = m.group(1), m.group(2)
878
+ if not closing:
879
+ depth += 1
880
+ if depth == 2 and name == "e":
881
+ start = m.end()
882
+ else:
883
+ if depth == 2 and name == "e" and start is not None:
884
+ rows.append((start, m.start()))
885
+ start = None
886
+ depth -= 1
887
+ return rows