rapier-math 2.2.0 → 2.4.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.
@@ -56,6 +56,7 @@ 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
+ const MATH_TEX_TEXT_LETTERS = Object.freeze({ss: 'ß', ae: 'æ', AE: 'Æ', oe: 'œ', OE: 'Œ', o: 'ø', O: 'Ø', aa: 'å', AA: 'Å', l: 'ł', L: 'Ł', i: 'ı', j: 'ȷ'});
59
60
  const MATH_TEX_DECLARATIONS = Object.freeze({
60
61
  rm: {variant: 'roman'}, rmfamily: {variant: 'roman'}, normalfont: {variant: 'roman'},
61
62
  it: {variant: 'italic'}, itshape: {variant: 'italic'}, sl: {variant: 'italic'},
@@ -76,18 +77,36 @@ const MATH_TEX_ACCENTS = Object.freeze({
76
77
  underrightarrow: ['→', 'under', true], underleftarrow: ['←', 'under', true], underleftrightarrow: ['↔', 'under', true],
77
78
  overleftharpoon: ['↼', 'over', true], overrightharpoon: ['⇀', 'over', true], utilde: ['̃', 'under', true]
78
79
  });
79
- const MATH_TEX_LONG_ARROWS = {iff: 'Longleftrightarrow', implies: 'Longrightarrow', impliedby: 'Longleftarrow'};
80
+ const MATH_TEX_LONG_ARROWS = {iff: 'Longleftrightarrow', implies: 'Longrightarrow', impliedby: 'Longleftarrow', And: 'And'};
81
+ // mathtools: a colon or double colon joined to a relation, 1.2 mu apart.
82
+ const MATH_TEX_COLONS = {coloneq: '∶−', Coloneq: '∷−', Coloneqq: '∷=', Eqqcolon: '=∷', eqcolon: '−∶', Eqcolon: '−∷', colonapprox: '∶≈', Colonapprox: '∷≈', colonsim: '∶∼', Colonsim: '∷∼'};
83
+ // dvipsnames in CMYK percent (LaTeX graphics bundle), converted as xcolor does: each RGB channel is 1 − min(1, CMY + K).
84
+ const MATH_TEX_DVIPSNAMES = Object.create(null);
85
+ 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
+ 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
+ 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
88
+ CarnationPink 0 63 0 0 Magenta 0 100 0 0 VioletRed 0 81 0 0 Rhodamine 0 82 0 0 Mulberry 34 90 0 2 RedViolet 7 90 0 34 Fuchsia 47 91 0 8
89
+ Lavender 0 48 0 0 Thistle 12 59 0 0 Orchid 32 64 0 0 DarkOrchid 40 80 20 0 Purple 45 86 0 0 Plum 50 100 0 0 Violet 79 88 0 0 RoyalPurple 75 90 0 0
90
+ BlueViolet 86 91 0 4 Periwinkle 57 55 0 0 CadetBlue 62 57 23 0 CornflowerBlue 65 13 0 0 MidnightBlue 98 13 0 43 NavyBlue 94 54 0 0 RoyalBlue 100 50 0 0
91
+ Blue 100 100 0 0 Cerulean 94 11 0 0 Cyan 100 0 0 0 ProcessBlue 96 0 0 0 SkyBlue 62 0 12 0 Turquoise 85 0 20 0 TealBlue 86 0 34 2 Aquamarine 82 0 30 0
92
+ 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
+ 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
+ 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('');
80
96
  const MATH_TEX_SPACES = Object.freeze({
81
97
  ',': 3 / 18, ':': 4 / 18, ';': 5 / 18, '!': -3 / 18, ' ': 1 / 3,
82
98
  quad: 1, qquad: 2, enspace: .5, enskip: .5, thinspace: 3 / 18, medspace: 4 / 18, thickspace: 5 / 18,
83
99
  negthinspace: -3 / 18, negmedspace: -4 / 18, negthickspace: -5 / 18
84
100
  });
85
- const MATH_TEX_PACKAGES = new Set(('ams amsmath amssymb amsfonts mathtools color newcommand unicode mhchem physics bbm bboldx dsfont cancel bbox boldsymbol').split(' '));
86
- 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 gather split cases dcases rcases drcases subarray substack eqnarray multline equation').split(' '));
101
+ 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');
103
+ 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
+ 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
+ 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(' '));
87
106
  const MATH_TEX_LITERAL_CLASSES = Object.freeze({
88
107
  '+': 'bin', '−': 'bin', '-': 'bin', '±': 'bin', '∓': 'bin', '×': 'bin', '÷': 'bin', '*': 'bin', '⋅': 'bin',
89
108
  '=': 'rel', '<': 'rel', '>': 'rel', '≤': 'rel', '≥': 'rel', '≠': 'rel', ':': 'rel',
90
- '(': 'open', '[': 'open', '⟨': 'open', ')': 'close', ']': 'close', '⟩': 'close', ',': 'punct', ';': 'punct',
109
+ '(': 'open', '[': 'open', '{': 'open', '⟨': 'open', ')': 'close', ']': 'close', '}': 'close', '⟩': 'close', ',': 'punct', ';': 'punct',
91
110
  '∑': 'op', '∏': 'op', '∫': 'op', '∮': 'op', '∬': 'op', '∭': 'op'
92
111
  });
93
112
 
@@ -179,7 +198,9 @@ class MathTexParser {
179
198
  if (token.kind === 'command' && (Object.hasOwn(MATH_TEX_DECLARATIONS, token.value) || token.value === 'color')) {
180
199
  this.take();
181
200
  const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
182
- children.push(this.node('style', {...fields, body: this.nested(() => this.parseRow(stop, allowFraction))}));
201
+ // A declaration styles each following atom; the atoms keep their own classes and spacing.
202
+ const rest = this.nested(() => this.parseRow(stop, allowFraction));
203
+ for (const body of rest.type === 'row' ? rest.children : [rest]) children.push(this.node('style', {...fields, body}));
183
204
  break;
184
205
  }
185
206
  if (token.kind === 'command' && /^(over|atop|choose|brace|brack|above|overwithdelims|atopwithdelims|abovewithdelims)$/.test(token.value)) {
@@ -207,6 +228,8 @@ class MathTexParser {
207
228
  continue;
208
229
  }
209
230
  const atom = this.parseAtom();
231
+ // A symbol remembers where its source begins, so a tap on it can find its place in the source.
232
+ if (atom && (atom.type === 'glyph' || atom.type === 'text') && atom.at === undefined) atom.at = token.offset;
210
233
  if (atom) children.push(this.readScripts(atom));
211
234
  }
212
235
  // An equation tag follows its equation wherever \tag was written.
@@ -261,6 +284,7 @@ class MathTexParser {
261
284
  }
262
285
  const atom = this.parseAtom();
263
286
  if (!atom) this.error('missing-argument', 'An argument must contain a mathematical expression.', token);
287
+ if ((atom.type === 'glyph' || atom.type === 'text') && atom.at === undefined) atom.at = token.offset;
264
288
  return atom;
265
289
  }
266
290
  rawArgument() {
@@ -351,7 +375,12 @@ class MathTexParser {
351
375
  if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
352
376
  }
353
377
  if (Object.hasOwn(MATH_SYMBOLS, name)) return this.node('glyph', MATH_SYMBOLS[name]);
354
- if (Object.hasOwn(MATH_TEX_VARIANTS, name)) return this.node('style', {variant: MATH_TEX_VARIANTS[name], body: this.argument()});
378
+ if (Object.hasOwn(MATH_TEX_VARIANTS, name)) {
379
+ let body = this.argument();
380
+ // amsmath's \boldsymbol and \pmb, and bm's \bm, keep one symbol's class (\binrel@); a plain group is ordinary.
381
+ if (/^(boldsymbol|bm|pmb)$/.test(name) && body.type === 'row' && body.children.length === 1 && body.children[0].type === 'glyph') body = body.children[0];
382
+ return this.node('style', {variant: MATH_TEX_VARIANTS[name], body});
383
+ }
355
384
  if (Object.hasOwn(MATH_TEX_TEXT_VARIANTS, name)) return this.subparse(this.rawArgument(), true, MATH_TEX_TEXT_VARIANTS[name]);
356
385
  if (MATH_NAMED_OPERATORS.has(name) || MATH_LIMIT_OPERATORS.has(name)) {
357
386
  const values = {limsup: 'lim sup', liminf: 'lim inf', injlim: 'lim', projlim: 'lim', varlimsup: 'lim', varliminf: 'lim', varinjlim: 'lim', varprojlim: 'lim'};
@@ -369,7 +398,7 @@ class MathTexParser {
369
398
  if (name === 'frac' || name === 'dfrac' || name === 'tfrac' || name === 'cfrac') {
370
399
  const align = name === 'cfrac' ? this.optionalRaw() : null;
371
400
  if (align && !/^[lr]$/.test(mathTexTokenText(align).trim())) this.error('invalid-option', 'Continued-fraction alignment must be l or r.', token);
372
- 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()} : {})});
401
+ 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} : {})});
373
402
  }
