rapier-math 2.3.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -98,8 +98,11 @@ const MATH_TEX_SPACES = Object.freeze({
98
98
  quad: 1, qquad: 2, enspace: .5, enskip: .5, thinspace: 3 / 18, medspace: 4 / 18, thickspace: 5 / 18,
99
99
  negthinspace: -3 / 18, negmedspace: -4 / 18, negthickspace: -5 / 18
100
100
  });
101
- const MATH_TEX_PACKAGES = new Set(('ams amsmath amssymb amsfonts mathtools color newcommand unicode mhchem physics bbm bboldx dsfont cancel bbox boldsymbol').split(' '));
102
- 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(' '));
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(' '));
103
106
  const MATH_TEX_LITERAL_CLASSES = Object.freeze({
104
107
  '+': 'bin', '−': 'bin', '-': 'bin', '±': 'bin', '∓': 'bin', '×': 'bin', '÷': 'bin', '*': 'bin', '⋅': 'bin',
105
108
  '=': 'rel', '<': 'rel', '>': 'rel', '≤': 'rel', '≥': 'rel', '≠': 'rel', ':': 'rel',
@@ -225,6 +228,8 @@ class MathTexParser {
225
228
  continue;
226
229
  }
227
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;
228
233
  if (atom) children.push(this.readScripts(atom));
229
234
  }
230
235
  // An equation tag follows its equation wherever \tag was written.
@@ -279,6 +284,7 @@ class MathTexParser {
279
284
  }
280
285
  const atom = this.parseAtom();
281
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;
282
288
  return atom;
283
289
  }
284
290
  rawArgument() {
@@ -369,7 +375,12 @@ class MathTexParser {
369
375
  if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
370
376
  }
371
377
  if (Object.hasOwn(MATH_SYMBOLS, name)) return this.node('glyph', MATH_SYMBOLS[name]);
372
- 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
+ }
373
384
  if (Object.hasOwn(MATH_TEX_TEXT_VARIANTS, name)) return this.subparse(this.rawArgument(), true, MATH_TEX_TEXT_VARIANTS[name]);
374
385
  if (MATH_NAMED_OPERATORS.has(name) || MATH_LIMIT_OPERATORS.has(name)) {
375
386
  const values = {limsup: 'lim sup', liminf: 'lim inf', injlim: 'lim', projlim: 'lim', varlimsup: 'lim', varliminf: 'lim', varinjlim: 'lim', varprojlim: 'lim'};
@@ -585,6 +596,24 @@ class MathTexParser {
585
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()])})]);
586
597
  if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
587
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
+ }
588
617
  if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
589
618
  if (name === 'mmlToken') return this.mathmlToken(token);
590
619
  if (name === 'unicode' || name === 'char') return this.character(name, token);
@@ -653,7 +682,7 @@ class MathTexParser {
653
682
 
654
683
  environment(fullName, token) {
655
684
  const env = fullName.replace(/\*$/, '');
656
- 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});
657
686
  return this.nested(() => {
658
687
  let options = {};
659
688
  const position = this.optionalRaw();
@@ -670,7 +699,7 @@ class MathTexParser {
670
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);
671
700
  options.pairs = Number(value);
672
701
  }
673
- 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);
674
703
  this.expect('end', 'command');
675
704
  const ending = this.plainArgument();
676
705
  if (ending !== fullName) this.error('mismatched-environment', 'Expected \\end{' + fullName + '}, received \\end{' + ending + '}.', token);
@@ -760,7 +789,18 @@ class MathTexParser {
760
789
  if (!align.length) this.error('invalid-alignment', 'An array needs a column specification.', token);
761
790
  return {align, columnRules, columnInsertions};
762
791
  }
