rapier-math 2.2.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.
- package/README.md +1 -1
- package/dist/index.mjs +1 -1
- package/dist/rapier-math.js +319 -99
- package/docs/font-source.md +17 -11
- package/docs/math-components.json +6 -6
- package/docs/math-resources.json +26 -26
- package/package.json +1 -1
- package/src/math/browser.js +28 -17
- package/src/math/build-font.py +153 -226
- package/src/math/classic.js +1 -1
- package/src/math/font.js +66 -33
- package/src/math/layout.js +26 -14
- package/src/math/mathml.js +5 -3
- package/src/math/parser.js +169 -17
- package/src/math/responsive.js +7 -5
- package/src/math/symbols.js +17 -9
- package/src/tools/build-math.mjs +2 -2
package/src/math/layout.js
CHANGED
|
@@ -25,7 +25,7 @@ const mathConstant = (name, c, fallback) => (MATH_FONT.constants[name] ?? fallba
|
|
|
25
25
|
const mathScriptStyle = (c, cramped = c.cramped) => ({...c, level: Math.min(2, c.level + 1), display: false, cramped});
|
|
26
26
|
const mathScreenRelayout = (n,c,ratio) => mathLayout(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()});
|
|
27
27
|
const mathBox = (w = 0, h = 0, d = 0, svg = '', extra = {}) => ({w, h, d, svg, left: 0, right: w, inkTop: -h, inkBottom: d, class: 'ord', ...extra});
|
|
28
|
-
const mathMove = (b, x, y) => b.svg ? '<g transform="translate(' + mathNumber(x) + ' ' + mathNumber(y) + ')">' + b.svg + '</g>'
|
|
28
|
+
const mathMove = (b, x, y) => !b.svg || x === 0 && y === 0 ? b.svg : '<g transform="translate(' + mathNumber(x) + ' ' + mathNumber(y) + ')">' + b.svg + '</g>';
|
|
29
29
|
|
|
30
30
|
function mathCompose(items, width, extra = {}) {
|
|
31
31
|
let h = 0, d = 0, left = 0, right = width, inkTop=Infinity, inkBottom=-Infinity, svg = '';
|
|
@@ -245,7 +245,8 @@ function mathRow(children,c) {
|
|
|
245
245
|
const items=[];let x=0,previous=null;
|
|
246
246
|
for (const b of boxes) {
|
|
247
247
|
if (!b.space) {
|
|
248
|
-
|
|
248
|
+
// TeXbook Appendix G rule 17: a character's italic correction follows it, whatever comes next.
|
|
249
|
+
if(previous?.italic && previous.class!=='op')x+=previous.italic;
|
|
249
250
|
x+=mathSpace(previous?.class,b.class,c);
|
|
250
251
|
}
|
|
251
252
|
items.push([b,x,0]);x+=b.w;
|
|
@@ -337,14 +338,18 @@ function mathScripts(n,c) {
|
|
|
337
338
|
const x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,down,drop,nominal,c);
|
|
338
339
|
items.push([down,x,drop]);w=Math.max(w,x+down.w);
|
|
339
340
|
}
|
|
341
|
+
// \prescript's scripts end together at its base.
|
|
342
|
+
if (n.pre) for (const item of items.slice(1)) item[1]=w-item[0].w;
|
|
340
343
|
return mathCompose(items,w+mathConstant('SpaceAfterScript',c,0.05),{class:b.class});
|
|
341
344
|
}
|
|
342
345
|
|
|
343
346
|
function mathFraction(n,c,width) {
|
|
344
347
|
if (n.style) c={...c,level:({display:0,text:0,script:1,scriptscript:2})[n.style],display:n.style==='display',cramped:false};
|
|
345
348
|
const display=c.display && c.level===0, child=display?{...c,display:false}:mathScriptStyle(c);
|
|
346
|
-
|
|
347
|
-
|
|
349
|
+
let top=width===undefined?mathLayout(n.num,child):mathResponsiveLayout(n.num,child,Math.max(.05,width-.2*mathScale(c)));
|
|
350
|
+
// amsmath's \cfrac opens its numerator with LaTeX's \strut: 0.7 and 0.3 of a 1.2 em baseline skip.
|
|
351
|
+
if(n.strut)top={...top,h:Math.max(top.h,.84*mathScale(child)),d:Math.max(top.d,.36*mathScale(child))};
|
|
352
|
+
const bottom=mathLayout(n.den,{...child,cramped:true}),axis=mathConstant('AxisHeight',c,0.25);
|
|
348
353
|
const line=n.bar===false?0:n.barThickness===undefined?mathConstant('FractionRuleThickness',c,0.04):n.barThickness*mathScale(c);
|
|
349
354
|
let rise=mathConstant(line?(display?'FractionNumeratorDisplayStyleShiftUp':'FractionNumeratorShiftUp'):(display?'StackTopDisplayStyleShiftUp':'StackTopShiftUp'),c,display?0.68:0.4),
|
|
350
355
|
drop=mathConstant(line?(display?'FractionDenominatorDisplayStyleShiftDown':'FractionDenominatorShiftDown'):(display?'StackBottomDisplayStyleShiftDown':'StackBottomShiftDown'),c,display?0.68:0.35);
|
|
@@ -368,9 +373,12 @@ function mathFraction(n,c,width) {
|
|
|
368
373
|
}
|
|
369
374
|
|
|
370
375
|
function mathRoot(n,c) {
|
|
371
|
-
const body=mathLayout(n.body,{...c,cramped:true}),line=mathConstant('RadicalRuleThickness',c,0.04),
|
|
372
|
-
|
|
373
|
-
const sign=mathStretch('√',body.h+body.d+gap+line,c)
|
|
376
|
+
const body=mathLayout(n.body,{...c,cramped:true}),line=mathConstant('RadicalRuleThickness',c,0.04),extra=mathConstant('RadicalExtraAscender',c,0.05);
|
|
377
|
+
let gap=mathConstant(c.display && !c.level?'RadicalDisplayStyleVerticalGap':'RadicalVerticalGap',c,0.1);
|
|
378
|
+
const sign=mathStretch('√',body.h+body.d+gap+line,c);
|
|
379
|
+
// TeXbook Appendix G rule 11: a sign taller than needed splits its excess evenly above and below the radicand.
|
|
380
|
+
gap+=Math.max(0,sign.inkBottom-sign.inkTop-(body.h+body.d+gap+line))/2;
|
|
381
|
+
const rise=-sign.inkTop-body.h-gap-line,
|
|
374
382
|
index=n.index?mathLayout(n.index,{...c,level:2,display:false}):null;
|
|
375
383
|
let before=0,idxX=0;
|
|
376
384
|
if(index) {idxX=Math.max(0,mathConstant('RadicalKernBeforeDegree',c,0.2));before=idxX+index.w+Math.max(-index.w,mathConstant('RadicalKernAfterDegree',c,-0.3));}
|
|
@@ -409,11 +417,13 @@ function mathAccent(n,c) {
|
|
|
409
417
|
return result;
|
|
410
418
|
}
|
|
411
419
|
const names={hat:'̂',widehat:'̂',tilde:'̃',widetilde:'̃',bar:'̄',vec:'⃗',dot:'̇',ddot:'̈',dddot:'⃛',ddddot:'⃜',acute:'́',grave:'̀',breve:'̆',check:'̌',overbrace:'⏞',underbrace:'⏟',overrightarrow:'→',overleftarrow:'←',overleftrightarrow:'↔'};
|
|
420
|
+
// An under-accent (or \slashed's stroke) centres on its base, as in TeX and MathML Core: attachment points are for top accents.
|
|
412
421
|
const value=names[n.value] || n.value,accentStyle={...c,flattenAccent:position!=='under' && b.h>mathConstant('FlattenedAccentBaseHeight',c,0.65)},
|
|
413
422
|
a=n.stretch?mathStretch(value,Math.max(b.w,s*0.3),accentStyle,true):mathGlyph(value,accentStyle,{variant:'roman'}),
|
|
414
|
-
x=(b.accent ?? b.w/2)-(a.accent ?? a.w/2),combining=/^[\u0300-\u036f\u20d0-\u20ff]$/u.test(value);
|
|
423
|
+
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);
|
|
415
424
|
let y;
|
|
416
|
-
if(position==='
|
|
425
|
+
if(position==='through')y=0;
|
|
426
|
+
else if(position==='under')y=b.d+mathConstant('UnderbarVerticalGap',c,0.1)-a.inkTop;
|
|
417
427
|
else if(combining)y=-Math.max(0,b.h-mathConstant('AccentBaseHeight',c,0.48));
|
|
418
428
|
else y=-b.h-mathConstant('OverbarVerticalGap',c,0.1)-a.inkBottom;
|
|
419
429
|
return mathCompose([[b,0,0],[a,x,y]],b.w,semantics);
|
|
@@ -422,7 +432,7 @@ function mathAccent(n,c) {
|
|
|
422
432
|
function mathTable(n,c) {
|
|
423
433
|
const small=/smallmatrix$/.test(n.env) || n.env==='subarray' || n.env==='substack',
|
|
424
434
|
paired=/^(align(?:ed)?(?:at)?|flalign|split)$/.test(n.env),
|
|
425
|
-
display=paired || /^(gather(?:ed)?|eqnarray|multline|equation|drcases|dcases)$/.test(n.env),
|
|
435
|
+
display=paired || /^(gather(?:ed)?|eqnarray|multline|equation|drcases|dcases|darray)$/.test(n.env),
|
|
426
436
|
cellStyle={...c,level:small?Math.max(1,c.level):c.level,display:small?false:display};
|
|
427
437
|
const rows=n.rows.map(row=>row.map((cell,i)=>{
|
|
428
438
|
// The second cell in each equation pair continues the first math list.
|
|
@@ -441,7 +451,7 @@ function mathTable(n,c) {
|
|
|
441
451
|
insertions[insertion.before].push({...insertion,box:mathLayout(insertion.body,cellStyle)});
|
|
442
452
|
}
|
|
443
453
|
const gaps=Array.from({length:cols+1},(_,i)=>{
|
|
444
|
-
let gap=i===0 || i===cols?0:paired?(i%2?0:/^(alignat|alignedat)$/.test(n.env)?0:2*s):small?cs/3:s;
|
|
454
|
+
let gap=i===0 || i===cols?0:paired?(i%2?0:/^(alignat|alignedat)$/.test(n.env)?0:2*s):small?cs/3:n.env==='CD'?5/18*s:s;
|
|
445
455
|
if(insertions[i].some(item=>item.replaceGap))gap=0;
|
|
446
456
|
return gap+insertions[i].reduce((sum,item)=>sum+item.box.w,0);
|
|
447
457
|
});
|
|
@@ -501,7 +511,8 @@ function mathLayout(n,c) {
|
|
|
501
511
|
switch(n.type) {
|
|
502
512
|
case 'row': return mathRow(n.children,c);
|
|
503
513
|
case 'glyph': {
|
|
504
|
-
|
|
514
|
+
// Latin Modern's designed \big to \Bigg parentheses are 5 to 9 units short of 1.2, 1.8, 2.4 and 3 em.
|
|
515
|
+
if(n.delimiterSize || (n.delimiter && c.delimiterTarget))return {...mathDelimiter(n.value,n.delimiterSize?(n.delimiterSize-.01)*mathScale(c):c.delimiterTarget,c),class:n.class || 'ord'};
|
|
505
516
|
if(n.stretch)return {...mathStretch(n.value,c.stretchTarget || mathScale(c),c,true),class:n.class || 'rel',limits:n.limits,stretchAxis:'horizontal'};
|
|
506
517
|
if(n.value==='…' || n.value==='⋯') {
|
|
507
518
|
// TeX's \ldots and \cdots are three punctuation dots with punctuation spacing, wider than the font's ellipses.
|
|
@@ -553,7 +564,7 @@ function mathLayout(n,c) {
|
|
|
553
564
|
}
|
|
554
565
|
case 'overunder': {
|
|
555
566
|
const over=n.over?mathLayout(n.over,mathScriptStyle(c)):null,under=n.under?mathLayout(n.under,mathScriptStyle(c,true)):null,
|
|
556
|
-
b=mathLayout(n.base,{...c,stretchTarget:Math.max(mathScale(c),Math.max(over?.w || 0,under?.w || 0)+0.4*mathScale(c))});
|
|
567
|
+
b=mathLayout(n.base,{...c,stretchTarget:Math.max((n.minWidth || 1)*mathScale(c),Math.max(over?.w || 0,under?.w || 0)+0.4*mathScale(c))});
|
|
557
568
|
const w=Math.max(b.w,over?.w || 0,under?.w || 0),items=[[b,(w-b.w)/2,0]],stretched=b.stretchAxis==='horizontal';
|
|
558
569
|
if(over) {
|
|
559
570
|
const rise=stretched?Math.max(mathConstant('StretchStackTopShiftUp',c,0.8),b.h+over.inkBottom+mathConstant('StretchStackGapAboveMin',c,0.1)):
|
|
@@ -569,7 +580,8 @@ function mathLayout(n,c) {
|
|
|
569
580
|
}
|
|
570
581
|
case 'phantom': {const b=mathLayout(n.body,c);return mathBox(n.mode==='v'?0:b.w,n.mode==='h'?0:b.h,n.mode==='h'?0:b.d);}
|
|
571
582
|
case 'smash': {const b=mathLayout(n.body,c);return {...b,h:n.mode==='b'?b.h:0,d:n.mode==='t'?b.d:0};}
|
|
572
|
-
|
|
583
|
+
// \vcenter centres its box on the maths axis.
|
|
584
|
+
case 'raise': {const b=mathLayout(n.body,c),s=mathScale(c);return mathCompose([[b,0,n.center?(b.h-b.d)/2-mathConstant('AxisHeight',c,0.25):-n.amount*s]],b.w,{class:b.class,...(n.height===undefined?{}:{h:n.height*s}),...(n.depth===undefined?{}:{d:n.depth*s})});}
|
|
573
585
|
case 'rule': {const s=mathScale(c);return mathRule(n.width*s,(n.height+n.depth)*s,-n.height*s);}
|
|
574
586
|
case 'link': {const b=mathLayout(n.body,c);const url=new URL(n.href);if(!['http:','https:'].includes(url.protocol))throw Object.assign(new Error('Unsupported equation link'),{code:'unsafe-url'});b.svg='<a href="'+mathEscape(n.href)+'" aria-label="'+mathEscape(n.href)+'" tabindex="0" target="_blank" rel="noopener noreferrer">'+b.svg+'</a>';return b;}
|
|
575
587
|
default: throw Object.assign(new Error('Unsupported maths construct: '+n.type),{code:'unsupported-construct'});
|
package/src/math/mathml.js
CHANGED
|
@@ -102,7 +102,7 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
102
102
|
if (kind === 'mi' && face !== 'normal' && face !== 'italic') attributes.mathvariant = 'normal';
|
|
103
103
|
token(kind, styled, attributes, context);
|
|
104
104
|
};
|
|
105
|
-
const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[
|
|
105
|
+
const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[∞∅ℵℶℷℸ℘]$/.test(node.value) ? 'mi' :
|
|
106
106
|
['op', 'bin', 'rel', 'open', 'close', 'punct', 'inner'].includes(node.class) ||
|
|
107
107
|
/^[\p{Sm}\p{P}\p{Sc}\p{So}\p{Sk}\u2061-\u2064]$/u.test(node.value) ? 'mo' : 'mi');
|
|
108
108
|
const classOf = node => {
|
|
@@ -156,6 +156,8 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
156
156
|
}
|
|
157
157
|
|
|
158
158
|
function row(children, context, depth) {
|
|
159
|
+
// movablelimits belongs to an operator that is itself the base, not to operators inside a compound base.
|
|
160
|
+
if (children.length > 1) context = {...context, movableLimits: undefined};
|
|
159
161
|
open('mrow');
|
|
160
162
|
let previous;
|
|
161
163
|
for (let index = 0; index < children.length; index++) {
|
|
@@ -283,7 +285,7 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
283
285
|
case 'fence':
|
|
284
286
|
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;
|
|
285
287
|
case 'accent': {
|
|
286
|
-
if (node.overlay) {
|
|
288
|
+
if (node.overlay || node.position === 'through') {
|
|
287
289
|
warn('semantic-overlay', 'An overlay uses the MathML 3 menclose extension; hosts implementing only Core may omit the cancellation or negation mark.');
|
|
288
290
|
const notation = node.value === '╲' ? 'downdiagonalstrike' : node.value === '╳' ? 'updiagonalstrike downdiagonalstrike' : node.value === '↗' ? 'updiagonalarrow' : node.value === '─' ? 'horizontalstrike' : 'updiagonalstrike';
|
|
289
291
|
open('menclose', {notation}); emit(node.base, context, depth + 1); close('menclose'); break;
|
|
@@ -342,7 +344,7 @@ function mathML(tree, source, safeSource, options = {}) {
|
|
|
342
344
|
open('mpadded', {height: node.mode === 'b' ? undefined : '0', depth: node.mode === 't' ? undefined : '0'});
|
|
343
345
|
emit(node.body, context, depth + 1); close('mpadded'); break;
|
|
344
346
|
case 'raise':
|
|
345
|
-
open('mpadded', {voffset: em(node.amount), height: node.height === undefined ? undefined : em(node.height), depth: node.depth === undefined ? undefined : em(node.depth)});
|
|
347
|
+
open('mpadded', {voffset: node.center ? undefined : em(node.amount), height: node.height === undefined ? undefined : em(node.height), depth: node.depth === undefined ? undefined : em(node.depth)});
|
|
346
348
|
emit(node.body, context, depth + 1); close('mpadded'); break;
|
|
347
349
|
case 'rule':
|
|
348
350
|
warn('semantic-rule-presentation', 'A rule is represented as a decorative mathematical space; no additional mathematical relationship is inferred.');
|
package/src/math/parser.js
CHANGED
|
@@ -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
|
|
|
@@ -179,7 +195,9 @@ class MathTexParser {
|
|
|
179
195
|
if (token.kind === 'command' && (Object.hasOwn(MATH_TEX_DECLARATIONS, token.value) || token.value === 'color')) {
|
|
180
196
|
this.take();
|
|
181
197
|
const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
|
|
182
|
-
|
|
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}));
|
|
183
201
|
break;
|
|
184
202
|
}
|
|
185
203
|
if (token.kind === 'command' && /^(over|atop|choose|brace|brack|above|overwithdelims|atopwithdelims|abovewithdelims)$/.test(token.value)) {
|
|
@@ -369,7 +387,7 @@ class MathTexParser {
|
|
|
369
387
|
if (name === 'frac' || name === 'dfrac' || name === 'tfrac' || name === 'cfrac') {
|
|
370
388
|
const align = name === 'cfrac' ? this.optionalRaw() : null;
|
|
371
389
|
if (align && !/^[lr]$/.test(mathTexTokenText(align).trim())) this.error('invalid-option', 'Continued-fraction alignment must be l or r.', token);
|
|
372
|
-
return this.node('frac', {num: this.argument(), den: this.argument(), bar: true, ...(name === 'dfrac' || name === 'cfrac' ? {style: 'display'} : name === 'tfrac' ? {style: 'text'} : {}), ...(align ? {align: mathTexTokenText(align).trim()} : {})});
|
|
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} : {})});
|
|
373
391
|
}
|
|
374
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'} : {})});
|
|
375
393
|
if (name === 'genfrac') {
|
|
@@ -409,8 +427,8 @@ class MathTexParser {
|
|
|
409
427
|
if (name === 'begin') return this.environment(this.plainArgument(), token);
|
|
410
428
|
if (name === 'substack') return this.tableFromTokens(this.rawArgument(), 'substack');
|
|
411
429
|
if (/^(matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases|smallmatrix)$/.test(name)) return this.tableFromTokens(this.rawArgument(), name);
|
|
412
|
-
if (name === 'operatorname') {
|
|
413
|
-
const starred = this.is('*'); if (starred) this.take();
|
|
430
|
+
if (name === 'operatorname' || name === 'operatornamewithlimits') {
|
|
431
|
+
const starred = name !== 'operatorname' || this.is('*'); if (starred && name === 'operatorname') this.take();
|
|
414
432
|
const body = this.subparse(this.rawArgument(), true, 'roman');
|
|
415
433
|
return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
|
|
416
434
|
}
|
|
@@ -450,7 +468,7 @@ class MathTexParser {
|
|
|
450
468
|
}
|
|
451
469
|
if (name === 'raisebox') {
|
|
452
470
|
const amount = this.dimension(this.plainArgument(), token), height = this.optionalRaw(), depth = this.optionalRaw();
|
|
453
|
-
return this.node('raise', {body: this.
|
|
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)} : {})});
|
|
454
472
|
}
|
|
455
473
|
if (name === 'raise' || name === 'lower') return this.node('raise', {amount: this.readDimension() * (name === 'lower' ? -1 : 1), body: this.argument()});
|
|
456
474
|
if (name === 'textcolor') { const color = this.readColor(); return this.node('style', {body: this.argument(), color}); }
|
|
@@ -463,10 +481,28 @@ class MathTexParser {
|
|
|
463
481
|
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(colorName)) this.error('invalid-color', 'Invalid colour name.', token);
|
|
464
482
|
this.colors[colorName] = this.color(value, model, token); return null;
|
|
465
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
|
+
}
|
|
466
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});
|
|
467
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});
|
|
468
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}); }
|
|
469
|
-
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
|
+
}
|
|
470
506
|
if (name === 'require') {
|
|
471
507
|
const value = this.plainArgument();
|
|
472
508
|
if (!MATH_TEX_PACKAGES.has(value)) this.error('unsupported-package', 'Unsupported maths package: ' + value + '.', token, name);
|
|
@@ -487,9 +523,66 @@ class MathTexParser {
|
|
|
487
523
|
const body = this.subparse(this.rawArgument(), true);
|
|
488
524
|
return {...this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]), semanticRole: 'tag'};
|
|
489
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'});
|
|
490
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})]);
|
|
491
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()])})]);
|
|
492
|
-
if (name === 'bmod') return this.node('text', {value: 'mod', variant: 'roman', class: 'bin'});
|
|
493
586
|
if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
|
|
494
587
|
if (name === 'pu') return {...this.units(this.rawArgument()), semanticRole: 'units'};
|
|
495
588
|
if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
|
|
@@ -543,6 +636,7 @@ class MathTexParser {
|
|
|
543
636
|
color(value, model, token) {
|
|
544
637
|
if (!model) {
|
|
545
638
|
if (Object.hasOwn(this.colors, value)) return this.colors[value];
|
|
639
|
+
if (MATH_TEX_DVIPSNAMES[value]) return MATH_TEX_DVIPSNAMES[value];
|
|
546
640
|
if (/^#[a-fA-F0-9]{3,8}$/.test(value) && [4, 5, 7, 9].includes(value.length)) return value;
|
|
547
641
|
if (/^[A-Za-z]{1,32}$/.test(value) && !/^(inherit|unset|initial|revert)$/i.test(value)) return value;
|
|
548
642
|
} else if (model === 'HTML' && /^[a-fA-F0-9]{6}$/.test(value)) return '#' + value;
|
|
@@ -565,11 +659,12 @@ class MathTexParser {
|
|
|
565
659
|
const position = this.optionalRaw();
|
|
566
660
|
if (position) {
|
|
567
661
|
const value = mathTexTokenText(position).trim();
|
|
568
|
-
if (!/^[
|
|
662
|
+
if (!/^[tbclr]$/.test(value)) this.error('invalid-option', 'Invalid matrix alignment.', token);
|
|
569
663
|
if (['l', 'r', 'c'].includes(value)) options.columnAlign = value;
|
|
570
664
|
else options.position = value;
|
|
571
665
|
}
|
|
572
|
-
if (env === '
|
|
666
|
+
if (env === 'CD') return this.commutativeDiagram(fullName, token);
|
|
667
|
+
if (env === 'array' || env === 'subarray' || env === 'darray') options = {...options, ...this.columnSpec(this.rawArgument(), token)};
|
|
573
668
|
if (env === 'alignedat' || env === 'alignat') {
|
|
574
669
|
const value = this.plainArgument();
|
|
575
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);
|
|
@@ -582,6 +677,50 @@ class MathTexParser {
|
|
|
582
677
|
return body;
|
|
583
678
|
});
|
|
584
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
|
+
}
|
|
585
724
|
tableFromTokens(tokens, env) {
|
|
586
725
|
return this.nested(() => {
|
|
587
726
|
const parser = new MathTexParser(this.source, {tokens, scopes: this.scopes, budget: this.budget, colors: this.colors});
|
|
@@ -669,13 +808,18 @@ class MathTexParser {
|
|
|
669
808
|
const nameTokens = this.rawArgument().filter(item => item.kind !== 'space');
|
|
670
809
|
if (nameTokens.length !== 1 || nameTokens[0].kind !== 'command') this.error('invalid-macro', 'A macro name must be one command.', token);
|
|
671
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});
|
|
672
813
|
if (name === 'DeclareMathOperator') {
|
|
673
814
|
const body = this.rawArgument();
|
|
674
|
-
const make = value => ({kind: 'command', value, offset: token.offset});
|
|
675
|
-
const literal = value => ({kind: 'char', value, offset: token.offset});
|
|
676
815
|
this.scopes[this.scopes.length - 1][macroName] = {params: [], prefix: [], body: [make('operatorname'), ...(starred ? [literal('*')] : []), literal('{'), ...body, literal('}')], optional: null};
|
|
677
816
|
return;
|
|
678
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
|
+
}
|
|
679
823
|
if (name === 'let') {
|
|
680
824
|
if (this.rawPeek().kind === 'char' && this.rawPeek().value === '=') this.rawTake();
|
|
681
825
|
const target = this.rawTake();
|
|
@@ -685,7 +829,7 @@ class MathTexParser {
|
|
|
685
829
|
return;
|
|
686
830
|
}
|
|
687
831
|
let params = [], prefix = [], optional = null, body;
|
|
688
|
-
if (
|
|
832
|
+
if (/^[egx]?def$/.test(name)) {
|
|
689
833
|
const specification = [];
|
|
690
834
|
while (!(this.rawPeek().kind === 'char' && this.rawPeek().value === '{')) {
|
|
691
835
|
const item = this.rawTake(false);
|
|
@@ -703,6 +847,12 @@ class MathTexParser {
|
|
|
703
847
|
} else current.push(item);
|
|
704
848
|
}
|
|
705
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
|
+
}
|
|
706
856
|
} else {
|
|
707
857
|
const countTokens = this.optionalRaw();
|
|
708
858
|
const count = countTokens ? mathTexTokenText(countTokens).trim() : '0';
|
|
@@ -720,7 +870,7 @@ class MathTexParser {
|
|
|
720
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);
|
|
721
871
|
if (name === 'providecommand' && existing) return;
|
|
722
872
|
if (name === 'newcommand' && existing) this.error('duplicate-macro', '\\' + macroName + ' is already defined.', token);
|
|
723
|
-
this.scopes[name === 'gdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
|
|
873
|
+
this.scopes[name === 'gdef' || name === 'xdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
|
|
724
874
|
}
|
|
725
875
|
expand(macro, token) {
|
|
726
876
|
if (++this.budget.expansions > 4096) this.error('resource-limit', 'Macro expansion did not finish within the rendering limit.', token);
|
|
@@ -779,7 +929,8 @@ class MathTexParser {
|
|
|
779
929
|
parseText(variant = 'roman') {
|
|
780
930
|
const children = [];
|
|
781
931
|
let value = '';
|
|
782
|
-
|
|
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 = ''; };
|
|
783
934
|
for (;;) {
|
|
784
935
|
const token = this.take(false);
|
|
785
936
|
if (token.kind === 'eof') break;
|
|
@@ -850,6 +1001,7 @@ class MathTexParser {
|
|
|
850
1001
|
if ([...letters].length !== 1) this.error('invalid-accent', 'A text accent needs one character.', token);
|
|
851
1002
|
value += (letters + marks[name]).normalize('NFC'); continue;
|
|
852
1003
|
}
|
|
1004
|
+
if (Object.hasOwn(MATH_TEX_TEXT_LETTERS, name)) { value += MATH_TEX_TEXT_LETTERS[name]; continue; }
|
|
853
1005
|
if (Object.hasOwn(MATH_SYMBOLS, name) && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
|
|
854
1006
|
flush();
|
|
855
1007
|
const body = this.command(token);
|
package/src/math/responsive.js
CHANGED
|
@@ -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]),
|
|
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 &&
|
|
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.
|
|
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
|
-
|
|
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;
|
package/src/math/symbols.js
CHANGED
|
@@ -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=⋅
|
|
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=·
|
|
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
|
|
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
|
|
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=⎰ llbracket=⟦ ulcorner=⌜ llcorner=⌞', {variant: 'roman'});
|
|
87
|
-
mathSymbolGroup('close', 'rangle=⟩ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱ rrbracket=⟧ urcorner=⌝ lrcorner=⌟', {variant: 'roman'});
|
|
88
|
-
mathSymbolGroup('ord', 'vert=| Vert=‖ backslash
|
|
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
|
|
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
|
|