374
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'} : {})});
375
404
  if (name === 'genfrac') {
@@ -409,8 +438,8 @@ class MathTexParser {
409
438
  if (name === 'begin') return this.environment(this.plainArgument(), token);
410
439
  if (name === 'substack') return this.tableFromTokens(this.rawArgument(), 'substack');
411
440
  if (/^(matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases|smallmatrix)$/.test(name)) return this.tableFromTokens(this.rawArgument(), name);
412
- if (name === 'operatorname') {
413
- const starred = this.is('*'); if (starred) this.take();
441
+ if (name === 'operatorname' || name === 'operatornamewithlimits') {
442
+ const starred = name !== 'operatorname' || this.is('*'); if (starred && name === 'operatorname') this.take();
414
443
  const body = this.subparse(this.rawArgument(), true, 'roman');
415
444
  return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
416
445
  }
@@ -450,7 +479,7 @@ class MathTexParser {
450
479
  }
451
480
  if (name === 'raisebox') {
452
481
  const amount = this.dimension(this.plainArgument(), token), height = this.optionalRaw(), depth = this.optionalRaw();
453
- return this.node('raise', {body: this.argument(), amount, ...(height ? {height: this.dimension(mathTexTokenText(height), token)} : {}), ...(depth ? {depth: this.dimension(mathTexTokenText(depth), token)} : {})});
482
+ 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)} : {})});
454
483
  }
455
484
  if (name === 'raise' || name === 'lower') return this.node('raise', {amount: this.readDimension() * (name === 'lower' ? -1 : 1), body: this.argument()});
456
485
  if (name === 'textcolor') { const color = this.readColor(); return this.node('style', {body: this.argument(), color}); }
@@ -463,10 +492,28 @@ class MathTexParser {
463
492
  if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(colorName)) this.error('invalid-color', 'Invalid colour name.', token);
464
493
  this.colors[colorName] = this.color(value, model, token); return null;
465
494
  }
495
+ // MathJax's bbox: a background colour, a padding length and a CSS border whose last word is its colour.
496
+ if (name === 'bbox') {
497
+ const fields = {padding: 0}, options = this.optionalRaw();
498
+ for (const option of options ? mathTexTokenText(options).split(',') : []) {
499
+ const value = option.trim(), border = /^border\s*:(.*)$/i.exec(value);
500
+ if (border) fields.border = this.color(border[1].trim().split(/\s+/).pop(), '', token);
501
+ else if (/^[+-]?[\d.]/.test(value)) fields.padding = this.dimension(value, token);
502
+ else if (value) fields.background = this.color(value, '', token);
503
+ }
504
+ return this.node('style', {body: this.argument(), ...fields});
505
+ }
466
506
  if (name === 'boxed' || name === 'fbox') return this.node('style', {body: name === 'fbox' ? this.subparse(this.rawArgument(), true, 'roman') : this.argument(), border: 'currentColor', padding: .25});
467
507
  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});
468
508
  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}); }
469
- if (['newcommand', 'renewcommand', 'providecommand', 'def', 'gdef', 'DeclareMathOperator', 'let'].includes(name)) { this.define(name, token); return null; }
509
+ if (['newcommand', 'renewcommand', 'providecommand', 'def', 'gdef', 'edef', 'xdef', 'DeclareMathOperator', 'DeclarePairedDelimiter', 'let'].includes(name)) { this.define(name, token); return null; }
510
+ // Assignment prefixes: \global makes the next definition global; \long and \outer change nothing here.
511
+ if (name === 'global' || name === 'long' || name === 'outer') {
512
+ let next = token, global = false;
513
+ while (next.kind === 'command' && /^(global|long|outer)$/.test(next.value)) { global ||= next.value === 'global'; next = this.rawTake(); }
514
+ if (next.kind !== 'command' || !/^[egx]?def$/.test(next.value)) this.error('invalid-macro', '\\' + name + ' needs a \\def.', token);
515
+ this.define(global ? {def: 'gdef', edef: 'xdef'}[next.value] || next.value : next.value, next); return null;
516
+ }
470
517
  if (name === 'require') {
471
518
  const value = this.plainArgument();
472
519
  if (!MATH_TEX_PACKAGES.has(value)) this.error('unsupported-package', 'Unsupported maths package: ' + value + '.', token, name);
@@ -487,11 +534,86 @@ class MathTexParser {
487
534
  const body = this.subparse(this.rawArgument(), true);
488
535
  return {...this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]), semanticRole: 'tag'};