763
- 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) {
764
804
  const rows = [], rowGaps = [], rowRules = [];
765
805
  let cells = [], endedAfterBreak = false;
766
806
  const separator = item => (item.kind === 'char' && item.value === '&') || (item.kind === 'command' && ['\\', 'cr', 'crcr'].includes(item.value)) || end(item);
@@ -778,7 +818,7 @@ class MathTexParser {
778
818
  if (cells.length || (!rows.length && !endedAfterBreak)) { cells.push(this.row([])); rows.push(cells); }
779
819
  break;
780
820
  }
781
- cells.push(this.nested(() => this.parseRow(separator)));
821
+ cells.push(cells.length === textColumn ? this.textCell(separator) : this.nested(() => this.parseRow(separator)));
782
822
  endedAfterBreak = false;
783
823
  const next = this.peek();
784
824
  if (next.kind === 'char' && next.value === '&') { this.take(); continue; }
@@ -798,7 +838,7 @@ class MathTexParser {
798
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.');
799
839
  if (options.pairs && rows.some(row => row.length > options.pairs * 2)) this.error('invalid-alignment', 'This row has more cells than alignedat declares.');
800
840
  let align = options.align;
801
- 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');
802
842
  return this.node('table', {env, rows, ...options, align, rowGaps, rowRules});
803
843
  }
804
844
 
@@ -1012,7 +1052,7 @@ class MathTexParser {
1012
1052
  }
1013
1053
 
1014
1054
  physicsCommand(name) {
1015
- 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);
1016
1056
  }
1017
1057
  physics(name, token) {
1018
1058
  const starred = this.is('*'); if (starred) this.take();
@@ -1039,30 +1079,40 @@ class MathTexParser {
1039
1079
  if (name === 'laplacian') base = this.node('scripts', {base, sup: this.literal('2', {variant: 'roman'})});
1040
1080
  return this.row([base, ...(/^(divergence|curl)$/.test(name) ? [this.literal(name === 'curl' ? '×' : '⋅', {class: 'bin', variant: 'roman'})] : []), ...(this.is('{') ? [this.argument()] : [])]);
1041
1081
  }
1042
- if (['Tr', 'tr', 'trace', 'rank', 'diag'].includes(name)) return this.node('text', {value: name === 'trace' ? 'tr' : name, variant: 'roman', class: 'op', limits: 'never'});
1043
- if (name === 'eval' || name === 'evaluated') return this.node('fence', {left: '', right: '|', body: this.argument()});
1044
- if (name === 'order') return this.row([this.literal('O'), this.node('fence', {left: '(', right: ')', body: this.argument()})]);
1045
- if (/^(mqty|pmqty|bmqty|vmqty|smqty)$/.test(name)) {
1046
- const env = name === 'bmqty' ? 'bmatrix' : name === 'vmqty' ? 'vmatrix' : name === 'smqty' ? 'smallmatrix' : name === 'pmqty' ? 'pmatrix' : 'matrix';
1047
- return this.tableFromTokens(this.rawArgument(), env);
1048
- }
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'});
1049
1083
  if (name === 'qty' || name === 'quantity') {
1050
- if (this.is('{')) return this.node('fence', {left: '(', right: ')', body: this.argument()});
1084
+ if (this.is('{')) return this.node('fence', {left: '{', right: '}', body: this.argument()});
1051
1085
  const left = this.readDelimiter(), right = {'(': ')', '[': ']', '{': '}', '|': '|', '‖': '‖', '⟨': '⟩'}[left];
1052
1086
  if (!right) this.error('invalid-delimiter', 'A quantity needs paired delimiters.', token);
1053
1087
  const body = this.nested(() => this.parseRow(item => item.kind === 'char' && item.value === right));
1054
1088
  this.expect(right);
1055
1089
  return this.node('fence', {left, right, body});
1056
1090
  }
1091
+ // \qq{text} and the \qif family: text between quads; \qc is a comma and a quad.
1092
+ if (/^q/.test(name)) {
1093
+ const quad = () => this.node('space', {width: 1}), words = {qcc: 'c.c.'};
1094
+ if (name === 'qc') return this.node('style', {class: 'punct', body: this.row([this.literal(',', {class: 'punct'}), quad()])});
1095
+ return this.row([quad(), name === 'qq' ? this.subparse(this.rawArgument(), true) : this.node('text', {value: words[name] || name.slice(1), variant: 'roman'}), quad()]);
1096
+ }
1097
+ if (name === 'eval' || name === 'evaluated') return this.node('fence', {left: '', right: '|', body: this.argument()});
1098
+ if (name === 'order') return this.row([this.literal('O'), this.node('fence', {left: '(', right: ')', body: this.argument()})]);
1099
+ if (/^(mqty|pmqty|bmqty|vmqty|smqty)$/.test(name)) {
1100
+ const env = name === 'bmqty' ? 'bmatrix' : name === 'vmqty' ? 'vmatrix' : name === 'smqty' ? 'smallmatrix' : name === 'pmqty' ? 'pmatrix' : 'matrix';
1101
+ return this.tableFromTokens(this.rawArgument(), env);
1102
+ }
1057
1103
  const first = this.argument();
1058
1104
  if (/^(bra|ket|pqty|bqty|Bqty|vqty|abs|absolutevalue|norm)$/.test(name)) {
1059
1105
  const ends = {bra: ['⟨', '|'], ket: ['|', '⟩'], pqty: ['(', ')'], bqty: ['[', ']'], Bqty: ['{', '}'], vqty: ['|', '|'], abs: ['|', '|'], absolutevalue: ['|', '|'], norm: ['‖', '‖']}[name];
1060
1106
  return this.node('fence', {left: ends[0], right: ends[1], body: first});
1061
1107
  }
1062
- 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
+ }
1063
1113
  const second = this.is('{') ? this.argument() : null;
