rapier-math 2.4.1 → 2.7.0
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.
- package/CHANGELOG.md +10 -0
- package/LICENSE +10 -3
- package/README.md +4 -5
- package/dist/index.mjs +1 -1
- package/dist/markdown-rules.mjs +47 -0
- package/dist/rapier-math.js +875 -321
- package/docs/api.md +6 -2
- package/docs/font-source.md +54 -35
- package/docs/math-components.json +51 -7
- package/docs/math-resources.json +59 -64
- package/package.json +3 -3
- package/src/math/FONT-LICENSE.txt +9 -2
- package/src/math/build-font.py +88 -80
- package/src/math/classic.js +1 -1
- package/src/math/font.js +24 -488
- package/src/math/layout.js +356 -182
- package/src/math/mathml.js +79 -14
- package/src/math/package-layout.mjs +1 -0
- package/src/math/package-readme.mjs +3 -4
- package/src/math/parser.js +398 -82
- package/src/tools/build-math.mjs +22 -7
- package/tests/adoption.mjs +0 -252
- package/tests/check.mjs +0 -134
- package/tests/semantics.mjs +0 -340
- package/tests/typeset.mjs +0 -172
- package/tests/verify.mjs +0 -49
package/src/math/parser.js
CHANGED
|
@@ -12,6 +12,7 @@ class MathTexError extends Error {
|
|
|
12
12
|
|
|
13
13
|
function mathTexTokens(source, offset = 0) {
|
|
14
14
|
const tokens = [];
|
|
15
|
+
let count = 0;
|
|
15
16
|
for (let i = 0; i < source.length;) {
|
|
16
17
|
const start = i, value = String.fromCodePoint(source.codePointAt(i));
|
|
17
18
|
i += value.length;
|
|
@@ -26,8 +27,27 @@ function mathTexTokens(source, offset = 0) {
|
|
|
26
27
|
let command = '';
|
|
27
28
|
if (/[A-Za-z@]/.test(source[i])) {
|
|
28
29
|
while (i < source.length && /[A-Za-z@]/.test(source[i])) command += source[i++];
|
|
29
|
-
|
|
30
|
-
|
|
30
|
+
if (command === 'verb') {
|
|
31
|
+
// Verbatim changes TeX's character categories before its body is read.
|
|
32
|
+
while (source[i] === ' ' || source[i] === '\t') i++;
|
|
33
|
+
const starred = source[i] === '*';
|
|
34
|
+
if (starred) i++;
|
|
35
|
+
while (source[i] === ' ' || source[i] === '\t') i++;
|
|
36
|
+
const delimiter = i < source.length ? String.fromCodePoint(source.codePointAt(i)) : '';
|
|
37
|
+
if (!delimiter || /[\r\n]/.test(delimiter))
|
|
38
|
+
throw new MathTexError('unclosed-verb', 'A verbatim span needs a delimiter on the same line.', offset + start, 'verb');
|
|
39
|
+
i += delimiter.length;
|
|
40
|
+
const end = source.indexOf(delimiter, i), newline = source.slice(i, end < 0 ? undefined : end).search(/[\r\n]/);
|
|
41
|
+
if (end < 0 || newline >= 0)
|
|
42
|
+
throw new MathTexError('unclosed-verb', 'A verbatim span must close on the same line.', offset + start, 'verb');
|
|
43
|
+
if (count + end - i + 1 > 100000)
|
|
44
|
+
throw new MathTexError('resource-limit', 'This formula has too many tokens to render safely.', offset + start, 'verb');
|
|
45
|
+
tokens.push({kind: 'verbatim', value: source.slice(i, end), starred, delimiter, offset: offset + start});
|
|
46
|
+
i = end + delimiter.length;
|
|
47
|
+
} else {
|
|
48
|
+
tokens.push({kind: 'command', value: command, offset: offset + start});
|
|
49
|
+
while (i < source.length && /\s/.test(source[i])) i++;
|
|
50
|
+
}
|
|
31
51
|
} else {
|
|
32
52
|
command = String.fromCodePoint(source.codePointAt(i));
|
|
33
53
|
i += command.length;
|
|
@@ -37,7 +57,8 @@ function mathTexTokens(source, offset = 0) {
|
|
|
37
57
|
while (i < source.length && /\s/.test(source[i])) i++;
|
|
38
58
|
tokens.push({kind: 'space', value: ' ', offset: offset + start});
|
|
39
59
|
} else tokens.push({kind: 'char', value, offset: offset + start});
|
|
40
|
-
|
|
60
|
+
count += tokens.at(-1).kind === 'verbatim' ? 1 + tokens.at(-1).value.length : 1;
|
|
61
|
+
if (count > 100000)
|
|
41
62
|
throw new MathTexError('resource-limit', 'This formula has too many tokens to render safely.', offset + start);
|
|
42
63
|
}
|
|
43
64
|
return tokens;
|
|
@@ -56,6 +77,21 @@ const MATH_TEX_TEXT_VARIANTS = Object.freeze({
|
|
|
56
77
|
textbf: 'bold', textit: 'italic', emph: 'italic', textsl: 'italic', textsf: 'sans-serif', texttt: 'monospace',
|
|
57
78
|
textsc: 'roman'
|
|
58
79
|
});
|
|
80
|
+
// LaTeX's text commands set series, shape and family independently: \textit inside \textbf is bold italic.
|
|
81
|
+
function mathTextVariant(outer, name) {
|
|
82
|
+
let family = /sans-serif/.test(outer) ? 'sans-serif' : outer === 'monospace' ? 'monospace' : 'roman', bold = /bold/.test(outer), italic = /italic/.test(outer);
|
|
83
|
+
if (name === 'textnormal') { family = 'roman'; bold = italic = false; }
|
|
84
|
+
else if (name === 'textbf') bold = true;
|
|
85
|
+
else if (name === 'textit' || name === 'textsl') italic = true;
|
|
86
|
+
else if (name === 'emph') italic = !italic;
|
|
87
|
+
else if (name === 'textup') italic = false;
|
|
88
|
+
else if (name === 'textrm') family = 'roman';
|
|
89
|
+
else if (name === 'textsf') family = 'sans-serif';
|
|
90
|
+
else if (name === 'texttt') family = 'monospace';
|
|
91
|
+
if (family === 'monospace') return 'monospace';
|
|
92
|
+
const style = (bold ? '-bold' : '') + (italic ? '-italic' : '');
|
|
93
|
+
return family === 'sans-serif' ? 'sans-serif' + style : style ? style.slice(1) : 'roman';
|
|
94
|
+
}
|
|
59
95
|
const MATH_TEX_TEXT_LETTERS = Object.freeze({ss: 'ß', ae: 'æ', AE: 'Æ', oe: 'œ', OE: 'Œ', o: 'ø', O: 'Ø', aa: 'å', AA: 'Å', l: 'ł', L: 'Ł', i: 'ı', j: 'ȷ'});
|
|
60
96
|
const MATH_TEX_DECLARATIONS = Object.freeze({
|
|
61
97
|
rm: {variant: 'roman'}, rmfamily: {variant: 'roman'}, normalfont: {variant: 'roman'},
|
|
@@ -78,10 +114,17 @@ const MATH_TEX_ACCENTS = Object.freeze({
|
|
|
78
114
|
overleftharpoon: ['↼', 'over', true], overrightharpoon: ['⇀', 'over', true], utilde: ['̃', 'under', true]
|
|
79
115
|
});
|
|
80
116
|
const MATH_TEX_LONG_ARROWS = {iff: 'Longleftrightarrow', implies: 'Longrightarrow', impliedby: 'Longleftarrow', And: 'And'};
|
|
117
|
+
// These unicode-math aliases do not expose a binary/relation mathchar to amsmath's raw-token lookahead.
|
|
118
|
+
const MATH_TEX_DOTS_LOW = new Set('circ bullet diamond lor land smallsetminus bigcirc dag ddag bigtriangledown le ge neq owns Join blacktriangleleft blacktriangleright therefore because coloneqq eqqcolon dblcolon gets to'.split(' '));
|
|
81
119
|
// mathtools: a colon or double colon joined to a relation, 1.2 mu apart.
|
|
82
120
|
const MATH_TEX_COLONS = {coloneq: '∶−', Coloneq: '∷−', Coloneqq: '∷=', Eqqcolon: '=∷', eqcolon: '−∶', Eqcolon: '−∷', colonapprox: '∶≈', Colonapprox: '∷≈', colonsim: '∶∼', Colonsim: '∷∼'};
|
|
83
121
|
// dvipsnames in CMYK percent (LaTeX graphics bundle), converted as xcolor does: each RGB channel is 1 − min(1, CMY + K).
|
|
84
|
-
|
|
122
|
+
// xcolor's base colors in RGB, for mixing.
|
|
123
|
+
const MATH_TEX_XCOLOR_BASE = Object.freeze(Object.fromEntries(Object.entries({red: [1, 0, 0], green: [0, 1, 0], blue: [0, 0, 1], cyan: [0, 1, 1], magenta: [1, 0, 1],
|
|
124
|
+
yellow: [1, 1, 0], black: [0, 0, 0], white: [1, 1, 1], gray: [.5, .5, .5], darkgray: [.25, .25, .25], lightgray: [.75, .75, .75], brown: [.75, .5, .25],
|
|
125
|
+
lime: [.75, 1, 0], olive: [.5, .5, 0], orange: [1, .5, 0], pink: [1, .75, .75], purple: [.75, 0, .25], teal: [0, .5, .5], violet: [.5, 0, .5]})
|
|
126
|
+
.map(([name, rgb]) => [name, '#' + rgb.map(c => Math.round(c * 255).toString(16).padStart(2, '0')).join('')])));
|
|
127
|
+
const MATH_TEX_DVIPSNAMES = Object.create(null), MATH_TEX_DVIPS_CMYK = Object.create(null);
|
|
85
128
|
for (const [, name, ...cmyk] of `GreenYellow 15 0 69 0 Yellow 0 0 100 0 Goldenrod 0 10 84 0 Dandelion 0 29 84 0 Apricot 0 32 52 0 Peach 0 50 70 0
|
|
86
129
|
Melon 0 46 50 0 YellowOrange 0 42 100 0 Orange 0 61 87 0 BurntOrange 0 51 100 0 Bittersweet 0 75 100 24 RedOrange 0 77 87 0 Mahogany 0 85 87 35
|
|
87
130
|
Maroon 0 87 68 32 BrickRed 0 89 94 28 Red 0 100 100 0 OrangeRed 0 100 50 0 RubineRed 0 100 13 0 WildStrawberry 0 96 39 0 Salmon 0 53 38 0
|
|
@@ -92,26 +135,45 @@ Blue 100 100 0 0 Cerulean 94 11 0 0 Cyan 100 0 0 0 ProcessBlue 96 0 0 0 SkyBlue
|
|
|
92
135
|
BlueGreen 85 0 33 0 Emerald 100 0 50 0 JungleGreen 99 0 52 0 SeaGreen 69 0 50 0 Green 100 0 100 0 ForestGreen 91 0 88 12 PineGreen 92 0 59 25
|
|
93
136
|
LimeGreen 50 0 100 0 YellowGreen 44 0 74 0 SpringGreen 26 0 76 0 OliveGreen 64 0 95 40 RawSienna 0 72 100 45 Sepia 0 83 100 70 Brown 0 81 100 60
|
|
94
137
|
Tan 14 42 56 0 Gray 0 0 0 50 Black 0 0 0 100 White 0 0 0 0`.matchAll(/(\w+) (\d+) (\d+) (\d+) (\d+)/g))
|
|
95
|
-
MATH_TEX_DVIPSNAMES[name] = '#' + cmyk.slice(0, 3).map(value => Math.round(255 * (1 - Math.min(1, (+value + +cmyk[3]) / 100))).toString(16).padStart(2, '0')).join('');
|
|
138
|
+
MATH_TEX_DVIPS_CMYK[name] = cmyk.map(value => value / 100), MATH_TEX_DVIPSNAMES[name] = '#' + cmyk.slice(0, 3).map(value => Math.round(255 * (1 - Math.min(1, (+value + +cmyk[3]) / 100))).toString(16).padStart(2, '0')).join('');
|
|
96
139
|
const MATH_TEX_SPACES = Object.freeze({
|
|
97
140
|
',': 3 / 18, ':': 4 / 18, ';': 5 / 18, '!': -3 / 18, ' ': 1 / 3,
|
|
98
141
|
quad: 1, qquad: 2, enspace: .5, enskip: .5, thinspace: 3 / 18, medspace: 4 / 18, thickspace: 5 / 18,
|
|
99
142
|
negthinspace: -3 / 18, negmedspace: -4 / 18, negthickspace: -5 / 18
|
|
100
143
|
});
|
|
101
144
|
const mathSITable = text => Object.freeze(Object.fromEntries(text.split(' ').map(entry => entry.split('='))));
|
|
102
|
-
const MATH_SI_UNITS = mathSITable('gram=g metre=m meter=m second=s ampere=A kelvin=K mole=mol candela=cd newton=N joule=J watt=W pascal=Pa hertz=Hz volt=V ohm=Ω coulomb=C farad=F henry=H tesla=T weber=Wb siemens=S celsius=°C litre=L liter=L electronvolt=eV degree=° percent=% minute=min hour=h day=d hectare=ha tonne=t becquerel=Bq gray=Gy sievert=Sv katal=kat lumen=lm lux=lx radian=rad steradian=sr arcminute=′ arcsecond=″ bar=bar angstrom=Å dalton=Da bel=B decibel=dB astronomicalunit=au atomicmassunit=u neper=Np');
|
|
145
|
+
const MATH_SI_UNITS = mathSITable('gram=g metre=m meter=m second=s ampere=A kelvin=K mole=mol candela=cd newton=N joule=J watt=W pascal=Pa hertz=Hz volt=V ohm=Ω coulomb=C farad=F henry=H tesla=T weber=Wb siemens=S celsius=°C degreeCelsius=°C litre=L liter=L electronvolt=eV degree=° percent=% minute=min hour=h day=d hectare=ha tonne=t becquerel=Bq gray=Gy sievert=Sv katal=kat lumen=lm lux=lx radian=rad steradian=sr arcminute=′ arcsecond=″ bar=bar angstrom=Å dalton=Da bel=B decibel=dB astronomicalunit=au atomicmassunit=u neper=Np');
|
|
146
|
+
// siunitx's abbreviated units (\km, \kHz, \uA...): prefix letters (u for micro) and a unit symbol.
|
|
147
|
+
const MATH_SI_ABBREVIATIONS = Object.freeze(Object.fromEntries(`f,p,n,u,m,,k:g p,n,u,m,c,d,,k:m a,f,p,n,u,m,:s f,p,n,u,m,,k:mol p,n,u,m,,k:A u,m,,h:L u,m,,h:l
|
|
148
|
+
,m,k,M,G,T:Hz m,,k,M:N ,k,M,G:Pa m,k,M:ohm p,n,u,m,,k:V u,m,,k,M,G:W u,m,,k:J ,m,k,M,G,T:eV k:Wh f,p,n,u,m,:F ,m:H n,u,m,:C ,m:T :K d:B`.split(/\s+/).flatMap(entry => {
|
|
149
|
+
const [prefixes, unit] = entry.split(':'), symbol = {ohm: 'Ω', l: 'L'}[unit] || unit;
|
|
150
|
+
return prefixes.split(',').map(prefix => [prefix + unit, (prefix === 'u' ? 'µ' : prefix) + symbol]);
|
|
151
|
+
}).filter(([name]) => name.length > 1 || /^[gmsAJLlVWNFHCTK]$/.test(name))));
|
|
103
152
|
const MATH_SI_PREFIXES = mathSITable('quecto=q ronto=r yocto=y zepto=z atto=a femto=f pico=p nano=n micro=µ milli=m centi=c deci=d deca=da deka=da hecto=h kilo=k mega=M giga=G tera=T peta=P exa=E zetta=Z yotta=Y ronna=R quetta=Q');
|
|
104
153
|
const MATH_TEX_PACKAGES = new Set(('ams amsmath amssymb amsfonts mathtools color newcommand unicode mhchem physics siunitx bbm bboldx dsfont cancel bbox boldsymbol').split(' '));
|
|
154
|
+
const MATH_TEX_PHYSICS = new Set('dv derivative pdv pderivative fdv functionalderivative dd differential qty quantity pqty bqty Bqty vqty abs absolutevalue norm bra ket braket innerproduct ip ketbra dyad outerproduct op expval expectationvalue ev mel matrixel matrixelement comm commutator acomm anticommutator pb poissonbracket vb va vu vectorbold vectorarrow vectorunit grad gradient divergence curl laplacian eval evaluated order Tr tr trace rank diag Res mqty pmqty bmqty Bmqty Pmqty vmqty smqty dmat diagonalmatrix admat antidiagonalmatrix imat identitymatrix zmat zeromatrix xmat xmatrix pmat paulimatrix qq qc qcc qif qthen qelse qotherwise qunless qgiven qusing qassume qsince qlet qfor qall qeven qodd qinteger qand qor qas qin'.split(' '));
|
|
105
155
|
const MATH_TEX_ENVIRONMENTS = new Set(('matrix pmatrix bmatrix Bmatrix vmatrix Vmatrix smallmatrix psmallmatrix bsmallmatrix Bsmallmatrix vsmallmatrix Vsmallmatrix array aligned alignedat align alignat flalign gathered lgathered rgathered gather split cases dcases rcases drcases subarray substack eqnarray multline multlined equation darray CD').split(' '));
|
|
156
|
+
const MATH_TABLE_DELIMITERS = Object.freeze({pmatrix: ['(', ')'], bmatrix: ['[', ']'], Bmatrix: ['{', '}'], vmatrix: ['|', '|'], Vmatrix: ['‖', '‖'], cases: ['{', ''], rcases: ['', '}']});
|
|
157
|
+
function mathTableDelimiters(environment) { return MATH_TABLE_DELIMITERS[environment.replace(/smallmatrix$/, 'matrix').replace(/^d(r?cases)$/, '$1')]; }
|
|
158
|
+
const MATH_ENCLOSE_NOTATIONS = new Set('box roundedbox circle left right top bottom horizontalstrike verticalstrike updiagonalstrike downdiagonalstrike updiagonalarrow longdiv actuarial madruwb radical phasorangle'.split(' '));
|
|
106
159
|
const MATH_TEX_LITERAL_CLASSES = Object.freeze({
|
|
107
160
|
'+': 'bin', '−': 'bin', '-': 'bin', '±': 'bin', '∓': 'bin', '×': 'bin', '÷': 'bin', '*': 'bin', '⋅': 'bin',
|
|
108
161
|
'=': 'rel', '<': 'rel', '>': 'rel', '≤': 'rel', '≥': 'rel', '≠': 'rel', ':': 'rel',
|
|
109
162
|
'(': 'open', '[': 'open', '{': 'open', '⟨': 'open', ')': 'close', ']': 'close', '}': 'close', '⟩': 'close', ',': 'punct', ';': 'punct',
|
|
163
|
+
'!': 'close',
|
|
110
164
|
'∑': 'op', '∏': 'op', '∫': 'op', '∮': 'op', '∬': 'op', '∭': 'op'
|
|
111
165
|
});
|
|
112
166
|
|
|
113
167
|
function mathTexTokenText(tokens) {
|
|
114
|
-
return tokens.map(token => token.kind === '
|
|
168
|
+
return tokens.map(token => token.kind === 'verbatim' ? '\\verb' + (token.starred ? '*' : '') + token.delimiter + token.value + token.delimiter :
|
|
169
|
+
token.kind === 'command' ? '\\' + token.value + (/^[A-Za-z@]+$/.test(token.value) ? ' ' : '') : token.value).join('');
|
|
170
|
+
}
|
|
171
|
+
function mathChoice(node, context) { return node.choices[context.level ? Math.min(context.level + 1, 3) : context.display ? 0 : 1]; }
|
|
172
|
+
// Whether braces in a token run pair up without closing below their start.
|
|
173
|
+
function mathTexBalanced(tokens) {
|
|
174
|
+
let depth = 0;
|
|
175
|
+
for (const token of tokens) if (token.kind === 'char') { depth += token.value === '{' ? 1 : token.value === '}' ? -1 : 0; if (depth < 0) return false; }
|
|
176
|
+
return depth === 0;
|
|
115
177
|
}
|
|
116
178
|
function mathTexTokenEqual(a, b) { return !!a && !!b && a.kind === b.kind && a.value === b.value; }
|
|
117
179
|
|
|
@@ -198,9 +260,12 @@ class MathTexParser {
|
|
|
198
260
|
if (token.kind === 'command' && (Object.hasOwn(MATH_TEX_DECLARATIONS, token.value) || token.value === 'color')) {
|
|
199
261
|
this.take();
|
|
200
262
|
const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
|
|
263
|
+
// A math style is an ordered list node: a selected mathchoice can change the style of later atoms.
|
|
264
|
+
if (fields.mathStyle) { children.push(this.node('style', {...fields, declaration: true, body: this.row([])})); continue; }
|
|
201
265
|
// A declaration styles each following atom; the atoms keep their own classes and spacing.
|
|
202
266
|
const rest = this.nested(() => this.parseRow(stop, allowFraction));
|
|
203
|
-
|
|
267
|
+
// The first one notes where the declaration stood: TeX keeps no italic correction across it.
|
|
268
|
+
for (const [at, body] of (rest.type === 'row' ? rest.children : [rest]).entries()) children.push(this.styledDeclaration(fields, body, at === 0));
|
|
204
269
|
break;
|
|
205
270
|
}
|
|
206
271
|
if (token.kind === 'command' && /^(over|atop|choose|brace|brack|above|overwithdelims|atopwithdelims|abovewithdelims)$/.test(token.value)) {
|
|
@@ -217,6 +282,7 @@ class MathTexParser {
|
|
|
217
282
|
}
|
|
218
283
|
if (token.kind === 'char' && (token.value === '^' || token.value === '_' || token.value === "'")) {
|
|
219
284
|
let base = children.pop() || this.row([]);
|
|
285
|
+
if (base.type === 'choice' || base.type === 'style' && base.mathStyle && base.declaration && !base.body.children.length) { children.push(base); base = this.row([]); }
|
|
220
286
|
children.push(this.readScripts(base));
|
|
221
287
|
continue;
|
|
222
288
|
}
|
|
@@ -230,12 +296,21 @@ class MathTexParser {
|
|
|
230
296
|
const atom = this.parseAtom();
|
|
231
297
|
// A symbol remembers where its source begins, so a tap on it can find its place in the source.
|
|
232
298
|
if (atom && (atom.type === 'glyph' || atom.type === 'text') && atom.at === undefined) atom.at = token.offset;
|
|
233
|
-
if (atom) children.push(this.readScripts(atom));
|
|
299
|
+
if (atom) children.push(atom.type === 'choice' ? atom : this.readScripts(atom));
|
|
234
300
|
}
|
|
235
301
|
// An equation tag follows its equation wherever \tag was written.
|
|
236
302
|
const tags = children.filter(child => child?.semanticRole === 'tag');
|
|
237
303
|
return this.row(tags.length ? [...children.filter(child => child?.semanticRole !== 'tag'), ...tags] : children);
|
|
238
304
|
}
|
|
305
|
+
styledDeclaration(fields, body, first) {
|
|
306
|
+
// Font/color assignments are group-local; math-style nodes remain in the list even through these assignments.
|
|
307
|
+
if (body.type === 'style' && body.mathStyle && body.declaration) return body;
|
|
308
|
+
if (body.type === 'choice') {
|
|
309
|
+
for (const branch of body.choices) branch.children = branch.children.map((child, index) => this.styledDeclaration(fields, child, first && index === 0));
|
|
310
|
+
return body;
|
|
311
|
+
}
|
|
312
|
+
return this.node('style', {...fields, body, ...(first ? {declaration: true} : {})});
|
|
313
|
+
}
|
|
239
314
|
readScripts(base) {
|
|
240
315
|
let result = base;
|
|
241
316
|
for (;;) {
|
|
@@ -278,6 +353,8 @@ class MathTexParser {
|
|
|
278
353
|
this.take();
|
|
279
354
|
return this.nested(() => {
|
|
280
355
|
const body = this.parseRow(item => item.kind === 'char' && item.value === '}');
|
|
356
|
+
// An empty argument remembers the place inside its braces, so a tap can put the caret there.
|
|
357
|
+
if (body.type === 'row' && !body.children.length) body.at = token.offset + 1;
|
|
281
358
|
this.expect('}');
|
|
282
359
|
return body;
|
|
283
360
|
});
|
|
@@ -335,11 +412,14 @@ class MathTexParser {
|
|
|
335
412
|
parseAtom() {
|
|
336
413
|
const token = this.take();
|
|
337
414
|
if (token.kind === 'eof') this.error('missing-argument', 'A mathematical expression is missing.', token);
|
|
415
|
+
if (token.kind === 'verbatim') return this.readVerb(token);
|
|
338
416
|
if (token.kind === 'command') return this.command(token);
|
|
339
417
|
if (token.value === '{') {
|
|
340
418
|
return this.nested(() => {
|
|
341
419
|
const body = this.parseRow(item => item.kind === 'char' && item.value === '}');
|
|
342
420
|
this.expect('}');
|
|
421
|
+
// TeX makes a braced group in a formula one ordinary atom, whatever it holds: a{=}b has no relation spaces.
|
|
422
|
+
body.group = true;
|
|
343
423
|
return body;
|
|
344
424
|
});
|
|
345
425
|
}
|
|
@@ -365,15 +445,16 @@ class MathTexParser {
|
|
|
365
445
|
}
|
|
366
446
|
command(token) {
|
|
367
447
|
const name = token.value;
|
|
448
|
+
if (name === 'mathchoice') return this.node('choice', {choices: Array.from({length: 4}, () => {
|
|
449
|
+
if (!this.is('{')) this.error('missing-argument', 'Each math choice needs a braced expression.');
|
|
450
|
+
return this.argument();
|
|
451
|
+
})});
|
|
368
452
|
if (Object.hasOwn(MATH_TEX_SPACES, name)) return this.node('space', {width: MATH_TEX_SPACES[name]});
|
|
369
453
|
// amsmath: \iff, \implies and \impliedby are a long double arrow between thick spaces, one relation.
|
|
370
454
|
if (Object.hasOwn(MATH_TEX_LONG_ARROWS, name)) return this.node('style', {class: 'rel', body: this.row([this.node('space', {width: 5 / 18}), this.node('glyph', MATH_SYMBOLS[MATH_TEX_LONG_ARROWS[name]]), this.node('space', {width: 5 / 18})])});
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
const centred = next.kind === 'char' ? '+-=<>*:'.includes(next.value) : !!after && (['bin', 'rel'].includes(after.class) || /^(?:int|iint|iiint|oint)$/.test(next.value));
|
|
375
|
-
if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
|
|
376
|
-
}
|
|
455
|
+
if (/^dots[bcimo]?$/.test(name)) return this.readDots(name);
|
|
456
|
+
// amsmath's \colon: a colon 2 mu after the left side and 6 mu before the right, with no punctuation space.
|
|
457
|
+
if (name === 'colon') return this.row([this.node('space', {width: 2 / 18}), this.node('glyph', {value: ':', class: 'ord', variant: 'roman', tokenKind: 'mo'}), this.node('space', {width: 6 / 18})]);
|
|
377
458
|
if (Object.hasOwn(MATH_SYMBOLS, name)) return this.node('glyph', MATH_SYMBOLS[name]);
|
|
378
459
|
if (Object.hasOwn(MATH_TEX_VARIANTS, name)) {
|
|
379
460
|
let body = this.argument();
|
|
@@ -383,15 +464,19 @@ class MathTexParser {
|
|
|
383
464
|
}
|
|
384
465
|
if (Object.hasOwn(MATH_TEX_TEXT_VARIANTS, name)) return this.subparse(this.rawArgument(), true, MATH_TEX_TEXT_VARIANTS[name]);
|
|
385
466
|
if (MATH_NAMED_OPERATORS.has(name) || MATH_LIMIT_OPERATORS.has(name)) {
|
|
386
|
-
const values = {limsup: 'lim
|
|
467
|
+
const values = {limsup: 'lim\u2009sup', liminf: 'lim\u2009inf', injlim: 'inj\u2009lim', projlim: 'proj\u2009lim', varlimsup: 'lim', varliminf: 'lim', varinjlim: 'lim', varprojlim: 'lim'};
|
|
387
468
|
let body = this.node('text', {value: values[name] || name, class: 'op', limits: MATH_LIMIT_OPERATORS.has(name) ? 'display' : 'never', variant: 'roman'});
|
|
388
|
-
|
|
389
|
-
if (
|
|
469
|
+
// amsmath's \injlim and \projlim are the words inj lim and proj lim; the var forms draw an arrow under lim.
|
|
470
|
+
if (['varinjlim', 'varprojlim'].includes(name)) body = this.node('accent', {base: body, value: /inj/.test(name) ? '→' : '←', position: 'under', stretch: true, class: 'op', limits: 'display', varlim: true});
|
|
471
|
+
if (name === 'varlimsup' || name === 'varliminf') body = this.node('accent', {base: body, value: '¯', position: name === 'varlimsup' ? 'over' : 'under', stretch: true, class: 'op', limits: 'display', varlim: true});
|
|
390
472
|
return body;
|
|
391
473
|
}
|
|
392
474
|
if (Object.hasOwn(MATH_TEX_ACCENTS, name)) {
|
|
393
475
|
const [value, position, stretch] = MATH_TEX_ACCENTS[name];
|
|
394
|
-
|
|
476
|
+
// mathtools' \overbracket[rule][height]{...}: the font's bracket keeps its own rule and height.
|
|
477
|
+
if (/bracket$/.test(name) && this.optionalRaw()) this.optionalRaw();
|
|
478
|
+
// TeX's braces, parentheses and brackets over or under a formula are operators with limits.
|
|
479
|
+
return this.node('accent', {base: this.argument(), value, position, stretch, ...(/(brace|paren|bracket)$/.test(name) ? {limits: 'always'} : {})});
|
|
395
480
|
}
|
|
396
481
|
if (/^[{}%$&#_]$/.test(name)) return this.literal(name, {variant: 'roman'});
|
|
397
482
|
if (name === '|') return this.literal('‖', {variant: 'roman'});
|
|
@@ -400,12 +485,12 @@ class MathTexParser {
|
|
|
400
485
|
if (align && !/^[lr]$/.test(mathTexTokenText(align).trim())) this.error('invalid-option', 'Continued-fraction alignment must be l or r.', token);
|
|
401
486
|
return this.node('frac', {num: this.argument(), den: this.argument(), bar: true, ...(name === 'dfrac' || name === 'cfrac' ? {style: 'display'} : name === 'tfrac' ? {style: 'text'} : {}), ...(align ? {align: mathTexTokenText(align).trim()} : {}), ...(name === 'cfrac' ? {strut: true} : {})});
|
|
402
487
|
}
|
|
403
|
-
if (/^(binom|dbinom|tbinom)$/.test(name)) return this.node('frac', {num: this.argument(), den: this.argument(), bar: false, left: '(', right: ')', ...(name[0] === 'd' ? {style: 'display'} : name[0] === 't' ? {style: 'text'} : {})});
|
|
488
|
+
if (/^(binom|dbinom|tbinom)$/.test(name)) return this.node('frac', {num: this.argument(), den: this.argument(), bar: false, left: '(', right: ')', textDelimiters: true, ...(name[0] === 'd' ? {style: 'display'} : name[0] === 't' ? {style: 'text'} : {})});
|
|
404
489
|
if (name === 'genfrac') {
|
|
405
490
|
const left = this.delimiterArgument(), right = this.delimiterArgument(), thickness = this.plainArgument(), style = this.plainArgument();
|
|
406
491
|
if (!/^[0-3]?$/.test(style)) this.error('invalid-style', 'The fraction style must be 0, 1, 2 or 3.', token);
|
|
407
492
|
const barThickness = thickness ? this.dimension(thickness, token) : undefined;
|
|
408
|
-
return this.node('frac', {num: this.argument(), den: this.argument(), bar: barThickness !== 0, left, right, ...(barThickness === undefined ? {} : {barThickness}), ...(style ? {style: ['display', 'text', 'script', 'scriptscript'][Number(style)]} : {})});
|
|
493
|
+
return this.node('frac', {num: this.argument(), den: this.argument(), bar: barThickness !== 0, left, right, textDelimiters: true, ...(barThickness === undefined ? {} : {barThickness}), ...(style ? {style: ['display', 'text', 'script', 'scriptscript'][Number(style)]} : {})});
|
|
409
494
|
}
|
|
410
495
|
if (name === 'sqrt') {
|
|
411
496
|
const index = this.optionalRaw();
|
|
@@ -431,7 +516,7 @@ class MathTexParser {
|
|
|
431
516
|
return value ? this.literal(value, {class: 'rel', delimiter: true, variant: 'roman'}) : this.row([]);
|
|
432
517
|
}
|
|
433
518
|
if (/^(big|Big|bigg|Bigg)[lrm]?$/.test(name)) {
|
|
434
|
-
const value = this.
|
|
519
|
+
const value = this.delimiterArgument(), sizes = {big: 1.2, Big: 1.8, bigg: 2.4, Bigg: 3};
|
|
435
520
|
const base = name.replace(/[lrm]$/, '');
|
|
436
521
|
return this.literal(value, {delimiterSize: sizes[base], class: name.endsWith('l') ? 'open' : name.endsWith('r') ? 'close' : name.endsWith('m') ? 'rel' : 'ord', variant: 'roman'});
|
|
437
522
|
}
|
|
@@ -440,10 +525,22 @@ class MathTexParser {
|
|
|
440
525
|
if (/^(matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases|smallmatrix)$/.test(name)) return this.tableFromTokens(this.rawArgument(), name);
|
|
441
526
|
if (name === 'operatorname' || name === 'operatornamewithlimits') {
|
|
442
527
|
const starred = name !== 'operatorname' || this.is('*'); if (starred && name === 'operatorname') this.take();
|
|
443
|
-
|
|
528
|
+
// The name is set in math mode, where TeX ignores spaces: \operatorname{arg max} is argmax.
|
|
529
|
+
const body = this.subparse(this.rawArgument().filter(token => token.kind !== 'space'), true, 'roman');
|
|
444
530
|
return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
|
|
445
531
|
}
|
|
446
532
|
if (/^math(ord|op|bin|rel|open|close|punct|inner)$/.test(name)) return this.node('style', {body: this.argument(), class: name.slice(4), ...(name === 'mathop' ? {limits: 'display'} : {})});
|
|
533
|
+
// Plain TeX's \buildrel top \over relation is \stackrel{top}{relation}.
|
|
534
|
+
if (name === 'buildrel') {
|
|
535
|
+
const top = [];
|
|
536
|
+
for (let depth = 0, item = this.rawTake(false); !(depth === 0 && item.kind === 'command' && item.value === 'over'); item = this.rawTake(false)) {
|
|
537
|
+
if (item.kind === 'eof') this.error('missing-argument', '\\buildrel needs \\over.', token);
|
|
538
|
+
if (item.kind === 'char' && item.value === '{') depth++;
|
|
539
|
+
if (item.kind === 'char' && item.value === '}') depth--;
|
|
540
|
+
top.push(item);
|
|
541
|
+
}
|
|
542
|
+
return this.node('overunder', {base: this.argument(), over: this.subparse(top), class: 'rel'});
|
|
543
|
+
}
|
|
447
544
|
if (name === 'overset' || name === 'underset' || name === 'stackrel' || name === 'stackbin') {
|
|
448
545
|
const decoration = this.argument(), base = this.argument();
|
|
449
546
|
return this.node('overunder', {base, [name === 'underset' ? 'under' : 'over']: decoration, ...(name === 'stackrel' ? {class: 'rel'} : name === 'stackbin' ? {class: 'bin'} : {})});
|
|
@@ -451,7 +548,7 @@ class MathTexParser {
|
|
|
451
548
|
if (name === 'overunderset') { const over = this.argument(), under = this.argument(); return this.node('overunder', {base: this.argument(), over, under}); }
|
|
452
549
|
if (/^x(leftarrow|rightarrow|leftrightarrow|Leftarrow|Rightarrow|Leftrightarrow|mapsto|hookleftarrow|hookrightarrow|leftharpoonup|leftharpoondown|rightharpoonup|rightharpoondown|rightleftharpoons|leftrightharpoons|twoheadleftarrow|twoheadrightarrow|longequal)$/.test(name)) {
|
|
453
550
|
const under = this.optionalRaw(), over = this.argument(), symbol = name === 'xlongequal' ? '=' : MATH_SYMBOLS[name.slice(1)].value;
|
|
454
|
-
return this.node('overunder', {base: this.literal(symbol, {class: 'rel', stretch: true}), over, ...(under ? {under: this.subparse(under)} : {}), class: 'rel'});
|
|
551
|
+
return this.node('overunder', {base: this.literal(symbol, {class: 'rel', stretch: true}), over, ...(under ? {under: this.subparse(under)} : {}), class: 'rel', arrow: name.slice(1)});
|
|
455
552
|
}
|
|
456
553
|
if (name === 'not') {
|
|
457
554
|
const base = this.argument(), negated = {'=': '≠', '<': '≮', '>': '≯', '≤': '≰', '≥': '≱', '∈': '∉', '∋': '∌', '⊂': '⊄', '⊃': '⊅', '⊆': '⊈', '⊇': '⊉', '∣': '∤', '∥': '∦', '∼': '≁', '≈': '≉', '≡': '≢', '→': '↛', '←': '↚', '↔': '↮', '⇒': '⇏', '⇐': '⇍', '⇔': '⇎'};
|
|
@@ -482,14 +579,14 @@ class MathTexParser {
|
|
|
482
579
|
return this.node('raise', {body: this.subparse(this.rawArgument(), true, 'roman'), amount, ...(height ? {height: this.dimension(mathTexTokenText(height), token)} : {}), ...(depth ? {depth: this.dimension(mathTexTokenText(depth), token)} : {})});
|
|
483
580
|
}
|
|
484
581
|
if (name === 'raise' || name === 'lower') return this.node('raise', {amount: this.readDimension() * (name === 'lower' ? -1 : 1), body: this.argument()});
|
|
485
|
-
if (name === 'textcolor') { const color = this.readColor(); return this.node('style', {body: this.argument(), color}); }
|
|
582
|
+
if (name === 'textcolor' || name === 'mathcolor') { const color = this.readColor(); return this.node('style', {body: this.argument(), color}); }
|
|
486
583
|
if (name === 'colorbox' || name === 'fcolorbox') {
|
|
487
584
|
const border = name === 'fcolorbox' ? this.readColor() : undefined, background = this.readColor();
|
|
488
585
|
return this.node('style', {body: this.subparse(this.rawArgument(), true, 'roman'), background, ...(border ? {border} : {})});
|
|
489
586
|
}
|
|
490
587
|
if (name === 'definecolor') {
|
|
491
588
|
const colorName = this.plainArgument(), model = this.plainArgument(), value = this.plainArgument();
|
|
492
|
-
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(colorName)) this.error('invalid-color', 'Invalid
|
|
589
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(colorName)) this.error('invalid-color', 'Invalid color name.', token);
|
|
493
590
|
this.colors[colorName] = this.color(value, model, token); return null;
|
|
494
591
|
}
|
|
495
592
|
// MathJax's bbox: a background colour, a padding length and a CSS border whose last word is its colour.
|
|
@@ -503,6 +600,20 @@ class MathTexParser {
|
|
|
503
600
|
}
|
|
504
601
|
return this.node('style', {body: this.argument(), ...fields});
|
|
505
602
|
}
|
|
603
|
+
if (name === 'intertext' || name === 'multicolumn' || name === 'hdotsfor')
|
|
604
|
+
this.error('misplaced-alignment', name === 'intertext' ? '\\intertext goes at the start of a row of align, alignat, flalign or gather.' : '\\' + name + ' fills a whole cell of a matrix or array.', token);
|
|
605
|
+
// MathJax's \enclose{notation}[attributes]{body}: MathML's menclose notations, with mathcolor and mathbackground.
|
|
606
|
+
if (name === 'enclose') {
|
|
607
|
+
const notation = this.plainArgument().split(/[\s,]+/).filter(Boolean), options = this.optionalRaw();
|
|
608
|
+
if (!notation.length) this.error('missing-argument', '\\enclose needs a notation.', token);
|
|
609
|
+
for (const item of notation) if (!MATH_ENCLOSE_NOTATIONS.has(item)) this.error('unsupported-notation', 'Unsupported enclose notation: ' + item + '.', token);
|
|
610
|
+
const fields = {};
|
|
611
|
+
for (const pair of options ? mathTexTokenText(options).split(',') : []) {
|
|
612
|
+
const [key, value = ''] = pair.split('=').map(part => part.trim());
|
|
613
|
+
if (key === 'mathcolor' || key === 'mathbackground') fields[key === 'mathcolor' ? 'color' : 'background'] = this.color(value, '', token);
|
|
614
|
+
}
|
|
615
|
+
return this.node('enclose', {notation: [...new Set(notation)], body: this.argument(), ...fields});
|
|
616
|
+
}
|
|
506
617
|
if (name === 'boxed' || name === 'fbox') return this.node('style', {body: name === 'fbox' ? this.subparse(this.rawArgument(), true, 'roman') : this.argument(), border: 'currentColor', padding: .25});
|
|
507
618
|
if (name === 'cancel' || name === 'bcancel' || name === 'xcancel' || name === 'sout') return this.node('accent', {base: this.argument(), value: name === 'bcancel' ? '╲' : name === 'xcancel' ? '╳' : name === 'sout' ? '─' : '╱', position: 'over', overlay: true, stretch: true});
|
|
508
619
|
if (name === 'cancelto') { const over = this.argument(); return this.node('overunder', {base: this.node('accent', {base: this.argument(), value: '↗', position: 'over', overlay: true, stretch: true}), over}); }
|
|
@@ -516,7 +627,7 @@ class MathTexParser {
|
|
|
516
627
|
}
|
|
517
628
|
if (name === 'require') {
|
|
518
629
|
const value = this.plainArgument();
|
|
519
|
-
if (!MATH_TEX_PACKAGES.has(value)) this.error('unsupported-package', 'Unsupported
|
|
630
|
+
if (!MATH_TEX_PACKAGES.has(value)) this.error('unsupported-package', 'Unsupported math package: ' + value + '.', token, name);
|
|
520
631
|
return null;
|
|
521
632
|
}
|
|
522
633
|
if (name === 'href') {
|
|
@@ -553,14 +664,17 @@ class MathTexParser {
|
|
|
553
664
|
const raw = this.rawArgument(), delimiter = value => value === '|' ? make('|', 'char') : make(value);
|
|
554
665
|
let divided = false;
|
|
555
666
|
for (let i = 0; i < raw.length; i++) {
|
|
556
|
-
|
|
667
|
+
// braket.sty reads || and \| as one double bar.
|
|
668
|
+
const item = raw[i], command = name !== 'set' && item.kind === 'command' && item.value === '|', bar = command || item.kind === 'char' && item.value === '|',
|
|
669
|
+
double = command || bar && raw[i + 1]?.kind === 'char' && raw[i + 1].value === '|';
|
|
557
670
|
if (!bar || divided || (name !== 'Braket' && name !== 'Set' && name !== 'set')) { body.push(item); continue; }
|
|
558
|
-
if (double) i++;
|
|
671
|
+
if (double && !command) i++;
|
|
559
672
|
divided = name !== 'Braket';
|
|
560
673
|
body.push(...(name === 'set' ? [make('mid')] : [make(name === 'Set' ? ';' : ','), make('middle'), double ? make('|') : make('|', 'char'), make(name === 'Set' ? ';' : ',')]));
|
|
561
674
|
}
|
|
562
675
|
if (name === 'set') return this.subparse([make('{'), make(','), ...body, make(','), make('}')]);
|
|
563
|
-
|
|
676
|
+
// braket.sty pads \Set with a medium space inside its braces.
|
|
677
|
+
return this.subparse([make('left'), delimiter(left), ...(name === 'Set' ? [make(':')] : []), ...body, ...(name === 'Set' ? [make(':')] : []), make('right'), delimiter(right)]);
|
|
564
678
|
}
|
|
565
679
|
// units' \nicefrac (and xfrac's \sfrac): a script numerator raised 0.5 ex, a solidus, a script denominator lowered 0.25 ex.
|
|
566
680
|
if (name === 'nicefrac' || name === 'sfrac') {
|
|
@@ -589,14 +703,19 @@ class MathTexParser {
|
|
|
589
703
|
return this.node('accent', {base: this.argument(), value, position: name === 'accentset' ? 'over' : 'under', stretch});
|
|
590
704
|
}
|
|
591
705
|
const decoration = this.subparse(mark);
|
|
592
|
-
return this.node('overunder', {base: this.argument(), [name === 'accentset' ? 'over' : 'under']: decoration});
|
|
706
|
+
return this.node('overunder', {base: this.argument(), [name === 'accentset' ? 'over' : 'under']: decoration, accentGap: true});
|
|
593
707
|
}
|
|
594
708
|
if (name === 'slashed') return this.node('accent', {base: this.argument(), value: '/', position: 'through'});
|
|
595
|
-
if (name === '
|
|
596
|
-
if (name === '
|
|
709
|
+
if (name === 'bmod') return this.row([this.node('space', {width: 5 / 18}), this.node('text', {value: 'mod', variant: 'roman', class: 'bin'}), this.node('space', {width: 5 / 18})]);
|
|
710
|
+
if (name === 'mod' || name === 'pmod' || name === 'pod') return this.row([
|
|
711
|
+
this.node('space', {width: (name === 'mod' ? 12 : 8) / 18, displayWidth: 1}),
|
|
712
|
+
...(name === 'mod' ? [] : [this.literal('(')]),
|
|
713
|
+
...(name === 'pod' ? [] : [this.node('text', {value: 'mod', variant: 'roman'}), this.node('space', {width: 1 / 3})]),
|
|
714
|
+
this.argument(), ...(name === 'mod' ? [] : [this.literal(')')])
|
|
715
|
+
]);
|
|
597
716
|
if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
|
|
598
717
|
if (name === 'pu') return {...this.units(this.rawArgument()), semanticRole: 'units'};
|
|
599
|
-
if (/^(SI|si|num|unit|ang)$/.test(name)) return {...this.siunitx(name, token), semanticRole: 'units'};
|
|
718
|
+
if (/^(SI|si|num|unit|ang|SIrange|numrange|qtyrange)$/.test(name)) return {...this.siunitx(name, token), semanticRole: 'units'};
|
|
600
719
|
// mathtools \smashoperator[lr]{op}: the limits overhang the operator's own width on the named sides.
|
|
601
720
|
if (name === 'smashoperator') {
|
|
602
721
|
const sides = mathTexTokenText(this.optionalRaw() || []).trim() || 'lr';
|
|
@@ -614,7 +733,7 @@ class MathTexParser {
|
|
|
614
733
|
const integral = () => this.literal('∫', {large: true, limits: 'never', class: 'op'});
|
|
615
734
|
return this.node('style', {class: 'op', limits: 'never', body: this.row([integral(), this.node('space', {width: -1 / 6}), this.node('glyph', MATH_SYMBOLS.cdots), this.node('space', {width: -1 / 6}), integral()])});
|
|
616
735
|
}
|
|
617
|
-
if (
|
|
736
|
+
if (MATH_TEX_PHYSICS.has(name)) return {...this.physics(name, token), semanticRole: 'physics'};
|
|
618
737
|
if (name === 'mmlToken') return this.mathmlToken(token);
|
|
619
738
|
if (name === 'unicode' || name === 'char') return this.character(name, token);
|
|
620
739
|
if (name === 'TeX' || name === 'LaTeX') return this.node('text', {value: name, variant: 'roman'});
|
|
@@ -622,7 +741,7 @@ class MathTexParser {
|
|
|
622
741
|
if (name === 'textasciitilde') return this.literal('~', {variant: 'roman'});
|
|
623
742
|
if (name === 'textasciicircum') return this.literal('^', {variant: 'roman'});
|
|
624
743
|
if (['end', 'right', '\\', 'cr', 'of'].includes(name)) this.error('unexpected-command', '\\' + name + ' has no matching opening command.', token);
|
|
625
|
-
this.error('unsupported-command', 'Unsupported
|
|
744
|
+
this.error('unsupported-command', 'Unsupported math command: \\' + name + '.', token);
|
|
626
745
|
}
|
|
627
746
|
|
|
628
747
|
delimiterArgument() {
|
|
@@ -630,16 +749,41 @@ class MathTexParser {
|
|
|
630
749
|
if (!tokens.length) return '';
|
|
631
750
|
const parser = new MathTexParser(this.source, {tokens, scopes: this.scopes, budget: this.budget});
|
|
632
751
|
const delimiter = parser.readDelimiter();
|
|
633
|
-
if (parser.peek().kind !== 'eof') this.error('invalid-delimiter', 'A
|
|
752
|
+
if (parser.peek().kind !== 'eof') this.error('invalid-delimiter', 'A delimiter must be one symbol.', tokens[0]);
|
|
634
753
|
return delimiter;
|
|
635
754
|
}
|
|
755
|
+
readDots(name) {
|
|
756
|
+
let next = this.rawPeek();
|
|
757
|
+
if (name === 'dots' && next.kind === 'command' && next.value === 'boldsymbol') {
|
|
758
|
+
const frames = this.frames.map(frame => ({...frame}));
|
|
759
|
+
try { this.rawTake(); next = this.rawArgument()[0] || this.eof; }
|
|
760
|
+
finally { this.frames = frames; }
|
|
761
|
+
}
|
|
762
|
+
let macro = next.kind === 'command' && !next.builtin && this.macro(next.value);
|
|
763
|
+
if (macro?.body?.[0]?.builtin) { next = macro.body[0]; macro = null; }
|
|
764
|
+
const first = macro?.body?.[0], command = next.kind === 'command' ? next.value : '',
|
|
765
|
+
centered = macro ? first?.kind === 'command' && /^(mathbin|mathrel|not|DOTSB)$/.test(first.value) :
|
|
766
|
+
next.kind === 'char' ? ['bin', 'rel'].includes(MATH_TEX_LITERAL_CLASSES[next.value]) :
|
|
767
|
+
command === 'not' || Object.hasOwn(MATH_TEX_LONG_ARROWS, command) ||
|
|
768
|
+
!MATH_TEX_DOTS_LOW.has(command) && ['bin', 'rel'].includes(MATH_SYMBOLS[command]?.class),
|
|
769
|
+
integral = name === 'dotsi' || name === 'dots' && (command === 'idotsint' || first?.value === 'DOTSI'),
|
|
770
|
+
raised = integral || name === 'dotsb' || name === 'dotsm' || name === 'dots' && centered,
|
|
771
|
+
closing = next.kind === 'eof' || next.kind === 'char' && /^(\)|\]|\$)$/.test(next.value) ||
|
|
772
|
+
/^(rbrack|\}|rbrace|rangle|rceil|rfloor|rgroup|rmoustache|right|bigr|biggr|Bigr|Biggr)$/.test(command),
|
|
773
|
+
extra = !integral && (name === 'dots' ? !raised && closing : closing || next.kind === 'char' &&
|
|
774
|
+
(name === 'dotsc' ? /^[.;]$/.test(next.value) : /^[,.;]$/.test(next.value))),
|
|
775
|
+
dots = this.node('glyph', raised ? MATH_SYMBOLS.cdots : MATH_SYMBOLS.ldots);
|
|
776
|
+
return integral || extra ? this.node('style', {class: 'inner', body: this.row([
|
|
777
|
+
...(integral ? [this.node('space', {width: -1 / 6})] : []), dots, ...(extra ? [this.node('space', {width: 1 / 6})] : [])
|
|
778
|
+
])}) : dots;
|
|
779
|
+
}
|
|
636
780
|
readLink(token) {
|
|
637
781
|
const href = this.rawArgument().map(item => {
|
|
638
782
|
if (item.kind !== 'command' || /^[#$%&_]$/.test(item.value)) return item.value;
|
|
639
783
|
this.error('unsafe-link', 'A link address cannot contain TeX commands.', item);
|
|
640
784
|
}).join('').trim();
|
|
641
785
|
if (!/^https?:\/\/[^\s<>"'\\]+$/i.test(href) || /[\u0000-\u0020\u007f]/.test(href))
|
|
642
|
-
this.error('unsafe-link', 'A
|
|
786
|
+
this.error('unsafe-link', 'A math link must use an HTTP or HTTPS address.', token);
|
|
643
787
|
return href;
|
|
644
788
|
}
|
|
645
789
|
dimension(value, token = this.rawPeek()) {
|
|
@@ -663,6 +807,30 @@ class MathTexParser {
|
|
|
663
807
|
return this.color(this.plainArgument(), model ? mathTexTokenText(model).trim() : '', this.rawPeek());
|
|
664
808
|
}
|
|
665
809
|
color(value, model, token) {
|
|
810
|
+
// xcolor's mixes: red!30 is 30% red in white; red!30!blue is 30% red in blue, and so on along the expression.
|
|
811
|
+
if (!model && value.includes('!')) {
|
|
812
|
+
const parts = value.split('!'), rgb = name => {
|
|
813
|
+
const hex = Object.hasOwn(MATH_TEX_XCOLOR_BASE, name) ? MATH_TEX_XCOLOR_BASE[name] : Object.hasOwn(this.colors, name) ? this.colors[name] : MATH_TEX_DVIPSNAMES[name] || (/^#[a-fA-F0-9]{6}$/.test(name) ? name : null);
|
|
814
|
+
if (!hex || !/^#[a-fA-F0-9]{6}$/.test(hex)) this.error('invalid-color', 'Unsupported or invalid color value.', token, 'color');
|
|
815
|
+
return [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255);
|
|
816
|
+
};
|
|
817
|
+
// xcolor mixes in the first color's model: a dvipsnames color mixes in CMYK, with RGB as 1 - x less its black.
|
|
818
|
+
const cmyk = !Object.hasOwn(this.colors, parts[0].trim()) && MATH_TEX_DVIPS_CMYK[parts[0].trim()], channels = name => {
|
|
819
|
+
if (!cmyk) return rgb(name);
|
|
820
|
+
if (!Object.hasOwn(this.colors, name) && MATH_TEX_DVIPS_CMYK[name]) return MATH_TEX_DVIPS_CMYK[name];
|
|
821
|
+
const [c, m, y] = rgb(name).map(channel => 1 - channel), k = Math.min(c, m, y);
|
|
822
|
+
return [c - k, m - k, y - k, k];
|
|
823
|
+
};
|
|
824
|
+
let mixed = channels(parts[0].trim());
|
|
825
|
+
for (let i = 1; i < parts.length; i += 2) {
|
|
826
|
+
const percent = Number(parts[i]);
|
|
827
|
+
if (!/^\s*\d+(?:\.\d+)?\s*$/.test(parts[i]) || percent > 100) this.error('invalid-color', 'Unsupported or invalid color value.', token, 'color');
|
|
828
|
+
const other = i + 1 < parts.length ? channels(parts[i + 1].trim()) : cmyk ? [0, 0, 0, 0] : [1, 1, 1];
|
|
829
|
+
mixed = mixed.map((channel, k) => channel * percent / 100 + other[k] * (1 - percent / 100));
|
|
830
|
+
}
|
|
831
|
+
if (cmyk) mixed = mixed.slice(0, 3).map(channel => 1 - Math.min(1, channel + mixed[3]));
|
|
832
|
+
return '#' + mixed.map(channel => Math.round(channel * 255).toString(16).padStart(2, '0')).join('');
|
|
833
|
+
}
|
|
666
834
|
if (!model) {
|
|
667
835
|
if (Object.hasOwn(this.colors, value)) return this.colors[value];
|
|
668
836
|
if (MATH_TEX_DVIPSNAMES[value]) return MATH_TEX_DVIPSNAMES[value];
|
|
@@ -677,12 +845,12 @@ class MathTexParser {
|
|
|
677
845
|
return '#' + rgb.map(number => Math.round(number * (model === 'RGB' ? 1 : 255)).toString(16).padStart(2, '0')).join('');
|
|
678
846
|
}
|
|
679
847
|
}
|
|
680
|
-
this.error('invalid-color', 'Unsupported or invalid
|
|
848
|
+
this.error('invalid-color', 'Unsupported or invalid color value.', token, 'color');
|
|
681
849
|
}
|
|
682
850
|
|
|
683
851
|
environment(fullName, token) {
|
|
684
852
|
const env = fullName.replace(/\*$/, '');
|
|
685
|
-
if (!MATH_TEX_ENVIRONMENTS.has(env)) throw Object.assign(new MathTexError('unsupported-environment', 'Unsupported
|
|
853
|
+
if (!MATH_TEX_ENVIRONMENTS.has(env)) throw Object.assign(new MathTexError('unsupported-environment', 'Unsupported math environment: ' + fullName + '.', token.offset, 'begin'), {environment: env});
|
|
686
854
|
return this.nested(() => {
|
|
687
855
|
let options = {};
|
|
688
856
|
const position = this.optionalRaw();
|
|
@@ -708,15 +876,18 @@ class MathTexParser {
|
|
|
708
876
|
}
|
|
709
877
|
// amscd: rows of objects joined by @>>>, @<<< and @= arrows, between rows of @VVV, @AAA, @| and @. arrows.
|
|
710
878
|
commutativeDiagram(fullName, token) {
|
|
711
|
-
const rows = []
|
|
879
|
+
const rows = [];
|
|
712
880
|
let cells = [], current = [];
|
|
713
881
|
const arrow = (kind, labels) => {
|
|
714
882
|
const label = tokens => tokens.length ? this.subparse(tokens) : null;
|
|
715
|
-
if (kind === '>' || kind === '<' || kind === '=')
|
|
716
|
-
|
|
883
|
+
if (kind === '>' || kind === '<' || kind === '=') {
|
|
884
|
+
const body = this.node('overunder', {base: this.literal(kind === '>' ? '→' : kind === '<' ? '←' : '=', {class: 'rel', stretch: true}),
|
|
885
|
+
...(kind !== '=' ? {over: label(labels[0]) || this.row([])} : {}), ...(labels[1]?.length ? {under: label(labels[1])} : {}), class: 'rel', minWidth: 3, labelPad: 15, diagram: true});
|
|
886
|
+
return this.row([this.node('space', {width: 0.5}), body, this.node('space', {width: 0.5})]);
|
|
887
|
+
}
|
|
717
888
|
if (kind === '.') return this.row([]);
|
|
718
|
-
const side = (tokens, align) => tokens?.length ? [this.node('style', {width: 0, align, body: this.node('style', {mathStyle: 'script', body: label(tokens)})})] : [];
|
|
719
|
-
return this.row([...side(labels[0], 'right'), this.literal(kind === 'V' ? '↓' : kind === 'A' ? '↑' : '‖', {delimiterSize:
|
|
889
|
+
const side = (tokens, align) => tokens?.length ? [this.node('style', {width: 0, align, body: this.node('raise', {center: true, body: this.node('style', {mathStyle: 'script', body: label(tokens)})})})] : [];
|
|
890
|
+
return this.row([...side(labels[0], 'right'), this.literal(kind === 'V' ? '↓' : kind === 'A' ? '↑' : '‖', {delimiterSize: 1.8, class: 'ord'}), ...side(labels[1], 'left')]);
|
|
720
891
|
};
|
|
721
892
|
for (;;) {
|
|
722
893
|
const item = this.rawTake(false);
|
|
@@ -760,11 +931,12 @@ class MathTexParser {
|
|
|
760
931
|
}
|
|
761
932
|
columnSpec(tokens, token) {
|
|
762
933
|
const parser = new MathTexParser(this.source, {tokens, scopes: this.scopes, budget: this.budget, colors: this.colors});
|
|
763
|
-
|
|
934
|
+
// arydshln's : is a dashed rule; columnDashes marks which rules are dashed.
|
|
935
|
+
const align = [], columnRules = [], columnInsertions = [], columnDashes = [];
|
|
764
936
|
while (parser.peek().kind !== 'eof') {
|
|
765
937
|
const item = parser.take();
|
|
766
938
|
if (item.kind === 'char' && /^[lcr]$/.test(item.value)) { this.reserveParts(1, item); align.push(item.value); }
|
|
767
|
-
else if (item.kind === 'char' && item.value === '|') { this.reserveParts(1, item); columnRules.push(align.length); }
|
|
939
|
+
else if (item.kind === 'char' && (item.value === '|' || item.value === ':')) { this.reserveParts(1, item); columnRules.push(align.length); columnDashes.push(item.value === ':'); }
|
|
768
940
|
else if (item.kind === 'char' && (item.value === '@' || item.value === '!')) {
|
|
769
941
|
this.reserveParts(1, item);
|
|
770
942
|
columnInsertions.push({before: align.length, body: this.subparse(parser.rawArgument()), replaceGap: item.value === '@'});
|
|
@@ -779,7 +951,7 @@ class MathTexParser {
|
|
|
779
951
|
this.reserveParts(Number(count) * (repeated.align.length + repeated.columnRules.length + repeated.columnInsertions.length), item);
|
|
780
952
|
for (let i = 0; i < Number(count); i++) {
|
|
781
953
|
const at = align.length;
|
|
782
|
-
columnRules.push(...repeated.columnRules.map(index => at + index));
|
|
954
|
+
columnRules.push(...repeated.columnRules.map(index => at + index)); columnDashes.push(...(repeated.columnDashes || repeated.columnRules.map(() => false)));
|
|
783
955
|
columnInsertions.push(...repeated.columnInsertions.map(insertion => ({...insertion, before: at + insertion.before})));
|
|
784
956
|
align.push(...repeated.align);
|
|
785
957
|
}
|
|
@@ -787,7 +959,7 @@ class MathTexParser {
|
|
|
787
959
|
if (align.length > 256) this.error('resource-limit', 'This array has too many columns to render safely.', token);
|
|
788
960
|
}
|
|
789
961
|
if (!align.length) this.error('invalid-alignment', 'An array needs a column specification.', token);
|
|
790
|
-
return {align, columnRules, columnInsertions};
|
|
962
|
+
return {align, columnRules, columnInsertions, ...(columnDashes.some(Boolean) ? {columnDashes} : {})};
|
|
791
963
|
}
|
|
792
964
|
// mathtools' starred cases set their condition column as text, with $...$ for maths.
|
|
793
965
|
textCell(separator) {
|
|
@@ -818,7 +990,34 @@ class MathTexParser {
|
|
|
818
990
|
if (cells.length || (!rows.length && !endedAfterBreak)) { cells.push(this.row([])); rows.push(cells); }
|
|
819
991
|
break;
|
|
820
992
|
}
|
|
821
|
-
|
|
993
|
+
// amsmath's \intertext is a line of text between the rows of an alignment, set at its left.
|
|
994
|
+
if (this.commandIs('intertext')) {
|
|
995
|
+
const at = this.take();
|
|
996
|
+
if (!/^(align|alignat|flalign|gather)$/.test(env) || cells.length) this.error('unexpected-intertext', '\\intertext goes at the start of a row of align, alignat, flalign or gather.', at);
|
|
997
|
+
rows.push([this.node('row', {children: [this.subparse(this.rawArgument(), true)], intertext: true})]);
|
|
998
|
+
// It sits a display skip (10 pt, 1 em with the row's \jot) from the rows around it.
|
|
999
|
+
if (rows.length > 1) rowGaps[rows.length - 2] = (rowGaps[rows.length - 2] || 0) + 0.7;
|
|
1000
|
+
rowGaps[rows.length - 1] = 0.7;
|
|
1001
|
+
continue;
|
|
1002
|
+
}
|
|
1003
|
+
// \multicolumn{n}{spec}{body} and amsmath's \hdotsfor[spacing]{n} fill n columns of one row.
|
|
1004
|
+
if (this.commandIs('multicolumn') || this.commandIs('hdotsfor')) {
|
|
1005
|
+
const at = this.take(), dots = at.value === 'hdotsfor', spacing = dots ? this.optionalRaw() : null, count = this.plainArgument();
|
|
1006
|
+
if (!/^\d+$/.test(count) || +count < 1 || cells.length + +count > 256) this.error('invalid-alignment', '\\' + at.value + ' needs a column count.', at);
|
|
1007
|
+
let cell;
|
|
1008
|
+
if (dots) {
|
|
1009
|
+
const factor = spacing ? Number(mathTexTokenText(spacing).trim()) : 1;
|
|
1010
|
+
if (!(factor > 0 && factor <= 16)) this.error('invalid-option', '\\hdotsfor spacing must be a positive number.', at);
|
|
1011
|
+
cell = this.node('row', {children: [], span: +count, dots: factor});
|
|
1012
|
+
} else {
|
|
1013
|
+
const spec = this.columnSpec(this.rawArgument(), at);
|
|
1014
|
+
if (spec.align.length !== 1) this.error('invalid-alignment', '\\multicolumn takes one column.', at);
|
|
1015
|
+
cell = this.node('row', {children: [this.argument()], span: +count, spanAlign: spec.align[0], ...(spec.columnRules.length ? {spanRules: spec.columnRules} : {})});
|
|
1016
|
+
}
|
|
1017
|
+
if (!separator(this.peek())) this.error('unexpected-token', 'A \\' + at.value + ' fills its whole cell.', this.peek());
|
|
1018
|
+
cells.push(cell);
|
|
1019
|
+
for (let i = 1; i < +count; i++) cells.push(this.node('row', {children: [], covered: true}));
|
|
1020
|
+
} else cells.push(cells.length === textColumn ? this.textCell(separator) : this.nested(() => this.parseRow(separator)));
|
|
822
1021
|
endedAfterBreak = false;
|
|
823
1022
|
const next = this.peek();
|
|
824
1023
|
if (next.kind === 'char' && next.value === '&') { this.take(); continue; }
|
|
@@ -966,6 +1165,14 @@ class MathTexParser {
|
|
|
966
1165
|
this.frames.push({tokens: replacement, at: 0});
|
|
967
1166
|
}
|
|
968
1167
|
|
|
1168
|
+
readVerb(token) {
|
|
1169
|
+
// Raw spans are single tokens, but each copied character consumes the same admission budget as a glyph.
|
|
1170
|
+
this.reserveParts(token.value.length, token);
|
|
1171
|
+
// LaTeX places \verb in a text-size hbox, including when it occurs in a script.
|
|
1172
|
+
return this.node('style', {mathStyle: 'text', body: this.node('text', {
|
|
1173
|
+
value: token.value.replace(/[ \t]/g, token.starred ? '\u2423' : '\u00a0'), variant: 'monospace', verbatim: true, at: token.offset
|
|
1174
|
+
})});
|
|
1175
|
+
}
|
|
969
1176
|
parseText(variant = 'roman') {
|
|
970
1177
|
const children = [];
|
|
971
1178
|
let value = '';
|
|
@@ -974,6 +1181,7 @@ class MathTexParser {
|
|
|
974
1181
|
for (;;) {
|
|
975
1182
|
const token = this.take(false);
|
|
976
1183
|
if (token.kind === 'eof') break;
|
|
1184
|
+
if (token.kind === 'verbatim') { flush(); children.push(this.readVerb(token)); continue; }
|
|
977
1185
|
if (token.kind === 'space') { value += ' '; continue; }
|
|
978
1186
|
if (token.kind === 'char') {
|
|
979
1187
|
if (token.value === '{') {
|
|
@@ -1004,7 +1212,7 @@ class MathTexParser {
|
|
|
1004
1212
|
continue;
|
|
1005
1213
|
}
|
|
1006
1214
|
if (Object.hasOwn(MATH_TEX_TEXT_VARIANTS, name)) {
|
|
1007
|
-
flush(); children.push(this.subparse(this.rawArgument(), true,
|
|
1215
|
+
flush(); children.push(this.subparse(this.rawArgument(), true, mathTextVariant(variant, name))); continue;
|
|
1008
1216
|
}
|
|
1009
1217
|
if (name === 'color' || name === 'textcolor') {
|
|
1010
1218
|
flush();
|
|
@@ -1051,9 +1259,6 @@ class MathTexParser {
|
|
|
1051
1259
|
return this.row(children);
|
|
1052
1260
|
}
|
|
1053
1261
|
|
|
1054
|
-
physicsCommand(name) {
|
|
1055
|
-
return /^(dv|derivative|pdv|pderivative|fdv|functionalderivative|dd|differential|qty|quantity|pqty|bqty|Bqty|vqty|abs|absolutevalue|norm|bra|ket|braket|innerproduct|ip|ketbra|dyad|outerproduct|op|expval|expectationvalue|ev|mel|matrixel|matrixelement|comm|commutator|acomm|anticommutator|pb|poissonbracket|vb|va|vu|vectorbold|vectorarrow|vectorunit|grad|gradient|divergence|curl|laplacian|eval|evaluated|order|Tr|tr|trace|rank|diag|Res|mqty|pmqty|bmqty|vmqty|smqty|qq|qc|qcc|q(?:if|then|else|otherwise|unless|given|using|assume|since|let|for|all|even|odd|integer|and|or|as|in))$/.test(name);
|
|
1056
|
-
}
|
|
1057
1262
|
physics(name, token) {
|
|
1058
1263
|
const starred = this.is('*'); if (starred) this.take();
|
|
1059
1264
|
if (/^(dv|derivative|pdv|pderivative|fdv|functionalderivative)$/.test(name)) {
|
|
@@ -1096,10 +1301,58 @@ class MathTexParser {
|
|
|
1096
1301
|
}
|
|
1097
1302
|
if (name === 'eval' || name === 'evaluated') return this.node('fence', {left: '', right: '|', body: this.argument()});
|
|
1098
1303
|
if (name === 'order') return this.row([this.literal('O'), this.node('fence', {left: '(', right: ')', body: this.argument()})]);
|
|
1099
|
-
|
|
1100
|
-
|
|
1304
|
+
// \mqty(…), \mqty[…] and \mqty|…| choose their brackets as physics.sty does.
|
|
1305
|
+
if (name === 'mqty' && ['(', '[', '|'].includes(this.rawPeek().value) && this.rawPeek().kind === 'char') {
|
|
1306
|
+
const open = this.rawTake().value, close = {'(': ')', '[': ']', '|': '|'}[open], tokens = [];
|
|
1307
|
+
for (let depth = 0, token = this.rawTake(false); ; token = this.rawTake(false)) {
|
|
1308
|
+
if (token.kind === 'eof') this.error('unclosed-group', 'Expected ' + close + '.', token);
|
|
1309
|
+
if (token.kind === 'char' && token.value === '{') depth++;
|
|
1310
|
+
if (token.kind === 'char' && token.value === '}') depth--;
|
|
1311
|
+
if (!depth && token.kind === 'char' && token.value === close) break;
|
|
1312
|
+
tokens.push(token);
|
|
1313
|
+
}
|
|
1314
|
+
return this.tableFromTokens(tokens, {'(': 'pmatrix', '[': 'bmatrix', '|': 'vmatrix'}[open]);
|
|
1315
|
+
}
|
|
1316
|
+
if (/^(mqty|pmqty|bmqty|Bmqty|vmqty|smqty)$/.test(name)) {
|
|
1317
|
+
const env = name === 'bmqty' ? 'bmatrix' : name === 'Bmqty' ? 'Bmatrix' : name === 'vmqty' ? 'vmatrix' : name === 'smqty' ? 'smallmatrix' : name === 'pmqty' ? 'pmatrix' : 'matrix';
|
|
1101
1318
|
return this.tableFromTokens(this.rawArgument(), env);
|
|
1102
1319
|
}
|
|
1320
|
+
if (name === 'Pmqty') return this.node('fence', {left: '⟮', right: '⟯', body: this.tableFromTokens(this.rawArgument(), 'matrix')});
|
|
1321
|
+
// physics.sty's matrix contents: diagonal and antidiagonal (a filler fills the rest), identity, zero, a matrix of x_{ij}, Pauli.
|
|
1322
|
+
if (/^(dmat|diagonalmatrix|admat|antidiagonalmatrix|imat|identitymatrix|zmat|zeromatrix|xmat|xmatrix|pmat|paulimatrix)$/.test(name)) {
|
|
1323
|
+
const text = tokens => mathTexTokenText(tokens).trim(), cells = [];
|
|
1324
|
+
const count = tokens => { const n = Number(text(tokens)); if (!Number.isInteger(n) || n < 1 || n > 32) this.error('invalid-argument', 'A matrix size is a whole number from 1 to 32.', token); return n; };
|
|
1325
|
+
if (/^(dmat|diagonalmatrix|admat|antidiagonalmatrix)$/.test(name)) {
|
|
1326
|
+
const filler = this.optionalRaw() || [], entries = [], raw = this.rawArgument();
|
|
1327
|
+
let depth = 0, entry = [];
|
|
1328
|
+
for (const item of raw) {
|
|
1329
|
+
if (item.kind === 'char' && item.value === '{') depth++;
|
|
1330
|
+
if (item.kind === 'char' && item.value === '}') depth--;
|
|
1331
|
+
if (!depth && item.kind === 'char' && item.value === ',') { entries.push(entry); entry = []; } else entry.push(item);
|
|
1332
|
+
}
|
|
1333
|
+
entries.push(entry);
|
|
1334
|
+
if (entries.length > 32) this.error('resource-limit', 'This matrix is too large to render safely.', token);
|
|
1335
|
+
const anti = /^a/.test(name);
|
|
1336
|
+
// Each diagonal entry is its own \mqty, as in physics.sty.
|
|
1337
|
+
const own = entry => [{kind: 'command', value: 'mqty', offset: token.offset}, {kind: 'char', value: '{', offset: token.offset}, ...entry, {kind: 'char', value: '}', offset: token.offset}];
|
|
1338
|
+
for (let r = 0; r < entries.length; r++) cells.push(entries.map((_, c) => (anti ? c === entries.length - 1 - r : c === r) ? own(entries[r]) : filler));
|
|
1339
|
+
} else if (/^(imat|identitymatrix)$/.test(name)) {
|
|
1340
|
+
const n = count(this.rawArgument()), one = mathTexTokens('1', token.offset), zero = mathTexTokens('0', token.offset);
|
|
1341
|
+
for (let r = 0; r < n; r++) cells.push(Array.from({length: n}, (_, c) => c === r ? one : zero));
|
|
1342
|
+
} else if (/^(zmat|zeromatrix)$/.test(name)) {
|
|
1343
|
+
const rows = count(this.rawArgument()), columns = this.is('{') ? count(this.rawArgument()) : rows, zero = mathTexTokens('0', token.offset);
|
|
1344
|
+
for (let r = 0; r < rows; r++) cells.push(Array(columns).fill(zero));
|
|
1345
|
+
} else if (/^(xmat|xmatrix)$/.test(name)) {
|
|
1346
|
+
const symbol = this.rawArgument(), rows = count(this.rawArgument()), columns = count(this.rawArgument());
|
|
1347
|
+
for (let r = 1; r <= rows; r++) cells.push(Array.from({length: columns}, (_, c) => [...symbol, ...(starred ? mathTexTokens('_{' + (rows > 1 ? r : '') + (columns > 1 ? c + 1 : '') + '}', token.offset) : [])]));
|
|
1348
|
+
} else {
|
|
1349
|
+
const which = text(this.rawArgument()), rows = {'0': '1&0\\\\0&1', '1': '0&1\\\\1&0', x: '0&1\\\\1&0', '2': '0&-i\\\\i&0', y: '0&-i\\\\i&0', '3': '1&0\\\\0&-1', z: '1&0\\\\0&-1'}[which];
|
|
1350
|
+
if (!rows) this.error('invalid-argument', 'A Pauli matrix is 0, 1, 2, 3, x, y or z.', token);
|
|
1351
|
+
return this.tableFromTokens(mathTexTokens(rows, token.offset), 'matrix');
|
|
1352
|
+
}
|
|
1353
|
+
const amp = {kind: 'char', value: '&', offset: token.offset}, newline = {kind: 'command', value: '\\', offset: token.offset};
|
|
1354
|
+
return this.tableFromTokens(cells.flatMap((row, r) => [...(r ? [newline] : []), ...row.flatMap((cell, c) => [...(c ? [amp] : []), ...cell])]), 'matrix');
|
|
1355
|
+
}
|
|
1103
1356
|
const first = this.argument();
|
|
1104
1357
|
if (/^(bra|ket|pqty|bqty|Bqty|vqty|abs|absolutevalue|norm)$/.test(name)) {
|
|
1105
1358
|
const ends = {bra: ['⟨', '|'], ket: ['|', '⟩'], pqty: ['(', ')'], bqty: ['[', ']'], Bqty: ['{', '}'], vqty: ['|', '|'], abs: ['|', '|'], absolutevalue: ['|', '|'], norm: ['‖', '‖']}[name];
|
|
@@ -1125,11 +1378,14 @@ class MathTexParser {
|
|
|
1125
1378
|
chemicalRow(stop) {
|
|
1126
1379
|
const children = [];
|
|
1127
1380
|
let spaced = true, subAllowed = false, moleculeParts = 0, isotope = null;
|
|
1381
|
+
// mhchem hangs a count, then a charge, each on its own X-high phantom after the formula, side by side.
|
|
1128
1382
|
const script = (key, body) => {
|
|
1129
|
-
|
|
1130
|
-
if (
|
|
1131
|
-
|
|
1132
|
-
|
|
1383
|
+
const last = children.at(-1);
|
|
1384
|
+
if (last?.chemical && !(key === 'sup' && last.sub && !last.sup)) {
|
|
1385
|
+
if (last[key]) last[key] = this.row([last[key], body]); else last[key] = body;
|
|
1386
|
+
return;
|
|
1387
|
+
}
|
|
1388
|
+
children.push(this.node('scripts', {base: this.node('phantom', {body: this.node('text', {value: 'X', variant: 'roman'}), mode: 'v'}), [key]: body, chemical: true}));
|
|
1133
1389
|
};
|
|
1134
1390
|
const consumeRun = predicate => {
|
|
1135
1391
|
let value = '';
|
|
@@ -1145,7 +1401,7 @@ class MathTexParser {
|
|
|
1145
1401
|
spaced = true; subAllowed = false; moleculeParts = 0;
|
|
1146
1402
|
// An operator or arrow already carries its own spacing; a separating space adds none beside it.
|
|
1147
1403
|
const after = this.rawPeek(false), before = children.at(-1)?.class;
|
|
1148
|
-
if (before !== 'bin' && before !== 'rel' && !(after.kind === 'char' && /^[+<=-]$/.test(after.value))) children.push(this.node('space', {width: 3 / 18}));
|
|
1404
|
+
if (before !== 'bin' && before !== 'rel' && !children.at(-2)?.unspaced && !(after.kind === 'char' && /^[+<=-]$/.test(after.value))) children.push(this.node('space', {width: 3 / 18}));
|
|
1149
1405
|
continue;
|
|
1150
1406
|
}
|
|
1151
1407
|
if (token.kind === 'command') {
|
|
@@ -1160,14 +1416,26 @@ class MathTexParser {
|
|
|
1160
1416
|
spaced = false; subAllowed = true; continue;
|
|
1161
1417
|
}
|
|
1162
1418
|
if (token.value === '$') {
|
|
1163
|
-
children.push(this.nested(() => this.parseRow(item => item.kind === 'char' && item.value === '$')));
|
|
1419
|
+
children.push(this.node('style', {variant: 'normal', body: this.nested(() => this.parseRow(item => item.kind === 'char' && item.value === '$'))}));
|
|
1164
1420
|
this.expect('$'); spaced = false; subAllowed = false; continue;
|
|
1165
1421
|
}
|
|
1422
|
+
// mhchem's (^) and (v): a gas given off and a precipitate, with a thin space after.
|
|
1423
|
+
if (token.value === '(' && this.rawPeek(false).kind === 'char' && /^[\^v]$/.test(this.rawPeek(false).value)) {
|
|
1424
|
+
const mark = this.rawTake(false).value;
|
|
1425
|
+
if (this.rawPeek(false).value !== ')') this.error('unexpected-token', 'Expected ).', this.rawPeek(false));
|
|
1426
|
+
this.rawTake(false);
|
|
1427
|
+
children.push(this.literal(mark === '^' ? '↑' : '↓', {class: 'ord', variant: 'roman'}), this.node('space', {width: 3 / 18})); spaced = false; subAllowed = false; continue;
|
|
1428
|
+
}
|
|
1166
1429
|
if (token.value === '(' || token.value === '[') {
|
|
1430
|
+
// mhchem separates a lowercase state from its formula by 0.2 ex (Latin Modern's x height is 0.431 em).
|
|
1431
|
+
const before = children.at(-1)?.type === 'space' ? children.at(-2) : children.at(-1), first = this.rawPeek(false);
|
|
1432
|
+
if (token.value === '(' && before && !['bin', 'rel'].includes(before.class) && first.kind === 'char' && /^[a-z]$/.test(first.value))
|
|
1433
|
+
children.push(this.node('space', {width: .0862}));
|
|
1167
1434
|
const end = token.value === '(' ? ')' : ']';
|
|
1168
1435
|
const body = this.nested(() => this.chemicalRow(item => item.kind === 'char' && item.value === end));
|
|
1169
1436
|
this.expect(end);
|
|
1170
|
-
|
|
1437
|
+
// mhchem's brackets are plain opening and closing characters: an ordinary group, with no inner spacing.
|
|
1438
|
+
children.push(this.node('fence', {left: token.value, right: end, body, class: 'ord'}));
|
|
1171
1439
|
spaced = false; subAllowed = true; moleculeParts++; continue;
|
|
1172
1440
|
}
|
|
1173
1441
|
if (token.value === '{') {
|
|
@@ -1178,13 +1446,20 @@ class MathTexParser {
|
|
|
1178
1446
|
if (token.value === '^' || token.value === '_') {
|
|
1179
1447
|
const key = token.value === '^' ? 'sup' : 'sub';
|
|
1180
1448
|
if (token.value === '^' && (this.rawPeek(false).kind === 'space' || this.rawPeek(false).kind === 'eof')) {
|
|
1181
|
-
children.push(this.literal('↑', {class: 'ord', variant: 'roman'})); spaced = false; subAllowed = false; continue;
|
|
1449
|
+
children.push(this.literal('↑', {class: 'ord', variant: 'roman'}), this.node('space', {width: 3 / 18})); spaced = false; subAllowed = false; continue;
|
|
1182
1450
|
}
|
|
1183
1451
|
let body;
|
|
1184
|
-
if (this.is('{'))
|
|
1452
|
+
if (this.is('{')) {
|
|
1453
|
+
const tokens = this.rawArgument(), value = mathTexTokenText(tokens).trim(), math = tokens[0]?.value === '$' && tokens.at(-1)?.value === '$';
|
|
1454
|
+
body = /^[A-Za-z]{2,}$/.test(value) ? this.node('text', {value, variant: 'roman'}) : this.subparse(math ? tokens.slice(1, -1) : tokens);
|
|
1455
|
+
// Single-letter variables and their integer expressions are math; words and oxidation numerals stay upright.
|
|
1456
|
+
if (math || /^\d*[a-z](?:[+\-−]\d*)?$/.test(value)) body = this.node('style', {variant: 'normal', body});
|
|
1457
|
+
}
|
|
1185
1458
|
else {
|
|
1186
1459
|
const value = consumeRun(character => /^[0-9+\-−IVX]$/.test(character));
|
|
1460
|
+
const variable = this.rawPeek(false).kind === 'char' && /^[a-z]$/.test(this.rawPeek(false).value);
|
|
1187
1461
|
body = value ? this.node('text', {value: value.replace(/-/g, '−'), variant: 'roman'}) : this.argument();
|
|
1462
|
+
if (!value && variable) body = this.node('style', {variant: 'normal', body});
|
|
1188
1463
|
}
|
|
1189
1464
|
// Scripts that open a term are an isotope's mass and atomic numbers, set before the next element.
|
|
1190
1465
|
if (spaced) {
|
|
@@ -1195,24 +1470,44 @@ class MathTexParser {
|
|
|
1195
1470
|
script(key, body); spaced = false; continue;
|
|
1196
1471
|
}
|
|
1197
1472
|
if (/^[0-9]$/.test(token.value)) {
|
|
1198
|
-
|
|
1473
|
+
// A subscript count is whole: in CuSO4.5H2O the point is the addition dot.
|
|
1474
|
+
const number = token.value + consumeRun(character => subAllowed && !spaced ? /^[0-9]$/.test(character) : /^[0-9.]$/.test(character));
|
|
1475
|
+
// 1/2 opening a term is mhchem's text-style fraction.
|
|
1476
|
+
if (!(subAllowed && !spaced) && this.rawPeek(false).value === '/' && /^[0-9]$/.test(this.frames.at(-1)?.tokens[this.frames.at(-1).at + 1]?.value ?? '')) {
|
|
1477
|
+
this.rawTake(false);
|
|
1478
|
+
const denominator = consumeRun(character => /^[0-9]$/.test(character));
|
|
1479
|
+
children.push(this.node('frac', {num: this.node('text', {value: number, variant: 'roman'}), den: this.node('text', {value: denominator, variant: 'roman'}), bar: true, style: 'text'}));
|
|
1480
|
+
spaced = false; subAllowed = false; continue;
|
|
1481
|
+
}
|
|
1199
1482
|
if (subAllowed && !spaced) {
|
|
1200
1483
|
if (moleculeParts === 1 && ['+', '-'].includes(this.rawPeek(false).value)) {
|
|
1201
1484
|
const sign = this.rawTake(false).value;
|
|
1202
1485
|
script('sup', this.node('text', {value: number + (sign === '-' ? '−' : '+'), variant: 'roman'}));
|
|
1203
1486
|
} else script('sub', this.node('text', {value: number, variant: 'roman'}));
|
|
1204
|
-
} else
|
|
1487
|
+
} else {
|
|
1488
|
+
// A coefficient keeps a thin space before its formula.
|
|
1489
|
+
children.push(this.node('text', {value: number, variant: 'roman'}));
|
|
1490
|
+
if (this.rawPeek(false).kind === 'char' && /^[A-Z(\[]$/.test(this.rawPeek(false).value)) children.push(this.node('space', {width: 3 / 18}));
|
|
1491
|
+
}
|
|
1205
1492
|
spaced = false; continue;
|
|
1206
1493
|
}
|
|
1207
1494
|
if (token.value === '<' || token.value === '-' || token.value === '=') {
|
|
1208
1495
|
let arrow = token.value;
|
|
1209
1496
|
while (this.rawPeek(false).kind === 'char' && /^[<=>-]$/.test(this.rawPeek(false).value) && arrow.length < 5) arrow += this.rawTake(false).value;
|
|
1210
|
-
const arrows = {'->': '→', '<-': '←', '<->': '↔', '<=>': '⇌', '=>': '⇒', '<=': '⇐', '<<=>': '⇋', '<=>>': '⇌'};
|
|
1497
|
+
const arrows = {'->': '→', '<-': '←', '<->': '↔', '<-->': '⇄', '<=>': '⇌', '=>': '⇒', '<=': '⇐', '<<=>': '⇋', '<=>>': '⇌'};
|
|
1211
1498
|
if (arrows[arrow]) {
|
|
1212
1499
|
// Only an adjacent bracket labels the arrow; a peek that skips spaces would drop the next one.
|
|
1213
1500
|
const over = this.rawPeek(false).value === '[' ? this.optionalRaw() : null, under = over && this.rawPeek(false).value === '[' ? this.optionalRaw() : null;
|
|
1214
|
-
|
|
1215
|
-
|
|
1501
|
+
// mhchem's arrow is at least 2 em, with a thick space inside each end; <-> and <--> pad a label by 18 mu.
|
|
1502
|
+
const base = this.literal(arrows[arrow], {class: 'rel', variant: 'roman', stretch: true}), space = () => this.node('space', {width: 5 / 18});
|
|
1503
|
+
// A label in braces is text, with its word spaces; otherwise it is chemistry.
|
|
1504
|
+
const label = tokens => {
|
|
1505
|
+
if (!tokens?.some(item => item.kind !== 'space')) return null;
|
|
1506
|
+
const inner = tokens.filter(item => item.kind !== 'space');
|
|
1507
|
+
if (inner[0]?.value === '{' && inner.at(-1)?.value === '}' && tokens.indexOf(inner[0]) === 0 && mathTexBalanced(inner.slice(1, -1))) return this.subparse(tokens.slice(1, tokens.lastIndexOf(inner.at(-1))), true, 'roman');
|
|
1508
|
+
return this.chemistry(tokens);
|
|
1509
|
+
};
|
|
1510
|
+
children.push(space(), this.node('overunder', {base, over: label(over), under: label(under), class: 'rel', minWidth: 2, unspaced: true, ...(/^<--?>$/.test(arrow) ? {labelPad: 18} : {})}), space());
|
|
1216
1511
|
spaced = true; subAllowed = false; moleculeParts = 0; continue;
|
|
1217
1512
|
}
|
|
1218
1513
|
if (arrow.length !== 1) this.error('unsupported-reaction', 'Unsupported chemical reaction arrow: ' + arrow + '.', token);
|
|
@@ -1227,13 +1522,18 @@ class MathTexParser {
|
|
|
1227
1522
|
}
|
|
1228
1523
|
if (/^[A-Za-z]$/.test(token.value)) {
|
|
1229
1524
|
const word = token.value + consumeRun(character => /^[a-z]$/.test(character));
|
|
1230
|
-
|
|
1525
|
+
if (word === 'v' && spaced && !isotope) { children.push(this.literal('↓', {class: 'ord', variant: 'roman'}), this.node('space', {width: 3 / 18})); spaced = false; subAllowed = false; continue; }
|
|
1526
|
+
const element = this.node('text', {value: word, variant: 'roman'});
|
|
1231
1527
|
if (isotope) { isotope.base = this.node('phantom', {body: element, mode: 'v'}); isotope = null; }
|
|
1232
1528
|
children.push(element);
|
|
1233
1529
|
moleculeParts++; spaced = false; subAllowed = true; continue;
|
|
1234
1530
|
}
|
|
1235
1531
|
if (token.value === '#') children.push(this.literal('≡', {class: 'ord', variant: 'roman'}));
|
|
1236
|
-
|
|
1532
|
+
// mhchem's addition dot (. or *) has a thin space on each side and starts a new formula.
|
|
1533
|
+
else if (token.value === '.' || token.value === '·' || token.value === '*') {
|
|
1534
|
+
children.push(this.node('space', {width: 3 / 18}), this.literal('⋅', {class: 'ord', variant: 'roman'}), this.node('space', {width: 3 / 18}));
|
|
1535
|
+
spaced = true; subAllowed = false; moleculeParts = 0; continue;
|
|
1536
|
+
}
|
|
1237
1537
|
else if (token.value === '~') children.push(this.node('space', {width: 1 / 3}));
|
|
1238
1538
|
else children.push(this.literal(token.value, {variant: 'roman'}));
|
|
1239
1539
|
spaced = false;
|
|
@@ -1251,6 +1551,12 @@ class MathTexParser {
|
|
|
1251
1551
|
if (parts.length > 3) this.error('invalid-number', 'An angle has at most degrees, minutes and seconds.', token);
|
|
1252
1552
|
return this.row(parts.flatMap((part, i) => part.trim() ? [this.siNumber(mathTexTokens(part.trim(), token.offset)), this.literal('°′″'[i], {variant: 'roman'})] : []));
|
|
1253
1553
|
}
|
|
1554
|
+
// \numrange and \SIrange: "1 to 5", the unit after each number.
|
|
1555
|
+
if (/range$/.test(name)) {
|
|
1556
|
+
const from = this.siNumber(this.rawArgument()), to = this.siNumber(this.rawArgument()), word = {type: 'text', value: 'to', variant: 'roman'},
|
|
1557
|
+
unit = name === 'numrange' ? null : this.rawArgument(), quantity = value => unit ? [value, this.node('space', {width: 3 / 18}), this.siUnit(unit, token)] : [value];
|
|
1558
|
+
return this.row([...quantity(from), this.node('space', {width: 1 / 3}), this.node('text', word), this.node('space', {width: 1 / 3}), ...quantity(to)]);
|
|
1559
|
+
}
|
|
1254
1560
|
const value = this.siNumber(this.rawArgument()), before = this.optionalRaw();
|
|
1255
1561
|
return this.row([...(before ? [this.siUnit(before, token), this.node('space', {width: 3 / 18})] : []), value, this.node('space', {width: 3 / 18}), this.siUnit(this.rawArgument(), token)]);
|
|
1256
1562
|
}
|
|
@@ -1265,7 +1571,7 @@ class MathTexParser {
|
|
|
1265
1571
|
}
|
|
1266
1572
|
siUnit(tokens, token) {
|
|
1267
1573
|
const units = MATH_SI_UNITS, prefixes = MATH_SI_PREFIXES, items = [];
|
|
1268
|
-
if (!tokens.some(item => item.kind === 'command' && (Object.hasOwn(units, item.value) || Object.hasOwn(prefixes, item.value) || /^(per|square|cubic|squared|cubed|tothe|raiseto)$/.test(item.value))))
|
|
1574
|
+
if (!tokens.some(item => item.kind === 'command' && (Object.hasOwn(units, item.value) || Object.hasOwn(prefixes, item.value) || Object.hasOwn(MATH_SI_ABBREVIATIONS, item.value) || /^(per|square|cubic|squared|cubed|tothe|raiseto)$/.test(item.value))))
|
|
1269
1575
|
return this.node('style', {variant: 'roman', body: this.subparse(tokens.map(item => item.kind === 'char' && (item.value === '.' || item.value === '~') ? {...item, kind: 'command', value: ','} : item))});
|
|
1270
1576
|
let prefix = '', power = 1, per = false;
|
|
1271
1577
|
const number = at => { const group = tokens[at]?.value === '{' ? tokens.slice(at + 1, tokens.findIndex((item, i) => i > at && item.value === '}')) : [tokens[at]]; return [mathTexTokenText(group.filter(Boolean)).trim(), at + (group.length > 1 || tokens[at]?.value === '{' ? group.length + 1 : 0)]; };
|
|
@@ -1280,15 +1586,18 @@ class MathTexParser {
|
|
|
1280
1586
|
if (value === 'tothe' || value === 'raiseto') [exponent, at] = number(at + 1);
|
|
1281
1587
|
if (!/^-?\d+(\.\d+)?$/.test(exponent)) this.error('invalid-unit', 'A unit power must be a number.', item);
|
|
1282
1588
|
items.at(-1).power = exponent;
|
|
1283
|
-
} else if (item.kind === '
|
|
1284
|
-
|
|
1589
|
+
} else if (item.kind === 'char' && value === '/' && items.length) items.at(-1).slash = true;
|
|
1590
|
+
else if (item.kind === 'command' && (Object.hasOwn(units, value) || !prefix && Object.hasOwn(MATH_SI_ABBREVIATIONS, value)) || item.kind === 'char' && /^[A-Za-z]$/.test(value)) {
|
|
1591
|
+
items.push({symbol: prefix + (item.kind === 'command' ? units[value] ?? MATH_SI_ABBREVIATIONS[value] : value), power: String(power), per});
|
|
1285
1592
|
prefix = ''; power = 1; per = false;
|
|
1286
1593
|
} else this.error('invalid-unit', 'Unsupported unit: ' + mathTexTokenText([item]).trim() + '.', item);
|
|
1287
1594
|
}
|
|
1288
|
-
if (prefix || per || !items.length) this.error('invalid-unit', 'A unit prefix
|
|
1595
|
+
if (prefix || per || !items.length || items.at(-1).slash) this.error('invalid-unit', 'A unit prefix, \\per or / needs a unit.', token);
|
|
1596
|
+
// A unit after a written solidus follows it directly: m/s.
|
|
1289
1597
|
return this.row(items.flatMap((unit, i) => {
|
|
1290
1598
|
const exponent = (unit.per ? '−' : '') + unit.power.replace('-', '−'), base = this.node('text', {value: unit.symbol, variant: 'roman'});
|
|
1291
|
-
return [...(i ? [this.node('space', {width: 3 / 18})] : []), exponent === '1' ? base : this.node('scripts', {base, sup: this.node('text', {value: exponent, variant: 'roman'})})
|
|
1599
|
+
return [...(i && !items[i - 1].slash ? [this.node('space', {width: 3 / 18})] : []), exponent === '1' ? base : this.node('scripts', {base, sup: this.node('text', {value: exponent, variant: 'roman'})}),
|
|
1600
|
+
...(unit.slash ? [this.literal('/', {variant: 'roman'})] : [])];
|
|
1292
1601
|
}));
|
|
1293
1602
|
}
|
|
1294
1603
|
units(tokens) {
|
|
@@ -1316,7 +1625,7 @@ class MathTexParser {
|
|
|
1316
1625
|
let raw;
|
|
1317
1626
|
if (name === 'unicode') {
|
|
1318
1627
|
const metrics = this.optionalRaw(), font = this.optionalRaw();
|
|
1319
|
-
if (metrics || font) this.error('unsupported-character-option', 'Unicode characters use the embedded
|
|
1628
|
+
if (metrics || font) this.error('unsupported-character-option', 'Unicode characters use the embedded math font.', token);
|
|
1320
1629
|
raw = this.plainArgument();
|
|
1321
1630
|
} else if (this.is('{')) raw = this.plainArgument();
|
|
1322
1631
|
else {
|
|
@@ -1346,6 +1655,11 @@ function parseMathTexPreview(source, error, caret = source.length) {
|
|
|
1346
1655
|
caret = Math.max(0, Math.min(source.length, Math.floor(caret) || 0));
|
|
1347
1656
|
let text = source;
|
|
1348
1657
|
const tail = /(?<!\\)\\(?:[A-Za-z]*|(?:begin|end)\{[A-Za-z*]*)$/.exec(text.slice(0, caret));
|
|
1658
|
+
// A name being typed previews blank; a finished misspelling (no known name continues it) keeps its fix.
|
|
1659
|
+
if (tail && error?.code === 'unsupported-command' && error.offset === tail.index && /^\\[A-Za-z]+$/.test(tail[0])) {
|
|
1660
|
+
const name = tail[0].slice(1), suggestion = mathSuggest(name);
|
|
1661
|
+
if (suggestion && !mathTexNames.command.some(candidate => candidate.length > name.length && candidate.startsWith(name))) return null;
|
|
1662
|
+
}
|
|
1349
1663
|
if (tail) text = text.slice(0, tail.index) + ' '.repeat(tail[0].length) + text.slice(caret);
|
|
1350
1664
|
const atEnd = (cause, length) => /^unclosed-(group|option|environment)$/.test(cause.code) || cause.offset >= length;
|
|
1351
1665
|
for (let attempt = 0; attempt < 24; attempt++) {
|
|
@@ -1370,12 +1684,14 @@ function parseMathTexPreview(source, error, caret = source.length) {
|
|
|
1370
1684
|
|
|
1371
1685
|
// The command or environment a mistyped name most likely meant: one edit away (two for longer names), where swapping
|
|
1372
1686
|
// two neighbouring letters is one edit.
|
|
1373
|
-
const MATH_TEX_STRUCTURE = 'frac dfrac tfrac cfrac binom dbinom tbinom genfrac sqrt root left right middle big Big bigg Bigg bigl bigr Bigl Bigr begin end text textbf textit mathrm mathbf operatorname overset underset stackrel xrightarrow xleftarrow not phantom smash hspace quad qquad color textcolor colorbox boxed cancel newcommand renewcommand def ce pu SI si num unit ang dv pdv qty abs norm bra ket braket substack tag label href';
|
|
1687
|
+
const MATH_TEX_STRUCTURE = 'enclose multicolumn hdotsfor intertext frac dfrac tfrac cfrac binom dbinom tbinom genfrac sqrt root left right middle big Big bigg Bigg bigl bigr Bigl Bigr begin end text textbf textit mathrm mathbf operatorname overset underset stackrel buildrel xrightarrow xleftarrow not phantom smash hspace quad qquad color textcolor mathcolor colorbox boxed cancel newcommand renewcommand def ce pu SI si num unit ang SIrange numrange qtyrange dv pdv qty abs norm bra ket braket substack tag label href';
|
|
1688
|
+
// Every other command the parser accepts: a name being typed toward one of them is not a misspelling.
|
|
1689
|
+
const MATH_TEX_OTHER = 'TeX let char over LaTeX Set unicode bbox matrix pmatrix bmatrix Bmatrix vmatrix Vmatrix smallmatrix cases atop choose brace brack above overwithdelims atopwithdelims abovewithdelims limits nolimits displaylimits long strut operatornamewithlimits mathop stackbin overunderset xlongequal hphantom vphantom mathstrut rlap llap clap mathrlap mathllap mathclap mspace kern mkern hskip mskip rule raise raisebox lower fcolorbox definecolor fbox bcancel xcancel sout cancelto providecommand gdef edef xdef DeclareMathOperator DeclarePairedDelimiter global outer require url notag nonumber relax allowbreak nobreak protect displaystylelimits mathopen mathclose mathbin mathrel mathord mathinner mathpunct Bra Ket Braket set nicefrac sfrac vcenter prescript sideset accentset underaccent slashed mod bmod pmod pod smashoperator mathmakebox idotsint mmlToken textbackslash textasciitilde textasciicircum mathchoice verb';
|
|
1374
1690
|
let mathTexNames;
|
|
1375
1691
|
function mathSuggest(name, environment = false) {
|
|
1376
1692
|
if (typeof name !== 'string' || name.length < 2 || name.length > 32) return undefined;
|
|
1377
|
-
mathTexNames ||= {command: [...new Set([...MATH_TEX_STRUCTURE.split(' '), ...Object.keys(MATH_SYMBOLS), ...Object.keys(MATH_TEX_VARIANTS), ...Object.keys(MATH_TEX_TEXT_VARIANTS),
|
|
1378
|
-
...Object.keys(MATH_TEX_ACCENTS), ...MATH_NAMED_OPERATORS, ...MATH_LIMIT_OPERATORS, ...Object.keys(MATH_TEX_SPACES), ...Object.keys(MATH_TEX_LONG_ARROWS)])], environment: [...MATH_TEX_ENVIRONMENTS]};
|
|
1693
|
+
mathTexNames ||= {command: [...new Set([...MATH_TEX_STRUCTURE.split(' '), ...MATH_TEX_OTHER.split(' '), ...Object.keys(MATH_SYMBOLS), ...Object.keys(MATH_TEX_VARIANTS), ...Object.keys(MATH_TEX_TEXT_VARIANTS),
|
|
1694
|
+
...Object.keys(MATH_TEX_ACCENTS), ...Object.keys(MATH_TEX_DECLARATIONS), ...Object.keys(MATH_TEX_COLONS), ...MATH_TEX_PHYSICS, ...MATH_NAMED_OPERATORS, ...MATH_LIMIT_OPERATORS, ...Object.keys(MATH_TEX_SPACES), ...Object.keys(MATH_TEX_LONG_ARROWS)])], environment: [...MATH_TEX_ENVIRONMENTS]};
|
|
1379
1695
|
const limit = name.length > 5 ? 2 : 1;
|
|
1380
1696
|
let best, bestDistance = limit + 1;
|
|
1381
1697
|
for (const candidate of mathTexNames[environment ? 'environment' : 'command']) {
|
|
@@ -1392,4 +1708,4 @@ function mathSuggest(name, environment = false) {
|
|
|
1392
1708
|
}
|
|
1393
1709
|
|
|
1394
1710
|
import {MATH_SYMBOLS, MATH_NAMED_OPERATORS, MATH_LIMIT_OPERATORS} from './symbols.js';
|
|
1395
|
-
export {parseMathTex, parseMathTexPreview, mathSuggest};
|
|
1711
|
+
export {parseMathTex, parseMathTexPreview, mathSuggest, mathChoice, mathTableDelimiters};
|