489
536
  }
537
+ if (Object.hasOwn(MATH_TEX_COLONS, name))
538
+ return this.node('style', {class: 'rel', body: this.row([...MATH_TEX_COLONS[name]].flatMap((value, i) => [...(i ? [this.node('space', {width: -1.2 / 18})] : []), this.literal(value, {class: 'ord', variant: 'roman'})]))});
539
+ const make = (value, kind = 'command') => ({kind, value, offset: token.offset});
540
+ // mathtools: \cmd{x} keeps the declared delimiters' size, \cmd*{x} stretches them and \cmd[\big]{x} sets it.
541
+ if (name === '@paired') {
542
+ const left = this.rawArgument(), right = this.rawArgument(), starred = this.is('*');
543
+ if (starred) this.take();
544
+ const size = starred ? null : this.optionalRaw()?.filter(item => item.kind !== 'space'), body = this.rawArgument();
545
+ if (size && (size.length !== 1 || !/^(big|Big|bigg|Bigg)$/.test(size[0].value))) this.error('invalid-option', 'A delimiter size must be \\big, \\Big, \\bigg or \\Bigg.', token);
546
+ const group = tokens => [make('{', 'char'), ...tokens, make('}', 'char')];
547
+ return this.subparse(starred ? [make('left'), ...left, ...body, make('right'), ...right] : size ? [make(size[0].value + 'l'), ...left, ...group(body), make(size[0].value + 'r'), ...right] :
548
+ [make('mathopen'), ...group(left), ...group(body), make('mathclose'), ...group(right)]);
549
+ }
550
+ // braket: \Bra, \Ket, \Braket and \Set stretch their delimiters; bars inside \Braket, and the first in \Set and \set, divide.
551
+ if (/^(Bra|Ket|Braket|Set|set)$/.test(name)) {
552
+ const [left, right] = {Bra: ['langle', '|'], Ket: ['|', 'rangle'], Braket: ['langle', 'rangle'], Set: ['{', '}'], set: ['{', '}']}[name], body = [];
553
+ const raw = this.rawArgument(), delimiter = value => value === '|' ? make('|', 'char') : make(value);
554
+ let divided = false;
555
+ for (let i = 0; i < raw.length; i++) {
556
+ const item = raw[i], bar = item.kind === 'char' && item.value === '|', double = bar && raw[i + 1]?.kind === 'char' && raw[i + 1].value === '|';
557
+ if (!bar || divided || (name !== 'Braket' && name !== 'Set' && name !== 'set')) { body.push(item); continue; }
558
+ if (double) i++;
559
+ divided = name !== 'Braket';
560
+ body.push(...(name === 'set' ? [make('mid')] : [make(name === 'Set' ? ';' : ','), make('middle'), double ? make('|') : make('|', 'char'), make(name === 'Set' ? ';' : ',')]));
561
+ }
562
+ if (name === 'set') return this.subparse([make('{'), make(','), ...body, make(','), make('}')]);
563
+ return this.subparse([make('left'), delimiter(left), ...(name === 'Set' ? [make(',')] : []), ...body, ...(name === 'Set' ? [make(',')] : []), make('right'), delimiter(right)]);
564
+ }
565
+ // units' \nicefrac (and xfrac's \sfrac): a script numerator raised 0.5 ex, a solidus, a script denominator lowered 0.25 ex.
566
+ if (name === 'nicefrac' || name === 'sfrac') {
567
+ const script = body => this.node('style', {mathStyle: 'script', body}), num = this.argument(), den = this.argument();
568
+ return this.row([this.node('raise', {amount: .225, body: script(num)}), this.node('space', {width: -.1}), this.literal('/'), this.node('space', {width: -.15}), this.node('raise', {amount: -.1125, body: script(den)})]);
569
+ }
570
+ if (name === 'vcenter') return this.node('raise', {body: this.argument(), center: true});
571
+ // mathtools \prescript{sup}{sub}{base}: scripts before the base, right aligned, at the base's height.
572
+ if (name === 'prescript') {
573
+ const sup = this.argument(), sub = this.argument(), base = this.argument();
574
+ return this.row([this.node('scripts', {base: this.node('phantom', {body: base, mode: 'v'}), sup, sub, pre: true}), base]);
575
+ }
576
+ // amsmath \sideset{_a^b}{_c^d}\sum: corner scripts beside the operator; later scripts become its limits.
577
+ if (name === 'sideset') {
578
+ const before = this.argument(), after = this.argument(), op = this.argument(), corners = (side, base) => {
579
+ const scripts = side.type === 'row' && side.children.length === 1 ? side.children[0] : side;
580
+ return scripts.type === 'scripts' ? {...scripts, base} : this.row([base, side]);
581
+ };
582
+ return this.node('style', {class: 'op', limits: 'display', body: this.row([corners(before, this.node('phantom', {body: op, mode: 'v'})), corners(after, {...op, limits: 'never'})])});
583
+ }
584
+ // accents.sty: \accentset sets any symbol over its base; \underaccent sets an accent or symbol under it.
585
+ if (name === 'accentset' || name === 'underaccent') {
586
+ const mark = this.rawArgument().filter(item => item.kind !== 'space');
587
+ if (mark.length === 1 && mark[0].kind === 'command' && Object.hasOwn(MATH_TEX_ACCENTS, mark[0].value)) {
588
+ const [value, , stretch] = MATH_TEX_ACCENTS[mark[0].value];
589
+ return this.node('accent', {base: this.argument(), value, position: name === 'accentset' ? 'over' : 'under', stretch});
590
+ }
591
+ const decoration = this.subparse(mark);
592
+ return this.node('overunder', {base: this.argument(), [name === 'accentset' ? 'over' : 'under']: decoration});
593
+ }
594
+ if (name === 'slashed') return this.node('accent', {base: this.argument(), value: '/', position: 'through'});
490
595
  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})]);
491
596
  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()])})]);
492
- if (name === 'bmod') return this.node('text', {value: 'mod', variant: 'roman', class: 'bin'});
493
597
  if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
494
598
  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'};