1064
- if (/^(ketbra|dyad|outerproduct)$/.test(name)) return this.row([this.node('fence', {left: '|', right: '⟩', body: first}), this.node('fence', {left: '⟨', right: '|', body: second || first})]);
1065
- 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});
1066
1116
  return this.node('fence', {left: '⟨', right: '⟩', body: second ? this.row([first, this.literal('|', {delimiter: true}), second]) : first});
1067
1117
  }
1068
1118
 
@@ -1074,7 +1124,7 @@ class MathTexParser {
1074
1124
  }
1075
1125
  chemicalRow(stop) {
1076
1126
  const children = [];
1077
- let spaced = true, subAllowed = false, moleculeParts = 0;
1127
+ let spaced = true, subAllowed = false, moleculeParts = 0, isotope = null;
1078
1128
  const script = (key, body) => {
1079
1129
  let base = children.pop() || this.row([]);
1080
1130
  if (base.type !== 'scripts') base = this.node('scripts', {base});
@@ -1090,6 +1140,7 @@ class MathTexParser {
1090
1140
  const next = this.peek(false);
1091
1141
  if (next.kind === 'eof' || stop(next)) break;
1092
1142
  const token = this.take(false);
1143
+ if (isotope && !(token.kind === 'char' && /^[\^_A-Za-z]$/.test(token.value))) isotope = null;
1093
1144
  if (token.kind === 'space') {
1094
1145
  spaced = true; subAllowed = false; moleculeParts = 0;
1095
1146
  // An operator or arrow already carries its own spacing; a separating space adds none beside it.
@@ -1135,6 +1186,12 @@ class MathTexParser {
1135
1186
  const value = consumeRun(character => /^[0-9+\-−IVX]$/.test(character));
1136
1187
  body = value ? this.node('text', {value: value.replace(/-/g, '−'), variant: 'roman'}) : this.argument();
1137
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
+ }
1138
1195
  script(key, body); spaced = false; continue;
1139
1196
  }
1140
1197
  if (/^[0-9]$/.test(token.value)) {
@@ -1170,7 +1227,9 @@ class MathTexParser {
1170
1227
  }
1171
1228
  if (/^[A-Za-z]$/.test(token.value)) {
1172
1229
  const word = token.value + consumeRun(character => /^[a-z]$/.test(character));
1173
- 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);
1174
1233
  moleculeParts++; spaced = false; subAllowed = true; continue;
1175
1234
  }
1176
1235
  if (token.value === '#') children.push(this.literal('≡', {class: 'ord', variant: 'roman'}));
@@ -1181,6 +1240,57 @@ class MathTexParser {
1181
1240
  }
1182
1241
  return this.row(children);
1183
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
+ }
1184
1294
  units(tokens) {
1185
1295
  let value = mathTexTokenText(tokens);
1186
1296
  value = value.replace(/(\d(?:[\d.]*\d)?)[eE]([+-]?\d+)/g, '$1\\times 10^{$2}');
@@ -1228,5 +1338,58 @@ function parseMathTex(source) {
1228
1338
  return new MathTexParser(source).parse();
1229
1339
  }
1230
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
+
1231
1394
  import {MATH_SYMBOLS, MATH_NAMED_OPERATORS, MATH_LIMIT_OPERATORS} from './symbols.js';
1232
- export {parseMathTex};
1395
+ export {parseMathTex, parseMathTexPreview, mathSuggest};
@@ -68,7 +68,8 @@ function mathFlowAtoms(n,box,x=0,y=0) {
68
68
  return n.children.flatMap((child,i)=>{const [b,dx,dy]=box.rowItems[i];return mathFlowAtoms(child,b,x+dx,y+dy);});
69
69
  if(n.type==='style' && n.width===undefined && !n.border && !n.background && !n.class && !n.limits) {
70
70
  const atoms=mathFlowAtoms(n.body,box,x,y);
71
- if(n.color) {
71
+ // A box the body did not unpack already carries this colour from mathLayout.
72
+ if(n.color && !(atoms.length===1 && atoms[0][0]===box)) {
72
73
  const paint=b=>({...b,svg:'<g fill="'+mathEscape(n.color)+'" color="'+mathEscape(n.color)+'" fill-opacity="1" stroke-opacity="1">'+b.svg+'</g>',
73
74
  ...(b.refit?{refit:ratio=>paint(b.refit(ratio))}:{}),...(b.flowWrap?{flowWrap:width=>paint(b.flowWrap(width))}:{})});
74
75
  return atoms.map(([b,dx,dy])=>[paint(b),dx,dy]);
@@ -254,4 +255,4 @@ function mathResponsiveLayout(n,c,width,natural=mathLayout(n,c)) {
254
255
 
255
256
  import {MATH_FONT} from './font.js';
256
257
  import {mathNumber, mathEscape, mathScale, mathScreenStroke, mathConstant, mathScreenRelayout, mathCompose, mathSpace, mathRow, mathFraction, mathFenceBoxes, mathLayout} from './layout.js';
257
- export {mathResponsiveLayout, mathInkWidth};
258
+ export {mathResponsiveLayout, mathInkWidth, mathHasMiddle};
@@ -48,6 +48,8 @@ function mathDiagnostic(cause) {
48
48
  offset:Number.isFinite(cause?.offset)?cause.offset:0};
49
49
  if(message.length>1024 || cause?.messageTruncated)error.messageTruncated=true;
50
50
  if(cause?.sourceOmitted)error.sourceOmitted=true;
51
+ const suggestion=cause?.suggestion ?? (cause?.code==='unsupported-command'?mathSuggest(cause.command):cause?.code==='unsupported-environment'?mathSuggest(cause.environment,true):undefined);
52
+ if(suggestion)error.suggestion=suggestion;
51
53
  if(rawCommand!==undefined) {
52
54
  const command=String(rawCommand);
53
55
  error.command=command.slice(0,128).replace(/[\ud800-\udbff]$/,'');
@@ -56,12 +58,15 @@ function mathDiagnostic(cause) {
56
58
  return error;
57
59
  }
58
60
 
59
- function mathPrepare(source) {
61
+ function mathPrepare(source, options) {
60
62
  const text = String(source ?? ''), safe = mathAdmitSource(text);
61
63
  let tree, error = safe.error;
62
- if (!error) try { tree = parseMathTex(text); } catch (cause) { error = mathDiagnostic(cause); }
64
+ if (!error) try { tree = parseMathTex(text); } catch (cause) {
65
+ tree = options?.preview ? parseMathTexPreview(text, cause, options.caret ?? text.length) : null;
66
+ if (!tree) { tree = undefined; error = mathDiagnostic(cause); }
67
+ }
63
68
  return {text, safe, tree, error};
64
69
  }
65
70
 
66
- import {parseMathTex} from './parser.js';
71
+ import {parseMathTex, parseMathTexPreview, mathSuggest} from './parser.js';
67
72
  export {mathDiagnostic, mathPrepare, mathSourceUTF16};
@@ -36,6 +36,7 @@ for (const name of Object.keys(MATH_SYMBOLS).filter(name => /^[a-z]+$/.test(name
36
36
  for (const name of Object.keys(MATH_SYMBOLS).filter(name => /^var[A-Z]/.test(name)))
37
37
  MATH_SYMBOLS[name] = Object.freeze({...MATH_SYMBOLS[name], variant: 'italic'});
38
38
  mathSymbolGroup('bin', `
39
+ dotminus=∸ cupdot=⊍ barvee=⊽
39
40
  pm=± mp=∓ times=× div=÷ cdot=⋅ ast=∗ star=⋆ circ=∘ bullet=∙ diamond=⋄
40
41
  cap=∩ cup=∪ uplus=⊎ sqcap=⊓ sqcup=⊔ vee/lor=∨ wedge/land=∧ setminus=∖ smallsetminus=∖
41
42
  oplus=⊕ ominus=⊖ otimes=⊗ oslash=⊘ odot=⊙ bigcirc=◯ dag/dagger=† ddag/ddagger=‡ amalg=⨿
@@ -67,6 +68,7 @@ nmid=∤ nparallel=∦ nshortmid=∤ nshortparallel=∦ nvdash=⊬ nVdash=⊮ nv
67
68
  ntriangleleft=⋪ ntriangleright=⋫ ntrianglelefteq=⋬ ntrianglerighteq=⋭ coloneqq=≔ eqqcolon=≕ vcentcolon=∶ dblcolon/Colon=∷ And=&
68
69
  `, {variant: 'roman'});
69
70
  mathSymbolGroup('rel', `
71
+ questeq=≟ veeeq=≚ stareq=≛ eqdef=≝ estimates/corresponds=≙ Equiv=≣
70
72
  leftarrow/gets=← rightarrow/to=→ leftrightarrow=↔ Leftarrow=⇐ Rightarrow=⇒ Leftrightarrow=⇔
71
73
  longleftarrow=⟵ longrightarrow=⟶ longleftrightarrow=⟷ Longleftarrow=⟸ Longrightarrow=⟹ Longleftrightarrow=⟺
72
74
  mapsto=↦ longmapsto=⟼ hookleftarrow=↩ hookrightarrow=↪ nearrow=↗ searrow=↘ nwarrow=↖ swarrow=↙
@@ -2,11 +2,11 @@
2
2
  // Unicode mathematical alphabets shared by SVG and MathML. No font lookup.
3
3
  const MATH_STYLED_RANGES = {
4
4
  italic: [0x1d434, 0x1d44e, null], bold: [0x1d400, 0x1d41a, 0x1d7ce],
5
- 'bold-italic': [0x1d468, 0x1d482, null], script: [0x1d49c, 0x1d4b6, null],
5
+ 'bold-italic': [0x1d468, 0x1d482, 0x1d7ce], script: [0x1d49c, 0x1d4b6, null],
6
6
  'bold-script': [0x1d4d0, 0x1d4ea, null], fraktur: [0x1d504, 0x1d51e, null],
7
7
  'bold-fraktur': [0x1d56c, 0x1d586, null], 'double-struck': [0x1d538, 0x1d552, 0x1d7d8],
8
8
  'sans-serif': [0x1d5a0, 0x1d5ba, 0x1d7e2], 'sans-serif-bold': [0x1d5d4, 0x1d5ee, 0x1d7ec],
9
- 'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, null],
9
+ 'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, 0x1d7ec],
10
10
  monospace: [0x1d670, 0x1d68a, 0x1d7f6],
11
11
  };
12
12
  const MATH_STYLED_LEGACY = {
@@ -12,10 +12,10 @@ import {mathModules, mathClassicSource} from '../math/package-build.mjs';
12
12
  import {mathReadme} from '../math/package-readme.mjs';
13
13
 
14
14
  const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
15
- export const MATH_VERSION = '2.3.0';
15
+ export const MATH_VERSION = '2.4.1';
16
16
  export const MATH_BUNDLE = 'rapier-math-' + MATH_VERSION + '.js';
17
17
  export const MATH_SOURCES = ['font.js', 'symbols.js', 'parser.js', 'source.js', 'variants.js', 'layout.js', 'fallbacks.js', 'responsive.js', 'api.js', 'browser.js', 'mathml.js', 'semantic-api.js', 'combined.js', 'classic.js'].map(name => 'math/' + name);
18
- export const MATH_RECIPE = ['math/build-font.py', 'math/FONT-SOURCE.md', 'math/FONT-LICENSE.txt', 'math/package-verify.mjs', 'tools/build-math.mjs', 'math/LICENSE-MIT', 'math/adoption-verify.mjs', 'math/package-build.mjs', 'math/package-layout.mjs', 'math/package-check.mjs', 'math/package-readme.mjs', 'math/README.md', 'math/SEMANTICS.md', 'math/semantic-verify.mjs'];
18
+ export const MATH_RECIPE = ['math/build-font.py', 'math/FONT-SOURCE.md', 'math/FONT-LICENSE.txt', 'math/package-verify.mjs', 'tools/build-math.mjs', 'math/LICENSE-MIT', 'math/adoption-verify.mjs', 'math/package-build.mjs', 'math/package-layout.mjs', 'math/package-check.mjs', 'math/package-readme.mjs', 'math/README.md', 'math/SEMANTICS.md', 'math/semantic-verify.mjs', 'math/typeset-verify.mjs'];
19
19
  export const MATH_ADOPTION = ['delimiters.mjs', 'markdown-rules.mjs', 'reuse.mjs', 'integration.mjs', 'markdown-it.mjs', 'rehype.mjs', 'stream.mjs',
20
20
  'accessible.mjs', 'accessible.css', 'mathml.d.ts', 'combined.d.ts', 'accessible.d.ts',
21
21
  'index.d.ts', 'classic.d.ts', 'delimiters.d.ts', 'integration.d.ts', 'markdown-it.d.ts', 'rehype.d.ts', 'stream.d.ts',
package/tests/check.mjs CHANGED
@@ -55,6 +55,7 @@ assert(Object.isFrozen(module.default));
55
55
  const context = createContext({atob, URL});
56
56
  new Script(classicSource, {filename: resources.bundle}).runInContext(context);
57
57
  const classic = context.RapierMath;
58
+ assert.equal(classic.version, pkg.version, 'classic/package release identity');
58
59
  const plain = value => JSON.parse(JSON.stringify(value));
59
60
  const unescape = text => text.replace(/&(amp|lt|gt|quot|apos|#\d+|#x[\da-f]+);/gi, (_, entity) =>
60
61
  entity[0] === '#' ? String.fromCodePoint(entity[1] === 'x' ? parseInt(entity.slice(2), 16) : Number(entity.slice(1))) :