rapier-math 2.3.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.
@@ -642,6 +642,7 @@ for (const name of Object.keys(MATH_SYMBOLS).filter(name => /^[a-z]+$/.test(name
642
642
  for (const name of Object.keys(MATH_SYMBOLS).filter(name => /^var[A-Z]/.test(name)))
643
643
  MATH_SYMBOLS[name] = Object.freeze({...MATH_SYMBOLS[name], variant: 'italic'});
644
644
  mathSymbolGroup('bin', `
645
+ dotminus=∸ cupdot=⊍ barvee=⊽
645
646
  pm=± mp=∓ times=× div=÷ cdot=⋅ ast=∗ star=⋆ circ=∘ bullet=∙ diamond=⋄
646
647
  cap=∩ cup=∪ uplus=⊎ sqcap=⊓ sqcup=⊔ vee/lor=∨ wedge/land=∧ setminus=∖ smallsetminus=∖
647
648
  oplus=⊕ ominus=⊖ otimes=⊗ oslash=⊘ odot=⊙ bigcirc=◯ dag/dagger=† ddag/ddagger=‡ amalg=⨿
@@ -673,6 +674,7 @@ nmid=∤ nparallel=∦ nshortmid=∤ nshortparallel=∦ nvdash=⊬ nVdash=⊮ nv
673
674
  ntriangleleft=⋪ ntriangleright=⋫ ntrianglelefteq=⋬ ntrianglerighteq=⋭ coloneqq=≔ eqqcolon=≕ vcentcolon=∶ dblcolon/Colon=∷ And=&
674
675
  `, {variant: 'roman'});
675
676
  mathSymbolGroup('rel', `
677
+ questeq=≟ veeeq=≚ stareq=≛ eqdef=≝ estimates/corresponds=≙ Equiv=≣
676
678
  leftarrow/gets=← rightarrow/to=→ leftrightarrow=↔ Leftarrow=⇐ Rightarrow=⇒ Leftrightarrow=⇔
677
679
  longleftarrow=⟵ longrightarrow=⟶ longleftrightarrow=⟷ Longleftarrow=⟸ Longrightarrow=⟹ Longleftrightarrow=⟺
678
680
  mapsto=↦ longmapsto=⟼ hookleftarrow=↩ hookrightarrow=↪ nearrow=↗ searrow=↘ nwarrow=↖ swarrow=↙
@@ -811,8 +813,11 @@ const MATH_TEX_SPACES = Object.freeze({
811
813
  quad: 1, qquad: 2, enspace: .5, enskip: .5, thinspace: 3 / 18, medspace: 4 / 18, thickspace: 5 / 18,
812
814
  negthinspace: -3 / 18, negmedspace: -4 / 18, negthickspace: -5 / 18
813
815
  });
814
- const MATH_TEX_PACKAGES = new Set(('ams amsmath amssymb amsfonts mathtools color newcommand unicode mhchem physics bbm bboldx dsfont cancel bbox boldsymbol').split(' '));
815
- 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 darray CD').split(' '));
816
+ const mathSITable = text => Object.freeze(Object.fromEntries(text.split(' ').map(entry => entry.split('='))));
817
+ 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');
818
+ 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');
819
+ const MATH_TEX_PACKAGES = new Set(('ams amsmath amssymb amsfonts mathtools color newcommand unicode mhchem physics siunitx bbm bboldx dsfont cancel bbox boldsymbol').split(' '));
820
+ 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(' '));
816
821
  const MATH_TEX_LITERAL_CLASSES = Object.freeze({
817
822
  '+': 'bin', '−': 'bin', '-': 'bin', '±': 'bin', '∓': 'bin', '×': 'bin', '÷': 'bin', '*': 'bin', '⋅': 'bin',
818
823
  '=': 'rel', '<': 'rel', '>': 'rel', '≤': 'rel', '≥': 'rel', '≠': 'rel', ':': 'rel',
@@ -938,6 +943,8 @@ class MathTexParser {
938
943
  continue;
939
944
  }
940
945
  const atom = this.parseAtom();
946
+ // A symbol remembers where its source begins, so a tap on it can find its place in the source.
947
+ if (atom && (atom.type === 'glyph' || atom.type === 'text') && atom.at === undefined) atom.at = token.offset;
941
948
  if (atom) children.push(this.readScripts(atom));
942
949
  }
943
950
  // An equation tag follows its equation wherever \tag was written.
@@ -992,6 +999,7 @@ class MathTexParser {
992
999
  }
993
1000
  const atom = this.parseAtom();
994
1001
  if (!atom) this.error('missing-argument', 'An argument must contain a mathematical expression.', token);
1002
+ if ((atom.type === 'glyph' || atom.type === 'text') && atom.at === undefined) atom.at = token.offset;
995
1003
  return atom;
996
1004
  }
997
1005
  rawArgument() {
@@ -1082,7 +1090,12 @@ class MathTexParser {
1082
1090
  if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
1083
1091
  }
1084
1092
  if (Object.hasOwn(MATH_SYMBOLS, name)) return this.node('glyph', MATH_SYMBOLS[name]);
1085
- if (Object.hasOwn(MATH_TEX_VARIANTS, name)) return this.node('style', {variant: MATH_TEX_VARIANTS[name], body: this.argument()});
1093
+ if (Object.hasOwn(MATH_TEX_VARIANTS, name)) {
1094
+ let body = this.argument();
1095
+ // amsmath's \boldsymbol and \pmb, and bm's \bm, keep one symbol's class (\binrel@); a plain group is ordinary.
1096
+ if (/^(boldsymbol|bm|pmb)$/.test(name) && body.type === 'row' && body.children.length === 1 && body.children[0].type === 'glyph') body = body.children[0];
1097
+ return this.node('style', {variant: MATH_TEX_VARIANTS[name], body});
1098
+ }
1086
1099
  if (Object.hasOwn(MATH_TEX_TEXT_VARIANTS, name)) return this.subparse(this.rawArgument(), true, MATH_TEX_TEXT_VARIANTS[name]);
1087
1100
  if (MATH_NAMED_OPERATORS.has(name) || MATH_LIMIT_OPERATORS.has(name)) {
1088
1101
  const values = {limsup: 'lim sup', liminf: 'lim inf', injlim: 'lim', projlim: 'lim', varlimsup: 'lim', varliminf: 'lim', varinjlim: 'lim', varprojlim: 'lim'};
@@ -1298,6 +1311,24 @@ class MathTexParser {
1298
1311
  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()])})]);
1299
1312
  if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
1300
1313
  if (name === 'pu') return {...this.units(this.rawArgument()), semanticRole: 'units'};
1314
+ if (/^(SI|si|num|unit|ang)$/.test(name)) return {...this.siunitx(name, token), semanticRole: 'units'};
1315
+ // mathtools \smashoperator[lr]{op}: the limits overhang the operator's own width on the named sides.
1316
+ if (name === 'smashoperator') {
1317
+ const sides = mathTexTokenText(this.optionalRaw() || []).trim() || 'lr';
1318
+ if (!/^(l|r|lr|rl)$/.test(sides)) this.error('invalid-option', 'A smashed operator side must be l, r or lr.', token);
1319
+ return this.node('style', {body: this.argument(), smashOperator: sides});
1320
+ }
1321
+ if (name === 'mathmakebox') {
1322
+ const width = this.optionalRaw(), position = mathTexTokenText(this.optionalRaw() || []).trim() || 'c';
1323
+ if (!/^[lrcs]$/.test(position)) this.error('invalid-option', 'A box position must be l, r, c or s.', token);
1324
+ const body = this.argument();
1325
+ return width ? this.node('style', {body, width: this.dimension(mathTexTokenText(width), token), align: {l: 'left', r: 'right'}[position] || 'center'}) : body;
1326
+ }
1327
+ // amsmath \idotsint: two integral signs joined by centred dots, one operator.
1328
+ if (name === 'idotsint') {
1329
+ const integral = () => this.literal('∫', {large: true, limits: 'never', class: 'op'});
1330
+ 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()])});
1331
+ }
1301
1332
  if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
1302
1333
  if (name === 'mmlToken') return this.mathmlToken(token);
1303
1334
  if (name === 'unicode' || name === 'char') return this.character(name, token);
@@ -1366,7 +1397,7 @@ class MathTexParser {
1366
1397
 
1367
1398
  environment(fullName, token) {
1368
1399
  const env = fullName.replace(/\*$/, '');
1369
- if (!MATH_TEX_ENVIRONMENTS.has(env)) this.error('unsupported-environment', 'Unsupported maths environment: ' + fullName + '.', token, 'begin');
1400
+ if (!MATH_TEX_ENVIRONMENTS.has(env)) throw Object.assign(new MathTexError('unsupported-environment', 'Unsupported maths environment: ' + fullName + '.', token.offset, 'begin'), {environment: env});
1370
1401
  return this.nested(() => {
1371
1402
  let options = {};
1372
1403
  const position = this.optionalRaw();
@@ -1383,7 +1414,7 @@ class MathTexParser {
1383
1414
  if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 256) this.error('invalid-alignment', 'An alignedat environment needs its number of column pairs.', token);
1384
1415
  options.pairs = Number(value);
1385
1416
  }
1386
- const body = this.readTable(env, options, item => item.kind === 'command' && item.value === 'end');
1417
+ const body = this.readTable(env, options, item => item.kind === 'command' && item.value === 'end', /cases\*$/.test(fullName) ? 1 : -1);
1387
1418
  this.expect('end', 'command');
1388
1419
  const ending = this.plainArgument();
1389
1420
  if (ending !== fullName) this.error('mismatched-environment', 'Expected \\end{' + fullName + '}, received \\end{' + ending + '}.', token);
@@ -1473,7 +1504,18 @@ class MathTexParser {
1473
1504
  if (!align.length) this.error('invalid-alignment', 'An array needs a column specification.', token);
1474
1505
  return {align, columnRules, columnInsertions};
1475
1506
  }
1476
- readTable(env, options, end) {
1507
+ // mathtools' starred cases set their condition column as text, with $...$ for maths.
1508
+ textCell(separator) {
1509
+ const tokens = [];
1510
+ for (let depth = 0, token = this.rawPeek(false); token.kind !== 'eof' && (depth > 0 || !separator(token)); token = this.rawPeek(false)) {
1511
+ if (token.kind === 'char') depth += token.value === '{' ? 1 : token.value === '}' ? -1 : 0;
1512
+ tokens.push(this.rawTake(false));
1513
+ }
1514
+ while (tokens[0]?.kind === 'space') tokens.shift();
1515
+ while (tokens.at(-1)?.kind === 'space') tokens.pop();
1516
+ return this.subparse(tokens, true);
1517
+ }
1518
+ readTable(env, options, end, textColumn = -1) {
1477
1519
  const rows = [], rowGaps = [], rowRules = [];
1478
1520
  let cells = [], endedAfterBreak = false;
1479
1521
  const separator = item => (item.kind === 'char' && item.value === '&') || (item.kind === 'command' && ['\\', 'cr', 'crcr'].includes(item.value)) || end(item);
@@ -1491,7 +1533,7 @@ class MathTexParser {
1491
1533
  if (cells.length || (!rows.length && !endedAfterBreak)) { cells.push(this.row([])); rows.push(cells); }
1492
1534
  break;
1493
1535
  }
1494
- cells.push(this.nested(() => this.parseRow(separator)));
1536
+ cells.push(cells.length === textColumn ? this.textCell(separator) : this.nested(() => this.parseRow(separator)));
1495
1537
  endedAfterBreak = false;
1496
1538
  const next = this.peek();
1497
1539
  if (next.kind === 'char' && next.value === '&') { this.take(); continue; }
@@ -1511,7 +1553,7 @@ class MathTexParser {
1511
1553
  if (options.align && rows.some(row => row.length > options.align.length)) this.error('invalid-alignment', 'This row has more cells than the array declares.');
1512
1554
  if (options.pairs && rows.some(row => row.length > options.pairs * 2)) this.error('invalid-alignment', 'This row has more cells than alignedat declares.');
1513
1555
  let align = options.align;
1514
- 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');
1556
+ 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');
1515
1557
  return this.node('table', {env, rows, ...options, align, rowGaps, rowRules});
1516
1558
  }
1517
1559
 
@@ -1725,7 +1767,7 @@ class MathTexParser {
1725
1767
  }
1726
1768
 
1727
1769
  physicsCommand(name) {
1728
- 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);
1770
+ 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);
1729
1771
  }
1730
1772
  physics(name, token) {
1731
1773
  const starred = this.is('*'); if (starred) this.take();
@@ -1752,7 +1794,13 @@ class MathTexParser {
1752
1794
  if (name === 'laplacian') base = this.node('scripts', {base, sup: this.literal('2', {variant: 'roman'})});
1753
1795
  return this.row([base, ...(/^(divergence|curl)$/.test(name) ? [this.literal(name === 'curl' ? '×' : '⋅', {class: 'bin', variant: 'roman'})] : []), ...(this.is('{') ? [this.argument()] : [])]);
1754
1796
  }
1755
- if (['Tr', 'tr', 'trace', 'rank', 'diag'].includes(name)) return this.node('text', {value: name === 'trace' ? 'tr' : name, variant: 'roman', class: 'op', limits: 'never'});
1797
+ if (['Tr', 'tr', 'trace', 'rank', 'diag', 'Res'].includes(name)) return this.node('text', {value: name === 'trace' ? 'tr' : name, variant: 'roman', class: 'op', limits: 'never'});
1798
+ // \qq{text} and the \qif family: text between quads; \qc is a comma and a quad.
1799
+ if (/^q/.test(name)) {
1800
+ const quad = () => this.node('space', {width: 1}), words = {qcc: 'c.c.'};
1801
+ if (name === 'qc') return this.node('style', {class: 'punct', body: this.row([this.literal(',', {class: 'punct'}), quad()])});
1802
+ return this.row([quad(), name === 'qq' ? this.subparse(this.rawArgument(), true) : this.node('text', {value: words[name] || name.slice(1), variant: 'roman'}), quad()]);
1803
+ }
1756
1804
  if (name === 'eval' || name === 'evaluated') return this.node('fence', {left: '', right: '|', body: this.argument()});
1757
1805
  if (name === 'order') return this.row([this.literal('O'), this.node('fence', {left: '(', right: ')', body: this.argument()})]);
1758
1806
  if (/^(mqty|pmqty|bmqty|vmqty|smqty)$/.test(name)) {
@@ -1772,10 +1820,14 @@ class MathTexParser {
1772
1820
  const ends = {bra: ['⟨', '|'], ket: ['|', '⟩'], pqty: ['(', ')'], bqty: ['[', ']'], Bqty: ['{', '}'], vqty: ['|', '|'], abs: ['|', '|'], absolutevalue: ['|', '|'], norm: ['‖', '‖']}[name];
1773
1821
  return this.node('fence', {left: ends[0], right: ends[1], body: first});
1774
1822
  }
1775
- 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()])});
1823
+ 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()])});
1824
+ if (/^(mel|matrixel|matrixelement)$/.test(name)) {
1825
+ const operator = this.argument(), right = this.argument();
1826
+ return this.node('fence', {left: '⟨', right: '⟩', body: this.row([first, this.literal('|', {delimiter: true}), operator, this.literal('|', {delimiter: true}), right])});
1827
+ }
1776
1828
  const second = this.is('{') ? this.argument() : null;
1777
- if (/^(ketbra|dyad|outerproduct)$/.test(name)) return this.row([this.node('fence', {left: '|', right: '⟩', body: first}), this.node('fence', {left: '⟨', right: '|', body: second || first})]);
1778
- 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});
1829
+ 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})]);
1830
+ 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});
1779
1831
  return this.node('fence', {left: '⟨', right: '⟩', body: second ? this.row([first, this.literal('|', {delimiter: true}), second]) : first});
1780
1832
  }
1781
1833
 
@@ -1787,7 +1839,7 @@ class MathTexParser {
1787
1839
  }
1788
1840
  chemicalRow(stop) {
1789
1841
  const children = [];
1790
- let spaced = true, subAllowed = false, moleculeParts = 0;
1842
+ let spaced = true, subAllowed = false, moleculeParts = 0, isotope = null;
1791
1843
  const script = (key, body) => {
1792
1844
  let base = children.pop() || this.row([]);
1793
1845
  if (base.type !== 'scripts') base = this.node('scripts', {base});
@@ -1803,6 +1855,7 @@ class MathTexParser {
1803
1855
  const next = this.peek(false);
1804
1856
  if (next.kind === 'eof' || stop(next)) break;
1805
1857
  const token = this.take(false);
1858
+ if (isotope && !(token.kind === 'char' && /^[\^_A-Za-z]$/.test(token.value))) isotope = null;
1806
1859
  if (token.kind === 'space') {
1807
1860
  spaced = true; subAllowed = false; moleculeParts = 0;
1808
1861
  // An operator or arrow already carries its own spacing; a separating space adds none beside it.
@@ -1848,6 +1901,12 @@ class MathTexParser {
1848
1901
  const value = consumeRun(character => /^[0-9+\-−IVX]$/.test(character));
1849
1902
  body = value ? this.node('text', {value: value.replace(/-/g, '−'), variant: 'roman'}) : this.argument();
1850
1903
  }
1904
+ // Scripts that open a term are an isotope's mass and atomic numbers, set before the next element.
1905
+ if (spaced) {
1906
+ if (!isotope) children.push(isotope = this.node('scripts', {base: this.row([]), pre: true}));
1907
+ if (isotope[key]) this.error('duplicate-script', 'An isotope cannot have two ' + (key === 'sub' ? 'subscripts' : 'superscripts') + '.', token);
1908
+ isotope[key] = body; continue;
1909
+ }
1851
1910
  script(key, body); spaced = false; continue;
1852
1911
  }
1853
1912
  if (/^[0-9]$/.test(token.value)) {
@@ -1883,7 +1942,9 @@ class MathTexParser {
1883
1942
  }
1884
1943
  if (/^[A-Za-z]$/.test(token.value)) {
1885
1944
  const word = token.value + consumeRun(character => /^[a-z]$/.test(character));
1886
- children.push(this.node('text', {value: word === 'v' && spaced ? '↓' : word, variant: 'roman'}));
1945
+ const element = this.node('text', {value: word === 'v' && spaced && !isotope ? '↓' : word, variant: 'roman'});
1946
+ if (isotope) { isotope.base = this.node('phantom', {body: element, mode: 'v'}); isotope = null; }
1947
+ children.push(element);
1887
1948
  moleculeParts++; spaced = false; subAllowed = true; continue;
1888
1949
  }
1889
1950
  if (token.value === '#') children.push(this.literal('≡', {class: 'ord', variant: 'roman'}));
@@ -1894,6 +1955,57 @@ class MathTexParser {
1894
1955
  }
1895
1956
  return this.row(children);
1896
1957
  }
1958
+ // siunitx: \num groups digits, \si and \unit set units upright (macros or literal), \SI joins them, \ang marks degrees.
1959
+ // Formatting options are accepted and not reproduced.
1960
+ siunitx(name, token) {
1961
+ this.optionalRaw();
1962
+ if (name === 'num') return this.siNumber(this.rawArgument());
1963
+ if (name === 'si' || name === 'unit') return this.siUnit(this.rawArgument(), token);
1964
+ if (name === 'ang') {
1965
+ const parts = mathTexTokenText(this.rawArgument()).split(';');
1966
+ if (parts.length > 3) this.error('invalid-number', 'An angle has at most degrees, minutes and seconds.', token);
1967
+ return this.row(parts.flatMap((part, i) => part.trim() ? [this.siNumber(mathTexTokens(part.trim(), token.offset)), this.literal('°′″'[i], {variant: 'roman'})] : []));
1968
+ }
1969
+ const value = this.siNumber(this.rawArgument()), before = this.optionalRaw();
1970
+ 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)]);
1971
+ }
1972
+ siNumber(tokens) {
1973
+ const text = mathTexTokenText(tokens).replace(/\s+/g, '');
1974
+ if (!/^[-+]?(\d+[.,]?\d*|[.,]\d+)(\+-\d+[.,]?\d*)?([eE][-+]?\d+)?$/.test(text)) return this.subparse(tokens);
1975
+ 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('\\,');
1976
+ const [, sign = '', whole = '', fraction, uncertainty, exponent] = /^([-+]?)(\d*)(?:[.,](\d*))?(?:\+-(\d+[.,]?\d*))?(?:[eE]([-+]?\d+))?$/.exec(text);
1977
+ const value = (sign === '-' ? '-' : sign) + (group(whole) || '0') + (fraction === undefined ? '' : '.' + group(fraction, true)) +
1978
+ (uncertainty ? '{\\pm}' + uncertainty.replace(',', '.') : '') + (exponent ? '\\times 10^{' + exponent.replace('+', '') + '}' : '');
1979
+ return this.subparse(mathTexTokens(value, tokens[0]?.offset || 0));
1980
+ }
1981
+ siUnit(tokens, token) {
1982
+ const units = MATH_SI_UNITS, prefixes = MATH_SI_PREFIXES, items = [];
1983
+ 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))))
1984
+ return this.node('style', {variant: 'roman', body: this.subparse(tokens.map(item => item.kind === 'char' && (item.value === '.' || item.value === '~') ? {...item, kind: 'command', value: ','} : item))});
1985
+ let prefix = '', power = 1, per = false;
1986
+ 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)]; };
1987
+ for (let at = 0; at < tokens.length; at++) {
1988
+ const item = tokens[at], value = item.value;
1989
+ if (item.kind === 'space' || item.kind === 'char' && (value === '.' || value === '~')) continue;
1990
+ if (item.kind === 'command' && Object.hasOwn(prefixes, value)) prefix += prefixes[value];
1991
+ else if (item.kind === 'command' && value === 'per') per = true;
1992
+ else if (item.kind === 'command' && (value === 'square' || value === 'cubic')) power = value === 'square' ? 2 : 3;
1993
+ else if (item.kind === 'command' && /^(squared|cubed|tothe|raiseto)$/.test(value) && items.length) {
1994
+ let exponent = value === 'squared' ? '2' : '3';
1995
+ if (value === 'tothe' || value === 'raiseto') [exponent, at] = number(at + 1);
1996
+ if (!/^-?\d+(\.\d+)?$/.test(exponent)) this.error('invalid-unit', 'A unit power must be a number.', item);
1997
+ items.at(-1).power = exponent;
1998
+ } else if (item.kind === 'command' && Object.hasOwn(units, value) || item.kind === 'char' && /^[A-Za-z]$/.test(value)) {
1999
+ items.push({symbol: prefix + (item.kind === 'command' ? units[value] : value), power: String(power), per});
2000
+ prefix = ''; power = 1; per = false;
2001
+ } else this.error('invalid-unit', 'Unsupported unit: ' + mathTexTokenText([item]).trim() + '.', item);
2002
+ }
2003
+ if (prefix || per || !items.length) this.error('invalid-unit', 'A unit prefix or \\per needs a unit.', token);
2004
+ return this.row(items.flatMap((unit, i) => {
2005
+ const exponent = (unit.per ? '−' : '') + unit.power.replace('-', '−'), base = this.node('text', {value: unit.symbol, variant: 'roman'});
2006
+ return [...(i ? [this.node('space', {width: 3 / 18})] : []), exponent === '1' ? base : this.node('scripts', {base, sup: this.node('text', {value: exponent, variant: 'roman'})})];
2007
+ }));
2008
+ }
1897
2009
  units(tokens) {
1898
2010
  let value = mathTexTokenText(tokens);
1899
2011
  value = value.replace(/(\d(?:[\d.]*\d)?)[eE]([+-]?\d+)/g, '$1\\times 10^{$2}');
@@ -1941,6 +2053,59 @@ function parseMathTex(source) {
1941
2053
  return new MathTexParser(source).parse();
1942
2054
  }
1943
2055
 
2056
+ // While a person types, a formula is unfinished where they are typing. Preview mends it there: a half-typed command
2057
+ // before the caret waits (blanked, so later offsets hold), a missing argument shows a placeholder box, and groups,
2058
+ // options, fences and environments left open at the end close. Any other fault stays a fault.
2059
+ function parseMathTexPreview(source, error, caret = source.length) {
2060
+ if (source.length > 4096) return null;
2061
+ caret = Math.max(0, Math.min(source.length, Math.floor(caret) || 0));
2062
+ let text = source;
2063
+ const tail = /(?<!\\)\\(?:[A-Za-z]*|(?:begin|end)\{[A-Za-z*]*)$/.exec(text.slice(0, caret));
2064
+ if (tail) text = text.slice(0, tail.index) + ' '.repeat(tail[0].length) + text.slice(caret);
2065
+ const atEnd = (cause, length) => /^unclosed-(group|option|environment)$/.test(cause.code) || cause.offset >= length;
2066
+ for (let attempt = 0; attempt < 24; attempt++) {
2067
+ try { return new MathTexParser(text).parse(); } catch (cause) { error = cause; }
2068
+ if (error.code === 'missing-argument' && error.offset < text.length) { text = text.slice(0, error.offset) + '{\\square}' + text.slice(error.offset); continue; }
2069
+ if (!atEnd(error, text.length)) return null;
2070
+ if (/[\^_]$/.test(text)) { text += '{\\square}'; continue; }
2071
+ if (/[{[]$/.test(text)) { text += '\\square'; continue; }
2072
+ const open = [...text.matchAll(/\\(begin|end)\{([A-Za-z*]+)\}/g)].reduce((stack, [, kind, name]) => (kind === 'begin' ? stack.push(name) : stack.pop(), stack), []).at(-1);
2073
+ const expected = /^Expected (.+)\.$/.exec(error.message)?.[1], fixes = ['}', ']', '\\right.', ...(open ? ['\\end{' + open + '}'] : []), '$', '{\\square}'];
2074
+ 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) : '}';
2075
+ let next = null;
2076
+ for (const fix of [first, ...fixes.filter(fix => fix !== first)]) {
2077
+ try { return new MathTexParser(text + fix).parse(); }
2078
+ catch (cause) { if (!next && atEnd(cause, text.length + fix.length)) next = text + fix; }
2079
+ }
2080
+ if (!next) return null;
2081
+ text = next;
2082
+ }
2083
+ return null;
2084
+ }
2085
+
2086
+ // The command or environment a mistyped name most likely meant: one edit away (two for longer names), where swapping
2087
+ // two neighbouring letters is one edit.
2088
+ 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';
2089
+ let mathTexNames;
2090
+ function mathSuggest(name, environment = false) {
2091
+ if (typeof name !== 'string' || name.length < 2 || name.length > 32) return undefined;
2092
+ mathTexNames ||= {command: [...new Set([...MATH_TEX_STRUCTURE.split(' '), ...Object.keys(MATH_SYMBOLS), ...Object.keys(MATH_TEX_VARIANTS), ...Object.keys(MATH_TEX_TEXT_VARIANTS),
2093
+ ...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]};
2094
+ const limit = name.length > 5 ? 2 : 1;
2095
+ let best, bestDistance = limit + 1;
2096
+ for (const candidate of mathTexNames[environment ? 'environment' : 'command']) {
2097
+ if (Math.abs(candidate.length - name.length) > limit) continue;
2098
+ const d = Array.from({length: name.length + 1}, (_, i) => [i, ...Array(candidate.length).fill(0)]);
2099
+ for (let j = 1; j <= candidate.length; j++) d[0][j] = j;
2100
+ for (let i = 1; i <= name.length; i++) for (let j = 1; j <= candidate.length; j++) {
2101
+ 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));
2102
+ 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);
2103
+ }
2104
+ if (d[name.length][candidate.length] < bestDistance) { best = candidate; bestDistance = d[name.length][candidate.length]; }
2105
+ }
2106
+ return best === undefined ? undefined : (environment ? best : '\\' + best);
2107
+ }
2108
+
1944
2109
  // SPDX-License-Identifier: MIT
1945
2110
  // Source custody and bounded diagnostics shared by SVG and MathML.
1946
2111
  function mathSourceUTF16(source) {
@@ -1991,6 +2156,8 @@ function mathDiagnostic(cause) {
1991
2156
  offset:Number.isFinite(cause?.offset)?cause.offset:0};
1992
2157
  if(message.length>1024 || cause?.messageTruncated)error.messageTruncated=true;
1993
2158
  if(cause?.sourceOmitted)error.sourceOmitted=true;
2159
+ const suggestion=cause?.suggestion ?? (cause?.code==='unsupported-command'?mathSuggest(cause.command):cause?.code==='unsupported-environment'?mathSuggest(cause.environment,true):undefined);
2160
+ if(suggestion)error.suggestion=suggestion;
1994
2161
  if(rawCommand!==undefined) {
1995
2162
  const command=String(rawCommand);
1996
2163
  error.command=command.slice(0,128).replace(/[\ud800-\udbff]$/,'');
@@ -1999,10 +2166,13 @@ function mathDiagnostic(cause) {
1999
2166
  return error;
2000
2167
  }
2001
2168
 
2002
- function mathPrepare(source) {
2169
+ function mathPrepare(source, options) {
2003
2170
  const text = String(source ?? ''), safe = mathAdmitSource(text);
2004
2171
  let tree, error = safe.error;
2005
- if (!error) try { tree = parseMathTex(text); } catch (cause) { error = mathDiagnostic(cause); }
2172
+ if (!error) try { tree = parseMathTex(text); } catch (cause) {
2173
+ tree = options?.preview ? parseMathTexPreview(text, cause, options.caret ?? text.length) : null;
2174
+ if (!tree) { tree = undefined; error = mathDiagnostic(cause); }
2175
+ }
2006
2176
  return {text, safe, tree, error};
2007
2177
  }
2008
2178
 
@@ -2010,11 +2180,11 @@ function mathPrepare(source) {
2010
2180
  // Unicode mathematical alphabets shared by SVG and MathML. No font lookup.
2011
2181
  const MATH_STYLED_RANGES = {
2012
2182
  italic: [0x1d434, 0x1d44e, null], bold: [0x1d400, 0x1d41a, 0x1d7ce],
2013
- 'bold-italic': [0x1d468, 0x1d482, null], script: [0x1d49c, 0x1d4b6, null],
2183
+ 'bold-italic': [0x1d468, 0x1d482, 0x1d7ce], script: [0x1d49c, 0x1d4b6, null],
2014
2184
  'bold-script': [0x1d4d0, 0x1d4ea, null], fraktur: [0x1d504, 0x1d51e, null],
2015
2185
  'bold-fraktur': [0x1d56c, 0x1d586, null], 'double-struck': [0x1d538, 0x1d552, 0x1d7d8],
2016
2186
  'sans-serif': [0x1d5a0, 0x1d5ba, 0x1d7e2], 'sans-serif-bold': [0x1d5d4, 0x1d5ee, 0x1d7ec],
2017
- 'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, null],
2187
+ 'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, 0x1d7ec],
2018
2188
  monospace: [0x1d670, 0x1d68a, 0x1d7f6],
2019
2189
  };
2020
2190
  const MATH_STYLED_LEGACY = {
@@ -2112,8 +2282,10 @@ function mathGlyphIndex(id, c, extra = {}) {
2112
2282
  function mathGlyph(value, c, extra = {}) {
2113
2283
  const cp = value.codePointAt(0);
2114
2284
  if (value.length !== (cp > 0xffff ? 2 : 1)) return mathText(value, c, extra);
2115
- const mapped = mathStyledCodePoint(cp, extra.variant || c.variant);
2116
- const id = MATH_FONT.chars[mapped] ?? MATH_FONT.chars[cp];
2285
+ const variant = extra.variant || c.variant, mapped = mathStyledCodePoint(cp, variant);
2286
+ // A styled dotless i or j is the styled letter's dotless form (Unicode has italic ones only).
2287
+ const dotless = (cp === 0x1d6a4 || cp === 0x1d6a5) && !/^(normal|italic|roman)$/.test(variant) ? MATH_FONT.dotless[MATH_FONT.chars[mathStyledCodePoint(cp - 0x1d6a4 + 105, variant)]] : undefined;
2288
+ const id = dotless ?? MATH_FONT.chars[mapped] ?? MATH_FONT.chars[cp];
2117
2289
  if (id === undefined) {
2118
2290
  const composed = mathFallbackGlyph(value, c, extra);
2119
2291
  if (composed) return composed;
@@ -2253,7 +2425,9 @@ function mathStretch(value, target, c, horizontal = false) {
2253
2425
  function mathDelimiter(value, target, c) {
2254
2426
  if(!value || value==='.')return mathBox();
2255
2427
  const b=mathStretch(value,target,c), axis=mathConstant('AxisHeight',c,0.25);
2256
- return mathCompose([[b,0,-(b.inkTop+b.inkBottom)/2-axis]],b.w,{class:'inner',extended:true,italic:b.italic});
2428
+ // TeXbook rule 19 centres a delimiter's box on the axis; a corner's box keeps it at its corner.
2429
+ const centre=b.extended || b.glyph===undefined?(b.inkTop+b.inkBottom)/2:(b.d-b.h)/2;
2430
+ return mathCompose([[b,0,-centre-axis]],b.w,{class:'inner',extended:true,italic:b.italic});
2257
2431
  }
2258
2432
 
2259
2433
  // The TeXbook's inter-atom spacing table (chapter 18). Rows: the left atom; columns: the right atom, in
@@ -2301,7 +2475,7 @@ function mathRow(children,c) {
2301
2475
  }
2302
2476
  const last=boxes.at(-1);
2303
2477
  return mathCompose(items,x,{class:boxes.length===1?boxes[0].class:'ord',italic:boxes.length!==1 && last?.class==='op'?0:last?.italic || 0,rowItems:items,
2304
- ...(boxes.length===1 ? {accent:last.accent,limits:last.limits,large:last.large,scriptBase:last.scriptBase} : {})});
2478
+ ...(boxes.length===1 ? {accent:last.accent,limits:last.limits,large:last.large,scriptBase:last.scriptBase,accentInk:last.accentInk} : {})});
2305
2479
  }
2306
2480
 
2307
2481
  function mathKern(b,corner,height) {
@@ -2326,12 +2500,13 @@ function mathContourBands(box, dy = 0) {
2326
2500
  return bands;
2327
2501
  }
2328
2502
 
2503
+ const mathScriptGap = c => c.screen ? Math.max(.035 * mathScale(c), .9 / (c.screen.fontSize * c.screen.pixelRatio)) : .025 * mathScale(c);
2329
2504
  function mathContourScript(base, script, dy, nominal, c) {
2330
2505
  const a = mathContourBands(base);
2331
2506
  if (!a) return nominal;
2332
2507
  const b = mathContourBands(script, dy) || [{top: script.inkTop + dy, bottom: script.inkBottom + dy,
2333
2508
  left: script.left, right: script.right}];
2334
- const gap = c.screen ? Math.max(.035 * mathScale(c), .9 / (c.screen.fontSize * c.screen.pixelRatio)) : .025 * mathScale(c);
2509
+ const gap = mathScriptGap(c);
2335
2510
  let j = 0, edge = -Infinity;
2336
2511
  for (const left of a) {
2337
2512
  while (j < b.length && b[j].bottom + gap < left.top) j++;
@@ -2376,7 +2551,10 @@ function mathScripts(n,c) {
2376
2551
  const kern=Math.min(mathKern(base,0,rise-upDescent)+mathKern(up,3,-upDescent),mathKern(base,0,baseAscent)+mathKern(up,3,baseAscent-rise));
2377
2552
  // A large operator's italic correction moves its subscript left, not its superscript right.
2378
2553
  const nominal=b.w+(b.large?0:b.italic || 0)+kern;
2379
- const x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,up,-rise,nominal,c);
2554
+ let x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,up,-rise,nominal,c);
2555
+ // A superscript beside an over-accent clears the accent's ink as well as the letter's.
2556
+ const a=b.accentInk,gap=mathScriptGap(c);
2557
+ if(a && up.inkTop-rise<a.bottom+gap && up.inkBottom-rise+gap>a.top)x=Math.max(x,a.right+gap-up.left);
2380
2558
  items.push([up,x,-rise]);w=Math.max(w,x+up.w);
2381
2559
  }
2382
2560
  if (down) {
@@ -2387,7 +2565,9 @@ function mathScripts(n,c) {
2387
2565
  }
2388
2566
  // \prescript's scripts end together at its base.
2389
2567
  if (n.pre) for (const item of items.slice(1)) item[1]=w-item[0].w;
2390
- return mathCompose(items,w+mathConstant('SpaceAfterScript',c,0.05),{class:b.class});
2568
+ // A subscript tucked under a slanted letter leaves the letter's top overhang for the next atom to clear.
2569
+ const advance=w+mathConstant('SpaceAfterScript',c,0.05);
2570
+ return mathCompose(items,advance,{class:b.class,italic:n.pre || b.large?0:Math.max(0,b.w+(b.italic || 0)-advance)});
2391
2571
  }
2392
2572
 
2393
2573
  function mathFraction(n,c,width) {
@@ -2412,10 +2592,11 @@ function mathFraction(n,c,width) {
2412
2592
  const numeratorX=n.align==='l'?pad:n.align==='r'?w-pad-top.w:(w-top.w)/2;
2413
2593
  const items=[[top,numeratorX,-rise],[bottom,(w-bottom.w)/2,drop]];
2414
2594
  if (line) items.push([mathRule(w,line,-axis-line/2),0,0]);
2415
- const b=mathCompose(items,w,{class:'inner',innerLines:top.lines || 1,fitted:!!top.fitted});
2595
+ // LaTeX's \frac, \binom and \genfrac brace their fraction: an ordinary atom, not TeX's bare inner.
2596
+ const b=mathCompose(items,w,{class:'ord',innerLines:top.lines || 1,fitted:!!top.fitted});
2416
2597
  if(width!==undefined && c.screen)b.refit=ratio=>mathFraction(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()},width);
2417
2598
  // TeX's generalized fractions fence at least its delim1 (display) or delim2 size.
2418
- if (n.left || n.right) return mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.39:1.01);
2599
+ if (n.left || n.right) return {...mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.39:1.01),class:'ord'};
2419
2600
  return b;
2420
2601
  }
2421
2602
 
@@ -2428,7 +2609,7 @@ function mathRoot(n,c) {
2428
2609
  const rise=-sign.inkTop-body.h-gap-line,
2429
2610
  index=n.index?mathLayout(n.index,{...c,level:2,display:false}):null;
2430
2611
  let before=0,idxX=0;
2431
- if(index) {idxX=Math.max(0,mathConstant('RadicalKernBeforeDegree',c,0.2));before=idxX+index.w+Math.max(-index.w,mathConstant('RadicalKernAfterDegree',c,-0.3));}
2612
+ if(index) {idxX=Math.max(0,mathConstant('RadicalKernBeforeDegree',c,0.2));before=Math.max(0,idxX+index.w+mathConstant('RadicalKernAfterDegree',c,-0.3));}
2432
2613
  const bodyX=before+sign.w,w=bodyX+body.w,items=[[sign,before,rise],[body,bodyX,0]];
2433
2614
  items.push([mathRule(body.w,line,-body.h-gap-line),bodyX,0]);
2434
2615
  if(index) {const ratio=(MATH_FONT.constants.RadicalDegreeBottomRaisePercent ?? 60)/100;items.push([index,idxX,sign.inkBottom+rise-(sign.inkBottom-sign.inkTop)*ratio-index.inkBottom]);}
@@ -2445,7 +2626,8 @@ function mathAccent(n,c) {
2445
2626
  const position=n.position || 'over';let nucleus=n.base;
2446
2627
  while(nucleus?.type==='style' || (nucleus?.type==='row' && nucleus.children.length===1))nucleus=nucleus.type==='style'?nucleus.body:nucleus.children[0];
2447
2628
  const b=mathLayout(n.base,position==='under'?c:{...c,cramped:true,dotless:nucleus?.type==='glyph' && !n.overlay && /^[\u0300-\u036f\u20d0-\u20ff]$/u.test(n.value)}),s=mathScale(c);
2448
- const semantics={class:n.class || b.class,limits:n.limits || b.limits,italic:b.italic,accent:b.accent,scriptBase:b.scriptBase || b};
2629
+ // A brace is an operator: centred on its base, with no italic correction to shift its labels.
2630
+ const brace=n.limits==='always',semantics={class:n.class || b.class,limits:n.limits || b.limits,italic:brace?0:b.italic,accent:b.accent,scriptBase:b.scriptBase || b};
2449
2631
  if(n.overlay) {
2450
2632
  const w=Math.max(b.w,0.2*s),line=mathConstant('FractionRuleThickness',c,0.04);
2451
2633
  const rising='M0 '+mathNumber(b.d)+'L'+mathNumber(w)+' '+mathNumber(-b.h),
@@ -2467,20 +2649,26 @@ function mathAccent(n,c) {
2467
2649
  // An under-accent (or \slashed's stroke) centres on its base, as in TeX and MathML Core: attachment points are for top accents.
2468
2650
  const value=names[n.value] || n.value,accentStyle={...c,flattenAccent:position!=='under' && b.h>mathConstant('FlattenedAccentBaseHeight',c,0.65)},
2469
2651
  a=n.stretch?mathStretch(value,Math.max(b.w,s*0.3),accentStyle,true):mathGlyph(value,accentStyle,{variant:'roman'}),
2470
- x=position!=='over'?(b.w-a.w)/2:(b.accent ?? b.w/2)-(a.accent ?? a.w/2),combining=/^[\u0300-\u036f\u20d0-\u20ff]$/u.test(value);
2652
+ x=position!=='over' || brace?(b.w-a.w)/2:(b.accent ?? b.w/2)-(a.accent ?? a.w/2),combining=/^[\u0300-\u036f\u20d0-\u20ff]$/u.test(value);
2471
2653
  let y;
2472
2654
  if(position==='through')y=0;
2473
2655
  else if(position==='under')y=b.d+mathConstant('UnderbarVerticalGap',c,0.1)-a.inkTop;
2474
2656
  else if(combining)y=-Math.max(0,b.h-mathConstant('AccentBaseHeight',c,0.48));
2475
2657
  else y=-b.h-mathConstant('OverbarVerticalGap',c,0.1)-a.inkBottom;
2658
+ // A combining under-accent's box is its ink: its advance box rests far below the mark.
2659
+ if(position==='under')return mathCompose([[b,0,0],[{...a,h:-a.inkTop,d:a.inkBottom},x,y]],b.w,semantics);
2660
+ if(position==='over') {
2661
+ const g=a.glyph===undefined?null:MATH_FONT.glyph(a.glyph),left=g?(a.glyphX || 0)+g[1]*a.unitScale:a.left,right=g?(a.glyphX || 0)+g[3]*a.unitScale:a.right;
2662
+ semantics.accentInk={left:x+left,right:x+right,top:y+a.inkTop,bottom:y+a.inkBottom};
2663
+ }
2476
2664
  return mathCompose([[b,0,0],[a,x,y]],b.w,semantics);
2477
2665
  }
2478
2666
 
2479
2667
  function mathTable(n,c) {
2480
2668
  const small=/smallmatrix$/.test(n.env) || n.env==='subarray' || n.env==='substack',
2481
2669
  paired=/^(align(?:ed)?(?:at)?|flalign|split)$/.test(n.env),
2482
- display=paired || /^(gather(?:ed)?|eqnarray|multline|equation|drcases|dcases|darray)$/.test(n.env),
2483
- cellStyle={...c,level:small?Math.max(1,c.level):c.level,display:small?false:display};
2670
+ display=paired || /^([lr]?gather(?:ed)?|eqnarray|multline(?:d)?|equation|drcases|dcases|darray)$/.test(n.env),
2671
+ cellStyle={...c,level:small?Math.max(1,c.level):c.level,display:small?false:display,cramped:false};
2484
2672
  const rows=n.rows.map(row=>row.map((cell,i)=>{
2485
2673
  // The second cell in each equation pair continues the first math list.
2486
2674
  // An empty ordinary atom supplies the left neighbour of a leading relation.
@@ -2521,7 +2709,7 @@ function mathTable(n,c) {
2521
2709
  const offset=n.position==='t'?-(baselines[0] || 0):n.position==='b'?-(baselines.at(-1) || 0):-total/2-mathConstant('AxisHeight',c,0.25),items=[];
2522
2710
  for(let r=0;r<rows.length;r++) {
2523
2711
  for(let i=0;i<cols;i++) {
2524
- const b=rows[r][i] || mathBox(),a=n.env==='multline' && cols===1?(r===0?'l':r===rows.length-1?'r':'c'):align[i] || 'c',
2712
+ const b=rows[r][i] || mathBox(),a=/^multlined?$/.test(n.env) && cols===1?(r===0?'l':r===rows.length-1?'r':'c'):align[i] || 'c',
2525
2713
  dx=a==='r'?widths[i]-b.w:a==='l'?0:(widths[i]-b.w)/2;
2526
2714
  items.push([b,starts[i]+dx,baselines[r]+offset]);
2527
2715
  }
@@ -2554,6 +2742,11 @@ function mathTable(n,c) {
2554
2742
 
2555
2743
  function mathLayout(n,c) {
2556
2744
  if(!n)return mathBox();
2745
+ // With spans, each symbol carries its source offset for the host's tap-to-place.
2746
+ if(c.spans && n.at!==undefined && (n.type==='glyph' || n.type==='text')) {
2747
+ const b=mathLayout({...n,at:undefined},c);
2748
+ return {...b,svg:'<g data-math-at="'+n.at+'">'+b.svg+'</g>'};
2749
+ }
2557
2750
  if(c.budget && ++c.budget.nodes>100000)throw Object.assign(new Error('Mathematical layout exceeds the rendering budget'),{code:'resource-limit'});
2558
2751
  switch(n.type) {
2559
2752
  case 'row': return mathRow(n.children,c);
@@ -2584,7 +2777,8 @@ function mathLayout(n,c) {
2584
2777
  const cache=c.cache || (c.cache=new WeakMap()),key=[c.size,c.level,c.variant,c.display,c.cramped,c.stretchTarget].join('|');
2585
2778
  let entries=cache.get(n);if(entries?.has(key))return {...entries.get(key)};
2586
2779
  const local={...c,delimiterTarget:undefined};let b=mathLayout(n.body,local);
2587
- if(n.body) {
2780
+ // Only a \middle needs the second pass, sized to the first pass's body.
2781
+ if(n.body && mathHasMiddle(n.body)) {
2588
2782
  const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(b.h-axis,b.d+axis),target=Math.max(mathScale(c),2*reach*0.901,2*reach-0.5*mathScale(c));
2589
2783
  b=mathLayout(n.body,{...local,delimiterTarget:target});
2590
2784
  }
@@ -2597,6 +2791,10 @@ function mathLayout(n,c) {
2597
2791
  const style={...c};if(n.variant)style.variant=n.variant;if(n.absoluteSize!==undefined)style.size=n.absoluteSize;if(n.size!==undefined)style.size*=n.size;
2598
2792
  if(n.mathStyle) {style.level=({display:0,text:0,script:1,scriptscript:2})[n.mathStyle];style.display=n.mathStyle==='display';style.cramped=false;}
2599
2793
  const b=mathLayout(n.body,style);if(n.class)b.class=n.class;if(n.limits)b.limits=n.limits;
2794
+ if(n.smashOperator) {
2795
+ const op=mathLayout(n.body.type==='scripts'?n.body.base:n.body,style),extra=Math.max(0,(b.w-op.w)/2),left=n.smashOperator.includes('l')?extra:0;
2796
+ Object.assign(b,mathCompose([[{...b},-left,0]],b.w-left-(n.smashOperator.includes('r')?extra:0),{class:b.class}));
2797
+ }
2600
2798
  if(n.width!==undefined) {
2601
2799
  const width=n.width*mathScale(style),shift=n.align==='right'?width-b.w:n.align==='center'?(width-b.w)/2:0;
2602
2800
  Object.assign(b,mathCompose([[{...b},shift,0]],width,{class:b.class}));
@@ -2817,7 +3015,8 @@ function mathFlowAtoms(n,box,x=0,y=0) {
2817
3015
  return n.children.flatMap((child,i)=>{const [b,dx,dy]=box.rowItems[i];return mathFlowAtoms(child,b,x+dx,y+dy);});
2818
3016
  if(n.type==='style' && n.width===undefined && !n.border && !n.background && !n.class && !n.limits) {
2819
3017
  const atoms=mathFlowAtoms(n.body,box,x,y);
2820
- if(n.color) {
3018
+ // A box the body did not unpack already carries this colour from mathLayout.
3019
+ if(n.color && !(atoms.length===1 && atoms[0][0]===box)) {
2821
3020
  const paint=b=>({...b,svg:'<g fill="'+mathEscape(n.color)+'" color="'+mathEscape(n.color)+'" fill-opacity="1" stroke-opacity="1">'+b.svg+'</g>',
2822
3021
  ...(b.refit?{refit:ratio=>paint(b.refit(ratio))}:{}),...(b.flowWrap?{flowWrap:width=>paint(b.flowWrap(width))}:{})});
2823
3022
  return atoms.map(([b,dx,dy])=>[paint(b),dx,dy]);
@@ -3030,7 +3229,7 @@ function mathSvg(box,source,error,utf16,options={}) {
3030
3229
 
3031
3230
  function mathRenderPrepared(prepared,options={}) {
3032
3231
  const {text,safe,tree,error:parseError}=prepared;
3033
- const context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
3232
+ const context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,spans:!!options?.spans,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
3034
3233
  try {
3035
3234
  if(safe.error)throw safe.error;
3036
3235
  if(options?.screen!==undefined) {
@@ -3063,7 +3262,7 @@ function mathRenderPrepared(prepared,options={}) {
3063
3262
  }
3064
3263
 
3065
3264
  function renderMath(source,options={}) {
3066
- return mathRenderPrepared(mathPrepare(source),options);
3265
+ return mathRenderPrepared(mathPrepare(source,options),options);
3067
3266
  }
3068
3267
  function mathRenderToString(source,options) { return renderMath(source,options).svg; }
3069
3268
 
@@ -3327,7 +3526,9 @@ function mathML(tree, source, safeSource, options = {}) {
3327
3526
  else if (role === 'units') warn('semantic-units-presentation', 'Unit notation retains the parser-expanded mathematical structure; quantities and unit identities are not inferred.');
3328
3527
  else if (role === 'tag') warn('semantic-tag-presentation', 'An authored tag remains following content; no equation identity, numbering or cross-reference semantics are assigned.');
3329
3528
  };
3330
- const scriptContext = context => ({...context, display: false, level: Math.min(2, context.level + 1)});
3529
+ // An operator's form and movable limits belong to it alone, not to the expressions inside it.
3530
+ const inner = context => ({...context, form: undefined, movableLimits: undefined});
3531
+ const scriptContext = context => ({...inner(context), display: false, level: Math.min(2, context.level + 1)});
3331
3532
  const styledContext = (context, node) => {
3332
3533
  const next = {...context};
3333
3534
  if (node.variant) next.variant = node.variant;
@@ -3370,7 +3571,7 @@ function mathML(tree, source, safeSource, options = {}) {
3370
3571
  if (kind === 'mi' && face !== 'normal' && face !== 'italic') attributes.mathvariant = 'normal';
3371
3572
  token(kind, styled, attributes, context);
3372
3573
  };
3373
- const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[∞∅ℵℶℷℸ℘]$/.test(node.value) ? 'mi' :
3574
+ const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[∞∅ℵℶℷℸ℘℧⅁]$/.test(node.value) ? 'mi' :
3374
3575
  ['op', 'bin', 'rel', 'open', 'close', 'punct', 'inner'].includes(node.class) ||
3375
3576
  /^[\p{Sm}\p{P}\p{Sc}\p{So}\p{Sk}\u2061-\u2064]$/u.test(node.value) ? 'mo' : 'mi');
3376
3577
  const classOf = node => {
@@ -3452,8 +3653,11 @@ function mathML(tree, source, safeSource, options = {}) {
3452
3653
  previous = 'ord'; index = end - 1; continue;
3453
3654
  }
3454
3655
  let form;
3455
- if (node.type === 'glyph' && node.class === 'bin')
3456
- form = !previous || ['bin', 'op', 'rel', 'open', 'punct'].includes(previous) ? 'prefix' : 'infix';
3656
+ if ((node.type === 'glyph' || node.type === 'style' && node.body.type === 'glyph') && classOf(node) === 'bin') {
3657
+ // TeX's rule 5: a binary operator before a relation, a closing symbol or nothing is not infix.
3658
+ const next = children.slice(index + 1).find(child => child.type !== 'space');
3659
+ form = !previous || ['bin', 'op', 'rel', 'open', 'punct'].includes(previous) ? 'prefix' : !next || ['rel', 'close', 'punct'].includes(classOf(next)) ? 'postfix' : 'infix';
3660
+ }
3457
3661
  emit(node, {...context, form}, depth + 1);
3458
3662
  if (node.type !== 'space') previous = classOf(node);
3459
3663
  }
@@ -3481,7 +3685,7 @@ function mathML(tree, source, safeSource, options = {}) {
3481
3685
  before[insertion.before].push(insertion.body);
3482
3686
  }
3483
3687
  const small = /smallmatrix$/.test(node.env) || node.env === 'subarray' || node.env === 'substack';
3484
- const display = /^(align(?:ed)?(?:at)?|flalign|split|gather(?:ed)?|eqnarray|multline|equation|drcases|dcases)$/.test(node.env);
3688
+ const display = /^(align(?:ed)?(?:at)?|flalign|split|[lr]?gather(?:ed)?|eqnarray|multline(?:d)?|equation|drcases|dcases|darray)$/.test(node.env);
3485
3689
  const cellContext = {...context, display: small ? false : display, level: small ? Math.max(1, context.level) : context.level};
3486
3690
  const delimiters = {pmatrix: ['(', ')'], bmatrix: ['[', ']'], Bmatrix: ['{', '}'], vmatrix: ['|', '|'], Vmatrix: ['‖', '‖'],
3487
3691
  psmallmatrix: ['(', ')'], bsmallmatrix: ['[', ']'], Bsmallmatrix: ['{', '}'], vsmallmatrix: ['|', '|'], Vsmallmatrix: ['‖', '‖'],
@@ -3493,7 +3697,7 @@ function mathML(tree, source, safeSource, options = {}) {
3493
3697
  for (let column = 0; column < columns; column++) {
3494
3698
  if (++metrics.nodes > 100000) fail('resource-limit', 'MathML table cells exceed its work budget.');
3495
3699
  let align = node.env === 'eqnarray' ? ['r', 'c', 'l'][column % 3] : node.align?.[column] || 'c';
3496
- if (node.env === 'multline' && columns === 1) align = at === 0 ? 'l' : at === rows.length - 1 ? 'r' : 'c';
3700
+ if (/^multlined?$/.test(node.env) && columns === 1) align = at === 0 ? 'l' : at === rows.length - 1 ? 'r' : 'c';
3497
3701
  open('mtd', {style: 'text-align:' + ({l: 'left', r: 'right', c: 'center'}[align] || 'center')});
3498
3702
  open('mrow');
3499
3703
  for (const body of before[column]) emit(body, cellContext, depth + 1);
@@ -3540,18 +3744,18 @@ function mathML(tree, source, safeSource, options = {}) {
3540
3744
  if (node.left || node.right) { open('mrow'); fence(node.left, 'prefix', local); }
3541
3745
  open('mfrac', {linethickness: node.bar === false ? '0' : node.barThickness === undefined ? undefined : em(node.barThickness)});
3542
3746
  const child = local.display && local.level === 0 ? {...local, display: false} : scriptContext(local);
3543
- emit(node.num, child, depth + 1); emit(node.den, child, depth + 1); close('mfrac');
3747
+ emit(node.num, inner(child), depth + 1); emit(node.den, inner(child), depth + 1); close('mfrac');
3544
3748
  if (node.left || node.right) { fence(node.right, 'postfix', local); close('mrow'); }
3545
3749
  if (node.style) close('mstyle');
3546
3750
  if (node.align) warn('semantic-fraction-alignment', 'The fraction relationship is preserved; continued-fraction numerator alignment is left to the MathML host.');
3547
3751
  break;
3548
3752
  }
3549
3753
  case 'root':
3550
- open(node.index ? 'mroot' : 'msqrt'); emit(node.body, context, depth + 1);
3551
- if (node.index) emit(node.index, {...context, display: false, level: 2}, depth + 1);
3754
+ open(node.index ? 'mroot' : 'msqrt'); emit(node.body, inner(context), depth + 1);
3755
+ if (node.index) emit(node.index, {...inner(context), display: false, level: 2}, depth + 1);
3552
3756
  close(node.index ? 'mroot' : 'msqrt'); break;
3553
3757
  case 'fence':
3554
- open('mrow'); fence(node.left, 'prefix', context, node.size); emit(node.body, context, depth + 1); fence(node.right, 'postfix', context, node.size); close('mrow'); break;
3758
+ open('mrow'); fence(node.left, 'prefix', context, node.size); emit(node.body, inner(context), depth + 1); fence(node.right, 'postfix', context, node.size); close('mrow'); break;
3555
3759
  case 'accent': {
3556
3760
  if (node.overlay || node.position === 'through') {
3557
3761
  warn('semantic-overlay', 'An overlay uses the MathML 3 menclose extension; hosts implementing only Core may omit the cancellation or negation mark.');