600
+ // mathtools \smashoperator[lr]{op}: the limits overhang the operator's own width on the named sides.
601
+ if (name === 'smashoperator') {
602
+ const sides = mathTexTokenText(this.optionalRaw() || []).trim() || 'lr';
603
+ if (!/^(l|r|lr|rl)$/.test(sides)) this.error('invalid-option', 'A smashed operator side must be l, r or lr.', token);
604
+ return this.node('style', {body: this.argument(), smashOperator: sides});
605
+ }
606
+ if (name === 'mathmakebox') {
607
+ const width = this.optionalRaw(), position = mathTexTokenText(this.optionalRaw() || []).trim() || 'c';
608
+ if (!/^[lrcs]$/.test(position)) this.error('invalid-option', 'A box position must be l, r, c or s.', token);
609
+ const body = this.argument();
610
+ return width ? this.node('style', {body, width: this.dimension(mathTexTokenText(width), token), align: {l: 'left', r: 'right'}[position] || 'center'}) : body;
611
+ }
612
+ // amsmath \idotsint: two integral signs joined by centred dots, one operator.
613
+ if (name === 'idotsint') {
614
+ const integral = () => this.literal('∫', {large: true, limits: 'never', class: 'op'});
615
+ 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
+ }
495
617
  if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
496
618
  if (name === 'mmlToken') return this.mathmlToken(token);
497
619
  if (name === 'unicode' || name === 'char') return this.character(name, token);
