entrylib-pages 0.1.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.
- entrylib_pages/__init__.py +65 -0
- entrylib_pages/mathml.py +463 -0
- entrylib_pages/page.py +1696 -0
- entrylib_pages/page_css.py +131 -0
- entrylib_pages/paper.py +690 -0
- entrylib_pages/paper_page.py +490 -0
- entrylib_pages/refs.py +73 -0
- entrylib_pages/score_html.py +307 -0
- entrylib_pages/scoring.py +25 -0
- entrylib_pages/static/page.js +648 -0
- entrylib_pages/static/site.css +990 -0
- entrylib_pages/text.py +46 -0
- entrylib_pages-0.1.0.dist-info/METADATA +89 -0
- entrylib_pages-0.1.0.dist-info/RECORD +17 -0
- entrylib_pages-0.1.0.dist-info/WHEEL +5 -0
- entrylib_pages-0.1.0.dist-info/licenses/LICENSE +201 -0
- entrylib_pages-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""EntryLib's pages for a claimset: the paper view and the record, as entrylib.org shows them.
|
|
2
|
+
|
|
3
|
+
The claimset format (the `claimset` package) defines what a paper says; this package is how EntryLib shows it. The
|
|
4
|
+
portal draws its pages with it, and `claimset preview` draws the same page on the author's machine before
|
|
5
|
+
submitting, so that what the author sees is what will be published.
|
|
6
|
+
|
|
7
|
+
preview_html(doc, scores=None, view="paper", …) -> a self-contained HTML page of the claimset as it will look
|
|
8
|
+
stylesheet() -> the page view's stylesheet (claimset.css)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from importlib import resources
|
|
13
|
+
|
|
14
|
+
from . import page, paper_page
|
|
15
|
+
|
|
16
|
+
__version__ = "0.1.0"
|
|
17
|
+
|
|
18
|
+
#: EntryLib's address: figures already published there (a new version keeps them) are shown from it.
|
|
19
|
+
SITE = "https://entrylib.org"
|
|
20
|
+
IMAGE = re.compile(r"\.(png|jpe?g|gif|webp|svg)$", re.I)
|
|
21
|
+
|
|
22
|
+
#: A page on its own: no site header above it, so nothing sticks below one.
|
|
23
|
+
ALONE = ":root { --head: 0px; }"
|
|
24
|
+
|
|
25
|
+
BAR = ('<p class="preview-bar-text"><strong>Preview, not submitted.</strong> <span class="preview-more">This is how '
|
|
26
|
+
'EntryLib will show this paper once published. Nothing has been sent anywhere.</span></p>')
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def static(name):
|
|
30
|
+
"""The text of one of the site's assets this package carries: site.css, page.js."""
|
|
31
|
+
return (resources.files(__package__) / "static" / name).read_text(encoding="utf-8")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def stylesheet():
|
|
35
|
+
return page.stylesheet()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def file_url(a):
|
|
39
|
+
"""Where a preview shows a figure from: a file of the package by its relative path (beside the page), or one
|
|
40
|
+
already published on EntryLib from there."""
|
|
41
|
+
uri = a.get("uri")
|
|
42
|
+
if not isinstance(uri, str) or not IMAGE.search(uri.split("?")[0]):
|
|
43
|
+
return None
|
|
44
|
+
if uri.startswith(SITE + "/p/"):
|
|
45
|
+
return uri
|
|
46
|
+
if "://" in uri or uri.startswith(("/", "\\")) or ".." in uri.split("/"):
|
|
47
|
+
return None
|
|
48
|
+
return uri
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def preview_html(doc, scores=None, view="paper", note="", paper_href="?view=paper", record_href="?view=record"):
|
|
52
|
+
"""The claimset `doc` as EntryLib will show it, as one HTML document: its paper view (`view` "paper") or its record
|
|
53
|
+
("record"), with the site's stylesheets and script inlined; `paper_href` and `record_href` are the two views' addresses
|
|
54
|
+
(two files, when the page is opened from disk). Figures the package holds are shown by their relative
|
|
55
|
+
paths, so the page is written in the folder that holds the claimset and its files. `scores`: the rubric's, if
|
|
56
|
+
the caller has them (`claimset score`); without them the panel shows "–". `note`: HTML under the bar."""
|
|
57
|
+
main = paper_page.preview_main(doc, base_url=SITE, bar=BAR, statement=note, scores=scores, view=view,
|
|
58
|
+
paper_href=paper_href, record_href=record_href, file_url=file_url)
|
|
59
|
+
title = page.esc((doc.get("paper") or {}).get("title") or "Preview")
|
|
60
|
+
return ("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">"
|
|
61
|
+
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
|
|
62
|
+
f"<meta name=\"robots\" content=\"noindex\"><title>Preview: {title}</title>"
|
|
63
|
+
f"<style>{static('site.css')}\n{stylesheet()}\n{ALONE}</style></head>"
|
|
64
|
+
f"<body id=\"top\"><main id=\"content\"><div class=\"wrap\">{main}</div></main>"
|
|
65
|
+
f"<script>{static('page.js')}</script></body></html>\n")
|
entrylib_pages/mathml.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
"""Inline LaTeX, as claimsets write it in text ($...$), as MathML, which browsers show without a script.
|
|
2
|
+
|
|
3
|
+
to_mathml(tex, display=False) -> '<math>...</math>', or None if the expression cannot be read
|
|
4
|
+
|
|
5
|
+
The subset is what papers write in statements and definitions: letters, numbers and operators; sub- and
|
|
6
|
+
superscripts; \\frac, \\sqrt, \\binom; accents (\\hat, \\bar, \\tilde, \\dot, \\vec, \\overline, \\underline);
|
|
7
|
+
Greek letters; relations, arrows and big operators with limits; named functions (\\log, \\max, \\operatorname);
|
|
8
|
+
font commands (\\mathbf, \\mathbb, \\mathcal, \\mathrm, \\text, \\boldsymbol); \\left ... \\right; spaces; and the
|
|
9
|
+
matrix environments (matrix, pmatrix, bmatrix, vmatrix, cases, aligned, array). Every expression keeps its LaTeX in
|
|
10
|
+
an annotation, for copying and for models. Text is escaped: nothing from the expression becomes markup.
|
|
11
|
+
|
|
12
|
+
Standard library only (claimset uses no dependencies).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import html
|
|
16
|
+
import re
|
|
17
|
+
|
|
18
|
+
GREEK = {
|
|
19
|
+
"alpha": "α", "beta": "β", "gamma": "γ", "delta": "δ", "epsilon": "ϵ", "varepsilon": "ε", "zeta": "ζ",
|
|
20
|
+
"eta": "η", "theta": "θ", "vartheta": "ϑ", "iota": "ι", "kappa": "κ", "lambda": "λ", "mu": "μ", "nu": "ν",
|
|
21
|
+
"xi": "ξ", "pi": "π", "varpi": "ϖ", "rho": "ρ", "varrho": "ϱ", "sigma": "σ", "varsigma": "ς", "tau": "τ",
|
|
22
|
+
"upsilon": "υ", "phi": "ϕ", "varphi": "φ", "chi": "χ", "psi": "ψ", "omega": "ω",
|
|
23
|
+
"Gamma": "Γ", "Delta": "Δ", "Theta": "Θ", "Lambda": "Λ", "Xi": "Ξ", "Pi": "Π", "Sigma": "Σ",
|
|
24
|
+
"Upsilon": "Υ", "Phi": "Φ", "Psi": "Ψ", "Omega": "Ω",
|
|
25
|
+
}
|
|
26
|
+
#: Operators, relations, arrows and other symbols: shown as <mo>.
|
|
27
|
+
OPERATORS = {
|
|
28
|
+
"times": "×", "cdot": "⋅", "div": "÷", "pm": "±", "mp": "∓", "ast": "∗", "star": "⋆", "circ": "∘",
|
|
29
|
+
"bullet": "∙", "oplus": "⊕", "otimes": "⊗", "odot": "⊙", "setminus": "∖", "wedge": "∧", "land": "∧",
|
|
30
|
+
"vee": "∨", "lor": "∨", "cap": "∩", "cup": "∪",
|
|
31
|
+
"leq": "≤", "le": "≤", "geq": "≥", "ge": "≥", "neq": "≠", "ne": "≠", "ll": "≪", "gg": "≫", "approx": "≈",
|
|
32
|
+
"sim": "∼", "simeq": "≃", "cong": "≅", "equiv": "≡", "propto": "∝", "in": "∈", "notin": "∉", "ni": "∋",
|
|
33
|
+
"subset": "⊂", "subseteq": "⊆", "supset": "⊃", "supseteq": "⊇", "perp": "⊥", "parallel": "∥", "mid": "∣",
|
|
34
|
+
"nmid": "∤", "models": "⊨", "vdash": "⊢", "coloneqq": "≔", "triangleq": "≜", "doteq": "≐", "prec": "≺",
|
|
35
|
+
"succ": "≻", "preceq": "⪯", "succeq": "⪰",
|
|
36
|
+
"to": "→", "rightarrow": "→", "leftarrow": "←", "gets": "←", "leftrightarrow": "↔", "Rightarrow": "⇒",
|
|
37
|
+
"Leftarrow": "⇐", "Leftrightarrow": "⇔", "implies": "⟹", "iff": "⟺", "mapsto": "↦", "uparrow": "↑",
|
|
38
|
+
"downarrow": "↓", "longrightarrow": "⟶", "xrightarrow": "→",
|
|
39
|
+
"forall": "∀", "exists": "∃", "nexists": "∄", "neg": "¬", "lnot": "¬", "partial": "∂", "nabla": "∇",
|
|
40
|
+
"infty": "∞", "emptyset": "∅", "varnothing": "∅", "ldots": "…", "dots": "…", "cdots": "⋯", "vdots": "⋮",
|
|
41
|
+
"ddots": "⋱", "prime": "′", "top": "⊤", "bot": "⊥", "angle": "∠", "triangle": "△", "Box": "□", "dagger": "†",
|
|
42
|
+
"ell": "ℓ", "hbar": "ℏ", "Re": "ℜ", "Im": "ℑ", "aleph": "ℵ", "wp": "℘",
|
|
43
|
+
"lvert": "|", "rvert": "|", "vert": "|", "lVert": "‖", "rVert": "‖", "Vert": "‖", "|": "‖",
|
|
44
|
+
"langle": "⟨", "rangle": "⟩", "lfloor": "⌊", "rfloor": "⌋", "lceil": "⌈", "rceil": "⌉",
|
|
45
|
+
"{": "{", "}": "}", "lbrace": "{", "rbrace": "}", "lbrack": "[", "rbrack": "]",
|
|
46
|
+
"%": "%", "$": "$", "_": "_", "&": "&", "#": "#",
|
|
47
|
+
}
|
|
48
|
+
#: Identifiers that are symbols rather than letters: shown as <mi>.
|
|
49
|
+
LETTERLIKE = {"ell", "hbar", "Re", "Im", "aleph", "wp", "infty", "emptyset", "varnothing", "partial", "nabla", "top",
|
|
50
|
+
"bot"}
|
|
51
|
+
#: Big operators: their sub- and superscripts are limits.
|
|
52
|
+
BIG = {"sum": "∑", "prod": "∏", "coprod": "∐", "bigcup": "⋃", "bigcap": "⋂", "bigoplus": "⨁", "bigotimes": "⨂",
|
|
53
|
+
"int": "∫", "iint": "∬", "iiint": "∭", "oint": "∮"}
|
|
54
|
+
INTEGRALS = {"int", "iint", "iiint", "oint"}
|
|
55
|
+
#: Named functions, set upright; those in LIMITS take limits under them.
|
|
56
|
+
FUNCTIONS = {"log", "ln", "lg", "exp", "sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan",
|
|
57
|
+
"sinh", "cosh", "tanh", "max", "min", "sup", "inf", "lim", "liminf", "limsup", "arg", "argmax",
|
|
58
|
+
"argmin", "det", "dim", "ker", "deg", "gcd", "Pr", "mod", "var", "Var", "cov", "Cov", "corr", "tr", "diag",
|
|
59
|
+
"rank", "sgn", "sign", "E", "plim"}
|
|
60
|
+
LIMITS = {"max", "min", "sup", "inf", "lim", "liminf", "limsup", "argmax", "argmin", "plim"}
|
|
61
|
+
ACCENTS = {"hat": "^", "widehat": "^", "check": "ˇ", "bar": "¯", "overline": "‾", "tilde": "~", "widetilde": "~",
|
|
62
|
+
"dot": "˙", "ddot": "¨", "vec": "→", "overrightarrow": "→", "acute": "´", "grave": "`", "breve": "˘"}
|
|
63
|
+
UNDER = {"underline": "_", "underbrace": "⏟"}
|
|
64
|
+
STRETCHY_ACCENTS = {"widehat", "widetilde", "overline", "overrightarrow", "underline", "underbrace"}
|
|
65
|
+
SPACES = {",": "0.1667em", ":": "0.2222em", ">": "0.2222em", ";": "0.2778em", " ": "0.25em", "quad": "1em",
|
|
66
|
+
"qquad": "2em", "enspace": "0.5em", "thinspace": "0.1667em", "medspace": "0.2222em",
|
|
67
|
+
"thickspace": "0.2778em", "!": "-0.1667em", "negthinspace": "-0.1667em"}
|
|
68
|
+
IGNORED = {"displaystyle", "textstyle", "scriptstyle", "limits", "nolimits", "nonumber", "notag", "label", "tag"}
|
|
69
|
+
#: A delimiter of a size the author chose (\big( … \Big]): the heights TeX gives them.
|
|
70
|
+
SIZED = {**dict.fromkeys(("big", "bigl", "bigr", "bigm"), "1.2em"),
|
|
71
|
+
**dict.fromkeys(("Big", "Bigl", "Bigr", "Bigm"), "1.8em"),
|
|
72
|
+
**dict.fromkeys(("bigg", "biggl", "biggr", "biggm"), "2.4em"),
|
|
73
|
+
**dict.fromkeys(("Bigg", "Biggl", "Biggr", "Biggm"), "3em")}
|
|
74
|
+
#: After a function's name, what its argument does not start with: before these there is no thin space.
|
|
75
|
+
NO_GAP = set("()[]{}^_,;.:|=+-&/<>'!")
|
|
76
|
+
FENCES = {"(": "(", ")": ")", "[": "[", "]": "]", "|": "|", ".": "", "\\{": "{", "\\}": "}", "\\lbrace": "{",
|
|
77
|
+
"\\rbrace": "}", "\\langle": "⟨", "\\rangle": "⟩", "\\lvert": "|", "\\rvert": "|", "\\|": "‖",
|
|
78
|
+
"\\lVert": "‖", "\\rVert": "‖", "\\vert": "|", "\\Vert": "‖", "\\lfloor": "⌊", "\\rfloor": "⌋",
|
|
79
|
+
"\\lceil": "⌈", "\\rceil": "⌉", "\\lbrack": "[", "\\rbrack": "]"}
|
|
80
|
+
MATRICES = {"matrix": ("", ""), "pmatrix": ("(", ")"), "bmatrix": ("[", "]"), "Bmatrix": ("{", "}"),
|
|
81
|
+
"vmatrix": ("|", "|"), "Vmatrix": ("‖", "‖"), "smallmatrix": ("", ""), "cases": ("{", ""),
|
|
82
|
+
"aligned": ("", ""), "align": ("", ""), "align*": ("", ""), "array": ("", ""), "gathered": ("", ""),
|
|
83
|
+
"split": ("", "")}
|
|
84
|
+
TOKEN = re.compile(r"\\(?:[A-Za-z]+\*?|.)|\d+(?:\.\d+)?|[A-Za-z]|\s+|.", re.S)
|
|
85
|
+
MAX_LENGTH = 2000
|
|
86
|
+
MAX_DEPTH = 60
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class TexError(ValueError):
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _alphabet(ch, style):
|
|
94
|
+
"""A letter or digit in a mathematical alphabet (bold, double-struck, script, fraktur, sans-serif, monospace):
|
|
95
|
+
MathML Core shows styles only through these Unicode characters."""
|
|
96
|
+
bases = {"bold": (0x1D400, 0x1D41A, 0x1D7CE), "bb": (0x1D538, 0x1D552, 0x1D7D8), "cal": (0x1D49C, 0x1D4B6, None),
|
|
97
|
+
"frak": (0x1D504, 0x1D51E, None), "sf": (0x1D5A0, 0x1D5BA, 0x1D7E2), "tt": (0x1D670, 0x1D68A, 0x1D7F6),
|
|
98
|
+
"bfit": (0x1D468, 0x1D482, 0x1D7CE)}
|
|
99
|
+
holes = {"bb": {"C": "ℂ", "H": "ℍ", "N": "ℕ", "P": "ℙ", "Q": "ℚ", "R": "ℝ", "Z": "ℤ"},
|
|
100
|
+
"cal": {"B": "ℬ", "E": "ℰ", "F": "ℱ", "H": "ℋ", "I": "ℐ", "L": "ℒ", "M": "ℳ", "R": "ℛ", "e": "ℯ",
|
|
101
|
+
"g": "ℊ", "o": "ℴ"},
|
|
102
|
+
"frak": {"C": "ℭ", "H": "ℌ", "I": "ℑ", "R": "ℜ", "Z": "ℨ"}}
|
|
103
|
+
if style not in bases:
|
|
104
|
+
return ch
|
|
105
|
+
if ch in holes.get(style, {}):
|
|
106
|
+
return holes[style][ch]
|
|
107
|
+
upper, lower, digit = bases[style]
|
|
108
|
+
if "A" <= ch <= "Z":
|
|
109
|
+
return chr(upper + ord(ch) - ord("A"))
|
|
110
|
+
if "a" <= ch <= "z":
|
|
111
|
+
return chr(lower + ord(ch) - ord("a"))
|
|
112
|
+
if "0" <= ch <= "9" and digit:
|
|
113
|
+
return chr(digit + ord(ch) - ord("0"))
|
|
114
|
+
if style in ("bold", "bfit") and "\u0391" <= ch <= "\u03a9":
|
|
115
|
+
return chr((0x1D6A8 if style == "bold" else 0x1D71C) + ord(ch) - 0x391)
|
|
116
|
+
if style in ("bold", "bfit") and "\u03b1" <= ch <= "\u03c9":
|
|
117
|
+
return chr((0x1D6C2 if style == "bold" else 0x1D736) + ord(ch) - 0x3B1)
|
|
118
|
+
return ch
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
FONT_COMMANDS = {"mathbf": "bold", "textbf": "bold", "bm": "bfit", "boldsymbol": "bfit", "mathbb": "bb",
|
|
122
|
+
"mathcal": "cal", "mathscr": "cal", "mathfrak": "frak", "mathsf": "sf", "mathtt": "tt"}
|
|
123
|
+
TEXT_COMMANDS = {"text", "textrm", "textit", "textnormal", "mbox", "mathrm", "operatorname", "mathit"}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def esc(s):
|
|
127
|
+
return html.escape(s, quote=False)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def mi(s, normal=False):
|
|
131
|
+
return f'<mi mathvariant="normal">{esc(s)}</mi>' if normal else f"<mi>{esc(s)}</mi>"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def mo(s, **attrs):
|
|
135
|
+
a = "".join(f' {k.replace("_", "")}="{v}"' for k, v in attrs.items())
|
|
136
|
+
return f"<mo{a}>{esc(s)}</mo>"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def row(items):
|
|
140
|
+
items = [x for x in items if x]
|
|
141
|
+
return items[0] if len(items) == 1 else f"<mrow>{''.join(items)}</mrow>"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class _Parser:
|
|
145
|
+
def __init__(self, tex):
|
|
146
|
+
self.toks = [t for t in TOKEN.findall(tex)]
|
|
147
|
+
self.pos = 0
|
|
148
|
+
self.depth = 0
|
|
149
|
+
|
|
150
|
+
def peek(self, skip_space=True):
|
|
151
|
+
while skip_space and self.pos < len(self.toks) and self.toks[self.pos].isspace():
|
|
152
|
+
self.pos += 1
|
|
153
|
+
return self.toks[self.pos] if self.pos < len(self.toks) else None
|
|
154
|
+
|
|
155
|
+
def take(self, skip_space=True):
|
|
156
|
+
t = self.peek(skip_space)
|
|
157
|
+
if t is None:
|
|
158
|
+
raise TexError("unexpected end")
|
|
159
|
+
self.pos += 1
|
|
160
|
+
return t
|
|
161
|
+
|
|
162
|
+
def raw_group(self):
|
|
163
|
+
"""The text of a {group} as written (for \\text and environment names)."""
|
|
164
|
+
if self.peek() != "{":
|
|
165
|
+
return self.take()
|
|
166
|
+
self.pos += 1
|
|
167
|
+
depth, out = 1, []
|
|
168
|
+
while True:
|
|
169
|
+
t = self.take(skip_space=False)
|
|
170
|
+
if t == "{":
|
|
171
|
+
depth += 1
|
|
172
|
+
elif t == "}":
|
|
173
|
+
depth -= 1
|
|
174
|
+
if depth == 0:
|
|
175
|
+
return "".join(out)
|
|
176
|
+
out.append(t)
|
|
177
|
+
|
|
178
|
+
def argument(self):
|
|
179
|
+
"""One argument of a command that takes two (\\frac12, \\binom n2): a {group}, or one token as TeX reads
|
|
180
|
+
it, which of a number written without braces is its first digit."""
|
|
181
|
+
t = self.peek()
|
|
182
|
+
if t is not None and t.isdigit() and len(t) > 1:
|
|
183
|
+
self.toks[self.pos] = t[1:]
|
|
184
|
+
return f"<mn>{esc(t[0])}</mn>"
|
|
185
|
+
return self.group()
|
|
186
|
+
|
|
187
|
+
def gap(self):
|
|
188
|
+
"""The thin space between a function's name and its argument (ln y, tanh x); none before a bracket, a
|
|
189
|
+
script or an operator."""
|
|
190
|
+
t = self.peek()
|
|
191
|
+
if t is None or t in NO_GAP:
|
|
192
|
+
return ""
|
|
193
|
+
if t[0] == "\\":
|
|
194
|
+
name = t[1:]
|
|
195
|
+
if name in SIZED or name in SPACES or name in ("left", "right", "middle", "\\") or t in FENCES \
|
|
196
|
+
or (name in OPERATORS and name not in LETTERLIKE):
|
|
197
|
+
return ""
|
|
198
|
+
return '<mspace width="0.1667em"></mspace>'
|
|
199
|
+
|
|
200
|
+
def group(self):
|
|
201
|
+
"""One argument: a {group} or a single atom."""
|
|
202
|
+
if self.peek() == "{":
|
|
203
|
+
self.pos += 1
|
|
204
|
+
inner = self.expression(stop={"}"})
|
|
205
|
+
self.take()
|
|
206
|
+
return row(inner)
|
|
207
|
+
return self.atom()
|
|
208
|
+
|
|
209
|
+
def optional(self):
|
|
210
|
+
if self.peek() != "[":
|
|
211
|
+
return None
|
|
212
|
+
self.pos += 1
|
|
213
|
+
inner = self.expression(stop={"]"})
|
|
214
|
+
self.take()
|
|
215
|
+
return row(inner)
|
|
216
|
+
|
|
217
|
+
def expression(self, stop=frozenset()):
|
|
218
|
+
self.depth += 1
|
|
219
|
+
if self.depth > MAX_DEPTH:
|
|
220
|
+
raise TexError("too deeply nested")
|
|
221
|
+
out = []
|
|
222
|
+
while True:
|
|
223
|
+
t = self.peek()
|
|
224
|
+
if t is None or t in stop:
|
|
225
|
+
break
|
|
226
|
+
if t in ("^", "_"):
|
|
227
|
+
base = out.pop() if out else "<mrow></mrow>"
|
|
228
|
+
out.append(self.scripts(base))
|
|
229
|
+
continue
|
|
230
|
+
if t == "'":
|
|
231
|
+
self.pos += 1
|
|
232
|
+
primes = "′"
|
|
233
|
+
while self.peek(False) == "'":
|
|
234
|
+
self.pos += 1
|
|
235
|
+
primes += "′"
|
|
236
|
+
base = out.pop() if out else "<mrow></mrow>"
|
|
237
|
+
out.append(f"<msup>{base}{mo(primes)}</msup>")
|
|
238
|
+
continue
|
|
239
|
+
atom = self.atom()
|
|
240
|
+
if atom is not None:
|
|
241
|
+
out.append(atom)
|
|
242
|
+
self.depth -= 1
|
|
243
|
+
return out
|
|
244
|
+
|
|
245
|
+
def scripts(self, base, big=False):
|
|
246
|
+
sub = sup = None
|
|
247
|
+
while self.peek() in ("^", "_"):
|
|
248
|
+
t = self.take()
|
|
249
|
+
arg = self.group()
|
|
250
|
+
if t == "_":
|
|
251
|
+
sub = arg
|
|
252
|
+
else:
|
|
253
|
+
sup = arg
|
|
254
|
+
if big:
|
|
255
|
+
tag = "munderover" if sub and sup else "munder" if sub else "mover"
|
|
256
|
+
else:
|
|
257
|
+
tag = "msubsup" if sub and sup else "msub" if sub else "msup"
|
|
258
|
+
parts = [base] + [x for x in (sub, sup) if x]
|
|
259
|
+
return f"<{tag}>{''.join(parts)}</{tag}>"
|
|
260
|
+
|
|
261
|
+
def atom(self):
|
|
262
|
+
t = self.take()
|
|
263
|
+
if t == "{":
|
|
264
|
+
inner = self.expression(stop={"}"})
|
|
265
|
+
self.take()
|
|
266
|
+
return row(inner)
|
|
267
|
+
if t == "}":
|
|
268
|
+
raise TexError("unbalanced }")
|
|
269
|
+
if t == "~":
|
|
270
|
+
return '<mspace width="0.25em"></mspace>'
|
|
271
|
+
if t[0] == "\\":
|
|
272
|
+
return self.command(t[1:])
|
|
273
|
+
if t[0].isdigit():
|
|
274
|
+
return f"<mn>{esc(t)}</mn>"
|
|
275
|
+
if t.isalpha():
|
|
276
|
+
return mi(t)
|
|
277
|
+
if t == "-":
|
|
278
|
+
return mo("−")
|
|
279
|
+
if t in "()[]":
|
|
280
|
+
return mo(t, stretchy="false")
|
|
281
|
+
if t == "|":
|
|
282
|
+
# a bar is a fence (|x|, E|x|), not an operator between two terms: no space on its sides
|
|
283
|
+
return mo("|", stretchy="false", lspace="0", rspace="0")
|
|
284
|
+
if t == "&":
|
|
285
|
+
raise TexError("& outside an environment")
|
|
286
|
+
return mo(t)
|
|
287
|
+
|
|
288
|
+
def command(self, name):
|
|
289
|
+
if name in IGNORED:
|
|
290
|
+
if name in ("label", "tag"):
|
|
291
|
+
self.raw_group()
|
|
292
|
+
return None
|
|
293
|
+
if name in SIZED:
|
|
294
|
+
ch = FENCES.get(self.peek() or "")
|
|
295
|
+
if not ch:
|
|
296
|
+
return None # no delimiter follows: the size says nothing
|
|
297
|
+
self.pos += 1
|
|
298
|
+
return mo(ch, fence="true", stretchy="true", symmetric="true", minsize=SIZED[name], maxsize=SIZED[name])
|
|
299
|
+
if name in SPACES:
|
|
300
|
+
return f'<mspace width="{SPACES[name]}"></mspace>'
|
|
301
|
+
if name in GREEK:
|
|
302
|
+
ch = GREEK[name]
|
|
303
|
+
return mi(ch, normal=ch.isupper())
|
|
304
|
+
if name in BIG:
|
|
305
|
+
op = mo(BIG[name], largeop="true", movablelimits="true") if name not in INTEGRALS \
|
|
306
|
+
else mo(BIG[name], largeop="true")
|
|
307
|
+
if self.peek() in ("^", "_"):
|
|
308
|
+
return self.scripts(op, big=name not in INTEGRALS)
|
|
309
|
+
return op
|
|
310
|
+
if name in FUNCTIONS:
|
|
311
|
+
fn = mi(name) if len(name) > 1 else mi(name, normal=True)
|
|
312
|
+
if self.peek() in ("^", "_"):
|
|
313
|
+
fn = self.scripts(fn, big=name in LIMITS)
|
|
314
|
+
return row([fn, mo("\u2061"), self.gap()])
|
|
315
|
+
if name in LETTERLIKE:
|
|
316
|
+
return mi(OPERATORS[name], normal=True)
|
|
317
|
+
if name in OPERATORS:
|
|
318
|
+
ch = OPERATORS[name]
|
|
319
|
+
if ch in "{}[]()|‖⟨⟩⌊⌋⌈⌉":
|
|
320
|
+
return mo(ch, stretchy="false")
|
|
321
|
+
return mo(ch)
|
|
322
|
+
if name in ("frac", "dfrac", "tfrac", "cfrac"):
|
|
323
|
+
return f"<mfrac>{self.argument()}{self.argument()}</mfrac>"
|
|
324
|
+
if name in ("binom", "dbinom", "tbinom"):
|
|
325
|
+
a, b = self.argument(), self.argument()
|
|
326
|
+
return row([mo("("), f'<mfrac linethickness="0">{a}{b}</mfrac>', mo(")")])
|
|
327
|
+
if name == "sqrt":
|
|
328
|
+
index = self.optional()
|
|
329
|
+
body = self.group()
|
|
330
|
+
return f"<mroot>{body}{index}</mroot>" if index else f"<msqrt>{body}</msqrt>"
|
|
331
|
+
if name in ACCENTS:
|
|
332
|
+
body = self.group()
|
|
333
|
+
stretchy = "true" if name in STRETCHY_ACCENTS else "false"
|
|
334
|
+
return f'<mover accent="true">{body}{mo(ACCENTS[name], stretchy=stretchy)}</mover>'
|
|
335
|
+
if name in UNDER:
|
|
336
|
+
body = self.group()
|
|
337
|
+
return f'<munder accentunder="true">{body}{mo(UNDER[name], stretchy="true")}</munder>'
|
|
338
|
+
if name in ("overset", "stackrel"):
|
|
339
|
+
over, body = self.group(), self.group()
|
|
340
|
+
return f"<mover>{body}{over}</mover>"
|
|
341
|
+
if name == "underset":
|
|
342
|
+
under, body = self.group(), self.group()
|
|
343
|
+
return f"<munder>{body}{under}</munder>"
|
|
344
|
+
if name in FONT_COMMANDS:
|
|
345
|
+
return self.styled(FONT_COMMANDS[name])
|
|
346
|
+
if name in TEXT_COMMANDS:
|
|
347
|
+
text = self.raw_group()
|
|
348
|
+
if name == "operatorname":
|
|
349
|
+
fn = mi(text, normal=True)
|
|
350
|
+
if self.peek() in ("^", "_"): # sech^2(x): the power belongs to the name
|
|
351
|
+
fn = self.scripts(fn)
|
|
352
|
+
return row([fn, mo("\u2061"), self.gap()])
|
|
353
|
+
if name == "mathrm":
|
|
354
|
+
return mi(text, normal=True)
|
|
355
|
+
if name == "mathit":
|
|
356
|
+
return mi(text)
|
|
357
|
+
# A browser drops the spaces at the ends of words in a formula: "$T \text{ is } U$" would read "TisU".
|
|
358
|
+
lead, trail = text[:len(text) - len(text.lstrip(" "))], text[len(text.rstrip(" ")):]
|
|
359
|
+
if text.strip(" "):
|
|
360
|
+
text = "\u00a0" * bool(lead) + text.strip(" ") + "\u00a0" * bool(trail)
|
|
361
|
+
return f"<mtext>{esc(text)}</mtext>"
|
|
362
|
+
if name == "left":
|
|
363
|
+
return self.fenced()
|
|
364
|
+
if name in ("right", "middle"):
|
|
365
|
+
raise TexError(f"\\{name} without \\left")
|
|
366
|
+
if name == "begin":
|
|
367
|
+
return self.environment(self.raw_group())
|
|
368
|
+
if name == "\\":
|
|
369
|
+
raise TexError("\\\\ outside an environment")
|
|
370
|
+
if name in ("not",):
|
|
371
|
+
nxt = self.atom()
|
|
372
|
+
return row([nxt, mo("\u0338")])
|
|
373
|
+
if name in ("pmod",):
|
|
374
|
+
return row([mo("("), mi("mod"), self.group(), mo(")")])
|
|
375
|
+
raise TexError(f"unknown command \\{name}")
|
|
376
|
+
|
|
377
|
+
def styled(self, style):
|
|
378
|
+
"""A font command over a group: its letters and digits in that mathematical alphabet."""
|
|
379
|
+
start = self.pos
|
|
380
|
+
body = self.group()
|
|
381
|
+
del start
|
|
382
|
+
|
|
383
|
+
def restyle(m):
|
|
384
|
+
tag, attrs, text = m.group(1), m.group(2), m.group(3)
|
|
385
|
+
text = "".join(_alphabet(c, style) for c in html.unescape(text))
|
|
386
|
+
attrs = attrs.replace(' mathvariant="normal"', "")
|
|
387
|
+
return f"<{tag}{attrs}>{esc(text)}</{tag}>"
|
|
388
|
+
return re.sub(r"<(mi|mn)([^>]*)>([^<]*)</\1>", restyle, body)
|
|
389
|
+
|
|
390
|
+
def fence_token(self):
|
|
391
|
+
t = self.take()
|
|
392
|
+
if t in FENCES:
|
|
393
|
+
return FENCES[t]
|
|
394
|
+
raise TexError(f"not a delimiter: {t}")
|
|
395
|
+
|
|
396
|
+
def fenced(self):
|
|
397
|
+
left = self.fence_token()
|
|
398
|
+
inner = []
|
|
399
|
+
while True:
|
|
400
|
+
inner += self.expression(stop={"\\right", "\\middle"})
|
|
401
|
+
t = self.take()
|
|
402
|
+
if t == "\\middle":
|
|
403
|
+
inner.append(mo(self.fence_token(), stretchy="true"))
|
|
404
|
+
continue
|
|
405
|
+
break
|
|
406
|
+
right = self.fence_token()
|
|
407
|
+
items = ([mo(left, fence="true", stretchy="true")] if left else []) + [row(inner)] + \
|
|
408
|
+
([mo(right, fence="true", stretchy="true")] if right else [])
|
|
409
|
+
return f"<mrow>{''.join(x for x in items if x)}</mrow>"
|
|
410
|
+
|
|
411
|
+
def environment(self, name):
|
|
412
|
+
if name not in MATRICES:
|
|
413
|
+
raise TexError(f"unknown environment {name}")
|
|
414
|
+
if name == "array" and self.peek() == "{":
|
|
415
|
+
self.raw_group() # column spec: alignment is not kept
|
|
416
|
+
rows, cells, current = [], [], []
|
|
417
|
+
while True:
|
|
418
|
+
current += self.expression(stop={"&", "\\\\", "\\end"})
|
|
419
|
+
t = self.take()
|
|
420
|
+
if t == "&":
|
|
421
|
+
cells.append(row(current))
|
|
422
|
+
current = []
|
|
423
|
+
elif t == "\\\\":
|
|
424
|
+
cells.append(row(current))
|
|
425
|
+
rows.append(cells)
|
|
426
|
+
cells, current = [], []
|
|
427
|
+
else:
|
|
428
|
+
end = self.raw_group()
|
|
429
|
+
if end != name:
|
|
430
|
+
raise TexError(f"\\begin{{{name}}} ended by \\end{{{end}}}")
|
|
431
|
+
if current or cells:
|
|
432
|
+
cells.append(row(current))
|
|
433
|
+
rows.append(cells)
|
|
434
|
+
break
|
|
435
|
+
align = (' columnalign="left"' if name == "cases" else
|
|
436
|
+
' columnalign="right left" columnspacing="0"' if name in ("aligned", "align", "align*", "split")
|
|
437
|
+
else "")
|
|
438
|
+
table = "<mtable" + align + ">" + "".join(
|
|
439
|
+
"<mtr>" + "".join(f"<mtd>{c or ''}</mtd>" for c in r) + "</mtr>" for r in rows) + "</mtable>"
|
|
440
|
+
left, right = MATRICES[name]
|
|
441
|
+
items = ([mo(left, fence="true", stretchy="true")] if left else []) + [table] + \
|
|
442
|
+
([mo(right, fence="true", stretchy="true")] if right else [])
|
|
443
|
+
return f"<mrow>{''.join(items)}</mrow>"
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def to_mathml(tex, display=False):
|
|
447
|
+
"""The expression as a <math> element, or None if it cannot be read (unknown command, unbalanced braces): the
|
|
448
|
+
caller then shows it as written."""
|
|
449
|
+
if not isinstance(tex, str) or not tex.strip() or len(tex) > MAX_LENGTH:
|
|
450
|
+
return None
|
|
451
|
+
p = _Parser(tex)
|
|
452
|
+
try:
|
|
453
|
+
body = p.expression()
|
|
454
|
+
if p.peek() is not None:
|
|
455
|
+
raise TexError(f"unexpected {p.peek()}")
|
|
456
|
+
except (TexError, RecursionError, IndexError):
|
|
457
|
+
return None
|
|
458
|
+
block = ' display="block"' if display else ""
|
|
459
|
+
math = (f"<math{block}><semantics>{row(body) or '<mrow></mrow>'}"
|
|
460
|
+
f'<annotation encoding="application/x-tex">{esc(tex)}</annotation></semantics></math>')
|
|
461
|
+
# A formula on its own line stands in a box of the line's width (`cs-eq`): one wider than the line is made a
|
|
462
|
+
# little smaller to fit, or scrolls inside the box, and never runs over what stands beside the text.
|
|
463
|
+
return f'<span class="cs-eq">{math}</span>' if display else math
|