mathshuttle 0.8.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mathshuttle/__init__.py +3 -0
- mathshuttle/__main__.py +343 -0
- mathshuttle/_clipboard_macos.py +235 -0
- mathshuttle/_clipboard_win32.py +199 -0
- mathshuttle/_hotkeys_macos.py +137 -0
- mathshuttle/app.py +1483 -0
- mathshuttle/clipboard.py +127 -0
- mathshuttle/compat.py +1537 -0
- mathshuttle/convert.py +496 -0
- mathshuttle/diagnose.py +184 -0
- mathshuttle/documents.py +903 -0
- mathshuttle/hotkeys.py +179 -0
- mathshuttle/latex_wrap.py +333 -0
- mathshuttle/office_html.py +234 -0
- mathshuttle/packs.py +610 -0
- mathshuttle/pandoc_engine.py +1732 -0
- mathshuttle/pandoc_fetch.py +325 -0
- mathshuttle/paths.py +19 -0
- mathshuttle/preview.py +232 -0
- mathshuttle/recall.py +337 -0
- mathshuttle/sv_theme/LICENSE +21 -0
- mathshuttle/sv_theme/sv.tcl +130 -0
- mathshuttle/sv_theme/theme/dark.tcl +465 -0
- mathshuttle/sv_theme/theme/light.tcl +469 -0
- mathshuttle/sv_theme/theme/sprites_dark.tcl +95 -0
- mathshuttle/sv_theme/theme/sprites_light.tcl +95 -0
- mathshuttle/sv_theme/theme/spritesheet_dark.png +0 -0
- mathshuttle/sv_theme/theme/spritesheet_light.png +0 -0
- mathshuttle/theme.py +127 -0
- mathshuttle/tidy.py +830 -0
- mathshuttle/wordexport.py +887 -0
- mathshuttle-0.8.0.dist-info/METADATA +113 -0
- mathshuttle-0.8.0.dist-info/RECORD +37 -0
- mathshuttle-0.8.0.dist-info/WHEEL +5 -0
- mathshuttle-0.8.0.dist-info/entry_points.txt +5 -0
- mathshuttle-0.8.0.dist-info/licenses/LICENSE +21 -0
- mathshuttle-0.8.0.dist-info/top_level.txt +1 -0
mathshuttle/diagnose.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""texmath's parse errors in plain words: which command it does not know (and what to do about it), a
|
|
2
|
+
brace that is never closed, an environment that is no equation.
|
|
3
|
+
|
|
4
|
+
texmath reports where its parser stopped ("unexpected control sequence \\ket", or ``unexpected "\\\\"``
|
|
5
|
+
when an unknown command sits inside an aligned block); :func:`explained` puts a line that says what is
|
|
6
|
+
wrong in front of that message, which stays below it.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import difflib
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from typing import Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
from .compat import _TOKEN, _in, _text_spans
|
|
16
|
+
|
|
17
|
+
# commands texmath takes (for "did you mean"); not complete, and it need not be
|
|
18
|
+
_KNOWN = set(("\\" + n) for n in r"""
|
|
19
|
+
alpha beta gamma delta epsilon varepsilon zeta eta theta vartheta iota kappa varkappa lambda mu nu xi pi varpi rho
|
|
20
|
+
varrho sigma varsigma tau upsilon phi varphi chi psi omega Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega
|
|
21
|
+
aleph beth gimel hbar hslash ell wp Re Im partial nabla infty emptyset varnothing forall exists nexists neg lnot top
|
|
22
|
+
bot angle triangle square blacksquare Box Diamond lozenge star ast circ bullet cdot cdots ldots vdots ddots dots times
|
|
23
|
+
div pm mp oplus ominus otimes oslash odot bigoplus bigotimes bigodot biguplus bigsqcup bigcup bigcap bigvee bigwedge
|
|
24
|
+
sum prod coprod int oint iint iiint cup cap sqcup sqcap uplus vee wedge land lor setminus smallsetminus wr amalg
|
|
25
|
+
dagger ddagger diamond leq le geq ge neq ne equiv sim simeq approx cong propto ll gg prec succ preceq succeq subset
|
|
26
|
+
supset subseteq supseteq subsetneq supsetneq in ni notin vdash dashv models perp parallel mid nmid asymp doteq
|
|
27
|
+
triangleq coloneqq lesssim gtrsim leqslant geqslant because therefore to gets rightarrow leftarrow leftrightarrow
|
|
28
|
+
Rightarrow Leftarrow Leftrightarrow longrightarrow longleftarrow Longrightarrow Longleftarrow mapsto longmapsto
|
|
29
|
+
hookrightarrow uparrow downarrow implies iff langle rangle lfloor rfloor lceil rceil lVert rVert lvert rvert vert Vert
|
|
30
|
+
backslash lbrace rbrace prime frac dfrac tfrac binom sqrt left right middle big Big bigg Bigg bigl bigr Bigl Bigr
|
|
31
|
+
mathbf mathrm mathit mathsf mathtt mathcal mathbb mathfrak mathscr boldsymbol bm operatorname text textrm textbf
|
|
32
|
+
textit mbox hat widehat tilde widetilde bar overline underline vec dot ddot check breve acute grave overbrace
|
|
33
|
+
underbrace overset underset stackrel xrightarrow xleftarrow limits nolimits displaystyle textstyle scriptstyle
|
|
34
|
+
quad qquad hspace mspace phantom label tag nonumber begin end sin cos tan cot sec csc arcsin arccos arctan sinh cosh
|
|
35
|
+
tanh log ln exp lim liminf limsup sup inf max min arg det dim ker deg gcd Pr hom cancel not mathop mathrel mathbin
|
|
36
|
+
color boxed substack pmod bmod pod
|
|
37
|
+
""".split())
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _known() -> set:
|
|
41
|
+
from . import compat, packs
|
|
42
|
+
return _KNOWN | set(packs.PACKS) | set(compat._RENAMES) | set(compat._STANDARD)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# commands of packages that MathShuttle does not write out, with what to do instead
|
|
46
|
+
_PACKAGES: Dict[str, str] = {
|
|
47
|
+
"\\ce": "chemistry from mhchem, which texmath does not write: give the formula as maths (\\mathrm{H_2O})",
|
|
48
|
+
"\\pu": "units from mhchem, which texmath does not write: use \\mathrm{...} or siunitx' \\qty",
|
|
49
|
+
"\\xymatrix": "a diagram (xy-pic), not an equation: Office cannot hold it as an equation",
|
|
50
|
+
"\\tikz": "a TikZ picture, not an equation: Office cannot hold it as an equation",
|
|
51
|
+
}
|
|
52
|
+
_DIAGRAM_ENVS = {"tikzcd", "tikzpicture", "xy", "pspicture", "CD"}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
_PROBED: Dict[tuple, List[str]] = {}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _probe(names: List[str]) -> List[str]:
|
|
59
|
+
"""Which of these control words texmath does not know: one pandoc run with each alone (and with
|
|
60
|
+
three arguments, so that commands that need some are not taken for unknown)."""
|
|
61
|
+
key = tuple(names)
|
|
62
|
+
if key not in _PROBED:
|
|
63
|
+
if len(_PROBED) > 64:
|
|
64
|
+
_PROBED.clear()
|
|
65
|
+
_PROBED[key] = _probe_now(names)
|
|
66
|
+
return _PROBED[key]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _probe_now(names: List[str]) -> List[str]:
|
|
70
|
+
from .pandoc_engine import _api, _mathml_flags, _run
|
|
71
|
+
if not names:
|
|
72
|
+
return []
|
|
73
|
+
blocks = [{"t": "Para", "c": [{"t": "Math", "c": [{"t": "InlineMath"}, "%s{a}{b}{c}" % n]}]} for n in names]
|
|
74
|
+
source = json.dumps({"pandoc-api-version": _api(), "meta": {}, "blocks": blocks}).encode("utf-8")
|
|
75
|
+
try:
|
|
76
|
+
_, err = _run(["-f", "json", "-t", "html", *_mathml_flags()], source)
|
|
77
|
+
except Exception: # noqa: BLE001 - the diagnosis is a courtesy; never fail because of it
|
|
78
|
+
return []
|
|
79
|
+
unknown = set(re.findall(r"unexpected control sequence (\\[A-Za-z@]+)", err))
|
|
80
|
+
return [n for n in names if n in unknown]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _unclosed(tex: str) -> Optional[str]:
|
|
84
|
+
"""A brace, \\left or \\begin that is never closed (or closed once too often), in words."""
|
|
85
|
+
opened: List[int] = []
|
|
86
|
+
for m in _TOKEN.finditer(tex):
|
|
87
|
+
tok = m.group()
|
|
88
|
+
if tok.startswith("%"):
|
|
89
|
+
continue
|
|
90
|
+
if tok == "{":
|
|
91
|
+
opened.append(m.start())
|
|
92
|
+
elif tok == "}":
|
|
93
|
+
if not opened:
|
|
94
|
+
return "a } closes a group that was never opened (after \"%s\")" % _before(tex, m.start())
|
|
95
|
+
opened.pop()
|
|
96
|
+
if opened:
|
|
97
|
+
return "a { is never closed (it opens before \"%s\")" % _after(tex, opened[-1])
|
|
98
|
+
tokens = [m for m in _TOKEN.finditer(tex) if not m.group().startswith("%")] # (a comment is ignored)
|
|
99
|
+
lefts = sum(1 for m in tokens if m.group() == "\\left")
|
|
100
|
+
rights = sum(1 for m in tokens if m.group() == "\\right")
|
|
101
|
+
if lefts != rights:
|
|
102
|
+
return "%d \\left but %d \\right: each \\left needs its \\right (\\right. for none)" % (lefts, rights)
|
|
103
|
+
begins = [m.group("env") for m in tokens if m.group("be") == "begin"]
|
|
104
|
+
ends = [m.group("env") for m in tokens if m.group("be") == "end"]
|
|
105
|
+
for env in begins + ends: # (also an \end{align} without its \begin)
|
|
106
|
+
if begins.count(env) != ends.count(env):
|
|
107
|
+
return "\\begin{%s} and \\end{%s} do not pair up" % (env, env)
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _before(tex: str, pos: int) -> str:
|
|
112
|
+
return " ".join(tex[max(0, pos - 25):pos].split())
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _after(tex: str, pos: int) -> str:
|
|
116
|
+
return " ".join(tex[pos:pos + 25].split())
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _control_words(tex: str) -> List[str]:
|
|
120
|
+
"""The control words of `tex` outside text arguments, in order, each once."""
|
|
121
|
+
spans = _text_spans(tex)
|
|
122
|
+
out: List[str] = []
|
|
123
|
+
for m in re.finditer(r"\\[A-Za-z@]+", tex):
|
|
124
|
+
if not _in(spans, m.start()) and m.group() not in out and m.group() not in ("\\begin", "\\end"):
|
|
125
|
+
out.append(m.group())
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def explain(original: str, prepared: str, message: str, short: bool = False) -> List[str]:
|
|
130
|
+
"""Lines in plain words for texmath's `message` on `prepared` (the TeX it was given, which came from
|
|
131
|
+
the user's `original`); `short`: one line without the advice (for a mark in an exported file)."""
|
|
132
|
+
lines: List[str] = []
|
|
133
|
+
problem = _unclosed(original)
|
|
134
|
+
if problem:
|
|
135
|
+
return ["the LaTeX is not complete: %s" % problem if short else "The LaTeX is not complete: %s." % problem]
|
|
136
|
+
for env in re.findall(r"\\begin\s*\{([^{}]*)\}", prepared):
|
|
137
|
+
if env in _DIAGRAM_ENVS:
|
|
138
|
+
return ["%s is a diagram, not an equation" % env if short else
|
|
139
|
+
"%s is a diagram, not an equation: texmath (and Office's equations) cannot hold it." % env]
|
|
140
|
+
stated = re.findall(r"unexpected control sequence (\\[A-Za-z@]+)", message)
|
|
141
|
+
if stated:
|
|
142
|
+
unknown = stated
|
|
143
|
+
else: # the parser stopped elsewhere (inside an aligned block it reports the \\ of the row)
|
|
144
|
+
candidates = [c for c in _control_words(prepared) if c not in _KNOWN]
|
|
145
|
+
unknown = _probe(candidates[:40])
|
|
146
|
+
if not unknown:
|
|
147
|
+
return lines
|
|
148
|
+
known = sorted(_known())
|
|
149
|
+
for name in unknown[:3]:
|
|
150
|
+
if name in _PACKAGES:
|
|
151
|
+
lines.append("%s: %s%s" % (name, _PACKAGES[name].split(", which")[0] if short else _PACKAGES[name],
|
|
152
|
+
"" if short else "."))
|
|
153
|
+
continue
|
|
154
|
+
guess = [g for g in difflib.get_close_matches(name, known, n=3, cutoff=0.8) if g != name][:2] \
|
|
155
|
+
if len(name) > 3 else []
|
|
156
|
+
if short:
|
|
157
|
+
lines.append("texmath does not know %s%s" % (name, " (%s?)" % " or ".join(guess) if guess else ""))
|
|
158
|
+
continue
|
|
159
|
+
hint = " Did you mean %s?" % " or ".join(guess) if guess and name not in guess else ""
|
|
160
|
+
lines.append("texmath does not know %s.%s If it is a macro of yours or of the paper's, give its "
|
|
161
|
+
"definition: Macros... in the window (or --macros FILE), or a \\newcommand before the "
|
|
162
|
+
"equation." % (name, hint))
|
|
163
|
+
return ["; ".join(lines)] if short and lines else lines
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def explained(error: Exception, original: str, prepared: str, which: str = ""):
|
|
167
|
+
"""`error` (a ConversionError from texmath) with the plain-words lines in front; `which`:
|
|
168
|
+
"Equation 3 of 5" when the input held several."""
|
|
169
|
+
from .pandoc_engine import ConversionError
|
|
170
|
+
message = str(error)
|
|
171
|
+
if not message.startswith("texmath could not parse"):
|
|
172
|
+
return error
|
|
173
|
+
try:
|
|
174
|
+
lines = explain(original, prepared, message)
|
|
175
|
+
short = explain(original, prepared, message, short=True)
|
|
176
|
+
except Exception: # noqa: BLE001 - never hide texmath's own message because of a diagnosis bug
|
|
177
|
+
lines, short = [], []
|
|
178
|
+
if which:
|
|
179
|
+
lines = [which + ":"] + lines
|
|
180
|
+
if not lines:
|
|
181
|
+
return error
|
|
182
|
+
explained_error = ConversionError("\n".join(lines) + "\n\n" + message)
|
|
183
|
+
explained_error.short = short[0] if short else "" # for a one-line list (extract, a file's mark)
|
|
184
|
+
return explained_error
|