@@ -543,6 +665,7 @@ class MathTexParser {
543
665
  color(value, model, token) {
544
666
  if (!model) {
545
667
  if (Object.hasOwn(this.colors, value)) return this.colors[value];
668
+ if (MATH_TEX_DVIPSNAMES[value]) return MATH_TEX_DVIPSNAMES[value];
546
669
  if (/^#[a-fA-F0-9]{3,8}$/.test(value) && [4, 5, 7, 9].includes(value.length)) return value;
547
670
  if (/^[A-Za-z]{1,32}$/.test(value) && !/^(inherit|unset|initial|revert)$/i.test(value)) return value;
548
671
  } else if (model === 'HTML' && /^[a-fA-F0-9]{6}$/.test(value)) return '#' + value;
@@ -559,29 +682,74 @@ class MathTexParser {
559
682
 
560
683
  environment(fullName, token) {
561
684
  const env = fullName.replace(/\*$/, '');
562
- if (!MATH_TEX_ENVIRONMENTS.has(env)) this.error('unsupported-environment', 'Unsupported maths environment: ' + fullName + '.', token, 'begin');
685
+ if (!MATH_TEX_ENVIRONMENTS.has(env)) throw Object.assign(new MathTexError('unsupported-environment', 'Unsupported maths environment: ' + fullName + '.', token.offset, 'begin'), {environment: env});
563
686
  return this.nested(() => {
564
687
  let options = {};
565
688
  const position = this.optionalRaw();
566
689
  if (position) {
567
690
  const value = mathTexTokenText(position).trim();
568
- if (!/^[tbc l r]$/.test(value)) this.error('invalid-option', 'Invalid matrix alignment.', token);
691
+ if (!/^[tbclr]$/.test(value)) this.error('invalid-option', 'Invalid matrix alignment.', token);
569
692
  if (['l', 'r', 'c'].includes(value)) options.columnAlign = value;
570
693
  else options.position = value;
571
694
  }
572
- if (env === 'array' || env === 'subarray') options = {...options, ...this.columnSpec(this.rawArgument(), token)};
695
+ if (env === 'CD') return this.commutativeDiagram(fullName, token);
696
+ if (env === 'array' || env === 'subarray' || env === 'darray') options = {...options, ...this.columnSpec(this.rawArgument(), token)};
573
697
  if (env === 'alignedat' || env === 'alignat') {
574
698
  const value = this.plainArgument();
575
699
  if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 256) this.error('invalid-alignment', 'An alignedat environment needs its number of column pairs.', token);
576
700
  options.pairs = Number(value);
577
701
  }
578
- const body = this.readTable(env, options, item => item.kind === 'command' && item.value === 'end');
702
+ const body = this.readTable(env, options, item => item.kind === 'command' && item.value === 'end', /cases\*$/.test(fullName) ? 1 : -1);
579
703
  this.expect('end', 'command');
580
704
  const ending = this.plainArgument();
581
705
  if (ending !== fullName) this.error('mismatched-environment', 'Expected \\end{' + fullName + '}, received \\end{' + ending + '}.', token);
582
706
  return body;
583
707
  });
584
708
  }
709
+ // amscd: rows of objects joined by @>>>, @<<< and @= arrows, between rows of @VVV, @AAA, @| and @. arrows.
710
+ commutativeDiagram(fullName, token) {
711
+ const rows = [], make = (value, kind = 'command') => ({kind, value, offset: token.offset});
712
+ let cells = [], current = [];
713
+ const arrow = (kind, labels) => {
714
+ const label = tokens => tokens.length ? this.subparse(tokens) : null;
715
+ if (kind === '>' || kind === '<' || kind === '=')
716
+ return this.node('overunder', {base: this.literal(kind === '>' ? '→' : kind === '<' ? '←' : '=', {class: 'rel', stretch: true}), ...(labels[0]?.length ? {over: label(labels[0])} : {}), ...(labels[1]?.length ? {under: label(labels[1])} : {}), class: 'rel', minWidth: 3});
717
+ 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: 3, class: 'ord'}), ...side(labels[1], 'left')]);
720
+ };
721
+ for (;;) {
722
+ const item = this.rawTake(false);
723
+ if (item.kind === 'eof') this.error('unclosed-environment', 'A closing \\end command is missing.', token);
724
+ const end = item.kind === 'command' && item.value === 'end';
725
+ if (end || item.kind === 'command' && item.value === '\\') {
726
+ if (current.some(part => part.kind !== 'space')) cells.push(this.subparse(current));
727
+ if (cells.length) rows.push(cells);
728
+ if (end) break;
729
+ cells = []; current = []; continue;
730
+ }
731
+ if (!(item.kind === 'char' && item.value === '@')) { current.push(item); continue; }
732
+ const kind = this.rawTake(false), name = kind.kind === 'command' && kind.value === '|' ? '|' : kind.value;
733
+ if (!'><=VA|.'.includes(name) || kind.kind === 'eof') this.error('invalid-diagram', 'Expected an amscd arrow after @.', kind);
734
+ const labels = [];
735
+ if ('><VA'.includes(name)) for (let part = 0; part < 2; part++) {
736
+ const tokens = [];
737
+ for (let depth = 0, next = this.rawTake(false); depth || !(next.kind === 'char' && next.value === name); next = this.rawTake(false)) {
738
+ if (next.kind === 'eof') this.error('invalid-diagram', 'An amscd arrow is missing its closing ' + name + '.', kind);
739
+ if (next.kind === 'char') depth += next.value === '{' ? 1 : next.value === '}' ? -1 : 0;
740
+ tokens.push(next);
741
+ }
742
+ labels.push(tokens);
743
+ }
744
+ if ('VA|'.includes(name) || name === '.' && rows.length % 2) { cells.push(arrow(name, labels), this.row([])); current = []; continue; }
745
+ cells.push(current.some(part => part.kind !== 'space') ? this.subparse(current) : this.row([]), arrow(name, labels)); current = [];
746
+ }
747
+ const ending = this.plainArgument();
748
+ if (ending !== fullName) this.error('mismatched-environment', 'Expected \\end{' + fullName + '}, received \\end{' + ending + '}.', token);
749
+ for (const row of rows) if (row.length % 2 === 0 && row.at(-1).type === 'row' && !row.at(-1).children.length) row.pop();
750
+ const columns = Math.max(...rows.map(row => row.length));
751
+ return this.node('table', {env: 'CD', rows, align: Array(columns).fill('c'), rowGaps: [], rowRules: []});
752
+ }
585
753
  tableFromTokens(tokens, env) {
586
754
  return this.nested(() => {
587
755
  const parser = new MathTexParser(this.source, {tokens, scopes: this.scopes, budget: this.budget, colors: this.colors});
@@ -621,7 +789,18 @@ class MathTexParser {
621
789
  if (!align.length) this.error('invalid-alignment', 'An array needs a column specification.', token);
622
790
  return {align, columnRules, columnInsertions};
623
791
  }
624
- readTable(env, options, end) {
792
+ // mathtools' starred cases set their condition column as text, with $...$ for maths.
793
+ textCell(separator) {
794
+ const tokens = [];
795
+ for (let depth = 0, token = this.rawPeek(false); token.kind !== 'eof' && (depth > 0 || !separator(token)); token = this.rawPeek(false)) {
796
+ if (token.kind === 'char') depth += token.value === '{' ? 1 : token.value === '}' ? -1 : 0;
797
+ tokens.push(this.rawTake(false));
798
+ }
799
+ while (tokens[0]?.kind === 'space') tokens.shift();
800
+ while (tokens.at(-1)?.kind === 'space') tokens.pop();
801
+ return this.subparse(tokens, true);
802
+ }
803
+ readTable(env, options, end, textColumn = -1) {
625
804
  const rows = [], rowGaps = [], rowRules = [];
626
805
  let cells = [], endedAfterBreak = false;
627
806
  const separator = item => (item.kind === 'char' && item.value === '&') || (item.kind === 'command' && ['\\', 'cr', 'crcr'].includes(item.value)) || end(item);
@@ -639,7 +818,7 @@ class MathTexParser {
639
818
  if (cells.length || (!rows.length && !endedAfterBreak)) { cells.push(this.row([])); rows.push(cells); }
640
819
  break;
641
820
  }
642
- cells.push(this.nested(() => this.parseRow(separator)));
821
+ cells.push(cells.length === textColumn ? this.textCell(separator) : this.nested(() => this.parseRow(separator)));
643
822
  endedAfterBreak = false;
644
823
  const next = this.peek();
645
824
  if (next.kind === 'char' && next.value === '&') { this.take(); continue; }
@@ -659,7 +838,7 @@ class MathTexParser {
659
838
  if (options.align && rows.some(row => row.length > options.align.length)) this.error('invalid-alignment', 'This row has more cells than the array declares.');
660
839
  if (options.pairs && rows.some(row => row.length > options.pairs * 2)) this.error('invalid-alignment', 'This row has more cells than alignedat declares.');
661
840
  let align = options.align;
662
- if (!align) align = Array.from({length: columns}, (_, index) => /^(align|aligned|alignat|alignedat|flalign|split)$/.test(env) ? (index % 2 ? 'l' : 'r') : /cases$/.test(env) ? 'l' : options.columnAlign || 'c');
841
+ if (!align) align = Array.from({length: columns}, (_, index) => /^(align|aligned|alignat|alignedat|flalign|split)$/.test(env) ? (index % 2 ? 'l' : 'r') : /cases$/.test(env) || env === 'lgathered' ? 'l' : env === 'rgathered' ? 'r' : options.columnAlign || 'c');
663
842
  return this.node('table', {env, rows, ...options, align, rowGaps, rowRules});
664
843
  }
665
844
 
@@ -669,13 +848,18 @@ class MathTexParser {
669
848
  const nameTokens = this.rawArgument().filter(item => item.kind !== 'space');
670
849
  if (nameTokens.length !== 1 || nameTokens[0].kind !== 'command') this.error('invalid-macro', 'A macro name must be one command.', token);
671
850
  const macroName = nameTokens[0].value;
851
+ const make = value => ({kind: 'command', value, offset: token.offset});
852
+ const literal = value => ({kind: 'char', value, offset: token.offset});
672
853
  if (name === 'DeclareMathOperator') {
673
854
  const body = this.rawArgument();
674
- const make = value => ({kind: 'command', value, offset: token.offset});
675
- const literal = value => ({kind: 'char', value, offset: token.offset});
676
855
  this.scopes[this.scopes.length - 1][macroName] = {params: [], prefix: [], body: [make('operatorname'), ...(starred ? [literal('*')] : []), literal('{'), ...body, literal('}')], optional: null};
677
856
  return;
678
857
  }
858
+ if (name === 'DeclarePairedDelimiter') {
859
+ const left = this.rawArgument(), right = this.rawArgument();
860
+ this.scopes[this.scopes.length - 1][macroName] = {params: [], prefix: [], body: [make('@paired'), literal('{'), ...left, literal('}'), literal('{'), ...right, literal('}')], optional: null};
861
+ return;
862
+ }
679
863
  if (name === 'let') {
680
864
  if (this.rawPeek().kind === 'char' && this.rawPeek().value === '=') this.rawTake();
681
865
  const target = this.rawTake();
@@ -685,7 +869,7 @@ class MathTexParser {
685
869
  return;
686
870
  }
687
871
  let params = [], prefix = [], optional = null, body;
688
- if (name === 'def' || name === 'gdef') {
872
+ if (/^[egx]?def$/.test(name)) {
689
873
  const specification = [];
690
874
  while (!(this.rawPeek().kind === 'char' && this.rawPeek().value === '{')) {
691
875
  const item = this.rawTake(false);
@@ -703,6 +887,12 @@ class MathTexParser {
703
887
  } else current.push(item);
704
888
  }
705
889
  body = this.rawArgument();
890
+ if (name === 'edef' || name === 'xdef') {
891
+ // \edef expands the macros in its replacement when it is defined.
892
+ const parser = new MathTexParser(this.source, {tokens: body, scopes: this.scopes, budget: this.budget});
893
+ body = [];
894
+ for (let item = parser.take(false); item.kind !== 'eof'; item = parser.take(false)) body.push(item);
895
+ }
706
896
  } else {
707
897
  const countTokens = this.optionalRaw();
708
898
  const count = countTokens ? mathTexTokenText(countTokens).trim() : '0';
@@ -720,7 +910,7 @@ class MathTexParser {
720
910
  const existing = this.macro(macroName) || Object.hasOwn(MATH_SYMBOLS, macroName) || Object.hasOwn(MATH_TEX_VARIANTS, macroName) || MATH_NAMED_OPERATORS.has(macroName) || MATH_LIMIT_OPERATORS.has(macroName);
721
911
  if (name === 'providecommand' && existing) return;
722
912
  if (name === 'newcommand' && existing) this.error('duplicate-macro', '\\' + macroName + ' is already defined.', token);
723
- this.scopes[name === 'gdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
913
+ this.scopes[name === 'gdef' || name === 'xdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
724
914
  }
725
915
  expand(macro, token) {
726
916
  if (++this.budget.expansions > 4096) this.error('resource-limit', 'Macro expansion did not finish within the rendering limit.', token);
@@ -779,7 +969,8 @@ class MathTexParser {
779
969
  parseText(variant = 'roman') {
780
970
  const children = [];
781
971
  let value = '';
782
- const flush = () => { if (value) children.push(this.node('text', {value, variant})); value = ''; };
972
+ // TeX's text fonts join --- and -- into dashes and turn `` '' ` ' into curly quotes; typewriter text keeps them.
973
+ const flush = () => { if (value) children.push(this.node('text', {value: variant === 'monospace' ? value : value.replace(/---|--|``|''|`|'/g, run => ({'---': '—', '--': '–', '``': '“', "''": '”', '`': '‘', "'": '’'})[run]), variant})); value = ''; };
783
974
  for (;;) {
784
975
  const token = this.take(false);
785
976
  if (token.kind === 'eof') break;
@@ -850,6 +1041,7 @@ class MathTexParser {
850
1041
  if ([...letters].length !== 1) this.error('invalid-accent', 'A text accent needs one character.', token);
851
1042
  value += (letters + marks[name]).normalize('NFC'); continue;
852
1043
  }
1044
+ if (Object.hasOwn(MATH_TEX_TEXT_LETTERS, name)) { value += MATH_TEX_TEXT_LETTERS[name]; continue; }
853
1045
  if (Object.hasOwn(MATH_SYMBOLS, name) && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
854
1046
  flush();
855
1047
  const body = this.command(token);
@@ -860,7 +1052,7 @@ class MathTexParser {
860
1052
  }
861
1053
 
862
1054
  physicsCommand(name) {
863
- return /^(dv|derivative|pdv|pderivative|fdv|functionalderivative|dd|differential|qty|quantity|pqty|bqty|Bqty|vqty|abs|absolutevalue|norm|bra|ket|braket|innerproduct|ketbra|dyad|outerproduct|expval|expectationvalue|comm|commutator|acomm|anticommutator|vb|va|vu|vectorbold|vectorarrow|vectorunit|grad|gradient|divergence|curl|laplacian|eval|evaluated|order|Tr|tr|trace|rank|diag|mqty|pmqty|bmqty|vmqty|smqty)$/.test(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);
864
1056
  }
865
1057
  physics(name, token) {
866
1058
  const starred = this.is('*'); if (starred) this.take();
@@ -887,7 +1079,13 @@ class MathTexParser {
887
1079
  if (name === 'laplacian') base = this.node('scripts', {base, sup: this.literal('2', {variant: 'roman'})});
888
1080
  return this.row([base, ...(/^(divergence|curl)$/.test(name) ? [this.literal(name === 'curl' ? '×' : '⋅', {class: 'bin', variant: 'roman'})] : []), ...(this.is('{') ? [this.argument()] : [])]);
889
1081
  }
890
- if (['Tr', 'tr', 'trace', 'rank', 'diag'].includes(name)) return this.node('text', {value: name === 'trace' ? 'tr' : name, variant: 'roman', class: 'op', limits: 'never'});
1082
+ if (['Tr', 'tr', 'trace', 'rank', 'diag', 'Res'].includes(name)) return this.node('text', {value: name === 'trace' ? 'tr' : name, variant: 'roman', class: 'op', limits: 'never'});
1083
+ // \qq{text} and the \qif family: text between quads; \qc is a comma and a quad.
1084
+ if (/^q/.test(name)) {
1085
+ const quad = () => this.node('space', {width: 1}), words = {qcc: 'c.c.'};
1086
+ if (name === 'qc') return this.node('style', {class: 'punct', body: this.row([this.literal(',', {class: 'punct'}), quad()])});
1087
+ return this.row([quad(), name === 'qq' ? this.subparse(this.rawArgument(), true) : this.node('text', {value: words[name] || name.slice(1), variant: 'roman'}), quad()]);
1088
+ }
891
1089
  if (name === 'eval' || name === 'evaluated') return this.node('fence', {left: '', right: '|', body: this.argument()});
892
1090
  if (name === 'order') return this.row([this.literal('O'), this.node('fence', {left: '(', right: ')', body: this.argument()})]);
893
1091
  if (/^(mqty|pmqty|bmqty|vmqty|smqty)$/.test(name)) {
@@ -907,10 +1105,14 @@ class MathTexParser {
907
1105
  const ends = {bra: ['⟨', '|'], ket: ['|', '⟩'], pqty: ['(', ')'], bqty: ['[', ']'], Bqty: ['{', '}'], vqty: ['|', '|'], abs: ['|', '|'], absolutevalue: ['|', '|'], norm: ['‖', '‖']}[name];
908
1106
  return this.node('fence', {left: ends[0], right: ends[1], body: first});
909
1107
  }
910
- if (/^(comm|commutator|acomm|anticommutator)$/.test(name)) return this.node('fence', {left: /^(acomm|anticommutator)$/.test(name) ? '{' : '[', right: /^(acomm|anticommutator)$/.test(name) ? '}' : ']', body: this.row([first, this.literal(',', {class: 'punct'}), this.argument()])});
1108
+ if (/^(comm|commutator|acomm|anticommutator|pb|poissonbracket)$/.test(name)) return this.node('fence', {left: /^(comm|commutator)$/.test(name) ? '[' : '{', right: /^(comm|commutator)$/.test(name) ? ']' : '}', body: this.row([first, this.literal(',', {class: 'punct'}), this.argument()])});
1109
+ if (/^(mel|matrixel|matrixelement)$/.test(name)) {
1110
+ const operator = this.argument(), right = this.argument();
1111
+ return this.node('fence', {left: '⟨', right: '⟩', body: this.row([first, this.literal('|', {delimiter: true}), operator, this.literal('|', {delimiter: true}), right])});
1112
+ }
911
1113
  const second = this.is('{') ? this.argument() : null;
912
- if (/^(ketbra|dyad|outerproduct)$/.test(name)) return this.row([this.node('fence', {left: '|', right: '⟩', body: first}), this.node('fence', {left: '⟨', right: '|', body: second || first})]);
913
- if (/^(expval|expectationvalue)$/.test(name)) return this.node('fence', {left: '⟨', right: '⟩', body: second ? this.row([second, this.literal('|', {delimiter: true}), first, this.literal('|', {delimiter: true}), second]) : first});
1114
+ if (/^(ketbra|dyad|outerproduct|op)$/.test(name)) return this.row([this.node('fence', {left: '|', right: '⟩', body: first}), this.node('fence', {left: '⟨', right: '|', body: second || first})]);
1115
+ if (/^(expval|expectationvalue|ev)$/.test(name)) return this.node('fence', {left: '⟨', right: '⟩', body: second ? this.row([second, this.literal('|', {delimiter: true}), first, this.literal('|', {delimiter: true}), second]) : first});
914
1116
  return this.node('fence', {left: '⟨', right: '⟩', body: second ? this.row([first, this.literal('|', {delimiter: true}), second]) : first});
915
1117
  }
916
1118
 
@@ -922,7 +1124,7 @@ class MathTexParser {
922
1124
  }
923
1125
  chemicalRow(stop) {
924
1126
  const children = [];
925
- let spaced = true, subAllowed = false, moleculeParts = 0;
1127
+ let spaced = true, subAllowed = false, moleculeParts = 0, isotope = null;
926
1128
  const script = (key, body) => {
927
1129
  let base = children.pop() || this.row([]);
928
1130
  if (base.type !== 'scripts') base = this.node('scripts', {base});
@@ -938,6 +1140,7 @@ class MathTexParser {
938
1140
  const next = this.peek(false);
939
1141
  if (next.kind === 'eof' || stop(next)) break;
940
1142
  const token = this.take(false);
1143
+ if (isotope && !(token.kind === 'char' && /^[\^_A-Za-z]$/.test(token.value))) isotope = null;
941
1144
  if (token.kind === 'space') {
942
1145
  spaced = true; subAllowed = false; moleculeParts = 0;
943
1146
  // An operator or arrow already carries its own spacing; a separating space adds none beside it.
@@ -983,6 +1186,12 @@ class MathTexParser {
983
1186
  const value = consumeRun(character => /^[0-9+\-−IVX]$/.test(character));
984
1187
  body = value ? this.node('text', {value: value.replace(/-/g, '−'), variant: 'roman'}) : this.argument();
985
1188
  }
1189
+ // Scripts that open a term are an isotope's mass and atomic numbers, set before the next element.
1190
+ if (spaced) {
1191
+ if (!isotope) children.push(isotope = this.node('scripts', {base: this.row([]), pre: true}));
1192
+ if (isotope[key]) this.error('duplicate-script', 'An isotope cannot have two ' + (key === 'sub' ? 'subscripts' : 'superscripts') + '.', token);
1193
+ isotope[key] = body; continue;
1194
+ }
986
1195
  script(key, body); spaced = false; continue;
987
1196
  }
988
1197
  if (/^[0-9]$/.test(token.value)) {
@@ -1018,7 +1227,9 @@ class MathTexParser {
1018
1227
  }
1019
1228
  if (/^[A-Za-z]$/.test(token.value)) {
1020
1229
  const word = token.value + consumeRun(character => /^[a-z]$/.test(character));
1021
- children.push(this.node('text', {value: word === 'v' && spaced ? '↓' : word, variant: 'roman'}));
1230
+ const element = this.node('text', {value: word === 'v' && spaced && !isotope ? '↓' : word, variant: 'roman'});
1231
+ if (isotope) { isotope.base = this.node('phantom', {body: element, mode: 'v'}); isotope = null; }
1232
+ children.push(element);
1022
1233
  moleculeParts++; spaced = false; subAllowed = true; continue;
1023
1234
  }
1024
1235
  if (token.value === '#') children.push(this.literal('≡', {class: 'ord', variant: 'roman'}));
@@ -1029,6 +1240,57 @@ class MathTexParser {
1029
1240
  }
1030
1241
  return this.row(children);
1031
1242
  }
1243
+ // siunitx: \num groups digits, \si and \unit set units upright (macros or literal), \SI joins them, \ang marks degrees.
1244
+ // Formatting options are accepted and not reproduced.
1245
+ siunitx(name, token) {
1246
+ this.optionalRaw();
1247
+ if (name === 'num') return this.siNumber(this.rawArgument());
1248
+ if (name === 'si' || name === 'unit') return this.siUnit(this.rawArgument(), token);
1249
+ if (name === 'ang') {
1250
+ const parts = mathTexTokenText(this.rawArgument()).split(';');
1251
+ if (parts.length > 3) this.error('invalid-number', 'An angle has at most degrees, minutes and seconds.', token);
1252
+ return this.row(parts.flatMap((part, i) => part.trim() ? [this.siNumber(mathTexTokens(part.trim(), token.offset)), this.literal('°′″'[i], {variant: 'roman'})] : []));
1253
+ }
1254
+ const value = this.siNumber(this.rawArgument()), before = this.optionalRaw();
1255
+ 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
+ }
1257
+ siNumber(tokens) {
1258
+ const text = mathTexTokenText(tokens).replace(/\s+/g, '');
1259
+ if (!/^[-+]?(\d+[.,]?\d*|[.,]\d+)(\+-\d+[.,]?\d*)?([eE][-+]?\d+)?$/.test(text)) return this.subparse(tokens);
1260
+ const group = (digits, fromLeft) => digits.length < 5 ? digits : (fromLeft ? digits.match(/\d{1,3}/g) : digits.split('').reverse().join('').match(/\d{1,3}/g).map(part => part.split('').reverse().join('')).reverse()).join('\\,');
1261
+ const [, sign = '', whole = '', fraction, uncertainty, exponent] = /^([-+]?)(\d*)(?:[.,](\d*))?(?:\+-(\d+[.,]?\d*))?(?:[eE]([-+]?\d+))?$/.exec(text);
1262
+ const value = (sign === '-' ? '-' : sign) + (group(whole) || '0') + (fraction === undefined ? '' : '.' + group(fraction, true)) +
1263
+ (uncertainty ? '{\\pm}' + uncertainty.replace(',', '.') : '') + (exponent ? '\\times 10^{' + exponent.replace('+', '') + '}' : '');
1264
+ return this.subparse(mathTexTokens(value, tokens[0]?.offset || 0));
1265
+ }
1266
+ siUnit(tokens, token) {
1267
+ 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))))
1269
+ 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
+ let prefix = '', power = 1, per = false;
1271
+ 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)]; };
1272
+ for (let at = 0; at < tokens.length; at++) {
1273
+ const item = tokens[at], value = item.value;
1274
+ if (item.kind === 'space' || item.kind === 'char' && (value === '.' || value === '~')) continue;
1275
+ if (item.kind === 'command' && Object.hasOwn(prefixes, value)) prefix += prefixes[value];
1276
+ else if (item.kind === 'command' && value === 'per') per = true;
1277
+ else if (item.kind === 'command' && (value === 'square' || value === 'cubic')) power = value === 'square' ? 2 : 3;
1278
+ else if (item.kind === 'command' && /^(squared|cubed|tothe|raiseto)$/.test(value) && items.length) {
1279
+ let exponent = value === 'squared' ? '2' : '3';
1280
+ if (value === 'tothe' || value === 'raiseto') [exponent, at] = number(at + 1);
1281
+ if (!/^-?\d+(\.\d+)?$/.test(exponent)) this.error('invalid-unit', 'A unit power must be a number.', item);
1282
+ items.at(-1).power = exponent;
1283
+ } else if (item.kind === 'command' && Object.hasOwn(units, value) || item.kind === 'char' && /^[A-Za-z]$/.test(value)) {
1284
+ items.push({symbol: prefix + (item.kind === 'command' ? units[value] : value), power: String(power), per});
1285
+ prefix = ''; power = 1; per = false;
1286
+ } else this.error('invalid-unit', 'Unsupported unit: ' + mathTexTokenText([item]).trim() + '.', item);
1287
+ }
1288
+ if (prefix || per || !items.length) this.error('invalid-unit', 'A unit prefix or \\per needs a unit.', token);
1289
+ return this.row(items.flatMap((unit, i) => {
1290
+ 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'})})];
1292
+ }));
1293
+ }
1032
1294
  units(tokens) {
1033
1295
  let value = mathTexTokenText(tokens);
1034
1296
  value = value.replace(/(\d(?:[\d.]*\d)?)[eE]([+-]?\d+)/g, '$1\\times 10^{$2}');
@@ -1076,5 +1338,58 @@ function parseMathTex(source) {
1076
1338
  return new MathTexParser(source).parse();
1077
1339
  }
1078
1340
 
1341
+ // While a person types, a formula is unfinished where they are typing. Preview mends it there: a half-typed command
1342
+ // before the caret waits (blanked, so later offsets hold), a missing argument shows a placeholder box, and groups,
1343
+ // options, fences and environments left open at the end close. Any other fault stays a fault.
1344
+ function parseMathTexPreview(source, error, caret = source.length) {
1345
+ if (source.length > 4096) return null;
1346
+ caret = Math.max(0, Math.min(source.length, Math.floor(caret) || 0));
1347
+ let text = source;
1348
+ const tail = /(?<!\\)\\(?:[A-Za-z]*|(?:begin|end)\{[A-Za-z*]*)$/.exec(text.slice(0, caret));
1349
+ if (tail) text = text.slice(0, tail.index) + ' '.repeat(tail[0].length) + text.slice(caret);
1350
+ const atEnd = (cause, length) => /^unclosed-(group|option|environment)$/.test(cause.code) || cause.offset >= length;
1351
+ for (let attempt = 0; attempt < 24; attempt++) {
1352
+ try { return new MathTexParser(text).parse(); } catch (cause) { error = cause; }
1353
+ if (error.code === 'missing-argument' && error.offset < text.length) { text = text.slice(0, error.offset) + '{\\square}' + text.slice(error.offset); continue; }
1354
+ if (!atEnd(error, text.length)) return null;
1355
+ if (/[\^_]$/.test(text)) { text += '{\\square}'; continue; }
1356
+ if (/[{[]$/.test(text)) { text += '\\square'; continue; }
1357
+ const open = [...text.matchAll(/\\(begin|end)\{([A-Za-z*]+)\}/g)].reduce((stack, [, kind, name]) => (kind === 'begin' ? stack.push(name) : stack.pop(), stack), []).at(-1);
1358
+ const expected = /^Expected (.+)\.$/.exec(error.message)?.[1], fixes = ['}', ']', '\\right.', ...(open ? ['\\end{' + open + '}'] : []), '$', '{\\square}'];
1359
+ const first = error.code === 'unclosed-option' ? ']' : error.code === 'missing-argument' ? '{\\square}' : error.code === 'unclosed-environment' && open ? '\\end{' + open + '}' : expected && fixes.includes(expected === '\\right' ? '\\right.' : expected) ? (expected === '\\right' ? '\\right.' : expected) : '}';
1360
+ let next = null;
1361
+ for (const fix of [first, ...fixes.filter(fix => fix !== first)]) {
1362
+ try { return new MathTexParser(text + fix).parse(); }
1363
+ catch (cause) { if (!next && atEnd(cause, text.length + fix.length)) next = text + fix; }
1364
+ }
1365
+ if (!next) return null;
1366
+ text = next;
1367
+ }
1368
+ return null;
1369
+ }
1370
+
1371
+ // The command or environment a mistyped name most likely meant: one edit away (two for longer names), where swapping
1372
+ // 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';
1374
+ let mathTexNames;
1375
+ function mathSuggest(name, environment = false) {
1376
+ 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]};
1379
+ const limit = name.length > 5 ? 2 : 1;
1380
+ let best, bestDistance = limit + 1;
1381
+ for (const candidate of mathTexNames[environment ? 'environment' : 'command']) {
1382
+ if (Math.abs(candidate.length - name.length) > limit) continue;
1383
+ const d = Array.from({length: name.length + 1}, (_, i) => [i, ...Array(candidate.length).fill(0)]);
1384
+ for (let j = 1; j <= candidate.length; j++) d[0][j] = j;
1385
+ for (let i = 1; i <= name.length; i++) for (let j = 1; j <= candidate.length; j++) {
1386
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (name[i - 1] === candidate[j - 1] ? 0 : 1));
1387
+ if (i > 1 && j > 1 && name[i - 1] === candidate[j - 2] && name[i - 2] === candidate[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1388
+ }
1389
+ if (d[name.length][candidate.length] < bestDistance) { best = candidate; bestDistance = d[name.length][candidate.length]; }
1390
+ }
1391
+ return best === undefined ? undefined : (environment ? best : '\\' + best);
1392
+ }
1393
+
1079
1394
  import {MATH_SYMBOLS, MATH_NAMED_OPERATORS, MATH_LIMIT_OPERATORS} from './symbols.js';
1080
- export {parseMathTex};
1395
+ export {parseMathTex, parseMathTexPreview, mathSuggest};