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,234 @@
1
+ """The equations inside the HTML that Word copies (macOS ``public.html``, Windows ``HTML Format``).
2
+
3
+ Word copies a selection as HTML too, with each equation as OMML inside a conditional comment::
4
+
5
+ <!--[if gte msEquation 12]><m:oMathPara><m:oMath><m:sSup>...<i style='...'><span lang=EN-CA
6
+ style='...'><m:r>x</m:r></span></i>...</m:oMath></m:oMathPara><![endif]--><![if !msEquation]>
7
+ <img ...><![endif]>
8
+
9
+ That OMML is not well-formed as it stands: HTML formatting tags (``<span>``, ``<i>``, ``<br>``) sit
10
+ between the OMML elements, a run's text is not wrapped in ``<m:t>``, and both text and attribute
11
+ values are HTML (entities, unquoted values, line breaks from wrapping). :func:`omml_from_html`
12
+ turns it back into OMML that :func:`.pandoc_engine.read_omml` reads.
13
+
14
+ This is the fallback for what Word copies without MathML: a selection of text with equations in it
15
+ (Word on Windows and macOS), and a math paragraph of several aligned lines (Mac Word 16.115, which
16
+ announces MathML but delivers none). The formatting the HTML tags carried (font, colour) is not
17
+ needed for the LaTeX; the OMML's own properties (``m:sty``, ``m:scr``, ``m:aln``...) are kept.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import html
22
+ import re
23
+ from typing import List, Optional
24
+
25
+ _BLOCK = re.compile(r"<!--\[if gte msEquation 12\]>(.*?)<!\[endif\]-->", re.S | re.I)
26
+ _FRAGMENT = re.compile(r"<!--\s*StartFragment\s*-->(.*?)<!--\s*EndFragment\s*-->", re.S | re.I)
27
+ # a comment (no content, but a boundary between text nodes), or a start, end or empty tag; quoted
28
+ # attribute values may hold ">"
29
+ _TAG = re.compile(r"<!--.*?-->|<(/?)([A-Za-z][\w:.-]*)((?:[^>\"']|\"[^\"]*\"|'[^']*')*)>", re.S)
30
+ # as OMML spells them: m:val, m:alnAt of m:brk (which Word's HTML writes m:alignAt)
31
+ _OMML_ATTRIBUTES = {"val": "val", "alnat": "alnAt", "alignat": "alnAt"}
32
+ # an HTML attribute: name, then a double-quoted, single-quoted or unquoted value (which may hold "/")
33
+ _ATTR = re.compile(r"([A-Za-z_][\w:.-]*)(\s*=\s*(?:\"([^\"]*)\"|'([^']*)'|([^\s\"'=<>`]+)))?", re.S)
34
+ # the OMML element names (ECMA-376 part 1, 22.1), to spell an element as OMML does whatever the HTML did
35
+ _OMML_NAMES = {n.lower(): n for n in (
36
+ "acc accPr aln alnScr argPr argSz bar barPr baseJc begChr borderBox borderBoxPr box boxPr brk brkBin "
37
+ "brkBinSub cGp cGpRule chr count cSp ctrlPr d defJc deg degHide den diff dispDef dPr e endChr eqArr eqArrPr "
38
+ "f fName fPr func funcPr groupChr groupChrPr grow hideBot hideLeft hideRight hideTop interSp intLim intraSp "
39
+ "jc lim limLoc limLow limLowPr limUpp limUppPr lit lMargin m mathFont mathPr maxDist mc mcJc mcPr mcs mPr "
40
+ "mr nary naryLim naryPr noBreak nor num objDist oMath oMathPara oMathParaPr opEmu phant phantPr plcHide pos "
41
+ "postSp preSp r rad radPr rMargin rPr rSp rSpRule scr sepChr show shp smallFrac sPre sPrePr sSub sSubPr "
42
+ "sSubSup sSubSupPr sSup sSupPr strikeBLTR strikeH strikeTLBR strikeV sty sub subHide sup supHide t transp "
43
+ "type vertJc wrapIndent wrapRight zeroAsc zeroDesc zeroWid").split()}
44
+ # elements whose content is maths (runs and structures): stray text there becomes a run
45
+ _CONTENT = frozenset("m:oMath m:e m:num m:den m:sub m:sup m:deg m:lim m:fName".split())
46
+
47
+
48
+ def _omml_name(name: str) -> str:
49
+ """m:oMath, m:r... as OMML spells them; an unknown m: name as the HTML spelled it."""
50
+ local = name.split(":", 1)[1]
51
+ return "m:" + _OMML_NAMES.get(local.lower(), local)
52
+
53
+
54
+ def cf_html_fragment(raw: bytes) -> bytes:
55
+ """The fragment of Windows "HTML Format" data (the copied selection, between the byte offsets of
56
+ its header's StartFragment / EndFragment), or the data as it is if it has no usable header. The
57
+ header is the run of "Name:value" lines before the HTML, starting with Version; the fragment
58
+ starts after it."""
59
+ fields = {}
60
+ pos = 0
61
+ # lines end with CR LF, LF or (archaic, but allowed) CR alone
62
+ for line in re.finditer(rb"([^\r\n]*)(\r\n|\r|\n|$)", raw[:65536]):
63
+ m = re.match(rb"([A-Za-z]+):(.*)$", line.group(1))
64
+ if not m or (not fields and m.group(1) != b"Version") or not line.group(2):
65
+ break
66
+ fields[m.group(1).decode("ascii")] = m.group(2).strip()
67
+ pos = line.end()
68
+ try:
69
+ a, b = int(fields["StartFragment"]), int(fields["EndFragment"])
70
+ except (KeyError, ValueError):
71
+ return raw
72
+ return raw[a:b] if pos <= a <= b <= len(raw) else raw # 0 / 0: offsets not filled in
73
+
74
+
75
+ _ILLEGAL_XML = re.compile("[\x00-\x08\x0e-\x1f]")
76
+
77
+
78
+ def _xml_text(text: str) -> str:
79
+ """Decoded text that XML can hold: a vertical tab or form feed (a soft line break) is a space,
80
+ other control characters go."""
81
+ return _ILLEGAL_XML.sub("", text.replace("\x0b", " ").replace("\x0c", " "))
82
+
83
+
84
+ def _attributes(raw: str) -> "tuple[str, bool]":
85
+ """The OMML attributes (m:val...) of an HTML tag as XML attributes: values decoded, quoted and
86
+ escaped (an attribute without a value gets an empty one), each name once; other attributes (HTML's
87
+ class, Office's o: / w16se: ...) go, their prefixes would not be declared. And whether the tag
88
+ closes itself: a "/" after the last attribute, or ending its unquoted value when the rest is a word
89
+ (m:val=b/, XML's habit; HTML would read "b/"); an unquoted "/" alone is the value (m:val=/)."""
90
+ out, seen = [], set()
91
+ last = 0
92
+ empty = False
93
+ for m in _ATTR.finditer(raw):
94
+ if raw[last:m.start()].strip():
95
+ break # not attribute syntax: what follows is not an attribute either
96
+ last = m.end()
97
+ value = next((v for v in m.group(3, 4, 5) if v is not None), "")
98
+ if m.group(5) and not raw[last:].strip() and re.match(r"[A-Za-z0-9]+/$", value):
99
+ value, empty = value[:-1], True
100
+ prefix, _, local = m.group(1).partition(":")
101
+ if prefix.lower() != "m" or not re.match(r"[A-Za-z]+$", local) or local.lower() in seen:
102
+ continue
103
+ seen.add(local.lower())
104
+ name = _OMML_ATTRIBUTES.get(local.lower(), local)
105
+ out.append(' m:%s="%s"' % (name, html.escape(_xml_text(html.unescape(value)), quote=True)))
106
+ return "".join(out), empty or raw[last:].strip() == "/"
107
+
108
+
109
+ def _collapse(text: str) -> str:
110
+ """A run's text as HTML shows it. White space with a line break in it is one space between words;
111
+ at either end of the run it is the HTML's own layout (the indentation after a <br>, a line wrapped
112
+ between two tags) and goes, unless a space came before the line break (a line wrapped after a
113
+ space the text had)."""
114
+ def white(m) -> str:
115
+ s = m.group(0)
116
+ if "\n" not in s:
117
+ return s
118
+ at_edge = m.start() == 0 or m.end() == len(text)
119
+ return " " if not at_edge or s.split("\n", 1)[0].rstrip("\r") else ""
120
+ return re.sub(r"[ \t\r\n]+", white, text)
121
+
122
+
123
+ class _Run:
124
+ """An <m:r> being read: its start tag, its elements other than text (m:rPr), its text (each HTML
125
+ text node decoded on its own, in order, and whether it was inside an <m:t>), whether it held a
126
+ <br>."""
127
+
128
+ def __init__(self, start_tag: str):
129
+ self.start_tag = start_tag
130
+ self.parts: List[str] = []
131
+ self.text: "List[tuple[bool, str]]" = []
132
+ self.line_break = False
133
+
134
+ def xml(self) -> str:
135
+ pieces = self.text
136
+ if any(in_t for in_t, _ in pieces): # with an <m:t>, white space between the run's tags is layout
137
+ pieces = [(in_t, p) for in_t, p in pieces if in_t or p.strip(" \t\r\n")]
138
+ text = _xml_text(_collapse("".join(p for _, p in pieces)))
139
+ if self.line_break and not text.strip(" \t\r\n"):
140
+ return "" # the run that held Word's <br> between two lines of a math paragraph
141
+ if not text and not self.parts:
142
+ return ""
143
+ t = '<m:t xml:space="preserve">%s</m:t>' % html.escape(text, quote=False) if text else ""
144
+ return self.start_tag + "".join(self.parts) + t + "</m:r>" # one <m:t>: a run is one piece of text
145
+
146
+
147
+ def clean_block(block: str) -> str:
148
+ """One conditional-comment block of Word's HTML -> OMML (``m:`` prefixes, namespace undeclared)."""
149
+ out: List[str] = []
150
+ stack: List[str] = [] # the OMML elements open, as spelled in the output (m:oMath ...)
151
+ run: Optional[_Run] = None # the <m:r> being read; its content goes into it, not into `out`
152
+
153
+ def emit(piece: str) -> None:
154
+ (run.parts if run is not None else out).append(piece)
155
+
156
+ def text(raw: str) -> None:
157
+ if not raw:
158
+ return
159
+ top = stack[-1] if stack else ""
160
+ if run is not None and top in ("m:r", "m:t"):
161
+ run.text.append((top == "m:t", html.unescape(raw))) # each node on its own: "&" + "lt;" is not "<"
162
+ elif top in _CONTENT and raw.strip(): # text outside any run, in maths: a run of its own
163
+ out.append('<m:r><m:t xml:space="preserve">%s</m:t></m:r>'
164
+ % html.escape(_xml_text(_collapse(html.unescape(raw))).strip(), quote=False))
165
+ # anything else (white space between elements, text inside properties) is not maths
166
+
167
+ def close_top() -> None:
168
+ nonlocal run
169
+ name = stack.pop()
170
+ if name == "m:r":
171
+ finished, run = run, None
172
+ if finished is not None:
173
+ out.append(finished.xml())
174
+ elif name != "m:t" or run is None: # a run's <m:t> is written by the run
175
+ emit("</%s>" % name)
176
+
177
+ pos = 0
178
+ for m in _TAG.finditer(block):
179
+ text(block[pos:m.start()])
180
+ pos = m.end()
181
+ closing, raw_name, raw_attrs = m.group(1), m.group(2), m.group(3)
182
+ if raw_name is None:
183
+ continue # a comment: the text on either side stays two text nodes
184
+ if not raw_name.lower().startswith("m:"):
185
+ if raw_name.lower() == "br" and run is not None and stack[-1] in ("m:r", "m:t"):
186
+ run.line_break = True
187
+ run.text.append((stack[-1] == "m:t", "\n")) # a space between words, nothing at an end
188
+ continue # HTML formatting
189
+ name = _omml_name(raw_name)
190
+ if closing:
191
+ if name in stack:
192
+ while stack:
193
+ top = stack[-1]
194
+ close_top()
195
+ if top == name:
196
+ break
197
+ continue # (an end tag without its start tag is dropped)
198
+ attrs, empty = _attributes(raw_attrs)
199
+ if run is not None and stack[-1] == "m:r" and name not in ("m:rPr", "m:t"):
200
+ close_top() # a structure inside a run is not OMML: the run ended before it (</m:r> missing)
201
+ if name == "m:r":
202
+ if not empty:
203
+ while run is not None: # a run inside a run: the open one ends here
204
+ close_top()
205
+ run = _Run("<m:r%s>" % attrs)
206
+ stack.append(name)
207
+ continue
208
+ if name == "m:t" and run is not None:
209
+ if not empty:
210
+ stack.append(name) # its text goes into the run's text
211
+ continue
212
+ emit("<%s%s/>" % (name, attrs) if empty else "<%s%s>" % (name, attrs))
213
+ if not empty:
214
+ stack.append(name)
215
+ text(block[pos:])
216
+ while stack: # elements the HTML left open
217
+ close_top()
218
+ return "".join(out)
219
+
220
+
221
+ def omml_from_html(text: Optional[str]) -> Optional[str]:
222
+ """The OMML of every equation in Word's HTML (only in the copied fragment when the HTML marks it),
223
+ one fragment after the other; None if there is none."""
224
+ if not text:
225
+ return None
226
+ fragment = _FRAGMENT.search(text)
227
+ if fragment:
228
+ text = fragment.group(1)
229
+ else: # a start marker without the end one: what follows it
230
+ start = re.search(r"<!--\s*StartFragment\s*-->", text, re.I)
231
+ text = text[start.end():] if start else text
232
+ blocks = [clean_block(b) for b in _BLOCK.findall(text)]
233
+ blocks = [b for b in blocks if re.search(r"<m:oMath\b", b)]
234
+ return "\n".join(blocks) if blocks else None