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/hotkeys.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""A system-wide hotkey, heard while the app runs, even minimised: Win32 RegisterHotKey, or on macOS
|
|
2
|
+
Carbon's RegisterEventHotKey (:mod:`._hotkeys_macos`), both via ctypes.
|
|
3
|
+
|
|
4
|
+
RegisterHotKey with no window posts WM_HOTKEY to the message queue of the thread that registered it,
|
|
5
|
+
so the Windows :class:`HotkeyListener` registers the key in a thread of its own, which runs a message
|
|
6
|
+
loop and puts each press into a queue that the Tk thread polls (Tk must only be used from its own
|
|
7
|
+
thread). The macOS listener registers on Tk's thread and fills the same kind of queue.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import ctypes
|
|
12
|
+
import ctypes.wintypes as wt
|
|
13
|
+
import queue
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
from typing import Optional, Tuple
|
|
18
|
+
|
|
19
|
+
# Why there is no hotkey (None: there is one). The module still imports elsewhere, for parse() and so
|
|
20
|
+
# that the app can say so; a listener there reports this reason instead of starting.
|
|
21
|
+
UNAVAILABLE: Optional[str] = None if sys.platform in ("win32", "darwin") else "Windows and macOS only"
|
|
22
|
+
|
|
23
|
+
if sys.platform == "win32":
|
|
24
|
+
_user32 = ctypes.windll.user32
|
|
25
|
+
_kernel32 = ctypes.windll.kernel32
|
|
26
|
+
_user32.RegisterHotKey.argtypes = [wt.HWND, ctypes.c_int, wt.UINT, wt.UINT]
|
|
27
|
+
_user32.RegisterHotKey.restype = wt.BOOL
|
|
28
|
+
_user32.UnregisterHotKey.argtypes = [wt.HWND, ctypes.c_int]
|
|
29
|
+
_user32.GetMessageW.argtypes = [ctypes.POINTER(wt.MSG), wt.HWND, wt.UINT, wt.UINT]
|
|
30
|
+
_user32.GetMessageW.restype = wt.BOOL
|
|
31
|
+
_user32.PostThreadMessageW.argtypes = [wt.DWORD, wt.UINT, wt.WPARAM, wt.LPARAM]
|
|
32
|
+
_user32.PostThreadMessageW.restype = wt.BOOL
|
|
33
|
+
_user32.PeekMessageW.argtypes = [ctypes.POINTER(wt.MSG), wt.HWND, wt.UINT, wt.UINT, wt.UINT]
|
|
34
|
+
|
|
35
|
+
WM_HOTKEY = 0x0312
|
|
36
|
+
WM_QUIT = 0x0012
|
|
37
|
+
MOD_ALT, MOD_CONTROL, MOD_SHIFT, MOD_WIN, MOD_NOREPEAT = 0x1, 0x2, 0x4, 0x8, 0x4000
|
|
38
|
+
_MODIFIERS = {"ctrl": MOD_CONTROL, "control": MOD_CONTROL, "alt": MOD_ALT, "shift": MOD_SHIFT, "win": MOD_WIN}
|
|
39
|
+
_KEYS = {**{"f%d" % i: 0x6F + i for i in range(1, 25)}, "space": 0x20, "insert": 0x2D, "home": 0x24,
|
|
40
|
+
"end": 0x23, "pageup": 0x21, "pagedown": 0x22}
|
|
41
|
+
|
|
42
|
+
DEFAULT = "Ctrl+Alt+Shift+M" # on the Mac: Control+Option+Shift+M
|
|
43
|
+
|
|
44
|
+
# macOS: Carbon's modifier bits and the virtual key codes (positions on an ANSI keyboard)
|
|
45
|
+
_MAC_MODIFIERS = {"ctrl": 0x1000, "control": 0x1000, "alt": 0x0800, "option": 0x0800, "opt": 0x0800,
|
|
46
|
+
"shift": 0x0200, "cmd": 0x0100, "command": 0x0100, "win": 0x0100}
|
|
47
|
+
_MAC_KEYS = {
|
|
48
|
+
**dict(zip("asdfhgzxcv", range(0x00, 0x0A))), "b": 0x0B, "q": 0x0C, "w": 0x0D, "e": 0x0E, "r": 0x0F,
|
|
49
|
+
"y": 0x10, "t": 0x11, "1": 0x12, "2": 0x13, "3": 0x14, "4": 0x15, "6": 0x16, "5": 0x17, "9": 0x19,
|
|
50
|
+
"7": 0x1A, "8": 0x1C, "0": 0x1D, "o": 0x1F, "u": 0x20, "i": 0x22, "p": 0x23, "l": 0x25, "j": 0x26,
|
|
51
|
+
"k": 0x28, "n": 0x2D, "m": 0x2E,
|
|
52
|
+
"f1": 0x7A, "f2": 0x78, "f3": 0x63, "f4": 0x76, "f5": 0x60, "f6": 0x61, "f7": 0x62, "f8": 0x64,
|
|
53
|
+
"f9": 0x65, "f10": 0x6D, "f11": 0x67, "f12": 0x6F, "f13": 0x69, "f14": 0x6B, "f15": 0x71, "f16": 0x6A,
|
|
54
|
+
"f17": 0x40, "f18": 0x4F, "f19": 0x50, "f20": 0x5A,
|
|
55
|
+
"space": 0x31, "insert": 0x72, "home": 0x73, "end": 0x77, "pageup": 0x74, "pagedown": 0x79}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse_macos(hotkey: str) -> Tuple[int, int]:
|
|
59
|
+
"""``"Ctrl+Alt+Shift+M"`` -> (Carbon modifiers, virtual key code) on the Mac: Ctrl is Control, Alt
|
|
60
|
+
Option, Cmd (or Win) Command; ValueError if it is not one."""
|
|
61
|
+
parts = [p.strip().lower() for p in hotkey.split("+") if p.strip()]
|
|
62
|
+
if not parts:
|
|
63
|
+
raise ValueError("empty hotkey")
|
|
64
|
+
mods = 0
|
|
65
|
+
for p in parts[:-1]:
|
|
66
|
+
if p not in _MAC_MODIFIERS:
|
|
67
|
+
raise ValueError("unknown modifier %r in %r" % (p, hotkey))
|
|
68
|
+
mods |= _MAC_MODIFIERS[p]
|
|
69
|
+
if parts[-1] not in _MAC_KEYS:
|
|
70
|
+
raise ValueError("unknown key %r in %r" % (parts[-1], hotkey))
|
|
71
|
+
if not mods & (0x1000 | 0x0800 | 0x0100):
|
|
72
|
+
raise ValueError("%r needs Ctrl, Alt or Cmd (it would take the key from every program)" % hotkey)
|
|
73
|
+
return mods, _MAC_KEYS[parts[-1]]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def display(hotkey: str) -> str:
|
|
77
|
+
"""The hotkey as the user's system names its keys: Control+Option+Shift+M on the Mac."""
|
|
78
|
+
if sys.platform != "darwin":
|
|
79
|
+
return hotkey
|
|
80
|
+
names = {"ctrl": "Control", "control": "Control", "alt": "Option", "option": "Option", "opt": "Option",
|
|
81
|
+
"shift": "Shift", "cmd": "Command", "command": "Command", "win": "Command"}
|
|
82
|
+
parts = [p.strip() for p in hotkey.split("+") if p.strip()]
|
|
83
|
+
return "+".join([names.get(p.lower(), p) for p in parts[:-1]] + parts[-1:])
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def parse(hotkey: str) -> Tuple[int, int]:
|
|
87
|
+
"""The hotkey for this system: :func:`parse_macos` on the Mac, else :func:`parse_windows`."""
|
|
88
|
+
return parse_macos(hotkey) if sys.platform == "darwin" else parse_windows(hotkey)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_windows(hotkey: str) -> Tuple[int, int]:
|
|
92
|
+
"""``"Ctrl+Alt+Shift+M"`` -> (modifiers, virtual-key code); ValueError if it is not one."""
|
|
93
|
+
parts = [p.strip().lower() for p in hotkey.split("+") if p.strip()]
|
|
94
|
+
if not parts:
|
|
95
|
+
raise ValueError("empty hotkey")
|
|
96
|
+
mods = 0
|
|
97
|
+
for p in parts[:-1]:
|
|
98
|
+
if p not in _MODIFIERS:
|
|
99
|
+
raise ValueError("unknown modifier %r in %r" % (p, hotkey))
|
|
100
|
+
mods |= _MODIFIERS[p]
|
|
101
|
+
key = parts[-1]
|
|
102
|
+
if re.fullmatch(r"[a-z0-9]", key):
|
|
103
|
+
vk = ord(key.upper())
|
|
104
|
+
elif key in _KEYS:
|
|
105
|
+
vk = _KEYS[key]
|
|
106
|
+
else:
|
|
107
|
+
raise ValueError("unknown key %r in %r" % (key, hotkey))
|
|
108
|
+
if not mods & (MOD_CONTROL | MOD_ALT | MOD_WIN):
|
|
109
|
+
raise ValueError("%r needs Ctrl, Alt or Win (it would take the key from every program)" % hotkey)
|
|
110
|
+
return mods, vk
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class HotkeyListener(threading.Thread):
|
|
114
|
+
"""Listens for one hotkey; each press is put into `presses`. `error` says why it could not be
|
|
115
|
+
registered (another program holds the combination), after `started` is set."""
|
|
116
|
+
|
|
117
|
+
def __init__(self, hotkey: str) -> None:
|
|
118
|
+
super().__init__(daemon=True, name="hotkey")
|
|
119
|
+
self.hotkey = hotkey
|
|
120
|
+
self.mods, self.vk = parse_windows(hotkey)
|
|
121
|
+
self.presses: "queue.Queue[str]" = queue.Queue()
|
|
122
|
+
self.started = threading.Event()
|
|
123
|
+
self.cancelled = threading.Event() # given up on (start_and_wait timed out): must not keep the key
|
|
124
|
+
self._lock = threading.Lock()
|
|
125
|
+
self.error: Optional[str] = None
|
|
126
|
+
self.thread_id = 0
|
|
127
|
+
|
|
128
|
+
def run(self) -> None:
|
|
129
|
+
self.thread_id = _kernel32.GetCurrentThreadId()
|
|
130
|
+
msg = wt.MSG()
|
|
131
|
+
_user32.PeekMessageW(ctypes.byref(msg), None, 0, 0, 0) # create the message queue first
|
|
132
|
+
if not _user32.RegisterHotKey(None, 1, self.mods | MOD_NOREPEAT, self.vk):
|
|
133
|
+
self.error = "%s is already used by another program" % self.hotkey
|
|
134
|
+
self.started.set()
|
|
135
|
+
return
|
|
136
|
+
with self._lock: # against start_and_wait giving up at this very moment
|
|
137
|
+
if self.cancelled.is_set(): # registered after the caller stopped waiting: release the key
|
|
138
|
+
_user32.UnregisterHotKey(None, 1)
|
|
139
|
+
return
|
|
140
|
+
self.started.set()
|
|
141
|
+
try:
|
|
142
|
+
while _user32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
|
|
143
|
+
if msg.message == WM_HOTKEY:
|
|
144
|
+
self.presses.put(self.hotkey)
|
|
145
|
+
finally:
|
|
146
|
+
_user32.UnregisterHotKey(None, 1)
|
|
147
|
+
|
|
148
|
+
def start_and_wait(self, timeout: float = 2.0) -> Optional[str]:
|
|
149
|
+
"""Start; None once the hotkey is registered, else the reason it is not."""
|
|
150
|
+
if UNAVAILABLE is not None:
|
|
151
|
+
return UNAVAILABLE # no thread: there is nothing to register the key with
|
|
152
|
+
self.start()
|
|
153
|
+
if not self.started.wait(timeout):
|
|
154
|
+
with self._lock:
|
|
155
|
+
self.cancelled.set()
|
|
156
|
+
registered = self.started.is_set() and self.error is None # just now, after all
|
|
157
|
+
if registered:
|
|
158
|
+
self.stop()
|
|
159
|
+
return "the hotkey thread did not start"
|
|
160
|
+
return self.error
|
|
161
|
+
|
|
162
|
+
def stop(self) -> None:
|
|
163
|
+
if self.thread_id and self.is_alive():
|
|
164
|
+
_user32.PostThreadMessageW(self.thread_id, WM_QUIT, 0, 0)
|
|
165
|
+
self.join(1.0)
|
|
166
|
+
|
|
167
|
+
def simulate_press(self) -> None:
|
|
168
|
+
"""Post WM_HOTKEY as a press would (for tests: no keystroke is sent anywhere)."""
|
|
169
|
+
_user32.PostThreadMessageW(self.thread_id, WM_HOTKEY, 1, 0)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
if sys.platform == "darwin":
|
|
173
|
+
from . import _hotkeys_macos
|
|
174
|
+
|
|
175
|
+
class HotkeyListener(_hotkeys_macos.MacHotkeyListener): # type: ignore[no-redef] # noqa: F811
|
|
176
|
+
"""The macOS listener (Carbon), with the Windows listener's interface."""
|
|
177
|
+
|
|
178
|
+
def __init__(self, hotkey: str) -> None:
|
|
179
|
+
super().__init__(hotkey, *parse_macos(hotkey))
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""Re-wrapping LaTeX math: bare / $...$ / \\(...\\) / $$...$$ / \\[...\\] / environments.
|
|
2
|
+
|
|
3
|
+
pandoc keeps a display environment (equation, align, gather, ...) verbatim inside
|
|
4
|
+
the math string it hands us, so a TeX body may be
|
|
5
|
+
|
|
6
|
+
* plain math ``x^2``
|
|
7
|
+
* plain math in a display env ``\\begin{equation} x^2 \\end{equation}``
|
|
8
|
+
* an alignment env ``\\begin{align} a &= b \\\\ c &= d \\end{align}``
|
|
9
|
+
* plain math holding an inner env ``\\begin{aligned} ... \\end{aligned}``
|
|
10
|
+
|
|
11
|
+
:func:`wrap` converts any of those to the wrapper the user asked for.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from typing import List, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
# ---- environment classes ------------------------------------------------------------
|
|
19
|
+
PLAIN_ENVS = ("equation", "equation*", "displaymath", "math")
|
|
20
|
+
ALIGN_ENVS = ("align", "align*", "alignat", "alignat*", "flalign", "flalign*", "eqnarray", "eqnarray*")
|
|
21
|
+
GATHER_ENVS = ("gather", "gather*")
|
|
22
|
+
MULTLINE_ENVS = ("multline", "multline*")
|
|
23
|
+
# nested environments that are valid *inside* math mode
|
|
24
|
+
INNER_ALIGN = ("aligned", "split")
|
|
25
|
+
INNER_GATHER = ("gathered",)
|
|
26
|
+
INNER_MULTLINE = ("multlined",)
|
|
27
|
+
|
|
28
|
+
_OUTER = PLAIN_ENVS + ALIGN_ENVS + GATHER_ENVS + MULTLINE_ENVS
|
|
29
|
+
_INNER = INNER_ALIGN + INNER_GATHER + INNER_MULTLINE
|
|
30
|
+
|
|
31
|
+
_ENV_RE = re.compile(r"^\s*\\begin\{(?P<env>[a-zA-Z]+\*?)\}(?P<body>[\s\S]*?)\\end\{(?P=env)\}\s*$")
|
|
32
|
+
# LaTeX finds an environment's arguments after spaces and after comments (``\begin{aligned}% note``
|
|
33
|
+
# + newline + ``[t]``): group 1 is that gap, kept in the body
|
|
34
|
+
_BEFORE_ARG = r"^((?:\s|%[^\n]*(?:\n|$))*)"
|
|
35
|
+
_ALIGNAT_ARG_RE = re.compile(_BEFORE_ARG + r"\{\s*\d+\s*\}")
|
|
36
|
+
# vertical position of aligned / gathered ([t], [b], [c]); multlined also takes a width: [t][6cm]
|
|
37
|
+
_POSITION_ARG_RE = {"aligned": re.compile(_BEFORE_ARG + r"\[\s*[tbc]\s*\]"),
|
|
38
|
+
"gathered": re.compile(_BEFORE_ARG + r"\[\s*[tbc]\s*\]"),
|
|
39
|
+
"multlined": re.compile(_BEFORE_ARG + r"(?:\[[^\[\]]*\]\s*){1,2}")}
|
|
40
|
+
# \begin{env} / \end{env} (groups "be", "env"; spaces or comments may precede the name), other control
|
|
41
|
+
# sequences, comments, braces and &; a comment is one token, so nothing inside it counts
|
|
42
|
+
_TOKEN_RE = re.compile(r"\\(?P<be>begin|end)(?:\s|%[^\n]*\n)*\{(?P<env>[^{}]*)\}|\\[a-zA-Z@]+|\\.|%[^\n]*|[{}&]", re.S)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _top_level(body: str):
|
|
46
|
+
"""The tokens of `body` that are outside every brace group and nested environment (comments
|
|
47
|
+
skipped), as regex matches; \\begin / \\end tokens themselves are not yielded."""
|
|
48
|
+
depth = 0
|
|
49
|
+
for m in _TOKEN_RE.finditer(body):
|
|
50
|
+
tok = m.group()
|
|
51
|
+
if m.group("be"):
|
|
52
|
+
depth += 1 if m.group("be") == "begin" else -1
|
|
53
|
+
elif tok == "{":
|
|
54
|
+
depth += 1
|
|
55
|
+
elif tok == "}":
|
|
56
|
+
depth -= 1
|
|
57
|
+
elif depth <= 0 and not tok.startswith("%"):
|
|
58
|
+
yield m
|
|
59
|
+
|
|
60
|
+
# ---- output wrappers ---------------------------------------------------------------------
|
|
61
|
+
# key -> label shown in the UI
|
|
62
|
+
WRAPPERS = [
|
|
63
|
+
("auto", "Auto (keep environment, else by mode)"),
|
|
64
|
+
("bare", "Bare (no delimiters)"),
|
|
65
|
+
("dollar", "$ … $"),
|
|
66
|
+
("paren", "\\( … \\)"),
|
|
67
|
+
("ddollar", "$$ … $$"),
|
|
68
|
+
("bracket", "\\[ … \\]"),
|
|
69
|
+
("equation", "\\begin{equation}"),
|
|
70
|
+
("equation*", "\\begin{equation*}"),
|
|
71
|
+
("align", "\\begin{align}"),
|
|
72
|
+
("align*", "\\begin{align*}"),
|
|
73
|
+
("gather", "\\begin{gather}"),
|
|
74
|
+
("gather*", "\\begin{gather*}"),
|
|
75
|
+
("multline", "\\begin{multline}"),
|
|
76
|
+
("multline*", "\\begin{multline*}"),
|
|
77
|
+
]
|
|
78
|
+
WRAPPER_KEYS = [k for k, _ in WRAPPERS]
|
|
79
|
+
INLINE_WRAPPERS = ("dollar", "paren")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _balanced(body: str, env: str) -> bool:
|
|
83
|
+
"""True if the \\begin{env} / \\end{env} inside `body` pair up, i.e. the outer begin and end
|
|
84
|
+
enclose all of `tex` - not ``\\begin{aligned}..\\end{aligned} \\quad \\begin{aligned}..\\end{aligned}``."""
|
|
85
|
+
depth = 0
|
|
86
|
+
for m in _TOKEN_RE.finditer(body): # not inside comments
|
|
87
|
+
if m.group("be") and m.group("env").strip() == env:
|
|
88
|
+
depth += 1 if m.group("be") == "begin" else -1
|
|
89
|
+
if depth < 0:
|
|
90
|
+
return False
|
|
91
|
+
return depth == 0
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _eqnarray_to_align(body: str) -> str:
|
|
95
|
+
"""eqnarray rows have three columns (``a &=& b``); align / aligned have pairs (``a &= b``):
|
|
96
|
+
drop the second ``&`` of every row (not counting those of a nested matrix or array)."""
|
|
97
|
+
out, amps, last = [], 0, 0
|
|
98
|
+
for m in _top_level(body):
|
|
99
|
+
tok = m.group()
|
|
100
|
+
if tok == "\\\\":
|
|
101
|
+
amps = 0
|
|
102
|
+
elif tok == "&":
|
|
103
|
+
amps += 1
|
|
104
|
+
if amps == 2:
|
|
105
|
+
out.append(body[last:m.start()])
|
|
106
|
+
last = m.end()
|
|
107
|
+
return "".join(out) + body[last:]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def split_env(tex: str, envs: Tuple[str, ...]) -> Tuple[Optional[str], str]:
|
|
111
|
+
"""If `tex` is exactly one ``\\begin{env}...\\end{env}`` with env in `envs`, return (env, inner)."""
|
|
112
|
+
m = _ENV_RE.match(tex)
|
|
113
|
+
if m and m.group("env") in envs and _balanced(m.group("body"), m.group("env")):
|
|
114
|
+
env, body = m.group("env"), m.group("body")
|
|
115
|
+
if env.startswith("alignat"):
|
|
116
|
+
body = _ALIGNAT_ARG_RE.sub(r"\1", body, count=1) # drop the column-count argument
|
|
117
|
+
elif env.startswith("eqnarray"):
|
|
118
|
+
body = _eqnarray_to_align(body)
|
|
119
|
+
elif env in _POSITION_ARG_RE:
|
|
120
|
+
body = _POSITION_ARG_RE[env].sub(r"\1", body, count=1) # meaningless outside the enclosing formula
|
|
121
|
+
return env, body.strip("\n").strip()
|
|
122
|
+
return None, tex.strip()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _ends_in_comment(body: str) -> bool:
|
|
126
|
+
"""True if the last line of `body` ends in a % comment, which would swallow a closing delimiter."""
|
|
127
|
+
return any(m.group().startswith("%") for m in _TOKEN_RE.finditer(body.rsplit("\n", 1)[-1]))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _no_split(body: str) -> str:
|
|
131
|
+
"""split only works directly inside a display formula: inline, it becomes aligned - also when the
|
|
132
|
+
formula holds more than the split block (``\\label{eq:a}\\begin{split}...``)."""
|
|
133
|
+
env, inner = split_env(body, ("split",))
|
|
134
|
+
if env:
|
|
135
|
+
return _env("aligned", inner)
|
|
136
|
+
out, last = [], 0
|
|
137
|
+
for m in _TOKEN_RE.finditer(body):
|
|
138
|
+
if m.group("be") and m.group("env").strip() == "split":
|
|
139
|
+
out.append(body[last:m.start("env")] + "aligned")
|
|
140
|
+
last = m.end("env")
|
|
141
|
+
return "".join(out) + body[last:]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def classify(tex: str) -> Tuple[str, str]:
|
|
145
|
+
"""Return (kind, content) with kind in {"plain", "align", "gather", "multline"}.
|
|
146
|
+
|
|
147
|
+
`content` is the raw body of the alignment environment (with & and \\\\) for
|
|
148
|
+
the non-plain kinds, and ordinary math-mode TeX for "plain".
|
|
149
|
+
"""
|
|
150
|
+
env, inner = split_env(tex, _OUTER + _INNER)
|
|
151
|
+
if env is None:
|
|
152
|
+
return "plain", inner
|
|
153
|
+
if env in PLAIN_ENVS:
|
|
154
|
+
# equation{ aligned/split{...} } -> look one level further down
|
|
155
|
+
env2, inner2 = split_env(inner, _INNER)
|
|
156
|
+
if env2 is None:
|
|
157
|
+
return "plain", inner
|
|
158
|
+
env, inner = env2, inner2
|
|
159
|
+
if env in ALIGN_ENVS or env in INNER_ALIGN:
|
|
160
|
+
return "align", inner
|
|
161
|
+
if env in GATHER_ENVS or env in INNER_GATHER:
|
|
162
|
+
return "gather", inner
|
|
163
|
+
return "multline", inner
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def has_outer_env(tex: str) -> bool:
|
|
167
|
+
return split_env(tex, _OUTER)[0] is not None
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _env(name: str, body: str) -> str:
|
|
171
|
+
return "\\begin{%s}\n%s\n\\end{%s}" % (name, body, name)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def to_plain(kind: str, content: str) -> str:
|
|
175
|
+
"""Math-mode TeX usable inside any delimiter."""
|
|
176
|
+
if kind == "plain":
|
|
177
|
+
return content
|
|
178
|
+
if kind == "align":
|
|
179
|
+
return _env("aligned", content)
|
|
180
|
+
return _env("gathered", content) # gather-like and multline-like (multlined needs mathtools)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def plain_form(tex: str) -> str:
|
|
184
|
+
"""Math-mode TeX for `tex`, kept verbatim whenever it already is math-mode content."""
|
|
185
|
+
env, inner = split_env(tex, _OUTER + _INNER)
|
|
186
|
+
if env is None:
|
|
187
|
+
return inner
|
|
188
|
+
if env in _INNER:
|
|
189
|
+
return tex.strip()
|
|
190
|
+
if env in PLAIN_ENVS:
|
|
191
|
+
return inner # may itself be an aligned/split block: keep as written
|
|
192
|
+
return to_plain(*classify(tex))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _display(open_, close, body: str) -> str:
|
|
196
|
+
if "\n" in body or _ends_in_comment(body):
|
|
197
|
+
return "%s\n%s\n%s" % (open_, body, close)
|
|
198
|
+
return "%s %s %s" % (open_, body, close)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _inline(open_, close, body: str) -> str:
|
|
202
|
+
body = _no_split(body)
|
|
203
|
+
return "%s%s%s%s" % (open_, body, "\n" if _ends_in_comment(body) else "", close)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _env_sequence(tex: str) -> Optional[List[str]]:
|
|
207
|
+
"""`tex` as one or more outer environments one after the other (with only spaces and comments
|
|
208
|
+
between them), or None."""
|
|
209
|
+
envs, start, depth, last = [], None, 0, 0
|
|
210
|
+
for m in _TOKEN_RE.finditer(tex):
|
|
211
|
+
if m.group("be") is None:
|
|
212
|
+
if not depth and not m.group().startswith("%"):
|
|
213
|
+
return None # something between the environments
|
|
214
|
+
continue
|
|
215
|
+
if m.group("be") == "begin":
|
|
216
|
+
if not depth:
|
|
217
|
+
if tex[last:m.start()].strip() and not re.fullmatch(r"(?:\s|%[^\n]*)*", tex[last:m.start()]):
|
|
218
|
+
return None
|
|
219
|
+
start = m.start()
|
|
220
|
+
depth += 1
|
|
221
|
+
else:
|
|
222
|
+
depth -= 1
|
|
223
|
+
if not depth:
|
|
224
|
+
env = tex[start:m.end()]
|
|
225
|
+
if split_env(env, _OUTER)[0] is None:
|
|
226
|
+
return None
|
|
227
|
+
envs.append(env.strip())
|
|
228
|
+
last = m.end()
|
|
229
|
+
if depth or not envs or not re.fullmatch(r"(?:\s|%[^\n]*)*", tex[last:]):
|
|
230
|
+
return None
|
|
231
|
+
return envs
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
_LEADING_LABELS = re.compile(r"^((?:\s|%[^\n]*\n)*(?:\\label\s*\{[^{}]*\}(?:\s|%[^\n]*\n)*)+)")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def wrap(tex: str, wrapper: str, display: bool = True) -> str:
|
|
238
|
+
"""Return `tex` re-wrapped as `wrapper` (one of WRAPPER_KEYS)."""
|
|
239
|
+
if wrapper not in WRAPPER_KEYS:
|
|
240
|
+
raise ValueError("unknown wrapper %r" % wrapper)
|
|
241
|
+
labels = _LEADING_LABELS.match(tex)
|
|
242
|
+
rest = tex[labels.end():] if labels else tex
|
|
243
|
+
envs = _env_sequence(rest)
|
|
244
|
+
if envs and (labels or len(envs) > 1):
|
|
245
|
+
# \begin{subequations}\label{g} \begin{align}..\end{align} (or two equation environments): pandoc
|
|
246
|
+
# gives the group's label before the environments, which LaTeX takes only inside subequations
|
|
247
|
+
# (not inside \[ \]), as it takes several environments only one after the other
|
|
248
|
+
if wrapper == "auto":
|
|
249
|
+
return "\\begin{subequations}%s\n%s\n\\end{subequations}" % (
|
|
250
|
+
labels.group(1).strip() if labels else "", "\n".join(envs))
|
|
251
|
+
if len(envs) > 1: # each in the wrapper; the group's label has no place there
|
|
252
|
+
return "\n\n".join(wrap(env, wrapper, display) for env in envs)
|
|
253
|
+
tex = rest # the rows keep their own labels; the group's has no place in another wrapper
|
|
254
|
+
if wrapper == "auto":
|
|
255
|
+
if has_outer_env(tex):
|
|
256
|
+
return tex.strip()
|
|
257
|
+
wrapper = "bracket" if display else "dollar"
|
|
258
|
+
|
|
259
|
+
if wrapper == "bare":
|
|
260
|
+
return plain_form(tex)
|
|
261
|
+
if wrapper == "dollar":
|
|
262
|
+
return _inline("$", "$", plain_form(tex))
|
|
263
|
+
if wrapper == "paren":
|
|
264
|
+
return _inline("\\(", "\\)", plain_form(tex))
|
|
265
|
+
if wrapper == "ddollar":
|
|
266
|
+
return _display("$$", "$$", plain_form(tex))
|
|
267
|
+
if wrapper == "bracket":
|
|
268
|
+
return _display("\\[", "\\]", plain_form(tex))
|
|
269
|
+
if wrapper in ("equation", "equation*"):
|
|
270
|
+
return _env(wrapper, plain_form(tex))
|
|
271
|
+
|
|
272
|
+
kind, content = classify(tex)
|
|
273
|
+
if wrapper in ("align", "align*"):
|
|
274
|
+
# any multi-line body slots straight into align (lines without & are still valid)
|
|
275
|
+
return _env(wrapper, content)
|
|
276
|
+
if wrapper in ("gather", "gather*"):
|
|
277
|
+
body = _env("aligned", content) if kind == "align" else content
|
|
278
|
+
return _env(wrapper, body)
|
|
279
|
+
# multline / multline*
|
|
280
|
+
body = _env("aligned", content) if kind == "align" else content
|
|
281
|
+
return _env(wrapper, body)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def numbering_conflict(tex: str, wrapper: str, display: bool = True) -> bool:
|
|
285
|
+
"""True if `wrap(tex, wrapper, display)` puts ``\\tag`` / ``\\label`` commands somewhere LaTeX
|
|
286
|
+
rejects them: a ``\\tag`` in inline maths, or an environment's per-line tags / several labels
|
|
287
|
+
inside aligned / gathered, in a single-equation wrapper, or several tags in multline."""
|
|
288
|
+
labels = _LEADING_LABELS.match(tex)
|
|
289
|
+
rest = tex[labels.end():] if labels else tex
|
|
290
|
+
envs = _env_sequence(rest)
|
|
291
|
+
if envs and (labels or len(envs) > 1): # subequations (see wrap)
|
|
292
|
+
if wrapper == "auto":
|
|
293
|
+
return False # kept verbatim, in subequations
|
|
294
|
+
if len(envs) > 1:
|
|
295
|
+
return any(numbering_conflict(env, wrapper, display) for env in envs)
|
|
296
|
+
tex = rest
|
|
297
|
+
if wrapper == "auto":
|
|
298
|
+
if has_outer_env(tex):
|
|
299
|
+
return False # kept verbatim
|
|
300
|
+
wrapper = "bracket" if display else "dollar"
|
|
301
|
+
kind, content = classify(tex)
|
|
302
|
+
tags = bool(re.search(r"\\tag(?![a-zA-Z])", content))
|
|
303
|
+
if wrapper in INLINE_WRAPPERS and tags:
|
|
304
|
+
return True # \tag is an error in $...$ / \(...\), whatever the source environment
|
|
305
|
+
target = wrapper.rstrip("*")
|
|
306
|
+
if (kind == "plain" or target == "align" or (target == "gather" and kind != "align")
|
|
307
|
+
or (target == "multline" and kind == "multline")):
|
|
308
|
+
return False
|
|
309
|
+
return tags or len(re.findall(r"\\label(?![a-zA-Z])", content)) > 1
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def wrapper_is_inline(wrapper: str, display: bool) -> bool:
|
|
313
|
+
if wrapper == "auto":
|
|
314
|
+
return not display
|
|
315
|
+
return wrapper in INLINE_WRAPPERS
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def output_is_display(tex: str, wrapper: str, display: bool) -> bool:
|
|
319
|
+
"""Whether `wrap(tex, wrapper, display)` is display maths: Auto keeps an environment of the
|
|
320
|
+
input (display, except ``math``) whatever `display` asks for."""
|
|
321
|
+
if wrapper == "auto":
|
|
322
|
+
labels = _LEADING_LABELS.match(tex)
|
|
323
|
+
envs = _env_sequence(tex[labels.end():] if labels else tex)
|
|
324
|
+
if envs and (labels or len(envs) > 1):
|
|
325
|
+
return True # subequations (see wrap)
|
|
326
|
+
env = split_env(tex, _OUTER)[0]
|
|
327
|
+
if env is not None:
|
|
328
|
+
return env != "math"
|
|
329
|
+
return not wrapper_is_inline(wrapper, display)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def join_outputs(parts: List[str]) -> str:
|
|
333
|
+
return "\n\n".join(parts)
|