rapier-math 2.1.0 → 2.3.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.
@@ -44,7 +44,7 @@ function mathTexTokens(source, offset = 0) {
44
44
  }
45
45
 
46
46
  const MATH_TEX_VARIANTS = Object.freeze({
47
- mathrm: 'roman', mathnormal: 'normal', mathit: 'italic', mathbf: 'bold', boldsymbol: 'bold-italic', bm: 'bold-italic',
47
+ mathrm: 'roman', mathnormal: 'normal', mathit: 'italic', mathbf: 'bold', boldsymbol: 'bold-italic', bm: 'bold-italic', pmb: 'bold-italic',
48
48
  mathbb: 'double-struck', mathbbm: 'double-struck', mathbbmss: 'double-struck', mathbbmtt: 'double-struck', mathds: 'double-struck',
49
49
  Bbb: 'double-struck', mathcal: 'script', mathscr: 'script', mathfrak: 'fraktur', frak: 'fraktur',
50
50
  mathsf: 'sans-serif', mathss: 'sans-serif', mathtt: 'monospace', mathbfit: 'bold-italic',
@@ -56,6 +56,7 @@ const MATH_TEX_TEXT_VARIANTS = Object.freeze({
56
56
  textbf: 'bold', textit: 'italic', emph: 'italic', textsl: 'italic', textsf: 'sans-serif', texttt: 'monospace',
57
57
  textsc: 'roman'
58
58
  });
59
+ const MATH_TEX_TEXT_LETTERS = Object.freeze({ss: 'ß', ae: 'æ', AE: 'Æ', oe: 'œ', OE: 'Œ', o: 'ø', O: 'Ø', aa: 'å', AA: 'Å', l: 'ł', L: 'Ł', i: 'ı', j: 'ȷ'});
59
60
  const MATH_TEX_DECLARATIONS = Object.freeze({
60
61
  rm: {variant: 'roman'}, rmfamily: {variant: 'roman'}, normalfont: {variant: 'roman'},
61
62
  it: {variant: 'italic'}, itshape: {variant: 'italic'}, sl: {variant: 'italic'},
@@ -76,18 +77,33 @@ const MATH_TEX_ACCENTS = Object.freeze({
76
77
  underrightarrow: ['→', 'under', true], underleftarrow: ['←', 'under', true], underleftrightarrow: ['↔', 'under', true],
77
78
  overleftharpoon: ['↼', 'over', true], overrightharpoon: ['⇀', 'over', true], utilde: ['̃', 'under', true]
78
79
  });
79
- const MATH_TEX_LONG_ARROWS = {iff: 'Longleftrightarrow', implies: 'Longrightarrow', impliedby: 'Longleftarrow'};
80
+ const MATH_TEX_LONG_ARROWS = {iff: 'Longleftrightarrow', implies: 'Longrightarrow', impliedby: 'Longleftarrow', And: 'And'};
81
+ // mathtools: a colon or double colon joined to a relation, 1.2 mu apart.
82
+ const MATH_TEX_COLONS = {coloneq: '∶−', Coloneq: '∷−', Coloneqq: '∷=', Eqqcolon: '=∷', eqcolon: '−∶', Eqcolon: '−∷', colonapprox: '∶≈', Colonapprox: '∷≈', colonsim: '∶∼', Colonsim: '∷∼'};
83
+ // dvipsnames in CMYK percent (LaTeX graphics bundle), converted as xcolor does: each RGB channel is 1 − min(1, CMY + K).
84
+ const MATH_TEX_DVIPSNAMES = Object.create(null);
85
+ for (const [, name, ...cmyk] of `GreenYellow 15 0 69 0 Yellow 0 0 100 0 Goldenrod 0 10 84 0 Dandelion 0 29 84 0 Apricot 0 32 52 0 Peach 0 50 70 0
86
+ Melon 0 46 50 0 YellowOrange 0 42 100 0 Orange 0 61 87 0 BurntOrange 0 51 100 0 Bittersweet 0 75 100 24 RedOrange 0 77 87 0 Mahogany 0 85 87 35
87
+ Maroon 0 87 68 32 BrickRed 0 89 94 28 Red 0 100 100 0 OrangeRed 0 100 50 0 RubineRed 0 100 13 0 WildStrawberry 0 96 39 0 Salmon 0 53 38 0
88
+ CarnationPink 0 63 0 0 Magenta 0 100 0 0 VioletRed 0 81 0 0 Rhodamine 0 82 0 0 Mulberry 34 90 0 2 RedViolet 7 90 0 34 Fuchsia 47 91 0 8
89
+ Lavender 0 48 0 0 Thistle 12 59 0 0 Orchid 32 64 0 0 DarkOrchid 40 80 20 0 Purple 45 86 0 0 Plum 50 100 0 0 Violet 79 88 0 0 RoyalPurple 75 90 0 0
90
+ BlueViolet 86 91 0 4 Periwinkle 57 55 0 0 CadetBlue 62 57 23 0 CornflowerBlue 65 13 0 0 MidnightBlue 98 13 0 43 NavyBlue 94 54 0 0 RoyalBlue 100 50 0 0
91
+ Blue 100 100 0 0 Cerulean 94 11 0 0 Cyan 100 0 0 0 ProcessBlue 96 0 0 0 SkyBlue 62 0 12 0 Turquoise 85 0 20 0 TealBlue 86 0 34 2 Aquamarine 82 0 30 0
92
+ BlueGreen 85 0 33 0 Emerald 100 0 50 0 JungleGreen 99 0 52 0 SeaGreen 69 0 50 0 Green 100 0 100 0 ForestGreen 91 0 88 12 PineGreen 92 0 59 25
93
+ LimeGreen 50 0 100 0 YellowGreen 44 0 74 0 SpringGreen 26 0 76 0 OliveGreen 64 0 95 40 RawSienna 0 72 100 45 Sepia 0 83 100 70 Brown 0 81 100 60
94
+ Tan 14 42 56 0 Gray 0 0 0 50 Black 0 0 0 100 White 0 0 0 0`.matchAll(/(\w+) (\d+) (\d+) (\d+) (\d+)/g))
95
+ MATH_TEX_DVIPSNAMES[name] = '#' + cmyk.slice(0, 3).map(value => Math.round(255 * (1 - Math.min(1, (+value + +cmyk[3]) / 100))).toString(16).padStart(2, '0')).join('');
80
96
  const MATH_TEX_SPACES = Object.freeze({
81
97
  ',': 3 / 18, ':': 4 / 18, ';': 5 / 18, '!': -3 / 18, ' ': 1 / 3,
82
98
  quad: 1, qquad: 2, enspace: .5, enskip: .5, thinspace: 3 / 18, medspace: 4 / 18, thickspace: 5 / 18,
83
99
  negthinspace: -3 / 18, negmedspace: -4 / 18, negthickspace: -5 / 18
84
100
  });
85
101
  const MATH_TEX_PACKAGES = new Set(('ams amsmath amssymb amsfonts mathtools color newcommand unicode mhchem physics bbm bboldx dsfont cancel bbox boldsymbol').split(' '));
86
- const MATH_TEX_ENVIRONMENTS = new Set(('matrix pmatrix bmatrix Bmatrix vmatrix Vmatrix smallmatrix psmallmatrix bsmallmatrix Bsmallmatrix vsmallmatrix Vsmallmatrix array aligned alignedat align alignat flalign gathered gather split cases dcases rcases drcases subarray substack eqnarray multline equation').split(' '));
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(' '));
87
103
  const MATH_TEX_LITERAL_CLASSES = Object.freeze({
88
104
  '+': 'bin', '−': 'bin', '-': 'bin', '±': 'bin', '∓': 'bin', '×': 'bin', '÷': 'bin', '*': 'bin', '⋅': 'bin',
89
105
  '=': 'rel', '<': 'rel', '>': 'rel', '≤': 'rel', '≥': 'rel', '≠': 'rel', ':': 'rel',
90
- '(': 'open', '[': 'open', '⟨': 'open', ')': 'close', ']': 'close', '⟩': 'close', ',': 'punct', ';': 'punct',
106
+ '(': 'open', '[': 'open', '{': 'open', '⟨': 'open', ')': 'close', ']': 'close', '}': 'close', '⟩': 'close', ',': 'punct', ';': 'punct',
91
107
  '∑': 'op', '∏': 'op', '∫': 'op', '∮': 'op', '∬': 'op', '∭': 'op'
92
108
  });
93
109
 
@@ -113,9 +129,10 @@ class MathTexParser {
113
129
  this.reserveParts(1);
114
130
  return {type, ...fields};
115
131
  }
116
- reserveParts(count, token = this.rawPeek()) {
132
+ reserveParts(count, token) {
133
+ // Peeking only on refusal: a skipping peek here would consume the spaces that \ce reads.
117
134
  if (!Number.isSafeInteger(count) || count < 0 || this.budget.nodes + count > 50000)
118
- this.error('resource-limit', 'This formula has too many parts to render safely.', token);
135
+ this.error('resource-limit', 'This formula has too many parts to render safely.', token || this.rawPeek());
119
136
  this.budget.nodes += count;
120
137
  }
121
138
  row(children) { return this.node('row', {children: children.filter(Boolean)}); }
@@ -178,7 +195,9 @@ class MathTexParser {
178
195
  if (token.kind === 'command' && (Object.hasOwn(MATH_TEX_DECLARATIONS, token.value) || token.value === 'color')) {
179
196
  this.take();
180
197
  const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
181
- children.push(this.node('style', {...fields, body: this.nested(() => this.parseRow(stop, allowFraction))}));
198
+ // A declaration styles each following atom; the atoms keep their own classes and spacing.
199
+ const rest = this.nested(() => this.parseRow(stop, allowFraction));
200
+ for (const body of rest.type === 'row' ? rest.children : [rest]) children.push(this.node('style', {...fields, body}));
182
201
  break;
183
202
  }
184
203
  if (token.kind === 'command' && /^(over|atop|choose|brace|brack|above|overwithdelims|atopwithdelims|abovewithdelims)$/.test(token.value)) {
@@ -208,7 +227,9 @@ class MathTexParser {
208
227
  const atom = this.parseAtom();
209
228
  if (atom) children.push(this.readScripts(atom));
210
229
  }
211
- return this.row(children);
230
+ // An equation tag follows its equation wherever \tag was written.
231
+ const tags = children.filter(child => child?.semanticRole === 'tag');
232
+ return this.row(tags.length ? [...children.filter(child => child?.semanticRole !== 'tag'), ...tags] : children);
212
233
  }
213
234
  readScripts(base) {
214
235
  let result = base;
@@ -224,8 +245,11 @@ class MathTexParser {
224
245
  if (result.type !== 'scripts') result = this.node('scripts', {base: result, limits: result.limits});
225
246
  const key = token.value === '_' ? 'sub' : 'sup';
226
247
  if (token.value === "'") {
227
- const primes = [this.node('glyph', {value: '′', class: 'ord', variant: 'roman'})];
228
- while (this.is("'")) { this.take(); primes.push(this.node('glyph', {value: '′', class: 'ord', variant: 'roman'})); }
248
+ // Runs of primes use the font's joined double, triple and quadruple prime glyphs.
249
+ let count = 1;
250
+ while (this.is("'")) { this.take(); count++; }
251
+ const primes = [];
252
+ for (; count > 0; count -= 4) primes.push(this.node('glyph', {value: '′″‴⁗'[Math.min(count, 4) - 1], class: 'ord', variant: 'roman'}));
229
253
  if (this.is('^')) { this.take(); primes.push(this.argument()); }
230
254
  if (result.sup) this.error('duplicate-script', 'A base cannot have two superscripts.', token);
231
255
  result.sup = this.row(primes);
@@ -363,7 +387,7 @@ class MathTexParser {
363
387
  if (name === 'frac' || name === 'dfrac' || name === 'tfrac' || name === 'cfrac') {
364
388
  const align = name === 'cfrac' ? this.optionalRaw() : null;
365
389
  if (align && !/^[lr]$/.test(mathTexTokenText(align).trim())) this.error('invalid-option', 'Continued-fraction alignment must be l or r.', token);
366
- return this.node('frac', {num: this.argument(), den: this.argument(), bar: true, ...(name === 'dfrac' || name === 'cfrac' ? {style: 'display'} : name === 'tfrac' ? {style: 'text'} : {}), ...(align ? {align: mathTexTokenText(align).trim()} : {})});
390
+ return this.node('frac', {num: this.argument(), den: this.argument(), bar: true, ...(name === 'dfrac' || name === 'cfrac' ? {style: 'display'} : name === 'tfrac' ? {style: 'text'} : {}), ...(align ? {align: mathTexTokenText(align).trim()} : {}), ...(name === 'cfrac' ? {strut: true} : {})});
367
391
  }
368
392
  if (/^(binom|dbinom|tbinom)$/.test(name)) return this.node('frac', {num: this.argument(), den: this.argument(), bar: false, left: '(', right: ')', ...(name[0] === 'd' ? {style: 'display'} : name[0] === 't' ? {style: 'text'} : {})});
369
393
  if (name === 'genfrac') {
@@ -403,8 +427,8 @@ class MathTexParser {
403
427
  if (name === 'begin') return this.environment(this.plainArgument(), token);
404
428
  if (name === 'substack') return this.tableFromTokens(this.rawArgument(), 'substack');
405
429
  if (/^(matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases|smallmatrix)$/.test(name)) return this.tableFromTokens(this.rawArgument(), name);
406
- if (name === 'operatorname') {
407
- const starred = this.is('*'); if (starred) this.take();
430
+ if (name === 'operatorname' || name === 'operatornamewithlimits') {
431
+ const starred = name !== 'operatorname' || this.is('*'); if (starred && name === 'operatorname') this.take();
408
432
  const body = this.subparse(this.rawArgument(), true, 'roman');
409
433
  return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
410
434
  }
@@ -444,7 +468,7 @@ class MathTexParser {
444
468
  }
445
469
  if (name === 'raisebox') {
446
470
  const amount = this.dimension(this.plainArgument(), token), height = this.optionalRaw(), depth = this.optionalRaw();
447
- return this.node('raise', {body: this.argument(), amount, ...(height ? {height: this.dimension(mathTexTokenText(height), token)} : {}), ...(depth ? {depth: this.dimension(mathTexTokenText(depth), token)} : {})});
471
+ return this.node('raise', {body: this.subparse(this.rawArgument(), true, 'roman'), amount, ...(height ? {height: this.dimension(mathTexTokenText(height), token)} : {}), ...(depth ? {depth: this.dimension(mathTexTokenText(depth), token)} : {})});
448
472
  }
449
473
  if (name === 'raise' || name === 'lower') return this.node('raise', {amount: this.readDimension() * (name === 'lower' ? -1 : 1), body: this.argument()});
450
474
  if (name === 'textcolor') { const color = this.readColor(); return this.node('style', {body: this.argument(), color}); }
@@ -457,10 +481,28 @@ class MathTexParser {
457
481
  if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(colorName)) this.error('invalid-color', 'Invalid colour name.', token);
458
482
  this.colors[colorName] = this.color(value, model, token); return null;
459
483
  }
484
+ // MathJax's bbox: a background colour, a padding length and a CSS border whose last word is its colour.
485
+ if (name === 'bbox') {
486
+ const fields = {padding: 0}, options = this.optionalRaw();
487
+ for (const option of options ? mathTexTokenText(options).split(',') : []) {
488
+ const value = option.trim(), border = /^border\s*:(.*)$/i.exec(value);
489
+ if (border) fields.border = this.color(border[1].trim().split(/\s+/).pop(), '', token);
490
+ else if (/^[+-]?[\d.]/.test(value)) fields.padding = this.dimension(value, token);
491
+ else if (value) fields.background = this.color(value, '', token);
492
+ }
493
+ return this.node('style', {body: this.argument(), ...fields});
494
+ }
460
495
  if (name === 'boxed' || name === 'fbox') return this.node('style', {body: name === 'fbox' ? this.subparse(this.rawArgument(), true, 'roman') : this.argument(), border: 'currentColor', padding: .25});
461
- if (name === 'cancel' || name === 'bcancel' || name === 'xcancel') return this.node('accent', {base: this.argument(), value: name === 'bcancel' ? '╲' : name === 'xcancel' ? '╳' : '╱', position: 'over', overlay: true, stretch: true});
496
+ if (name === 'cancel' || name === 'bcancel' || name === 'xcancel' || name === 'sout') return this.node('accent', {base: this.argument(), value: name === 'bcancel' ? '╲' : name === 'xcancel' ? '╳' : name === 'sout' ? '─' : '╱', position: 'over', overlay: true, stretch: true});
462
497
  if (name === 'cancelto') { const over = this.argument(); return this.node('overunder', {base: this.node('accent', {base: this.argument(), value: '↗', position: 'over', overlay: true, stretch: true}), over}); }
463
- if (['newcommand', 'renewcommand', 'providecommand', 'def', 'gdef', 'DeclareMathOperator', 'let'].includes(name)) { this.define(name, token); return null; }
498
+ if (['newcommand', 'renewcommand', 'providecommand', 'def', 'gdef', 'edef', 'xdef', 'DeclareMathOperator', 'DeclarePairedDelimiter', 'let'].includes(name)) { this.define(name, token); return null; }
499
+ // Assignment prefixes: \global makes the next definition global; \long and \outer change nothing here.
500
+ if (name === 'global' || name === 'long' || name === 'outer') {
501
+ let next = token, global = false;
502
+ while (next.kind === 'command' && /^(global|long|outer)$/.test(next.value)) { global ||= next.value === 'global'; next = this.rawTake(); }
503
+ if (next.kind !== 'command' || !/^[egx]?def$/.test(next.value)) this.error('invalid-macro', '\\' + name + ' needs a \\def.', token);
504
+ this.define(global ? {def: 'gdef', edef: 'xdef'}[next.value] || next.value : next.value, next); return null;
505
+ }
464
506
  if (name === 'require') {
465
507
  const value = this.plainArgument();
466
508
  if (!MATH_TEX_PACKAGES.has(value)) this.error('unsupported-package', 'Unsupported maths package: ' + value + '.', token, name);
@@ -481,9 +523,66 @@ class MathTexParser {
481
523
  const body = this.subparse(this.rawArgument(), true);
482
524
  return {...this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]), semanticRole: 'tag'};
483
525
  }
526
+ if (Object.hasOwn(MATH_TEX_COLONS, name))
527
+ return this.node('style', {class: 'rel', body: this.row([...MATH_TEX_COLONS[name]].flatMap((value, i) => [...(i ? [this.node('space', {width: -1.2 / 18})] : []), this.literal(value, {class: 'ord', variant: 'roman'})]))});
528
+ const make = (value, kind = 'command') => ({kind, value, offset: token.offset});
529
+ // mathtools: \cmd{x} keeps the declared delimiters' size, \cmd*{x} stretches them and \cmd[\big]{x} sets it.
530
+ if (name === '@paired') {
531
+ const left = this.rawArgument(), right = this.rawArgument(), starred = this.is('*');
532
+ if (starred) this.take();
533
+ const size = starred ? null : this.optionalRaw()?.filter(item => item.kind !== 'space'), body = this.rawArgument();
534
+ if (size && (size.length !== 1 || !/^(big|Big|bigg|Bigg)$/.test(size[0].value))) this.error('invalid-option', 'A delimiter size must be \\big, \\Big, \\bigg or \\Bigg.', token);
535
+ const group = tokens => [make('{', 'char'), ...tokens, make('}', 'char')];
536
+ return this.subparse(starred ? [make('left'), ...left, ...body, make('right'), ...right] : size ? [make(size[0].value + 'l'), ...left, ...group(body), make(size[0].value + 'r'), ...right] :
537
+ [make('mathopen'), ...group(left), ...group(body), make('mathclose'), ...group(right)]);
538
+ }
539
+ // braket: \Bra, \Ket, \Braket and \Set stretch their delimiters; bars inside \Braket, and the first in \Set and \set, divide.
540
+ if (/^(Bra|Ket|Braket|Set|set)$/.test(name)) {
541
+ const [left, right] = {Bra: ['langle', '|'], Ket: ['|', 'rangle'], Braket: ['langle', 'rangle'], Set: ['{', '}'], set: ['{', '}']}[name], body = [];
542
+ const raw = this.rawArgument(), delimiter = value => value === '|' ? make('|', 'char') : make(value);
543
+ let divided = false;
544
+ for (let i = 0; i < raw.length; i++) {
545
+ const item = raw[i], bar = item.kind === 'char' && item.value === '|', double = bar && raw[i + 1]?.kind === 'char' && raw[i + 1].value === '|';
546
+ if (!bar || divided || (name !== 'Braket' && name !== 'Set' && name !== 'set')) { body.push(item); continue; }
547
+ if (double) i++;
548
+ divided = name !== 'Braket';
549
+ body.push(...(name === 'set' ? [make('mid')] : [make(name === 'Set' ? ';' : ','), make('middle'), double ? make('|') : make('|', 'char'), make(name === 'Set' ? ';' : ',')]));
550
+ }
551
+ if (name === 'set') return this.subparse([make('{'), make(','), ...body, make(','), make('}')]);
552
+ return this.subparse([make('left'), delimiter(left), ...(name === 'Set' ? [make(',')] : []), ...body, ...(name === 'Set' ? [make(',')] : []), make('right'), delimiter(right)]);
553
+ }
554
+ // units' \nicefrac (and xfrac's \sfrac): a script numerator raised 0.5 ex, a solidus, a script denominator lowered 0.25 ex.
555
+ if (name === 'nicefrac' || name === 'sfrac') {
556
+ const script = body => this.node('style', {mathStyle: 'script', body}), num = this.argument(), den = this.argument();
557
+ return this.row([this.node('raise', {amount: .225, body: script(num)}), this.node('space', {width: -.1}), this.literal('/'), this.node('space', {width: -.15}), this.node('raise', {amount: -.1125, body: script(den)})]);
558
+ }
559
+ if (name === 'vcenter') return this.node('raise', {body: this.argument(), center: true});
560
+ // mathtools \prescript{sup}{sub}{base}: scripts before the base, right aligned, at the base's height.
561
+ if (name === 'prescript') {
562
+ const sup = this.argument(), sub = this.argument(), base = this.argument();
563
+ return this.row([this.node('scripts', {base: this.node('phantom', {body: base, mode: 'v'}), sup, sub, pre: true}), base]);
564
+ }
565
+ // amsmath \sideset{_a^b}{_c^d}\sum: corner scripts beside the operator; later scripts become its limits.
566
+ if (name === 'sideset') {
567
+ const before = this.argument(), after = this.argument(), op = this.argument(), corners = (side, base) => {
568
+ const scripts = side.type === 'row' && side.children.length === 1 ? side.children[0] : side;
569
+ return scripts.type === 'scripts' ? {...scripts, base} : this.row([base, side]);
570
+ };
571
+ return this.node('style', {class: 'op', limits: 'display', body: this.row([corners(before, this.node('phantom', {body: op, mode: 'v'})), corners(after, {...op, limits: 'never'})])});
572
+ }
573
+ // accents.sty: \accentset sets any symbol over its base; \underaccent sets an accent or symbol under it.
574
+ if (name === 'accentset' || name === 'underaccent') {
575
+ const mark = this.rawArgument().filter(item => item.kind !== 'space');
576
+ if (mark.length === 1 && mark[0].kind === 'command' && Object.hasOwn(MATH_TEX_ACCENTS, mark[0].value)) {
577
+ const [value, , stretch] = MATH_TEX_ACCENTS[mark[0].value];
578
+ return this.node('accent', {base: this.argument(), value, position: name === 'accentset' ? 'over' : 'under', stretch});
579
+ }
580
+ const decoration = this.subparse(mark);
581
+ return this.node('overunder', {base: this.argument(), [name === 'accentset' ? 'over' : 'under']: decoration});
582
+ }
583
+ if (name === 'slashed') return this.node('accent', {base: this.argument(), value: '/', position: 'through'});
484
584
  if (name === 'mod' || name === 'bmod') return this.row([this.node('space', {width: name === 'bmod' ? 5 / 18 : 1}), this.node('text', {value: 'mod', variant: 'roman', class: name === 'bmod' ? 'bin' : 'op'}), this.node('space', {width: name === 'bmod' ? 5 / 18 : 1 / 3})]);
485
585
  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()])})]);
486
- if (name === 'bmod') return this.node('text', {value: 'mod', variant: 'roman', class: 'bin'});
487
586
  if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
488
587
  if (name === 'pu') return {...this.units(this.rawArgument()), semanticRole: 'units'};
489
588
  if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
@@ -537,6 +636,7 @@ class MathTexParser {
537
636
  color(value, model, token) {
538
637
  if (!model) {
539
638
  if (Object.hasOwn(this.colors, value)) return this.colors[value];
639
+ if (MATH_TEX_DVIPSNAMES[value]) return MATH_TEX_DVIPSNAMES[value];
540
640
  if (/^#[a-fA-F0-9]{3,8}$/.test(value) && [4, 5, 7, 9].includes(value.length)) return value;
541
641
  if (/^[A-Za-z]{1,32}$/.test(value) && !/^(inherit|unset|initial|revert)$/i.test(value)) return value;
542
642
  } else if (model === 'HTML' && /^[a-fA-F0-9]{6}$/.test(value)) return '#' + value;
@@ -559,11 +659,12 @@ class MathTexParser {
559
659
  const position = this.optionalRaw();
560
660
  if (position) {
561
661
  const value = mathTexTokenText(position).trim();
562
- if (!/^[tbc l r]$/.test(value)) this.error('invalid-option', 'Invalid matrix alignment.', token);
662
+ if (!/^[tbclr]$/.test(value)) this.error('invalid-option', 'Invalid matrix alignment.', token);
563
663
  if (['l', 'r', 'c'].includes(value)) options.columnAlign = value;
564
664
  else options.position = value;
565
665
  }
566
- if (env === 'array' || env === 'subarray') options = {...options, ...this.columnSpec(this.rawArgument(), token)};
666
+ if (env === 'CD') return this.commutativeDiagram(fullName, token);
667
+ if (env === 'array' || env === 'subarray' || env === 'darray') options = {...options, ...this.columnSpec(this.rawArgument(), token)};
567
668
  if (env === 'alignedat' || env === 'alignat') {
568
669
  const value = this.plainArgument();
569
670
  if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 256) this.error('invalid-alignment', 'An alignedat environment needs its number of column pairs.', token);
@@ -576,6 +677,50 @@ class MathTexParser {
576
677
  return body;
577
678
  });
578
679
  }
680
+ // amscd: rows of objects joined by @>>>, @<<< and @= arrows, between rows of @VVV, @AAA, @| and @. arrows.
681
+ commutativeDiagram(fullName, token) {
682
+ const rows = [], make = (value, kind = 'command') => ({kind, value, offset: token.offset});
683
+ let cells = [], current = [];
684
+ const arrow = (kind, labels) => {
685
+ const label = tokens => tokens.length ? this.subparse(tokens) : null;
686
+ if (kind === '>' || kind === '<' || kind === '=')
687
+ return this.node('overunder', {base: this.literal(kind === '>' ? '→' : kind === '<' ? '←' : '=', {class: 'rel', stretch: true}), ...(labels[0]?.length ? {over: label(labels[0])} : {}), ...(labels[1]?.length ? {under: label(labels[1])} : {}), class: 'rel', minWidth: 3});
688
+ if (kind === '.') return this.row([]);
689
+ const side = (tokens, align) => tokens?.length ? [this.node('style', {width: 0, align, body: this.node('style', {mathStyle: 'script', body: label(tokens)})})] : [];
690
+ return this.row([...side(labels[0], 'right'), this.literal(kind === 'V' ? '↓' : kind === 'A' ? '↑' : '‖', {delimiterSize: 3, class: 'ord'}), ...side(labels[1], 'left')]);
691
+ };
692
+ for (;;) {
693
+ const item = this.rawTake(false);
694
+ if (item.kind === 'eof') this.error('unclosed-environment', 'A closing \\end command is missing.', token);
695
+ const end = item.kind === 'command' && item.value === 'end';
696
+ if (end || item.kind === 'command' && item.value === '\\') {
697
+ if (current.some(part => part.kind !== 'space')) cells.push(this.subparse(current));
698
+ if (cells.length) rows.push(cells);
699
+ if (end) break;
700
+ cells = []; current = []; continue;
701
+ }
702
+ if (!(item.kind === 'char' && item.value === '@')) { current.push(item); continue; }
703
+ const kind = this.rawTake(false), name = kind.kind === 'command' && kind.value === '|' ? '|' : kind.value;
704
+ if (!'><=VA|.'.includes(name) || kind.kind === 'eof') this.error('invalid-diagram', 'Expected an amscd arrow after @.', kind);
705
+ const labels = [];
706
+ if ('><VA'.includes(name)) for (let part = 0; part < 2; part++) {
707
+ const tokens = [];
708
+ for (let depth = 0, next = this.rawTake(false); depth || !(next.kind === 'char' && next.value === name); next = this.rawTake(false)) {
709
+ if (next.kind === 'eof') this.error('invalid-diagram', 'An amscd arrow is missing its closing ' + name + '.', kind);
710
+ if (next.kind === 'char') depth += next.value === '{' ? 1 : next.value === '}' ? -1 : 0;
711
+ tokens.push(next);
712
+ }
713
+ labels.push(tokens);
714
+ }
715
+ if ('VA|'.includes(name) || name === '.' && rows.length % 2) { cells.push(arrow(name, labels), this.row([])); current = []; continue; }
716
+ cells.push(current.some(part => part.kind !== 'space') ? this.subparse(current) : this.row([]), arrow(name, labels)); current = [];
717
+ }
718
+ const ending = this.plainArgument();
719
+ if (ending !== fullName) this.error('mismatched-environment', 'Expected \\end{' + fullName + '}, received \\end{' + ending + '}.', token);
720
+ for (const row of rows) if (row.length % 2 === 0 && row.at(-1).type === 'row' && !row.at(-1).children.length) row.pop();
721
+ const columns = Math.max(...rows.map(row => row.length));
722
+ return this.node('table', {env: 'CD', rows, align: Array(columns).fill('c'), rowGaps: [], rowRules: []});
723
+ }
579
724
  tableFromTokens(tokens, env) {
580
725
  return this.nested(() => {
581
726
  const parser = new MathTexParser(this.source, {tokens, scopes: this.scopes, budget: this.budget, colors: this.colors});
@@ -663,13 +808,18 @@ class MathTexParser {
663
808
  const nameTokens = this.rawArgument().filter(item => item.kind !== 'space');
664
809
  if (nameTokens.length !== 1 || nameTokens[0].kind !== 'command') this.error('invalid-macro', 'A macro name must be one command.', token);
665
810
  const macroName = nameTokens[0].value;
811
+ const make = value => ({kind: 'command', value, offset: token.offset});
812
+ const literal = value => ({kind: 'char', value, offset: token.offset});
666
813
  if (name === 'DeclareMathOperator') {
667
814
  const body = this.rawArgument();
668
- const make = value => ({kind: 'command', value, offset: token.offset});
669
- const literal = value => ({kind: 'char', value, offset: token.offset});
670
815
  this.scopes[this.scopes.length - 1][macroName] = {params: [], prefix: [], body: [make('operatorname'), ...(starred ? [literal('*')] : []), literal('{'), ...body, literal('}')], optional: null};
671
816
  return;
672
817
  }
818
+ if (name === 'DeclarePairedDelimiter') {
819
+ const left = this.rawArgument(), right = this.rawArgument();
820
+ this.scopes[this.scopes.length - 1][macroName] = {params: [], prefix: [], body: [make('@paired'), literal('{'), ...left, literal('}'), literal('{'), ...right, literal('}')], optional: null};
821
+ return;
822
+ }
673
823
  if (name === 'let') {
674
824
  if (this.rawPeek().kind === 'char' && this.rawPeek().value === '=') this.rawTake();
675
825
  const target = this.rawTake();
@@ -679,7 +829,7 @@ class MathTexParser {
679
829
  return;
680
830
  }
681
831
  let params = [], prefix = [], optional = null, body;
682
- if (name === 'def' || name === 'gdef') {
832
+ if (/^[egx]?def$/.test(name)) {
683
833
  const specification = [];
684
834
  while (!(this.rawPeek().kind === 'char' && this.rawPeek().value === '{')) {
685
835
  const item = this.rawTake(false);
@@ -697,6 +847,12 @@ class MathTexParser {
697
847
  } else current.push(item);
698
848
  }
699
849
  body = this.rawArgument();
850
+ if (name === 'edef' || name === 'xdef') {
851
+ // \edef expands the macros in its replacement when it is defined.
852
+ const parser = new MathTexParser(this.source, {tokens: body, scopes: this.scopes, budget: this.budget});
853
+ body = [];
854
+ for (let item = parser.take(false); item.kind !== 'eof'; item = parser.take(false)) body.push(item);
855
+ }
700
856
  } else {
701
857
  const countTokens = this.optionalRaw();
702
858
  const count = countTokens ? mathTexTokenText(countTokens).trim() : '0';
@@ -714,7 +870,7 @@ class MathTexParser {
714
870
  const existing = this.macro(macroName) || Object.hasOwn(MATH_SYMBOLS, macroName) || Object.hasOwn(MATH_TEX_VARIANTS, macroName) || MATH_NAMED_OPERATORS.has(macroName) || MATH_LIMIT_OPERATORS.has(macroName);
715
871
  if (name === 'providecommand' && existing) return;
716
872
  if (name === 'newcommand' && existing) this.error('duplicate-macro', '\\' + macroName + ' is already defined.', token);
717
- this.scopes[name === 'gdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
873
+ this.scopes[name === 'gdef' || name === 'xdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
718
874
  }
719
875
  expand(macro, token) {
720
876
  if (++this.budget.expansions > 4096) this.error('resource-limit', 'Macro expansion did not finish within the rendering limit.', token);
@@ -773,7 +929,8 @@ class MathTexParser {
773
929
  parseText(variant = 'roman') {
774
930
  const children = [];
775
931
  let value = '';
776
- const flush = () => { if (value) children.push(this.node('text', {value, variant})); value = ''; };
932
+ // TeX's text fonts join --- and -- into dashes and turn `` '' ` ' into curly quotes; typewriter text keeps them.
933
+ const flush = () => { if (value) children.push(this.node('text', {value: variant === 'monospace' ? value : value.replace(/---|--|``|''|`|'/g, run => ({'---': '—', '--': '–', '``': '“', "''": '”', '`': '‘', "'": '’'})[run]), variant})); value = ''; };
777
934
  for (;;) {
778
935
  const token = this.take(false);
779
936
  if (token.kind === 'eof') break;
@@ -844,6 +1001,7 @@ class MathTexParser {
844
1001
  if ([...letters].length !== 1) this.error('invalid-accent', 'A text accent needs one character.', token);
845
1002
  value += (letters + marks[name]).normalize('NFC'); continue;
846
1003
  }
1004
+ if (Object.hasOwn(MATH_TEX_TEXT_LETTERS, name)) { value += MATH_TEX_TEXT_LETTERS[name]; continue; }
847
1005
  if (Object.hasOwn(MATH_SYMBOLS, name) && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
848
1006
  flush();
849
1007
  const body = this.command(token);
@@ -932,7 +1090,13 @@ class MathTexParser {
932
1090
  const next = this.peek(false);
933
1091
  if (next.kind === 'eof' || stop(next)) break;
934
1092
  const token = this.take(false);
935
- if (token.kind === 'space') { spaced = true; subAllowed = false; moleculeParts = 0; children.push(this.node('space', {width: 3 / 18})); continue; }
1093
+ if (token.kind === 'space') {
1094
+ spaced = true; subAllowed = false; moleculeParts = 0;
1095
+ // An operator or arrow already carries its own spacing; a separating space adds none beside it.
1096
+ const after = this.rawPeek(false), before = children.at(-1)?.class;
1097
+ if (before !== 'bin' && before !== 'rel' && !(after.kind === 'char' && /^[+<=-]$/.test(after.value))) children.push(this.node('space', {width: 3 / 18}));
1098
+ continue;
1099
+ }
936
1100
  if (token.kind === 'command') {
937
1101
  if (token.value === 'bond') {
938
1102
  const value = this.plainArgument(), bonds = {'-': '−', '=': '=', '#': '≡', '~': '∼', '->': '→', '<-': '←', '...': '⋯'};
@@ -988,7 +1152,8 @@ class MathTexParser {
988
1152
  while (this.rawPeek(false).kind === 'char' && /^[<=>-]$/.test(this.rawPeek(false).value) && arrow.length < 5) arrow += this.rawTake(false).value;
989
1153
  const arrows = {'->': '→', '<-': '←', '<->': '↔', '<=>': '⇌', '=>': '⇒', '<=': '⇐', '<<=>': '⇋', '<=>>': '⇌'};
990
1154
  if (arrows[arrow]) {
991
- const over = this.optionalRaw(), under = this.optionalRaw();
1155
+ // Only an adjacent bracket labels the arrow; a peek that skips spaces would drop the next one.
1156
+ const over = this.rawPeek(false).value === '[' ? this.optionalRaw() : null, under = over && this.rawPeek(false).value === '[' ? this.optionalRaw() : null;
992
1157
  const base = this.literal(arrows[arrow], {class: 'rel', variant: 'roman', stretch: true});
993
1158
  children.push(over || under ? this.node('overunder', {base, ...(over ? {over: this.chemistry(over)} : {}), ...(under ? {under: this.chemistry(under)} : {}), class: 'rel'}) : base);
994
1159
  spaced = true; subAllowed = false; moleculeParts = 0; continue;
@@ -77,8 +77,9 @@ function mathFlowAtoms(n,box,x=0,y=0) {
77
77
  }
78
78
  if(n.type==='frac' && n.bar!==false && n.barThickness!==0)box={...box,flowFactor:true};
79
79
  if(n.type==='glyph' && n.value==='⋯')box={...box,flowDots:true};
80
+ // An explicit \bigl or \bigr class wins; an ordinary \big( still pairs by its glyph.
80
81
  if(n.type==='glyph' && '([{⌈⌊⟨⦅⟦⟪⦃)]}⌉⌋⟩⦆⟧⟫⦄'.includes(n.value))
81
- box={...box,flowFence:')]}⌉⌋⟩⦆⟧⟫⦄'.includes(n.value)?'close':'open'};
82
+ box={...box,flowFence:n.class==='open' || n.class==='close'?n.class:')]}⌉⌋⟩⦆⟧⟫⦄'.includes(n.value)?'close':'open'};
82
83
  return [[box,x,y]];
83
84
  }
84
85
 
@@ -93,15 +94,15 @@ function mathRefitRow(items,advance,ratio) {
93
94
 
94
95
  function mathWrapRow(box,c,width,{relationIndent,binaryIndent}={}) {
95
96
  if(mathInkWidth(box)<=width || !box.rowItems?.length)return mathFitBox(box,width,c);
96
- const atoms=box.rowItems.map(item=>[...item]),breaks=[0];let ink=false,depth=0,previous=null;
97
+ const atoms=box.rowItems.map(item=>[...item]),found=[];let ink=false,depth=0,previous=null;
97
98
  for(let i=0;i<atoms.length;i++) {
98
99
  const b=atoms[i][0],next=atoms[i+1]?.[0],fence=b.flowFence || b.class;
99
100
  if(fence==='close')depth=Math.max(0,depth-1);
100
- if(ink && !depth && (b.class==='rel' || b.class==='bin' || b.flowDots && (previous?.flowFactor && next?.flowFactor || (previous?.flowFence || previous?.class)==='close' && (next?.flowFence || next?.class)==='open')))breaks.push(i);
101
+ if(ink && (b.class==='rel' || b.class==='bin' || b.flowDots && (previous?.flowFactor && next?.flowFactor || (previous?.flowFence || previous?.class)==='close' && (next?.flowFence || next?.class)==='open')))found.push([i,depth]);
101
102
  if(fence==='open')depth++;
102
103
  if(b.svg){ink=true;previous=b;}
103
104
  }
104
- breaks.push(atoms.length);
105
+ const breaks=[0,...found.map(([i])=>i),atoms.length],levels=[0,...found.map(([,level])=>level),0];
105
106
  // Reuse structural wrapping before shrinking an oversized, otherwise indivisible atom.
106
107
  const deltas=Array(atoms.length).fill(0);let changed=false;
107
108
  for(let segment=0;segment<breaks.length-1;segment++) {
@@ -150,7 +151,8 @@ function mathWrapRow(box,c,width,{relationIndent,binaryIndent}={}) {
150
151
  left=Math.min(left,x-origin+b.left);right=Math.max(right,x-origin+b.right,x-origin+b.w);
151
152
  }
152
153
  const extent=right-left,over=Math.max(0,extent-available)/available,slack=Math.max(0,available-extent)/available;
153
- const last=end===breaks.length-1,penalty=last?0:atoms[breaks[end]][0].class==='rel'?0:18;
154
+ // A break inside brackets costs more than any fitting line, yet less than overflowing one.
155
+ const last=end===breaks.length-1,penalty=last?0:(atoms[breaks[end]][0].class==='rel'?0:18)+200*levels[end];
154
156
  const cost=costs[end]+12+penalty+(last?8:60)*slack*slack+(over?100000*(1+over*over):0);
155
157
  if(cost<costs[start]) {costs[start]=cost;next[start]=end;}
156
158
  if(extent>available && end>start+1)break;
@@ -18,7 +18,7 @@ varGamma=Γ varDelta=Δ varTheta=Θ varLambda=Λ varXi=Ξ varPi=Π varSigma=Σ v
18
18
  aleph=ℵ beth=ℶ gimel=ℷ daleth=ℸ ell=ℓ hbar=ℏ hslash=ℏ imath=𝚤 jmath=𝚥
19
19
  Re=ℜ Im=ℑ wp=℘ partial=∂ nabla=∇ infty=∞ emptyset=∅ varnothing=∅ complement=∁
20
20
  top=⊤ bot=⊥ forall=∀ exists=∃ nexists=∄ neg/lnot=¬ angle=∠ measuredangle=∡ sphericalangle=∢
21
- triangle=△ blacktriangle=▴ triangledown=▽ blacktriangledown=▾ square/Box=□ blacksquare=■ Diamond=◇ blacklozenge=◆ lozenge=◊
21
+ triangle/vartriangle=△ blacktriangle=▴ triangledown=▽ blacktriangledown=▾ square/Box=□ blacksquare=■ Diamond=◇ blacklozenge=◆ lozenge=◊
22
22
  clubsuit=♣ diamondsuit=♢ heartsuit=♡ spadesuit=♠ checkmark=✓ maltese=✠ yen=¥ pounds=£ euro=€
23
23
  S=§ P=¶ copyright=© circledR=® circledS=Ⓢ mho=℧ Finv=Ⅎ Game=⅁ eth=ð
24
24
  prime=′ backprime=‵ doubleprime=″ tripleprime=‴ degree=° flat=♭ natural=♮ sharp=♯
@@ -27,16 +27,22 @@ surd=√ diagup=╱ diagdown=╲ Bbbk=𝕜
27
27
  // Lowercase Greek retains the ordinary mathematical italic convention.
28
28
  for (const name of 'alpha beta gamma delta epsilon varepsilon zeta eta theta vartheta iota kappa varkappa lambda mu nu xi omicron pi varpi rho varrho sigma varsigma tau upsilon phi varphi chi psi omega digamma'.split(' '))
29
29
  MATH_SYMBOLS[name] = Object.freeze({...MATH_SYMBOLS[name], variant: 'normal'});
30
+ // upgreek: \upalpha to \upomega and \Upgamma to \Upomega are upright.
31
+ for (const name of Object.keys(MATH_SYMBOLS).filter(name => /^[a-z]+$/.test(name) && MATH_SYMBOLS[name].variant === 'normal')) {
32
+ MATH_SYMBOLS['up' + name] = Object.freeze({...MATH_SYMBOLS[name], variant: 'roman'});
33
+ const capital = name[0].toUpperCase() + name.slice(1);
34
+ if (MATH_SYMBOLS[capital]) MATH_SYMBOLS['Up' + name] = MATH_SYMBOLS[capital];
35
+ }
30
36
  for (const name of Object.keys(MATH_SYMBOLS).filter(name => /^var[A-Z]/.test(name)))
31
37
  MATH_SYMBOLS[name] = Object.freeze({...MATH_SYMBOLS[name], variant: 'italic'});
32
38
  mathSymbolGroup('bin', `
33
- pm=± mp=∓ times=× div=÷ cdot=⋅ cdotp=⋅ ast=∗ star=⋆ circ=∘ bullet=∙ diamond=⋄
39
+ pm=± mp=∓ times=× div=÷ cdot=⋅ ast=∗ star=⋆ circ=∘ bullet=∙ diamond=⋄
34
40
  cap=∩ cup=∪ uplus=⊎ sqcap=⊓ sqcup=⊔ vee/lor=∨ wedge/land=∧ setminus=∖ smallsetminus=∖
35
41
  oplus=⊕ ominus=⊖ otimes=⊗ oslash=⊘ odot=⊙ bigcirc=◯ dag/dagger=† ddag/ddagger=‡ amalg=⨿
36
42
  triangleleft=◁ triangleright=▷ lhd=⊲ rhd=⊳ unlhd=⊴ unrhd=⊵ wr=≀
37
43
  barwedge=⊼ veebar=⊻ doublebarwedge=⩞ curlywedge=⋏ curlyvee=⋎ boxplus=⊞ boxminus=⊟ boxtimes=⊠ boxdot=⊡
38
44
  ltimes=⋉ rtimes=⋊ leftthreetimes=⋋ rightthreetimes=⋌ dotplus=∔ divideontimes=⋇
39
- circledast=⊛ circledcirc=⊚ circleddash=⊝ intercal=⊺ centerdot=· land=∧ lor=∨ bigtriangleup=△ bigtriangledown=▽
45
+ circledast=⊛ circledcirc=⊚ circleddash=⊝ intercal=⊺ centerdot=· bigtriangleup=△ bigtriangledown=▽ Cup=⋓ Cap=⋒
40
46
  `, {variant: 'roman'});
41
47
  mathSymbolGroup('rel', `
42
48
  le/leq=≤ ge/geq=≥ neq/ne=≠ equiv=≡ sim=∼ simeq=≃ approx=≈ cong=≅ asymp=≍ propto=∝
@@ -58,7 +64,7 @@ nprec=⊀ nsucc=⊁ npreceq=⋠ nsucceq=⋡ precneqq=⪵ succneqq=⪶ precnsim=
58
64
  nsubset=⊄ nsupset=⊅ nsubseteq=⊈ nsupseteq=⊉ nsubseteqq=⊈ nsupseteqq=⊉ subsetneq=⊊ supsetneq=⊋
59
65
  varsubsetneq=⊊ varsupsetneq=⊋ subsetneqq=⫋ supsetneqq=⫌ varsubsetneqq=⫋ varsupsetneqq=⫌
60
66
  nmid=∤ nparallel=∦ nshortmid=∤ nshortparallel=∦ nvdash=⊬ nVdash=⊮ nvDash=⊭ nVDash=⊯
61
- ntriangleleft=⋪ ntriangleright=⋫ ntrianglelefteq=⋬ ntrianglerighteq=⋭ coloneqq/coloneq=≔ eqqcolon=≕
67
+ ntriangleleft=⋪ ntriangleright=⋫ ntrianglelefteq=⋬ ntrianglerighteq=⋭ coloneqq=≔ eqqcolon=≕ vcentcolon=∶ dblcolon/Colon=∷ And=&
62
68
  `, {variant: 'roman'});
63
69
  mathSymbolGroup('rel', `
64
70
  leftarrow/gets=← rightarrow/to=→ leftrightarrow=↔ Leftarrow=⇐ Rightarrow=⇒ Leftrightarrow=⇔
@@ -72,29 +78,31 @@ Lleftarrow=⇚ Rrightarrow=⇛ twoheadleftarrow=↞ twoheadrightarrow=↠ leftar
72
78
  looparrowleft=↫ looparrowright=↬ leftrightsquigarrow=↭ rightsquigarrow/leadsto=⇝ curvearrowleft=↶ curvearrowright=↷
73
79
  circlearrowleft=↺ circlearrowright=↻ dashleftarrow=⇠ dashrightarrow=⇢ multimap=⊸
74
80
  nleftarrow=↚ nrightarrow=↛ nleftrightarrow=↮ nLeftarrow=⇍ nRightarrow=⇏ nLeftrightarrow=⇎
81
+ Lsh=↰ Rsh=↱ Ldsh=↲ Rdsh=↳ twoheaduparrow=↟ twoheaddownarrow=↡ updownarrows=⇅ downuparrows=⇵ leftsquigarrow=⇜ longrightsquigarrow=⟿
75
82
  `, {variant: 'roman'});
76
83
  mathSymbolGroup('op', `
77
84
  sum=∑ prod=∏ coprod=∐ bigcup=⋃ bigcap=⋂ bigvee=⋁ bigwedge=⋀ biguplus=⨄ bigsqcup=⨆
78
- bigotimes=⨂ bigoplus=⨁ bigodot=⨀ bigamalg=⨿ bigsqcap=⨅
85
+ bigotimes=⨂ bigoplus=⨁ bigodot=⨀ bigamalg=∐ bigsqcap=⨅ bigcupdot=⨃ bigtimes=⨉
79
86
  `, {large: true, limits: 'display', variant: 'roman'});
80
87
  mathSymbolGroup('op', `
81
88
  int=∫ iint=∬ iiint=∭ iiiint=⨌ oint=∮ oiint=∯ oiiint=∰ intop=∫ smallint=∫
82
- intclockwise=∱ varointclockwise=∲ ointctrclockwise=∳ sumint=⨋
89
+ intclockwise=∱ varointclockwise=∲ ointctrclockwise=∳ sumint=⨋ awint=⨑
83
90
  `, {large: true, limits: 'never', variant: 'roman'});
84
91
  MATH_SYMBOLS.intop = Object.freeze({...MATH_SYMBOLS.intop, limits: 'display'});
85
92
  MATH_SYMBOLS.smallint = Object.freeze({...MATH_SYMBOLS.smallint, large: false});
86
- mathSymbolGroup('open', 'langle=⟨ lbrace={ lgroup=⟮ lbrack=[ lfloor=⌊ lceil=⌈ lvert=| lVert=‖ lmoustache=⎰', {variant: 'roman'});
87
- mathSymbolGroup('close', 'rangle=⟩ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱', {variant: 'roman'});
88
- mathSymbolGroup('ord', 'vert=| Vert=‖ backslash=∖ slash=/', {variant: 'roman'});
93
+ mathSymbolGroup('open', 'langle/lang=⟨ lAngle=⟪ lbrace={ lgroup=⟮ lbrack=[ lfloor=⌊ lceil=⌈ lvert=| lVert=‖ lmoustache=⎰ llbracket=⟦ ulcorner=⌜ llcorner=⌞', {variant: 'roman'});
94
+ mathSymbolGroup('close', 'rangle/rang=⟩ rAngle=⟫ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱ rrbracket=⟧ urcorner=⌝ lrcorner=⌟', {variant: 'roman'});
95
+ mathSymbolGroup('ord', 'vert=| Vert=‖ backslash=\\ slash=/', {variant: 'roman'});
89
96
  mathSymbolGroup('inner', 'dotsc=… cdots=⋯ dotsb=⋯ dotsm=⋯ dotsi=⋯ dotso=… ddots=⋱ mathellipsis=…', {variant: 'roman'});
90
97
  mathSymbolGroup('ord', 'vdots=⋮', {variant: 'roman'});
98
+ mathSymbolGroup('inner', 'iddots/adots=⋰', {variant: 'roman'});
91
99
  mathSymbolGroup('punct', 'colon=: cdotp=⋅', {variant: 'roman'});
92
100
  MATH_SYMBOLS.ldots = MATH_SYMBOLS.dots = Object.freeze({type: 'glyph', value: '…', class: 'inner', variant: 'roman'});
93
101
  for (const [name, symbol] of Object.entries(MATH_SYMBOLS)) {
94
102
  const {variant, ...fields} = symbol;
95
103
  MATH_SYMBOLS[name] = Object.freeze({...fields, defaultVariant: variant});
96
104
  }
97
- const MATH_NAMED_OPERATORS = new Set(('arccos arcsin arctan arccot arcsec arccsc cos cosh cot coth csc csch sec sech sin sinh tan tanh exp log ln lg lb det dim gcd hom ker arg deg Pr erf erfc mod').split(' '));
105
+ const MATH_NAMED_OPERATORS = new Set(('arccos arcsin arctan arccot arcsec arccsc cos cosh cot coth csc csch sec sech sin sinh tan tanh exp log ln lg lb det dim gcd hom ker arg deg Pr erf erfc').split(' '));
98
106
  const MATH_LIMIT_OPERATORS = new Set(('lim limsup liminf sup inf max min injlim projlim varlimsup varliminf varinjlim varprojlim').split(' '));
99
107
 
100
108
 
@@ -12,7 +12,7 @@ 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.1.0';
15
+ export const MATH_VERSION = '2.3.0';
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
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'];
@@ -121,13 +121,12 @@ export async function buildMath({root = ROOT, updatePins = true, packageLayout =
121
121
  if (!block.test(loader)) throw new Error('The math loader pin could not be located');
122
122
  const version = /var MATH_VERSION = '[^']+';/;
123
123
  if (!version.test(loader)) throw new Error('The math loader version could not be located');
124
- const cdn = /(key: 'math',[\s\S]*?cdn: ')[^']+(')/;
124
+ // The route keeps its release-tagged origin (tools/version-sync.mjs); only the bundle's filename changes.
125
+ const cdn = /(key: 'math',[\s\S]*?url: '(https:\/\/cdn\.jsdelivr\.net\/gh\/jackskip22\/rapier-plugins@[^/']+\/)math\/)[^']+(')/;
125
126
  if (!cdn.test(loader)) throw new Error('The math loader CDN pin could not be located');
126
- // The old unversioned URL is shipped with a hash pin. Never replace its bytes.
127
- const immutableUrl = 'https://cdn.jsdelivr.net/gh/jackskip22/rapier-plugins@main/math/' + MATH_BUNDLE;
128
127
  await writeFile(loaderPath, loader.replace(version, "var MATH_VERSION = '" + MATH_VERSION + "';")
129
128
  .replace(block, (_, before, middle, after) => before + bytes.length + middle + sha384 + after)
130
- .replace(cdn, (_, before, after) => before + immutableUrl + after));
129
+ .replace(cdn, (_, before, origin, after) => before + MATH_BUNDLE + after));
131
130
  }
132
131
  return {bundle: MATH_BUNDLE, bytes: bytes.length, gzipBytes, sha256, sha384};
133
132
  }