rapier-math 2.4.0 → 2.6.1
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 +678 -229
- package/docs/api.md +6 -2
- package/docs/font-source.md +37 -29
- 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 +61 -65
- package/src/math/classic.js +1 -1
- package/src/math/font.js +23 -487
- package/src/math/layout.js +302 -112
- package/src/math/mathml.js +26 -7
- package/src/math/package-layout.mjs +1 -0
- package/src/math/package-readme.mjs +3 -4
- package/src/math/parser.js +306 -67
- package/src/tools/build-math.mjs +22 -7
- package/tests/adoption.mjs +0 -252
- package/tests/check.mjs +0 -133
- package/tests/semantics.mjs +0 -340
- package/tests/typeset.mjs +0 -172
- package/tests/verify.mjs +0 -49
package/src/math/parser.js
CHANGED
|
@@ -56,6 +56,21 @@ const MATH_TEX_TEXT_VARIANTS = Object.freeze({
|
|
|
56
56
|
textbf: 'bold', textit: 'italic', emph: 'italic', textsl: 'italic', textsf: 'sans-serif', texttt: 'monospace',
|
|
57
57
|
textsc: 'roman'
|
|
58
58
|
});
|
|
59
|
+
// LaTeX's text commands set series, shape and family independently: \textit inside \textbf is bold italic.
|
|
60
|
+
function mathTextVariant(outer, name) {
|
|
61
|
+
let family = /sans-serif/.test(outer) ? 'sans-serif' : outer === 'monospace' ? 'monospace' : 'roman', bold = /bold/.test(outer), italic = /italic/.test(outer);
|
|
62
|
+
if (name === 'textnormal') { family = 'roman'; bold = italic = false; }
|
|
63
|
+
else if (name === 'textbf') bold = true;
|
|
64
|
+
else if (name === 'textit' || name === 'textsl') italic = true;
|
|
65
|
+
else if (name === 'emph') italic = !italic;
|
|
66
|
+
else if (name === 'textup') italic = false;
|
|
67
|
+
else if (name === 'textrm') family = 'roman';
|
|
68
|
+
else if (name === 'textsf') family = 'sans-serif';
|
|
69
|
+
else if (name === 'texttt') family = 'monospace';
|
|
70
|
+
if (family === 'monospace') return 'monospace';
|
|
71
|
+
const style = (bold ? '-bold' : '') + (italic ? '-italic' : '');
|
|
72
|
+
return family === 'sans-serif' ? 'sans-serif' + style : style ? style.slice(1) : 'roman';
|
|
73
|
+
}
|
|
59
74
|
const MATH_TEX_TEXT_LETTERS = Object.freeze({ss: 'ß', ae: 'æ', AE: 'Æ', oe: 'œ', OE: 'Œ', o: 'ø', O: 'Ø', aa: 'å', AA: 'Å', l: 'ł', L: 'Ł', i: 'ı', j: 'ȷ'});
|
|
60
75
|
const MATH_TEX_DECLARATIONS = Object.freeze({
|
|
61
76
|
rm: {variant: 'roman'}, rmfamily: {variant: 'roman'}, normalfont: {variant: 'roman'},
|
|
@@ -81,7 +96,12 @@ const MATH_TEX_LONG_ARROWS = {iff: 'Longleftrightarrow', implies: 'Longrightarro
|
|
|
81
96
|
// mathtools: a colon or double colon joined to a relation, 1.2 mu apart.
|
|
82
97
|
const MATH_TEX_COLONS = {coloneq: '∶−', Coloneq: '∷−', Coloneqq: '∷=', Eqqcolon: '=∷', eqcolon: '−∶', Eqcolon: '−∷', colonapprox: '∶≈', Colonapprox: '∷≈', colonsim: '∶∼', Colonsim: '∷∼'};
|
|
83
98
|
// dvipsnames in CMYK percent (LaTeX graphics bundle), converted as xcolor does: each RGB channel is 1 − min(1, CMY + K).
|
|
84
|
-
|
|
99
|
+
// xcolor's base colors in RGB, for mixing.
|
|
100
|
+
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],
|
|
101
|
+
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],
|
|
102
|
+
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]})
|
|
103
|
+
.map(([name, rgb]) => [name, '#' + rgb.map(c => Math.round(c * 255).toString(16).padStart(2, '0')).join('')])));
|
|
104
|
+
const MATH_TEX_DVIPSNAMES = Object.create(null), MATH_TEX_DVIPS_CMYK = Object.create(null);
|
|
85
105
|
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
106
|
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
107
|
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,17 +112,24 @@ Blue 100 100 0 0 Cerulean 94 11 0 0 Cyan 100 0 0 0 ProcessBlue 96 0 0 0 SkyBlue
|
|
|
92
112
|
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
113
|
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
114
|
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('');
|
|
115
|
+
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
116
|
const MATH_TEX_SPACES = Object.freeze({
|
|
97
117
|
',': 3 / 18, ':': 4 / 18, ';': 5 / 18, '!': -3 / 18, ' ': 1 / 3,
|
|
98
118
|
quad: 1, qquad: 2, enspace: .5, enskip: .5, thinspace: 3 / 18, medspace: 4 / 18, thickspace: 5 / 18,
|
|
99
119
|
negthinspace: -3 / 18, negmedspace: -4 / 18, negthickspace: -5 / 18
|
|
100
120
|
});
|
|
101
121
|
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');
|
|
122
|
+
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');
|
|
123
|
+
// siunitx's abbreviated units (\km, \kHz, \uA...): prefix letters (u for micro) and a unit symbol.
|
|
124
|
+
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
|
|
125
|
+
,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 => {
|
|
126
|
+
const [prefixes, unit] = entry.split(':'), symbol = {ohm: 'Ω', l: 'L'}[unit] || unit;
|
|
127
|
+
return prefixes.split(',').map(prefix => [prefix + unit, (prefix === 'u' ? 'µ' : prefix) + symbol]);
|
|
128
|
+
}).filter(([name]) => name.length > 1 || /^[gmsAJLlVWNFHCTK]$/.test(name))));
|
|
103
129
|
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
130
|
const MATH_TEX_PACKAGES = new Set(('ams amsmath amssymb amsfonts mathtools color newcommand unicode mhchem physics siunitx bbm bboldx dsfont cancel bbox boldsymbol').split(' '));
|
|
105
131
|
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(' '));
|
|
132
|
+
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
133
|
const MATH_TEX_LITERAL_CLASSES = Object.freeze({
|
|
107
134
|
'+': 'bin', '−': 'bin', '-': 'bin', '±': 'bin', '∓': 'bin', '×': 'bin', '÷': 'bin', '*': 'bin', '⋅': 'bin',
|
|
108
135
|
'=': 'rel', '<': 'rel', '>': 'rel', '≤': 'rel', '≥': 'rel', '≠': 'rel', ':': 'rel',
|
|
@@ -113,6 +140,12 @@ const MATH_TEX_LITERAL_CLASSES = Object.freeze({
|
|
|
113
140
|
function mathTexTokenText(tokens) {
|
|
114
141
|
return tokens.map(token => token.kind === 'command' ? '\\' + token.value + (/^[A-Za-z@]+$/.test(token.value) ? ' ' : '') : token.value).join('');
|
|
115
142
|
}
|
|
143
|
+
// Whether braces in a token run pair up without closing below their start.
|
|
144
|
+
function mathTexBalanced(tokens) {
|
|
145
|
+
let depth = 0;
|
|
146
|
+
for (const token of tokens) if (token.kind === 'char') { depth += token.value === '{' ? 1 : token.value === '}' ? -1 : 0; if (depth < 0) return false; }
|
|
147
|
+
return depth === 0;
|
|
148
|
+
}
|
|
116
149
|
function mathTexTokenEqual(a, b) { return !!a && !!b && a.kind === b.kind && a.value === b.value; }
|
|
117
150
|
|
|
118
151
|
class MathTexParser {
|
|
@@ -200,7 +233,8 @@ class MathTexParser {
|
|
|
200
233
|
const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
|
|
201
234
|
// A declaration styles each following atom; the atoms keep their own classes and spacing.
|
|
202
235
|
const rest = this.nested(() => this.parseRow(stop, allowFraction));
|
|
203
|
-
|
|
236
|
+
// The first one notes where the declaration stood: TeX keeps no italic correction across it.
|
|
237
|
+
for (const [at, body] of (rest.type === 'row' ? rest.children : [rest]).entries()) children.push(this.node('style', {...fields, body, ...(at ? {} : {declaration: true})}));
|
|
204
238
|
break;
|
|
205
239
|
}
|
|
206
240
|
if (token.kind === 'command' && /^(over|atop|choose|brace|brack|above|overwithdelims|atopwithdelims|abovewithdelims)$/.test(token.value)) {
|
|
@@ -278,6 +312,8 @@ class MathTexParser {
|
|
|
278
312
|
this.take();
|
|
279
313
|
return this.nested(() => {
|
|
280
314
|
const body = this.parseRow(item => item.kind === 'char' && item.value === '}');
|
|
315
|
+
// An empty argument remembers the place inside its braces, so a tap can put the caret there.
|
|
316
|
+
if (body.type === 'row' && !body.children.length) body.at = token.offset + 1;
|
|
281
317
|
this.expect('}');
|
|
282
318
|
return body;
|
|
283
319
|
});
|
|
@@ -340,6 +376,8 @@ class MathTexParser {
|
|
|
340
376
|
return this.nested(() => {
|
|
341
377
|
const body = this.parseRow(item => item.kind === 'char' && item.value === '}');
|
|
342
378
|
this.expect('}');
|
|
379
|
+
// TeX makes a braced group in a formula one ordinary atom, whatever it holds: a{=}b has no relation spaces.
|
|
380
|
+
body.group = true;
|
|
343
381
|
return body;
|
|
344
382
|
});
|
|
345
383
|
}
|
|
@@ -374,6 +412,8 @@ class MathTexParser {
|
|
|
374
412
|
const centred = next.kind === 'char' ? '+-=<>*:'.includes(next.value) : !!after && (['bin', 'rel'].includes(after.class) || /^(?:int|iint|iiint|oint)$/.test(next.value));
|
|
375
413
|
if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
|
|
376
414
|
}
|
|
415
|
+
// amsmath's \colon: a colon 2 mu after the left side and 6 mu before the right, with no punctuation space.
|
|
416
|
+
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
417
|
if (Object.hasOwn(MATH_SYMBOLS, name)) return this.node('glyph', MATH_SYMBOLS[name]);
|
|
378
418
|
if (Object.hasOwn(MATH_TEX_VARIANTS, name)) {
|
|
379
419
|
let body = this.argument();
|
|
@@ -383,15 +423,19 @@ class MathTexParser {
|
|
|
383
423
|
}
|
|
384
424
|
if (Object.hasOwn(MATH_TEX_TEXT_VARIANTS, name)) return this.subparse(this.rawArgument(), true, MATH_TEX_TEXT_VARIANTS[name]);
|
|
385
425
|
if (MATH_NAMED_OPERATORS.has(name) || MATH_LIMIT_OPERATORS.has(name)) {
|
|
386
|
-
const values = {limsup: 'lim
|
|
426
|
+
const values = {limsup: 'lim\u2009sup', liminf: 'lim\u2009inf', injlim: 'inj\u2009lim', projlim: 'proj\u2009lim', varlimsup: 'lim', varliminf: 'lim', varinjlim: 'lim', varprojlim: 'lim'};
|
|
387
427
|
let body = this.node('text', {value: values[name] || name, class: 'op', limits: MATH_LIMIT_OPERATORS.has(name) ? 'display' : 'never', variant: 'roman'});
|
|
388
|
-
|
|
389
|
-
if (
|
|
428
|
+
// amsmath's \injlim and \projlim are the words inj lim and proj lim; the var forms draw an arrow under lim.
|
|
429
|
+
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});
|
|
430
|
+
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
431
|
return body;
|
|
391
432
|
}
|
|
392
433
|
if (Object.hasOwn(MATH_TEX_ACCENTS, name)) {
|
|
393
434
|
const [value, position, stretch] = MATH_TEX_ACCENTS[name];
|
|
394
|
-
|
|
435
|
+
// mathtools' \overbracket[rule][height]{...}: the font's bracket keeps its own rule and height.
|
|
436
|
+
if (/bracket$/.test(name) && this.optionalRaw()) this.optionalRaw();
|
|
437
|
+
// TeX's braces, parentheses and brackets over or under a formula are operators with limits.
|
|
438
|
+
return this.node('accent', {base: this.argument(), value, position, stretch, ...(/(brace|paren|bracket)$/.test(name) ? {limits: 'always'} : {})});
|
|
395
439
|
}
|
|
396
440
|
if (/^[{}%$&#_]$/.test(name)) return this.literal(name, {variant: 'roman'});
|
|
397
441
|
if (name === '|') return this.literal('‖', {variant: 'roman'});
|
|
@@ -440,10 +484,22 @@ class MathTexParser {
|
|
|
440
484
|
if (/^(matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases|smallmatrix)$/.test(name)) return this.tableFromTokens(this.rawArgument(), name);
|
|
441
485
|
if (name === 'operatorname' || name === 'operatornamewithlimits') {
|
|
442
486
|
const starred = name !== 'operatorname' || this.is('*'); if (starred && name === 'operatorname') this.take();
|
|
443
|
-
|
|
487
|
+
// The name is set in math mode, where TeX ignores spaces: \operatorname{arg max} is argmax.
|
|
488
|
+
const body = this.subparse(this.rawArgument().filter(token => token.kind !== 'space'), true, 'roman');
|
|
444
489
|
return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
|
|
445
490
|
}
|
|
446
491
|
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'} : {})});
|
|
492
|
+
// Plain TeX's \buildrel top \over relation is \stackrel{top}{relation}.
|
|
493
|
+
if (name === 'buildrel') {
|
|
494
|
+
const top = [];
|
|
495
|
+
for (let depth = 0, item = this.rawTake(false); !(depth === 0 && item.kind === 'command' && item.value === 'over'); item = this.rawTake(false)) {
|
|
496
|
+
if (item.kind === 'eof') this.error('missing-argument', '\\buildrel needs \\over.', token);
|
|
497
|
+
if (item.kind === 'char' && item.value === '{') depth++;
|
|
498
|
+
if (item.kind === 'char' && item.value === '}') depth--;
|
|
499
|
+
top.push(item);
|
|
500
|
+
}
|
|
501
|
+
return this.node('overunder', {base: this.argument(), over: this.subparse(top), class: 'rel'});
|
|
502
|
+
}
|
|
447
503
|
if (name === 'overset' || name === 'underset' || name === 'stackrel' || name === 'stackbin') {
|
|
448
504
|
const decoration = this.argument(), base = this.argument();
|
|
449
505
|
return this.node('overunder', {base, [name === 'underset' ? 'under' : 'over']: decoration, ...(name === 'stackrel' ? {class: 'rel'} : name === 'stackbin' ? {class: 'bin'} : {})});
|
|
@@ -451,7 +507,7 @@ class MathTexParser {
|
|
|
451
507
|
if (name === 'overunderset') { const over = this.argument(), under = this.argument(); return this.node('overunder', {base: this.argument(), over, under}); }
|
|
452
508
|
if (/^x(leftarrow|rightarrow|leftrightarrow|Leftarrow|Rightarrow|Leftrightarrow|mapsto|hookleftarrow|hookrightarrow|leftharpoonup|leftharpoondown|rightharpoonup|rightharpoondown|rightleftharpoons|leftrightharpoons|twoheadleftarrow|twoheadrightarrow|longequal)$/.test(name)) {
|
|
453
509
|
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'});
|
|
510
|
+
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
511
|
}
|
|
456
512
|
if (name === 'not') {
|
|
457
513
|
const base = this.argument(), negated = {'=': '≠', '<': '≮', '>': '≯', '≤': '≰', '≥': '≱', '∈': '∉', '∋': '∌', '⊂': '⊄', '⊃': '⊅', '⊆': '⊈', '⊇': '⊉', '∣': '∤', '∥': '∦', '∼': '≁', '≈': '≉', '≡': '≢', '→': '↛', '←': '↚', '↔': '↮', '⇒': '⇏', '⇐': '⇍', '⇔': '⇎'};
|
|
@@ -482,14 +538,14 @@ class MathTexParser {
|
|
|
482
538
|
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
539
|
}
|
|
484
540
|
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}); }
|
|
541
|
+
if (name === 'textcolor' || name === 'mathcolor') { const color = this.readColor(); return this.node('style', {body: this.argument(), color}); }
|
|
486
542
|
if (name === 'colorbox' || name === 'fcolorbox') {
|
|
487
543
|
const border = name === 'fcolorbox' ? this.readColor() : undefined, background = this.readColor();
|
|
488
544
|
return this.node('style', {body: this.subparse(this.rawArgument(), true, 'roman'), background, ...(border ? {border} : {})});
|
|
489
545
|
}
|
|
490
546
|
if (name === 'definecolor') {
|
|
491
547
|
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
|
|
548
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(colorName)) this.error('invalid-color', 'Invalid color name.', token);
|
|
493
549
|
this.colors[colorName] = this.color(value, model, token); return null;
|
|
494
550
|
}
|
|
495
551
|
// MathJax's bbox: a background colour, a padding length and a CSS border whose last word is its colour.
|
|
@@ -503,6 +559,20 @@ class MathTexParser {
|
|
|
503
559
|
}
|
|
504
560
|
return this.node('style', {body: this.argument(), ...fields});
|
|
505
561
|
}
|
|
562
|
+
if (name === 'intertext' || name === 'multicolumn' || name === 'hdotsfor')
|
|
563
|
+
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);
|
|
564
|
+
// MathJax's \enclose{notation}[attributes]{body}: MathML's menclose notations, with mathcolor and mathbackground.
|
|
565
|
+
if (name === 'enclose') {
|
|
566
|
+
const notation = this.plainArgument().split(/[\s,]+/).filter(Boolean), options = this.optionalRaw();
|
|
567
|
+
if (!notation.length) this.error('missing-argument', '\\enclose needs a notation.', token);
|
|
568
|
+
for (const item of notation) if (!MATH_ENCLOSE_NOTATIONS.has(item)) this.error('unsupported-notation', 'Unsupported enclose notation: ' + item + '.', token);
|
|
569
|
+
const fields = {};
|
|
570
|
+
for (const pair of options ? mathTexTokenText(options).split(',') : []) {
|
|
571
|
+
const [key, value = ''] = pair.split('=').map(part => part.trim());
|
|
572
|
+
if (key === 'mathcolor' || key === 'mathbackground') fields[key === 'mathcolor' ? 'color' : 'background'] = this.color(value, '', token);
|
|
573
|
+
}
|
|
574
|
+
return this.node('enclose', {notation: [...new Set(notation)], body: this.argument(), ...fields});
|
|
575
|
+
}
|
|
506
576
|
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
577
|
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
578
|
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 +586,7 @@ class MathTexParser {
|
|
|
516
586
|
}
|
|
517
587
|
if (name === 'require') {
|
|
518
588
|
const value = this.plainArgument();
|
|
519
|
-
if (!MATH_TEX_PACKAGES.has(value)) this.error('unsupported-package', 'Unsupported
|
|
589
|
+
if (!MATH_TEX_PACKAGES.has(value)) this.error('unsupported-package', 'Unsupported math package: ' + value + '.', token, name);
|
|
520
590
|
return null;
|
|
521
591
|
}
|
|
522
592
|
if (name === 'href') {
|
|
@@ -553,14 +623,17 @@ class MathTexParser {
|
|
|
553
623
|
const raw = this.rawArgument(), delimiter = value => value === '|' ? make('|', 'char') : make(value);
|
|
554
624
|
let divided = false;
|
|
555
625
|
for (let i = 0; i < raw.length; i++) {
|
|
556
|
-
|
|
626
|
+
// braket.sty reads || and \| as one double bar.
|
|
627
|
+
const item = raw[i], command = name !== 'set' && item.kind === 'command' && item.value === '|', bar = command || item.kind === 'char' && item.value === '|',
|
|
628
|
+
double = command || bar && raw[i + 1]?.kind === 'char' && raw[i + 1].value === '|';
|
|
557
629
|
if (!bar || divided || (name !== 'Braket' && name !== 'Set' && name !== 'set')) { body.push(item); continue; }
|
|
558
|
-
if (double) i++;
|
|
630
|
+
if (double && !command) i++;
|
|
559
631
|
divided = name !== 'Braket';
|
|
560
632
|
body.push(...(name === 'set' ? [make('mid')] : [make(name === 'Set' ? ';' : ','), make('middle'), double ? make('|') : make('|', 'char'), make(name === 'Set' ? ';' : ',')]));
|
|
561
633
|
}
|
|
562
634
|
if (name === 'set') return this.subparse([make('{'), make(','), ...body, make(','), make('}')]);
|
|
563
|
-
|
|
635
|
+
// braket.sty pads \Set with a medium space inside its braces.
|
|
636
|
+
return this.subparse([make('left'), delimiter(left), ...(name === 'Set' ? [make(':')] : []), ...body, ...(name === 'Set' ? [make(':')] : []), make('right'), delimiter(right)]);
|
|
564
637
|
}
|
|
565
638
|
// units' \nicefrac (and xfrac's \sfrac): a script numerator raised 0.5 ex, a solidus, a script denominator lowered 0.25 ex.
|
|
566
639
|
if (name === 'nicefrac' || name === 'sfrac') {
|
|
@@ -589,14 +662,14 @@ class MathTexParser {
|
|
|
589
662
|
return this.node('accent', {base: this.argument(), value, position: name === 'accentset' ? 'over' : 'under', stretch});
|
|
590
663
|
}
|
|
591
664
|
const decoration = this.subparse(mark);
|
|
592
|
-
return this.node('overunder', {base: this.argument(), [name === 'accentset' ? 'over' : 'under']: decoration});
|
|
665
|
+
return this.node('overunder', {base: this.argument(), [name === 'accentset' ? 'over' : 'under']: decoration, accentGap: true});
|
|
593
666
|
}
|
|
594
667
|
if (name === 'slashed') return this.node('accent', {base: this.argument(), value: '/', position: 'through'});
|
|
595
668
|
if (name === 'mod' || name === 'bmod') return this.row([this.node('space', {width: name === 'bmod' ? 5 / 18 : 1}), this.node('text', {value: 'mod', variant: 'roman', class: name === 'bmod' ? 'bin' : 'op'}), this.node('space', {width: name === 'bmod' ? 5 / 18 : 1 / 3})]);
|
|
596
669
|
if (name === 'pmod' || name === 'pod') return this.row([this.node('space', {width: 1}), this.node('fence', {left: '(', right: ')', body: this.row([...(name === 'pmod' ? [this.node('text', {value: 'mod', variant: 'roman'}), this.node('space', {width: 1 / 3})] : []), this.argument()])})]);
|
|
597
670
|
if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
|
|
598
671
|
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'};
|
|
672
|
+
if (/^(SI|si|num|unit|ang|SIrange|numrange|qtyrange)$/.test(name)) return {...this.siunitx(name, token), semanticRole: 'units'};
|
|
600
673
|
// mathtools \smashoperator[lr]{op}: the limits overhang the operator's own width on the named sides.
|
|
601
674
|
if (name === 'smashoperator') {
|
|
602
675
|
const sides = mathTexTokenText(this.optionalRaw() || []).trim() || 'lr';
|
|
@@ -622,7 +695,7 @@ class MathTexParser {
|
|
|
622
695
|
if (name === 'textasciitilde') return this.literal('~', {variant: 'roman'});
|
|
623
696
|
if (name === 'textasciicircum') return this.literal('^', {variant: 'roman'});
|
|
624
697
|
if (['end', 'right', '\\', 'cr', 'of'].includes(name)) this.error('unexpected-command', '\\' + name + ' has no matching opening command.', token);
|
|
625
|
-
this.error('unsupported-command', 'Unsupported
|
|
698
|
+
this.error('unsupported-command', 'Unsupported math command: \\' + name + '.', token);
|
|
626
699
|
}
|
|
627
700
|
|
|
628
701
|
delimiterArgument() {
|
|
@@ -639,7 +712,7 @@ class MathTexParser {
|
|
|
639
712
|
this.error('unsafe-link', 'A link address cannot contain TeX commands.', item);
|
|
640
713
|
}).join('').trim();
|
|
641
714
|
if (!/^https?:\/\/[^\s<>"'\\]+$/i.test(href) || /[\u0000-\u0020\u007f]/.test(href))
|
|
642
|
-
this.error('unsafe-link', 'A
|
|
715
|
+
this.error('unsafe-link', 'A math link must use an HTTP or HTTPS address.', token);
|
|
643
716
|
return href;
|
|
644
717
|
}
|
|
645
718
|
dimension(value, token = this.rawPeek()) {
|
|
@@ -663,6 +736,30 @@ class MathTexParser {
|
|
|
663
736
|
return this.color(this.plainArgument(), model ? mathTexTokenText(model).trim() : '', this.rawPeek());
|
|
664
737
|
}
|
|
665
738
|
color(value, model, token) {
|
|
739
|
+
// xcolor's mixes: red!30 is 30% red in white; red!30!blue is 30% red in blue, and so on along the expression.
|
|
740
|
+
if (!model && value.includes('!')) {
|
|
741
|
+
const parts = value.split('!'), rgb = name => {
|
|
742
|
+
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);
|
|
743
|
+
if (!hex || !/^#[a-fA-F0-9]{6}$/.test(hex)) this.error('invalid-color', 'Unsupported or invalid color value.', token, 'color');
|
|
744
|
+
return [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255);
|
|
745
|
+
};
|
|
746
|
+
// xcolor mixes in the first color's model: a dvipsnames color mixes in CMYK, with RGB as 1 - x less its black.
|
|
747
|
+
const cmyk = !Object.hasOwn(this.colors, parts[0].trim()) && MATH_TEX_DVIPS_CMYK[parts[0].trim()], channels = name => {
|
|
748
|
+
if (!cmyk) return rgb(name);
|
|
749
|
+
if (!Object.hasOwn(this.colors, name) && MATH_TEX_DVIPS_CMYK[name]) return MATH_TEX_DVIPS_CMYK[name];
|
|
750
|
+
const [c, m, y] = rgb(name).map(channel => 1 - channel), k = Math.min(c, m, y);
|
|
751
|
+
return [c - k, m - k, y - k, k];
|
|
752
|
+
};
|
|
753
|
+
let mixed = channels(parts[0].trim());
|
|
754
|
+
for (let i = 1; i < parts.length; i += 2) {
|
|
755
|
+
const percent = Number(parts[i]);
|
|
756
|
+
if (!/^\s*\d+(?:\.\d+)?\s*$/.test(parts[i]) || percent > 100) this.error('invalid-color', 'Unsupported or invalid color value.', token, 'color');
|
|
757
|
+
const other = i + 1 < parts.length ? channels(parts[i + 1].trim()) : cmyk ? [0, 0, 0, 0] : [1, 1, 1];
|
|
758
|
+
mixed = mixed.map((channel, k) => channel * percent / 100 + other[k] * (1 - percent / 100));
|
|
759
|
+
}
|
|
760
|
+
if (cmyk) mixed = mixed.slice(0, 3).map(channel => 1 - Math.min(1, channel + mixed[3]));
|
|
761
|
+
return '#' + mixed.map(channel => Math.round(channel * 255).toString(16).padStart(2, '0')).join('');
|
|
762
|
+
}
|
|
666
763
|
if (!model) {
|
|
667
764
|
if (Object.hasOwn(this.colors, value)) return this.colors[value];
|
|
668
765
|
if (MATH_TEX_DVIPSNAMES[value]) return MATH_TEX_DVIPSNAMES[value];
|
|
@@ -677,12 +774,12 @@ class MathTexParser {
|
|
|
677
774
|
return '#' + rgb.map(number => Math.round(number * (model === 'RGB' ? 1 : 255)).toString(16).padStart(2, '0')).join('');
|
|
678
775
|
}
|
|
679
776
|
}
|
|
680
|
-
this.error('invalid-color', 'Unsupported or invalid
|
|
777
|
+
this.error('invalid-color', 'Unsupported or invalid color value.', token, 'color');
|
|
681
778
|
}
|
|
682
779
|
|
|
683
780
|
environment(fullName, token) {
|
|
684
781
|
const env = fullName.replace(/\*$/, '');
|
|
685
|
-
if (!MATH_TEX_ENVIRONMENTS.has(env)) throw Object.assign(new MathTexError('unsupported-environment', 'Unsupported
|
|
782
|
+
if (!MATH_TEX_ENVIRONMENTS.has(env)) throw Object.assign(new MathTexError('unsupported-environment', 'Unsupported math environment: ' + fullName + '.', token.offset, 'begin'), {environment: env});
|
|
686
783
|
return this.nested(() => {
|
|
687
784
|
let options = {};
|
|
688
785
|
const position = this.optionalRaw();
|
|
@@ -708,15 +805,18 @@ class MathTexParser {
|
|
|
708
805
|
}
|
|
709
806
|
// amscd: rows of objects joined by @>>>, @<<< and @= arrows, between rows of @VVV, @AAA, @| and @. arrows.
|
|
710
807
|
commutativeDiagram(fullName, token) {
|
|
711
|
-
const rows = []
|
|
808
|
+
const rows = [];
|
|
712
809
|
let cells = [], current = [];
|
|
713
810
|
const arrow = (kind, labels) => {
|
|
714
811
|
const label = tokens => tokens.length ? this.subparse(tokens) : null;
|
|
715
|
-
if (kind === '>' || kind === '<' || kind === '=')
|
|
716
|
-
|
|
812
|
+
if (kind === '>' || kind === '<' || kind === '=') {
|
|
813
|
+
const body = this.node('overunder', {base: this.literal(kind === '>' ? '→' : kind === '<' ? '←' : '=', {class: 'rel', stretch: true}),
|
|
814
|
+
...(kind !== '=' ? {over: label(labels[0]) || this.row([])} : {}), ...(labels[1]?.length ? {under: label(labels[1])} : {}), class: 'rel', minWidth: 3, labelPad: 15, diagram: true});
|
|
815
|
+
return this.row([this.node('space', {width: 0.5}), body, this.node('space', {width: 0.5})]);
|
|
816
|
+
}
|
|
717
817
|
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:
|
|
818
|
+
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)})})})] : [];
|
|
819
|
+
return this.row([...side(labels[0], 'right'), this.literal(kind === 'V' ? '↓' : kind === 'A' ? '↑' : '‖', {delimiterSize: 1.8, class: 'ord'}), ...side(labels[1], 'left')]);
|
|
720
820
|
};
|
|
721
821
|
for (;;) {
|
|
722
822
|
const item = this.rawTake(false);
|
|
@@ -760,11 +860,12 @@ class MathTexParser {
|
|
|
760
860
|
}
|
|
761
861
|
columnSpec(tokens, token) {
|
|
762
862
|
const parser = new MathTexParser(this.source, {tokens, scopes: this.scopes, budget: this.budget, colors: this.colors});
|
|
763
|
-
|
|
863
|
+
// arydshln's : is a dashed rule; columnDashes marks which rules are dashed.
|
|
864
|
+
const align = [], columnRules = [], columnInsertions = [], columnDashes = [];
|
|
764
865
|
while (parser.peek().kind !== 'eof') {
|
|
765
866
|
const item = parser.take();
|
|
766
867
|
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); }
|
|
868
|
+
else if (item.kind === 'char' && (item.value === '|' || item.value === ':')) { this.reserveParts(1, item); columnRules.push(align.length); columnDashes.push(item.value === ':'); }
|
|
768
869
|
else if (item.kind === 'char' && (item.value === '@' || item.value === '!')) {
|
|
769
870
|
this.reserveParts(1, item);
|
|
770
871
|
columnInsertions.push({before: align.length, body: this.subparse(parser.rawArgument()), replaceGap: item.value === '@'});
|
|
@@ -779,7 +880,7 @@ class MathTexParser {
|
|
|
779
880
|
this.reserveParts(Number(count) * (repeated.align.length + repeated.columnRules.length + repeated.columnInsertions.length), item);
|
|
780
881
|
for (let i = 0; i < Number(count); i++) {
|
|
781
882
|
const at = align.length;
|
|
782
|
-
columnRules.push(...repeated.columnRules.map(index => at + index));
|
|
883
|
+
columnRules.push(...repeated.columnRules.map(index => at + index)); columnDashes.push(...(repeated.columnDashes || repeated.columnRules.map(() => false)));
|
|
783
884
|
columnInsertions.push(...repeated.columnInsertions.map(insertion => ({...insertion, before: at + insertion.before})));
|
|
784
885
|
align.push(...repeated.align);
|
|
785
886
|
}
|
|
@@ -787,7 +888,7 @@ class MathTexParser {
|
|
|
787
888
|
if (align.length > 256) this.error('resource-limit', 'This array has too many columns to render safely.', token);
|
|
788
889
|
}
|
|
789
890
|
if (!align.length) this.error('invalid-alignment', 'An array needs a column specification.', token);
|
|
790
|
-
return {align, columnRules, columnInsertions};
|
|
891
|
+
return {align, columnRules, columnInsertions, ...(columnDashes.some(Boolean) ? {columnDashes} : {})};
|
|
791
892
|
}
|
|
792
893
|
// mathtools' starred cases set their condition column as text, with $...$ for maths.
|
|
793
894
|
textCell(separator) {
|
|
@@ -818,7 +919,34 @@ class MathTexParser {
|
|
|
818
919
|
if (cells.length || (!rows.length && !endedAfterBreak)) { cells.push(this.row([])); rows.push(cells); }
|
|
819
920
|
break;
|
|
820
921
|
}
|
|
821
|
-
|
|
922
|
+
// amsmath's \intertext is a line of text between the rows of an alignment, set at its left.
|
|
923
|
+
if (this.commandIs('intertext')) {
|
|
924
|
+
const at = this.take();
|
|
925
|
+
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);
|
|
926
|
+
rows.push([this.node('row', {children: [this.subparse(this.rawArgument(), true)], intertext: true})]);
|
|
927
|
+
// It sits a display skip (10 pt, 1 em with the row's \jot) from the rows around it.
|
|
928
|
+
if (rows.length > 1) rowGaps[rows.length - 2] = (rowGaps[rows.length - 2] || 0) + 0.7;
|
|
929
|
+
rowGaps[rows.length - 1] = 0.7;
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
// \multicolumn{n}{spec}{body} and amsmath's \hdotsfor[spacing]{n} fill n columns of one row.
|
|
933
|
+
if (this.commandIs('multicolumn') || this.commandIs('hdotsfor')) {
|
|
934
|
+
const at = this.take(), dots = at.value === 'hdotsfor', spacing = dots ? this.optionalRaw() : null, count = this.plainArgument();
|
|
935
|
+
if (!/^\d+$/.test(count) || +count < 1 || cells.length + +count > 256) this.error('invalid-alignment', '\\' + at.value + ' needs a column count.', at);
|
|
936
|
+
let cell;
|
|
937
|
+
if (dots) {
|
|
938
|
+
const factor = spacing ? Number(mathTexTokenText(spacing).trim()) : 1;
|
|
939
|
+
if (!(factor > 0 && factor <= 16)) this.error('invalid-option', '\\hdotsfor spacing must be a positive number.', at);
|
|
940
|
+
cell = this.node('row', {children: [], span: +count, dots: factor});
|
|
941
|
+
} else {
|
|
942
|
+
const spec = this.columnSpec(this.rawArgument(), at);
|
|
943
|
+
if (spec.align.length !== 1) this.error('invalid-alignment', '\\multicolumn takes one column.', at);
|
|
944
|
+
cell = this.node('row', {children: [this.argument()], span: +count, spanAlign: spec.align[0], ...(spec.columnRules.length ? {spanRules: spec.columnRules} : {})});
|
|
945
|
+
}
|
|
946
|
+
if (!separator(this.peek())) this.error('unexpected-token', 'A \\' + at.value + ' fills its whole cell.', this.peek());
|
|
947
|
+
cells.push(cell);
|
|
948
|
+
for (let i = 1; i < +count; i++) cells.push(this.node('row', {children: [], covered: true}));
|
|
949
|
+
} else cells.push(cells.length === textColumn ? this.textCell(separator) : this.nested(() => this.parseRow(separator)));
|
|
822
950
|
endedAfterBreak = false;
|
|
823
951
|
const next = this.peek();
|
|
824
952
|
if (next.kind === 'char' && next.value === '&') { this.take(); continue; }
|
|
@@ -1004,7 +1132,7 @@ class MathTexParser {
|
|
|
1004
1132
|
continue;
|
|
1005
1133
|
}
|
|
1006
1134
|
if (Object.hasOwn(MATH_TEX_TEXT_VARIANTS, name)) {
|
|
1007
|
-
flush(); children.push(this.subparse(this.rawArgument(), true,
|
|
1135
|
+
flush(); children.push(this.subparse(this.rawArgument(), true, mathTextVariant(variant, name))); continue;
|
|
1008
1136
|
}
|
|
1009
1137
|
if (name === 'color' || name === 'textcolor') {
|
|
1010
1138
|
flush();
|
|
@@ -1052,7 +1180,7 @@ class MathTexParser {
|
|
|
1052
1180
|
}
|
|
1053
1181
|
|
|
1054
1182
|
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);
|
|
1183
|
+
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|Bmqty|Pmqty|vmqty|smqty|dmat|diagonalmatrix|admat|antidiagonalmatrix|imat|identitymatrix|zmat|zeromatrix|xmat|xmatrix|pmat|paulimatrix|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
1184
|
}
|
|
1057
1185
|
physics(name, token) {
|
|
1058
1186
|
const starred = this.is('*'); if (starred) this.take();
|
|
@@ -1080,6 +1208,14 @@ class MathTexParser {
|
|
|
1080
1208
|
return this.row([base, ...(/^(divergence|curl)$/.test(name) ? [this.literal(name === 'curl' ? '×' : '⋅', {class: 'bin', variant: 'roman'})] : []), ...(this.is('{') ? [this.argument()] : [])]);
|
|
1081
1209
|
}
|
|
1082
1210
|
if (['Tr', 'tr', 'trace', 'rank', 'diag', 'Res'].includes(name)) return this.node('text', {value: name === 'trace' ? 'tr' : name, variant: 'roman', class: 'op', limits: 'never'});
|
|
1211
|
+
if (name === 'qty' || name === 'quantity') {
|
|
1212
|
+
if (this.is('{')) return this.node('fence', {left: '{', right: '}', body: this.argument()});
|
|
1213
|
+
const left = this.readDelimiter(), right = {'(': ')', '[': ']', '{': '}', '|': '|', '‖': '‖', '⟨': '⟩'}[left];
|
|
1214
|
+
if (!right) this.error('invalid-delimiter', 'A quantity needs paired delimiters.', token);
|
|
1215
|
+
const body = this.nested(() => this.parseRow(item => item.kind === 'char' && item.value === right));
|
|
1216
|
+
this.expect(right);
|
|
1217
|
+
return this.node('fence', {left, right, body});
|
|
1218
|
+
}
|
|
1083
1219
|
// \qq{text} and the \qif family: text between quads; \qc is a comma and a quad.
|
|
1084
1220
|
if (/^q/.test(name)) {
|
|
1085
1221
|
const quad = () => this.node('space', {width: 1}), words = {qcc: 'c.c.'};
|
|
@@ -1088,17 +1224,57 @@ class MathTexParser {
|
|
|
1088
1224
|
}
|
|
1089
1225
|
if (name === 'eval' || name === 'evaluated') return this.node('fence', {left: '', right: '|', body: this.argument()});
|
|
1090
1226
|
if (name === 'order') return this.row([this.literal('O'), this.node('fence', {left: '(', right: ')', body: this.argument()})]);
|
|
1091
|
-
|
|
1092
|
-
|
|
1227
|
+
// \mqty(…), \mqty[…] and \mqty|…| choose their brackets as physics.sty does.
|
|
1228
|
+
if (name === 'mqty' && ['(', '[', '|'].includes(this.rawPeek().value) && this.rawPeek().kind === 'char') {
|
|
1229
|
+
const open = this.rawTake().value, close = {'(': ')', '[': ']', '|': '|'}[open], tokens = [];
|
|
1230
|
+
for (let depth = 0, token = this.rawTake(false); ; token = this.rawTake(false)) {
|
|
1231
|
+
if (token.kind === 'eof') this.error('unclosed-group', 'Expected ' + close + '.', token);
|
|
1232
|
+
if (token.kind === 'char' && token.value === '{') depth++;
|
|
1233
|
+
if (token.kind === 'char' && token.value === '}') depth--;
|
|
1234
|
+
if (!depth && token.kind === 'char' && token.value === close) break;
|
|
1235
|
+
tokens.push(token);
|
|
1236
|
+
}
|
|
1237
|
+
return this.tableFromTokens(tokens, {'(': 'pmatrix', '[': 'bmatrix', '|': 'vmatrix'}[open]);
|
|
1238
|
+
}
|
|
1239
|
+
if (/^(mqty|pmqty|bmqty|Bmqty|vmqty|smqty)$/.test(name)) {
|
|
1240
|
+
const env = name === 'bmqty' ? 'bmatrix' : name === 'Bmqty' ? 'Bmatrix' : name === 'vmqty' ? 'vmatrix' : name === 'smqty' ? 'smallmatrix' : name === 'pmqty' ? 'pmatrix' : 'matrix';
|
|
1093
1241
|
return this.tableFromTokens(this.rawArgument(), env);
|
|
1094
1242
|
}
|
|
1095
|
-
if (name === '
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
const
|
|
1100
|
-
|
|
1101
|
-
|
|
1243
|
+
if (name === 'Pmqty') return this.node('fence', {left: '⟮', right: '⟯', body: this.tableFromTokens(this.rawArgument(), 'matrix')});
|
|
1244
|
+
// physics.sty's matrix contents: diagonal and antidiagonal (a filler fills the rest), identity, zero, a matrix of x_{ij}, Pauli.
|
|
1245
|
+
if (/^(dmat|diagonalmatrix|admat|antidiagonalmatrix|imat|identitymatrix|zmat|zeromatrix|xmat|xmatrix|pmat|paulimatrix)$/.test(name)) {
|
|
1246
|
+
const text = tokens => mathTexTokenText(tokens).trim(), cells = [];
|
|
1247
|
+
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; };
|
|
1248
|
+
if (/^(dmat|diagonalmatrix|admat|antidiagonalmatrix)$/.test(name)) {
|
|
1249
|
+
const filler = this.optionalRaw() || [], entries = [], raw = this.rawArgument();
|
|
1250
|
+
let depth = 0, entry = [];
|
|
1251
|
+
for (const item of raw) {
|
|
1252
|
+
if (item.kind === 'char' && item.value === '{') depth++;
|
|
1253
|
+
if (item.kind === 'char' && item.value === '}') depth--;
|
|
1254
|
+
if (!depth && item.kind === 'char' && item.value === ',') { entries.push(entry); entry = []; } else entry.push(item);
|
|
1255
|
+
}
|
|
1256
|
+
entries.push(entry);
|
|
1257
|
+
if (entries.length > 32) this.error('resource-limit', 'This matrix is too large to render safely.', token);
|
|
1258
|
+
const anti = /^a/.test(name);
|
|
1259
|
+
// Each diagonal entry is its own \mqty, as in physics.sty.
|
|
1260
|
+
const own = entry => [{kind: 'command', value: 'mqty', offset: token.offset}, {kind: 'char', value: '{', offset: token.offset}, ...entry, {kind: 'char', value: '}', offset: token.offset}];
|
|
1261
|
+
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));
|
|
1262
|
+
} else if (/^(imat|identitymatrix)$/.test(name)) {
|
|
1263
|
+
const n = count(this.rawArgument()), one = mathTexTokens('1', token.offset), zero = mathTexTokens('0', token.offset);
|
|
1264
|
+
for (let r = 0; r < n; r++) cells.push(Array.from({length: n}, (_, c) => c === r ? one : zero));
|
|
1265
|
+
} else if (/^(zmat|zeromatrix)$/.test(name)) {
|
|
1266
|
+
const rows = count(this.rawArgument()), columns = this.is('{') ? count(this.rawArgument()) : rows, zero = mathTexTokens('0', token.offset);
|
|
1267
|
+
for (let r = 0; r < rows; r++) cells.push(Array(columns).fill(zero));
|
|
1268
|
+
} else if (/^(xmat|xmatrix)$/.test(name)) {
|
|
1269
|
+
const symbol = this.rawArgument(), rows = count(this.rawArgument()), columns = count(this.rawArgument());
|
|
1270
|
+
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) : [])]));
|
|
1271
|
+
} else {
|
|
1272
|
+
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];
|
|
1273
|
+
if (!rows) this.error('invalid-argument', 'A Pauli matrix is 0, 1, 2, 3, x, y or z.', token);
|
|
1274
|
+
return this.tableFromTokens(mathTexTokens(rows, token.offset), 'matrix');
|
|
1275
|
+
}
|
|
1276
|
+
const amp = {kind: 'char', value: '&', offset: token.offset}, newline = {kind: 'command', value: '\\', offset: token.offset};
|
|
1277
|
+
return this.tableFromTokens(cells.flatMap((row, r) => [...(r ? [newline] : []), ...row.flatMap((cell, c) => [...(c ? [amp] : []), ...cell])]), 'matrix');
|
|
1102
1278
|
}
|
|
1103
1279
|
const first = this.argument();
|
|
1104
1280
|
if (/^(bra|ket|pqty|bqty|Bqty|vqty|abs|absolutevalue|norm)$/.test(name)) {
|
|
@@ -1125,11 +1301,14 @@ class MathTexParser {
|
|
|
1125
1301
|
chemicalRow(stop) {
|
|
1126
1302
|
const children = [];
|
|
1127
1303
|
let spaced = true, subAllowed = false, moleculeParts = 0, isotope = null;
|
|
1304
|
+
// mhchem hangs a count, then a charge, each on its own X-high phantom after the formula, side by side.
|
|
1128
1305
|
const script = (key, body) => {
|
|
1129
|
-
|
|
1130
|
-
if (
|
|
1131
|
-
|
|
1132
|
-
|
|
1306
|
+
const last = children.at(-1);
|
|
1307
|
+
if (last?.chemical && !(key === 'sup' && last.sub && !last.sup)) {
|
|
1308
|
+
if (last[key]) last[key] = this.row([last[key], body]); else last[key] = body;
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
children.push(this.node('scripts', {base: this.node('phantom', {body: this.node('text', {value: 'X', variant: 'roman'}), mode: 'v'}), [key]: body, chemical: true}));
|
|
1133
1312
|
};
|
|
1134
1313
|
const consumeRun = predicate => {
|
|
1135
1314
|
let value = '';
|
|
@@ -1145,7 +1324,7 @@ class MathTexParser {
|
|
|
1145
1324
|
spaced = true; subAllowed = false; moleculeParts = 0;
|
|
1146
1325
|
// An operator or arrow already carries its own spacing; a separating space adds none beside it.
|
|
1147
1326
|
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}));
|
|
1327
|
+
if (before !== 'bin' && before !== 'rel' && !children.at(-2)?.unspaced && !(after.kind === 'char' && /^[+<=-]$/.test(after.value))) children.push(this.node('space', {width: 3 / 18}));
|
|
1149
1328
|
continue;
|
|
1150
1329
|
}
|
|
1151
1330
|
if (token.kind === 'command') {
|
|
@@ -1160,14 +1339,26 @@ class MathTexParser {
|
|
|
1160
1339
|
spaced = false; subAllowed = true; continue;
|
|
1161
1340
|
}
|
|
1162
1341
|
if (token.value === '$') {
|
|
1163
|
-
children.push(this.nested(() => this.parseRow(item => item.kind === 'char' && item.value === '$')));
|
|
1342
|
+
children.push(this.node('style', {variant: 'normal', body: this.nested(() => this.parseRow(item => item.kind === 'char' && item.value === '$'))}));
|
|
1164
1343
|
this.expect('$'); spaced = false; subAllowed = false; continue;
|
|
1165
1344
|
}
|
|
1345
|
+
// mhchem's (^) and (v): a gas given off and a precipitate, with a thin space after.
|
|
1346
|
+
if (token.value === '(' && this.rawPeek(false).kind === 'char' && /^[\^v]$/.test(this.rawPeek(false).value)) {
|
|
1347
|
+
const mark = this.rawTake(false).value;
|
|
1348
|
+
if (this.rawPeek(false).value !== ')') this.error('unexpected-token', 'Expected ).', this.rawPeek(false));
|
|
1349
|
+
this.rawTake(false);
|
|
1350
|
+
children.push(this.literal(mark === '^' ? '↑' : '↓', {class: 'ord', variant: 'roman'}), this.node('space', {width: 3 / 18})); spaced = false; subAllowed = false; continue;
|
|
1351
|
+
}
|
|
1166
1352
|
if (token.value === '(' || token.value === '[') {
|
|
1353
|
+
// mhchem separates a lowercase state from its formula by 0.2 ex (Latin Modern's x height is 0.431 em).
|
|
1354
|
+
const before = children.at(-1)?.type === 'space' ? children.at(-2) : children.at(-1), first = this.rawPeek(false);
|
|
1355
|
+
if (token.value === '(' && before && !['bin', 'rel'].includes(before.class) && first.kind === 'char' && /^[a-z]$/.test(first.value))
|
|
1356
|
+
children.push(this.node('space', {width: .0862}));
|
|
1167
1357
|
const end = token.value === '(' ? ')' : ']';
|
|
1168
1358
|
const body = this.nested(() => this.chemicalRow(item => item.kind === 'char' && item.value === end));
|
|
1169
1359
|
this.expect(end);
|
|
1170
|
-
|
|
1360
|
+
// mhchem's brackets are plain opening and closing characters: an ordinary group, with no inner spacing.
|
|
1361
|
+
children.push(this.node('fence', {left: token.value, right: end, body, class: 'ord'}));
|
|
1171
1362
|
spaced = false; subAllowed = true; moleculeParts++; continue;
|
|
1172
1363
|
}
|
|
1173
1364
|
if (token.value === '{') {
|
|
@@ -1178,13 +1369,20 @@ class MathTexParser {
|
|
|
1178
1369
|
if (token.value === '^' || token.value === '_') {
|
|
1179
1370
|
const key = token.value === '^' ? 'sup' : 'sub';
|
|
1180
1371
|
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;
|
|
1372
|
+
children.push(this.literal('↑', {class: 'ord', variant: 'roman'}), this.node('space', {width: 3 / 18})); spaced = false; subAllowed = false; continue;
|
|
1182
1373
|
}
|
|
1183
1374
|
let body;
|
|
1184
|
-
if (this.is('{'))
|
|
1375
|
+
if (this.is('{')) {
|
|
1376
|
+
const tokens = this.rawArgument(), value = mathTexTokenText(tokens).trim(), math = tokens[0]?.value === '$' && tokens.at(-1)?.value === '$';
|
|
1377
|
+
body = /^[A-Za-z]{2,}$/.test(value) ? this.node('text', {value, variant: 'roman'}) : this.subparse(math ? tokens.slice(1, -1) : tokens);
|
|
1378
|
+
// Single-letter variables and their integer expressions are math; words and oxidation numerals stay upright.
|
|
1379
|
+
if (math || /^\d*[a-z](?:[+\-−]\d*)?$/.test(value)) body = this.node('style', {variant: 'normal', body});
|
|
1380
|
+
}
|
|
1185
1381
|
else {
|
|
1186
1382
|
const value = consumeRun(character => /^[0-9+\-−IVX]$/.test(character));
|
|
1383
|
+
const variable = this.rawPeek(false).kind === 'char' && /^[a-z]$/.test(this.rawPeek(false).value);
|
|
1187
1384
|
body = value ? this.node('text', {value: value.replace(/-/g, '−'), variant: 'roman'}) : this.argument();
|
|
1385
|
+
if (!value && variable) body = this.node('style', {variant: 'normal', body});
|
|
1188
1386
|
}
|
|
1189
1387
|
// Scripts that open a term are an isotope's mass and atomic numbers, set before the next element.
|
|
1190
1388
|
if (spaced) {
|
|
@@ -1195,24 +1393,44 @@ class MathTexParser {
|
|
|
1195
1393
|
script(key, body); spaced = false; continue;
|
|
1196
1394
|
}
|
|
1197
1395
|
if (/^[0-9]$/.test(token.value)) {
|
|
1198
|
-
|
|
1396
|
+
// A subscript count is whole: in CuSO4.5H2O the point is the addition dot.
|
|
1397
|
+
const number = token.value + consumeRun(character => subAllowed && !spaced ? /^[0-9]$/.test(character) : /^[0-9.]$/.test(character));
|
|
1398
|
+
// 1/2 opening a term is mhchem's text-style fraction.
|
|
1399
|
+
if (!(subAllowed && !spaced) && this.rawPeek(false).value === '/' && /^[0-9]$/.test(this.frames.at(-1)?.tokens[this.frames.at(-1).at + 1]?.value ?? '')) {
|
|
1400
|
+
this.rawTake(false);
|
|
1401
|
+
const denominator = consumeRun(character => /^[0-9]$/.test(character));
|
|
1402
|
+
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'}));
|
|
1403
|
+
spaced = false; subAllowed = false; continue;
|
|
1404
|
+
}
|
|
1199
1405
|
if (subAllowed && !spaced) {
|
|
1200
1406
|
if (moleculeParts === 1 && ['+', '-'].includes(this.rawPeek(false).value)) {
|
|
1201
1407
|
const sign = this.rawTake(false).value;
|
|
1202
1408
|
script('sup', this.node('text', {value: number + (sign === '-' ? '−' : '+'), variant: 'roman'}));
|
|
1203
1409
|
} else script('sub', this.node('text', {value: number, variant: 'roman'}));
|
|
1204
|
-
} else
|
|
1410
|
+
} else {
|
|
1411
|
+
// A coefficient keeps a thin space before its formula.
|
|
1412
|
+
children.push(this.node('text', {value: number, variant: 'roman'}));
|
|
1413
|
+
if (this.rawPeek(false).kind === 'char' && /^[A-Z(\[]$/.test(this.rawPeek(false).value)) children.push(this.node('space', {width: 3 / 18}));
|
|
1414
|
+
}
|
|
1205
1415
|
spaced = false; continue;
|
|
1206
1416
|
}
|
|
1207
1417
|
if (token.value === '<' || token.value === '-' || token.value === '=') {
|
|
1208
1418
|
let arrow = token.value;
|
|
1209
1419
|
while (this.rawPeek(false).kind === 'char' && /^[<=>-]$/.test(this.rawPeek(false).value) && arrow.length < 5) arrow += this.rawTake(false).value;
|
|
1210
|
-
const arrows = {'->': '→', '<-': '←', '<->': '↔', '<=>': '⇌', '=>': '⇒', '<=': '⇐', '<<=>': '⇋', '<=>>': '⇌'};
|
|
1420
|
+
const arrows = {'->': '→', '<-': '←', '<->': '↔', '<-->': '⇄', '<=>': '⇌', '=>': '⇒', '<=': '⇐', '<<=>': '⇋', '<=>>': '⇌'};
|
|
1211
1421
|
if (arrows[arrow]) {
|
|
1212
1422
|
// Only an adjacent bracket labels the arrow; a peek that skips spaces would drop the next one.
|
|
1213
1423
|
const over = this.rawPeek(false).value === '[' ? this.optionalRaw() : null, under = over && this.rawPeek(false).value === '[' ? this.optionalRaw() : null;
|
|
1214
|
-
|
|
1215
|
-
|
|
1424
|
+
// mhchem's arrow is at least 2 em, with a thick space inside each end; <-> and <--> pad a label by 18 mu.
|
|
1425
|
+
const base = this.literal(arrows[arrow], {class: 'rel', variant: 'roman', stretch: true}), space = () => this.node('space', {width: 5 / 18});
|
|
1426
|
+
// A label in braces is text, with its word spaces; otherwise it is chemistry.
|
|
1427
|
+
const label = tokens => {
|
|
1428
|
+
if (!tokens?.some(item => item.kind !== 'space')) return null;
|
|
1429
|
+
const inner = tokens.filter(item => item.kind !== 'space');
|
|
1430
|
+
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');
|
|
1431
|
+
return this.chemistry(tokens);
|
|
1432
|
+
};
|
|
1433
|
+
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
1434
|
spaced = true; subAllowed = false; moleculeParts = 0; continue;
|
|
1217
1435
|
}
|
|
1218
1436
|
if (arrow.length !== 1) this.error('unsupported-reaction', 'Unsupported chemical reaction arrow: ' + arrow + '.', token);
|
|
@@ -1227,13 +1445,18 @@ class MathTexParser {
|
|
|
1227
1445
|
}
|
|
1228
1446
|
if (/^[A-Za-z]$/.test(token.value)) {
|
|
1229
1447
|
const word = token.value + consumeRun(character => /^[a-z]$/.test(character));
|
|
1230
|
-
|
|
1448
|
+
if (word === 'v' && spaced && !isotope) { children.push(this.literal('↓', {class: 'ord', variant: 'roman'}), this.node('space', {width: 3 / 18})); spaced = false; subAllowed = false; continue; }
|
|
1449
|
+
const element = this.node('text', {value: word, variant: 'roman'});
|
|
1231
1450
|
if (isotope) { isotope.base = this.node('phantom', {body: element, mode: 'v'}); isotope = null; }
|
|
1232
1451
|
children.push(element);
|
|
1233
1452
|
moleculeParts++; spaced = false; subAllowed = true; continue;
|
|
1234
1453
|
}
|
|
1235
1454
|
if (token.value === '#') children.push(this.literal('≡', {class: 'ord', variant: 'roman'}));
|
|
1236
|
-
|
|
1455
|
+
// mhchem's addition dot (. or *) has a thin space on each side and starts a new formula.
|
|
1456
|
+
else if (token.value === '.' || token.value === '·' || token.value === '*') {
|
|
1457
|
+
children.push(this.node('space', {width: 3 / 18}), this.literal('⋅', {class: 'ord', variant: 'roman'}), this.node('space', {width: 3 / 18}));
|
|
1458
|
+
spaced = true; subAllowed = false; moleculeParts = 0; continue;
|
|
1459
|
+
}
|
|
1237
1460
|
else if (token.value === '~') children.push(this.node('space', {width: 1 / 3}));
|
|
1238
1461
|
else children.push(this.literal(token.value, {variant: 'roman'}));
|
|
1239
1462
|
spaced = false;
|
|
@@ -1251,6 +1474,12 @@ class MathTexParser {
|
|
|
1251
1474
|
if (parts.length > 3) this.error('invalid-number', 'An angle has at most degrees, minutes and seconds.', token);
|
|
1252
1475
|
return this.row(parts.flatMap((part, i) => part.trim() ? [this.siNumber(mathTexTokens(part.trim(), token.offset)), this.literal('°′″'[i], {variant: 'roman'})] : []));
|
|
1253
1476
|
}
|
|
1477
|
+
// \numrange and \SIrange: "1 to 5", the unit after each number.
|
|
1478
|
+
if (/range$/.test(name)) {
|
|
1479
|
+
const from = this.siNumber(this.rawArgument()), to = this.siNumber(this.rawArgument()), word = {type: 'text', value: 'to', variant: 'roman'},
|
|
1480
|
+
unit = name === 'numrange' ? null : this.rawArgument(), quantity = value => unit ? [value, this.node('space', {width: 3 / 18}), this.siUnit(unit, token)] : [value];
|
|
1481
|
+
return this.row([...quantity(from), this.node('space', {width: 1 / 3}), this.node('text', word), this.node('space', {width: 1 / 3}), ...quantity(to)]);
|
|
1482
|
+
}
|
|
1254
1483
|
const value = this.siNumber(this.rawArgument()), before = this.optionalRaw();
|
|
1255
1484
|
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
1485
|
}
|
|
@@ -1265,7 +1494,7 @@ class MathTexParser {
|
|
|
1265
1494
|
}
|
|
1266
1495
|
siUnit(tokens, token) {
|
|
1267
1496
|
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))))
|
|
1497
|
+
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
1498
|
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
1499
|
let prefix = '', power = 1, per = false;
|
|
1271
1500
|
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 +1509,18 @@ class MathTexParser {
|
|
|
1280
1509
|
if (value === 'tothe' || value === 'raiseto') [exponent, at] = number(at + 1);
|
|
1281
1510
|
if (!/^-?\d+(\.\d+)?$/.test(exponent)) this.error('invalid-unit', 'A unit power must be a number.', item);
|
|
1282
1511
|
items.at(-1).power = exponent;
|
|
1283
|
-
} else if (item.kind === '
|
|
1284
|
-
|
|
1512
|
+
} else if (item.kind === 'char' && value === '/' && items.length) items.at(-1).slash = true;
|
|
1513
|
+
else if (item.kind === 'command' && (Object.hasOwn(units, value) || !prefix && Object.hasOwn(MATH_SI_ABBREVIATIONS, value)) || item.kind === 'char' && /^[A-Za-z]$/.test(value)) {
|
|
1514
|
+
items.push({symbol: prefix + (item.kind === 'command' ? units[value] ?? MATH_SI_ABBREVIATIONS[value] : value), power: String(power), per});
|
|
1285
1515
|
prefix = ''; power = 1; per = false;
|
|
1286
1516
|
} else this.error('invalid-unit', 'Unsupported unit: ' + mathTexTokenText([item]).trim() + '.', item);
|
|
1287
1517
|
}
|
|
1288
|
-
if (prefix || per || !items.length) this.error('invalid-unit', 'A unit prefix
|
|
1518
|
+
if (prefix || per || !items.length || items.at(-1).slash) this.error('invalid-unit', 'A unit prefix, \\per or / needs a unit.', token);
|
|
1519
|
+
// A unit after a written solidus follows it directly: m/s.
|
|
1289
1520
|
return this.row(items.flatMap((unit, i) => {
|
|
1290
1521
|
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'})})
|
|
1522
|
+
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'})}),
|
|
1523
|
+
...(unit.slash ? [this.literal('/', {variant: 'roman'})] : [])];
|
|
1292
1524
|
}));
|
|
1293
1525
|
}
|
|
1294
1526
|
units(tokens) {
|
|
@@ -1316,7 +1548,7 @@ class MathTexParser {
|
|
|
1316
1548
|
let raw;
|
|
1317
1549
|
if (name === 'unicode') {
|
|
1318
1550
|
const metrics = this.optionalRaw(), font = this.optionalRaw();
|
|
1319
|
-
if (metrics || font) this.error('unsupported-character-option', 'Unicode characters use the embedded
|
|
1551
|
+
if (metrics || font) this.error('unsupported-character-option', 'Unicode characters use the embedded math font.', token);
|
|
1320
1552
|
raw = this.plainArgument();
|
|
1321
1553
|
} else if (this.is('{')) raw = this.plainArgument();
|
|
1322
1554
|
else {
|
|
@@ -1346,6 +1578,11 @@ function parseMathTexPreview(source, error, caret = source.length) {
|
|
|
1346
1578
|
caret = Math.max(0, Math.min(source.length, Math.floor(caret) || 0));
|
|
1347
1579
|
let text = source;
|
|
1348
1580
|
const tail = /(?<!\\)\\(?:[A-Za-z]*|(?:begin|end)\{[A-Za-z*]*)$/.exec(text.slice(0, caret));
|
|
1581
|
+
// A name being typed previews blank; a finished misspelling (no known name continues it) keeps its fix.
|
|
1582
|
+
if (tail && error?.code === 'unsupported-command' && error.offset === tail.index && /^\\[A-Za-z]+$/.test(tail[0])) {
|
|
1583
|
+
const name = tail[0].slice(1), suggestion = mathSuggest(name);
|
|
1584
|
+
if (suggestion && !mathTexNames.command.some(candidate => candidate.length > name.length && candidate.startsWith(name))) return null;
|
|
1585
|
+
}
|
|
1349
1586
|
if (tail) text = text.slice(0, tail.index) + ' '.repeat(tail[0].length) + text.slice(caret);
|
|
1350
1587
|
const atEnd = (cause, length) => /^unclosed-(group|option|environment)$/.test(cause.code) || cause.offset >= length;
|
|
1351
1588
|
for (let attempt = 0; attempt < 24; attempt++) {
|
|
@@ -1370,11 +1607,13 @@ function parseMathTexPreview(source, error, caret = source.length) {
|
|
|
1370
1607
|
|
|
1371
1608
|
// The command or environment a mistyped name most likely meant: one edit away (two for longer names), where swapping
|
|
1372
1609
|
// 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';
|
|
1610
|
+
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';
|
|
1611
|
+
// Every other command the parser accepts: a name being typed toward one of them is not a misspelling.
|
|
1612
|
+
const MATH_TEX_OTHER = 'TeX let char rm rmfamily normalfont it itshape sl bf bfseries sf sffamily tt ttfamily cal displaystyle textstyle scriptstyle scriptscriptstyle tiny scriptsize footnotesize small normalsize large Large LARGE huge Huge over coloneq Coloneq Coloneqq Eqqcolon eqcolon Eqcolon colonapprox Colonapprox colonsim Colonsim LaTeX Set unicode bbox matrix pmatrix bmatrix Bmatrix vmatrix Vmatrix smallmatrix cases op 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 Bra Ket Braket set nicefrac sfrac vcenter prescript sideset accentset underaccent slashed mod bmod pmod pod smashoperator mathmakebox idotsint mmlToken textbackslash textasciitilde textasciicircum dd derivative pderivative fdv functionalderivative differential quantity pqty bqty Bqty vqty absolutevalue innerproduct ip ketbra dyad outerproduct 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';
|
|
1374
1613
|
let mathTexNames;
|
|
1375
1614
|
function mathSuggest(name, environment = false) {
|
|
1376
1615
|
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),
|
|
1616
|
+
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),
|
|
1378
1617
|
...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]};
|
|
1379
1618
|
const limit = name.length > 5 ? 2 : 1;
|
|
1380
1619
|
let best, bestDistance = limit + 1;
|