rapier-math 2.4.1 → 2.7.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.
@@ -47,28 +47,40 @@ function mathGlyphIndex(id, c, extra = {}) {
47
47
  const pixels=c.screen?c.screen.fontSize*scale:Infinity,
48
48
  optical=Math.max(c.level,pixels<10?2:pixels<15?1:0);
49
49
  if(optical && alternates)id=alternates[Math.min(optical,alternates.length)-1];
50
- if(c.flattenAccent)id=MATH_FONT.flatAccents[id] ?? id;
51
50
  const g = MATH_FONT.glyph(id), s = scale / MATH_FONT.units, stroke = mathScreenStroke(c,scale), radius = stroke / 2;
52
51
  if (!g) throw Object.assign(new Error('Unsupported mathematical glyph'), {code:'unsupported-glyph'});
53
52
  if(c.budget) {
54
53
  c.budget.outlineBytes=(c.budget.outlineBytes || 0)+g[7].length+96;
55
54
  if(c.budget.outlineBytes>4*1024*1024)throw Object.assign(new Error('Mathematical outlines exceed the rendering budget'),{code:'resource-limit'});
56
55
  }
57
- const svg = g[7] ? '<path d="' + g[7] + '" transform="scale(' + mathNumber(s) + ' ' + mathNumber(-s) + ')"'+
56
+ // A synthetic bold strokes the outline 0.03 em wide and adds 0.06 em of advance; a synthetic italic slants 14 degrees.
57
+ const bold = extra.embolden ? 0.03 * scale : 0, slope = extra.slant ? 0.25 : 0, pen = stroke + bold;
58
+ let svg = g[7] ? '<path d="' + g[7] + '" transform="scale(' + mathNumber(s) + ' ' + mathNumber(-s) + ')"'+
58
59
  (c.screen ? ' data-math-ink="' + mathNumber(scale) + '"' : '') +
59
- (stroke ? ' stroke="currentColor" stroke-width="' + mathNumber(stroke / s) + '" stroke-linejoin="round" paint-order="stroke fill"' : '') + '/>' : '';
60
- return mathBox(g[0] * s, Math.max(0, g[4] * s + radius), Math.max(0, -g[2] * s + radius), svg,
61
- {left: Math.min(0,g[1]*s-radius), right: Math.max(g[0]*s,g[3]*s+radius), inkTop:-g[4]*s-radius, inkBottom:-g[2]*s+radius, italic: g[5]*s, stroke,
62
- accent: g[6] == null ? g[0]*s/2 : g[6]*s,glyph:id,unitScale:s,glyphX:0,glyphY:0,extended:!!MATH_FONT.extendedShapes[id],...extra});
60
+ (pen ? ' stroke="currentColor" stroke-width="' + mathNumber(pen / s) + '" stroke-linejoin="round" paint-order="stroke fill"' : '') + '/>' : '';
61
+ if (svg && (bold || slope)) svg = '<g transform="translate(' + mathNumber(bold) + ' 0)' + (slope ? ' skewX(-14.04)' : '') + '">' + svg + '</g>';
62
+ const {embolden, slant, ...rest} = extra, r = pen / 2;
63
+ return mathBox(g[0] * s + 2 * bold, Math.max(0, g[4] * s + r), Math.max(0, -g[2] * s + r), svg,
64
+ {left: Math.min(0,g[1]*s-r+bold+slope*g[2]*s), right: Math.max(g[0]*s+2*bold,g[3]*s+r+bold+slope*g[4]*s), inkTop:-g[4]*s-r, inkBottom:-g[2]*s+r, italic: g[5]*s+slope*g[4]*s*0.5, stroke: pen || undefined,
65
+ accent: (g[6] == null ? g[0]*s/2 : g[6]*s)+bold+slope*g[4]*s*0.5,glyph:bold || slope?undefined:id,unitScale:s,glyphX:0,glyphY:0,extended:!!MATH_FONT.extendedShapes[id],...rest});
63
66
  }
64
67
 
65
68
  function mathGlyph(value, c, extra = {}) {
66
69
  const cp = value.codePointAt(0);
67
70
  if (value.length !== (cp > 0xffff ? 2 : 1)) return mathText(value, c, extra);
68
71
  const variant = extra.variant || c.variant, mapped = mathStyledCodePoint(cp, variant);
72
+ const styled = MATH_FONT.styledGlyphs[variant]?.[cp];
73
+ if (styled !== undefined) return mathGlyphIndex(styled, c, extra);
69
74
  // A styled dotless i or j is the styled letter's dotless form (Unicode has italic ones only).
70
75
  const dotless = (cp === 0x1d6a4 || cp === 0x1d6a5) && !/^(normal|italic|roman)$/.test(variant) ? MATH_FONT.dotless[MATH_FONT.chars[mathStyledCodePoint(cp - 0x1d6a4 + 105, variant)]] : undefined;
76
+ if (mapped === cp && !dotless && !/^(normal|roman)$/.test(variant)) {
77
+ const composed = mathStyledLetter(value, c, extra, variant);
78
+ if (composed) return composed;
79
+ }
71
80
  const id = dotless ?? MATH_FONT.chars[mapped] ?? MATH_FONT.chars[cp];
81
+ // A letter Unicode gives no bold or italic form (ø, ß, æ, þ) is the font's letter emboldened or slanted.
82
+ if (id !== undefined && mapped === cp && !dotless && /bold|italic/.test(variant || '') && !/script|fraktur|double/.test(variant) && /\p{L}/u.test(value))
83
+ return mathGlyphIndex(id, c, {...extra, embolden: /bold/.test(variant), slant: /italic/.test(variant)});
72
84
  if (id === undefined) {
73
85
  const composed = mathFallbackGlyph(value, c, extra);
74
86
  if (composed) return composed;
@@ -79,6 +91,24 @@ function mathGlyph(value, c, extra = {}) {
79
91
  return mathGlyphIndex(id, c, extra);
80
92
  }
81
93
 
94
+ // A styled accented letter (bold é) has no styled code point: draw its styled base letter with the font's
95
+ // combining marks, as an accent sits on a letter; a mark below hangs from the baseline.
96
+ function mathStyledLetter(value, c, extra, variant) {
97
+ // The font has no combining cedilla or ogonek; their spacing forms hang from the baseline the same way.
98
+ const [base, ...marks] = [...value.normalize('NFD')].map(m => MATH_FONT.chars[m.codePointAt(0)] === undefined ? {'\u0327': '¸', '\u0328': '˛'}[m] || m : m);
99
+ const cp = base.codePointAt(0);
100
+ if (!marks.length || mathStyledCodePoint(cp, variant) === cp || !marks.every(m => (/\p{M}/u.test(m) || '¸˛'.includes(m)) && MATH_FONT.chars[m.codePointAt(0)] !== undefined)) return null;
101
+ const glyphs = marks.map(m => mathGlyph(m, c, {variant: 'roman'})), above = glyphs.some(a => a.inkBottom <= 0);
102
+ const b = mathGlyph(base, {...c, dotless: above && /^[ij]$/.test(base)}, extra), items = [[b,0,0]];
103
+ let top = -Math.max(0, b.h - mathConstant('AccentBaseHeight', c, 0.45));
104
+ for (const a of glyphs) {
105
+ const over = a.inkBottom <= 0, x = (over ? b.accent ?? b.w/2 : b.w/2) - (a.accent ?? a.w/2);
106
+ items.push([a, x, over ? top : 0]);
107
+ if (over) top -= a.inkBottom - a.inkTop;
108
+ }
109
+ return mathCompose(items, b.w, {...extra, italic: b.italic, accent: b.accent, glyph: undefined});
110
+ }
111
+
82
112
  // Letters, digits, marks and symbols outside the embedded font (CJK, Cyrillic, emoji...) use the reader's
83
113
  // own serif font. Their advance is estimated, and textLength fits the drawn run to that box exactly.
84
114
  const MATH_HOST_TEXT = /^[\p{L}\p{N}\p{M}\p{S}\p{P}]+$/u;
@@ -94,18 +124,56 @@ function mathHostText(value, c, extra = {}) {
94
124
  '" lengthAdjust="spacingAndGlyphs">' + mathEscape(value) + '</text>', {inkTop: -0.8 * s, inkBottom: 0.2 * s, ...extra});
95
125
  }
96
126
 
97
- function mathText(value, c, extra = {}) {
98
- const items = [], text = {...c, variant: extra.variant || 'roman'}; let x = 0, run = '';
127
+ // One word of text: a run of host-font characters stays one text element, keeping its shaping and joining.
128
+ function mathTextWord(value, text) {
129
+ const items = []; let x = 0, run = '';
99
130
  const flush = () => { if (run) { const b = mathHostText(run, text); items.push([b,x,0]); x += b.w; run = ''; } };
100
- for (const ch of String(value)) {
101
- if (/\s/u.test(ch)) { flush(); x += mathScale(c)*0.25; continue; }
102
- // A run of host-font characters stays one text element, keeping its shaping and joining.
131
+ for (const ch of value) {
103
132
  if (run && /\p{M}/u.test(ch)) { run += ch; continue; }
104
133
  const b = mathGlyph(ch, text);
134
+ // LaTeX's visible verbatim space retains its TFM box around the same Mono outline.
135
+ if(text.verbatim && ch==='␣')Object.assign(b,{h:79/360*mathScale(text),d:1/9*mathScale(text)});
105
136
  if (b.host) { run += ch; continue; }
106
137
  flush(); items.push([b,x,0]); x += b.w;
107
138
  }
108
139
  flush();
140
+ return mathCompose(items,x);
141
+ }
142
+
143
+ // A word's direction from its first strong letter; a word without letters is a number or neutral.
144
+ const MATH_RTL = /[\p{sc=Hebrew}\p{sc=Arabic}\p{sc=Syriac}\p{sc=Thaana}\p{sc=Nko}\p{sc=Samaritan}\p{sc=Mandaic}\p{sc=Adlam}\p{sc=Hanifi_Rohingya}]/u;
145
+ const mathWordDirection = word => {
146
+ for (const ch of word) if (/\p{L}/u.test(ch)) return MATH_RTL.test(ch) ? 'R' : 'L';
147
+ return /\p{Nd}/u.test(word) ? 'N' : null;
148
+ };
149
+
150
+ function mathText(value, c, extra = {}) {
151
+ // Ordinary text collapses ASCII spaces; TeX ties and verbatim spaces retain each advance.
152
+ const text = {...c, variant: extra.variant || 'roman',verbatim:!!extra.verbatim}, space = mathScale(c)*(text.variant==='monospace'?.525:1/3), words = [];
153
+ // Letters (with their marks and joiners), numbers and punctuation are separate pieces of a word.
154
+ for (const part of String(value).match(/[ \t\r\n]+|\s|[\p{L}\p{M}\p{Cf}]+|\p{Nd}+(?:[.,]\p{Nd}+)*|[^\s\p{L}\p{M}\p{Cf}\p{Nd}]+/gu) || [])
155
+ words.push(/^\s+$/u.test(part) ? {w: part === '\u2009' ? mathScale(c)/6 : space, dir: null} : {box: mathTextWord(part, text), dir: mathWordDirection(part)});
156
+ // The Unicode bidirectional algorithm in a left-to-right line: a number after right-to-left words joins them,
157
+ // as does a neutral between two of them; each right-to-left run reads from the right.
158
+ let strong = 'L';
159
+ for (const word of words) {
160
+ if (word.dir === 'R' || word.dir === 'L') strong = word.level = word.dir;
161
+ else if (word.dir === 'N') word.level = strong;
162
+ }
163
+ for (let i = 0; i < words.length; i++) if (!words[i].level) {
164
+ let j = i; while (j < words.length && !words[j].level) j++;
165
+ const level = words[i - 1]?.level === 'R' && words[j]?.level === 'R' ? 'R' : 'L';
166
+ for (; i < j; i++) words[i].level = level;
167
+ i--;
168
+ }
169
+ const order = [];
170
+ for (let i = 0; i < words.length;) {
171
+ let j = i; while (j < words.length && words[j].level === words[i].level) j++;
172
+ const run = words.slice(i, j);
173
+ order.push(...(words[i].level === 'R' ? run.reverse() : run)); i = j;
174
+ }
175
+ const items = []; let x = 0;
176
+ for (const word of order) { if (word.box) items.push([word.box,x,0]); x += word.box ? word.box.w : word.w; }
109
177
  return mathCompose(items,x,{...extra,class:extra.class || 'ord'});
110
178
  }
111
179
 
@@ -114,7 +182,7 @@ function mathRule(w, thickness, y = 0) {
114
182
  '<path data-math-rule="" d="M0 ' + mathNumber(y) + 'H' + mathNumber(w) + 'v' + mathNumber(thickness) + 'H0Z"/>',{inkTop:y,inkBottom:y+thickness});
115
183
  }
116
184
 
117
- function mathStretch(value, target, c, horizontal = false) {
185
+ function mathStretch(value, target, c, horizontal = false, accent = false, exact = false) {
118
186
  if (!value || value === '.') return mathBox();
119
187
  const cp = value.codePointAt(0), id = MATH_FONT.chars[cp];
120
188
  if (id === undefined) return mathFallbackGlyph(value,c,{variant:'roman',stretchTarget:target,
@@ -128,54 +196,26 @@ function mathStretch(value, target, c, horizontal = false) {
128
196
  return mathCompose([[b,x,0]],width,{italic:b.italic,accent:b.accent+x});
129
197
  };
130
198
  const natural = shape(id);
131
- let construction = (horizontal ? MATH_FONT.horizontal : MATH_FONT.vertical)[id];
199
+ const construction = (horizontal ? MATH_FONT.horizontal : MATH_FONT.vertical)[id];
132
200
  const extent = b => horizontal ? b.w : b.inkBottom-b.inkTop;
133
201
  if (extent(natural) >= target) return natural;
134
- // Some donor arrowheads advertise a zero connector on the joining side.
135
- // Keep their designed heads and extend the drawn shaft instead of joining outside those bounds.
136
- if(horizontal && '→↔↦'.includes(value) && construction?.assembly?.parts.some((p,i,parts)=>i && Math.min(parts[i-1][2],p[1])<MATH_FONT.minConnectorOverlap))construction=null;
137
202
  if (!construction) {
138
203
  if(!horizontal || natural.w<=0)return natural;
139
- // These font glyphs have straight central shafts but no MATH assembly.
140
- // Preserve both end shapes and widen only a narrow central strip.
141
- if('=⇌⇋↞↠→↔↦'.includes(value)) {
142
- const g=MATH_FONT.glyph(natural.glyph),unit=natural.unitScale,added=target-natural.w,
143
- split=g[0]*(value==='↞'?0.75:value==='↠'?0.25:0.5),half=g[0]*0.05,
144
- left=split-half,right=split+half,delta=added/unit;
145
- // The two-headed arrows have their plain shaft opposite both heads.
146
- // All decoded font segments are absolute M/L/H/V/C/Z commands.
147
- const shift=x=>x<=left?x:x>=right?x+delta:x+(x-left)*delta/(right-left);
148
- let command='',coordinate=0;
149
- const path=g[7].replace(/[MLHVCZ]|-?\d+(?:\.\d+)?/g,token=>{
150
- if(/[MLHVCZ]/.test(token)){command=token;coordinate=0;return token;}
151
- const isX=command!=='V' && (command==='H' || coordinate%2===0);coordinate++;
152
- return isX?mathNumber(shift(Number(token))):token;
153
- });
154
- const svg='<path d="'+path+'" transform="scale('+mathNumber(unit)+' '+mathNumber(-unit)+')"'+
155
- (c.screen?' data-math-ink="'+mathNumber(mathScale(c))+'"':'')+
156
- (natural.stroke?' stroke="currentColor" stroke-width="'+mathNumber(natural.stroke/unit)+'" stroke-linejoin="round" paint-order="stroke fill"':'')+'/>';
157
- return {...natural,w:target,right:natural.right+added,accent:target/2,svg,glyph:undefined};
158
- }
159
204
  const ratio=target/natural.w;
160
205
  return {...natural,w:target,left:natural.left*ratio,right:natural.right*ratio,accent:(natural.accent ?? natural.w/2)*ratio,
161
206
  svg:'<g transform="scale('+mathNumber(ratio)+' 1)">'+natural.svg+'</g>',glyph:undefined};
162
207
  }
163
208
  let last = natural;
164
- for (const [glyph,advance] of construction.variants || []) {
165
- last = shape(glyph,advance);
166
- if (advance * mathScale(c) / MATH_FONT.units >= target) return last;
209
+ // An extensible arrow over a label is built to the label's width, as TeX's arrow fill is, not to the next designed size.
210
+ for (const [glyph,advance] of exact && construction.assembly?.parts?.some(p=>p[4]) ? [] : construction.variants || []) {
211
+ const next = shape(glyph,advance), size = horizontal ? next.w : advance * mathScale(c) / MATH_FONT.units;
212
+ // LuaTeX tests a horizontal variant's advance, not the variant record's ink span.
213
+ if (accent && size > target) return last;
214
+ last = next;
215
+ if (size >= target) return last;
167
216
  }
168
217
  const a = construction.assembly;
169
- if (!a?.parts?.length || !a.parts.some(p=>p[4])) {
170
- // A wide accent may outgrow its final designed variant without an extender.
171
- // Expand only its horizontal outline; retain the font's vertical stroke shape.
172
- if (horizontal && last.w>0 && target>last.w) {
173
- const ratio=target/last.w;
174
- return {...last,w:target,left:last.left*ratio,right:last.right*ratio,accent:(last.accent ?? last.w/2)*ratio,
175
- svg:'<g transform="scale('+mathNumber(ratio)+' 1)">'+last.svg+'</g>',glyph:undefined};
176
- }
177
- return last;
178
- }
218
+ if (!a?.parts?.length || !a.parts.some(p=>p[4])) return last;
179
219
  const unit = mathScale(c)/MATH_FONT.units, wanted = target/unit;
180
220
  const minOverlap = MATH_FONT.minConnectorOverlap || 0;
181
221
  const extenders=a.parts.filter(p=>p[4]),fixed=a.parts.filter(p=>!p[4]),
@@ -231,75 +271,60 @@ function mathSpace(left, right, c) {
231
271
  return s*({a:3,b:4,c:5})[code]/18;
232
272
  }
233
273
 
274
+ // A character noad: a plain symbol, with or without scripts; TeX reduces a group of one ordinary symbol to that symbol.
275
+ function mathCharacterNode(n) {
276
+ if (n?.type==='scripts') return mathCharacterNode(n.base);
277
+ if (n?.type==='row' && n.group && n.children.length===1 && (n.children[0].class || 'ord')==='ord') return mathCharacterNode(n.children[0]);
278
+ // A colour or font declaration styles the symbol itself. unicode-math maps \mathbb, \mathcal, \mathfrak and \mathbfit
279
+ // to characters; \mathrm, \mathit, \mathbf, \mathsf, \mathtt and \textcolor make a group.
280
+ if (n?.type==='style' && !n.declaration && Object.keys(n).every(key=>['type','body','color','variant'].includes(key))) {
281
+ if (n.body?.type!=='row') return mathCharacterNode(n.body);
282
+ if (!n.color && n.variant && !['roman','italic','bold','sans-serif','monospace'].includes(n.variant)) return mathCharacterNode(n.body.children[0]);
283
+ }
284
+ return n?.type==='glyph' && !n.delimiterSize;
285
+ }
286
+
234
287
  function mathRow(children,c) {
235
- const boxes=children.map(n=>{
236
- const box=mathLayout(n,c);
237
- if(c.screen)box.refit=ratio=>mathScreenRelayout(n,c,ratio);
238
- if(n.type==='frac' && n.bar!==false && n.barThickness!==0 && !n.left && !n.right)box.flowWrap=width=>mathFraction(n,c,width);
239
- if(n.type==='fence' && !n.size)box.flowWrap=width=>mathResponsiveLayout(n,c,width);
288
+ // A chosen math list is spliced into its surroundings. Its math-style nodes govern later atoms too.
289
+ const entries=[];let current=c;
290
+ const append=nodes=>{for(const n of nodes) {
291
+ if(n.type==='choice') {append(mathChoice(n,current).children);continue;}
292
+ const declaration=n.type==='style' && n.declaration && n.mathStyle;
293
+ if(declaration)current={...current,level:({display:0,text:0,script:1,scriptscript:2})[n.mathStyle],display:n.mathStyle==='display',cramped:false};
294
+ entries.push({n,context:current,declaration});
295
+ }};
296
+ append(children);children=entries.map(entry=>entry.n);
297
+ const boxes=entries.map(({n,context,declaration})=>{
298
+ const box=declaration?mathBox(0,0,0,'',{space:true}):mathLayout(n,context);
299
+ if(context.screen)box.refit=ratio=>mathScreenRelayout(n,context,ratio);
300
+ if(n.type==='frac' && n.bar!==false && n.barThickness!==0 && !n.left && !n.right)box.flowWrap=width=>mathFraction(n,context,width);
301
+ if(n.type==='fence' && !n.size)box.flowWrap=width=>mathResponsiveLayout(n,context,width);
240
302
  return box;
241
303
  });
242
304
  const significant=boxes.map((b,i)=>b.space?null:i).filter(i=>i!==null);
243
305
  for (let k=0;k<significant.length;k++) {
244
306
  const i=significant[k], b=boxes[i];
245
307
  if (b.class!=='bin') continue;
246
- const before=boxes[significant[k-1]]?.class, after=boxes[significant[k+1]]?.class;
308
+ const before=boxes[significant[k-1]]?.middle?'open':boxes[significant[k-1]]?.class, after=boxes[significant[k+1]]?.class;
247
309
  if (!before || ['bin','op','rel','open','punct'].includes(before) || !after || ['rel','close','punct'].includes(after)) b.class='ord';
248
310
  }
249
- const items=[];let x=0,previous=null;
250
- for (const b of boxes) {
311
+ const items=[];let x=0,previous=null,adjacent=false;
312
+ for (const [i,b] of boxes.entries()) {
251
313
  if (!b.space) {
252
- // TeXbook Appendix G rule 17: a character's italic correction follows it, whatever comes next.
253
- if(previous?.italic && previous.class!=='op')x+=previous.italic;
254
- x+=mathSpace(previous?.class,b.class,c);
314
+ // Appendix G rule 17 as LuaTeX applies it: a character's italic correction is kept only before another character.
315
+ if(previous?.italic && previous.class!=='op' && adjacent && mathCharacterNode(children[i]))x+=previous.italic;
316
+ x+=mathSpace(previous?.class,b.class,entries[i].context);
255
317
  }
256
318
  items.push([b,x,0]);x+=b.w;
257
319
  if (!b.space) previous=b;
320
+ adjacent=!b.space;
258
321
  }
259
322
  const last=boxes.at(-1);
260
323
  return mathCompose(items,x,{class:boxes.length===1?boxes[0].class:'ord',italic:boxes.length!==1 && last?.class==='op'?0:last?.italic || 0,rowItems:items,
261
324
  ...(boxes.length===1 ? {accent:last.accent,limits:last.limits,large:last.large,scriptBase:last.scriptBase,accentInk:last.accentInk} : {})});
262
325
  }
263
326
 
264
- function mathKern(b,corner,height) {
265
- const record=MATH_FONT.kern?.[b.glyph]?.[corner];
266
- if (!record || !b.unitScale) return 0;
267
- const [heights,values]=record; let i=0;
268
- while (i<heights.length && (height+(b.glyphY || 0))/b.unitScale>=heights[i]) i++;
269
- return (values[i] || 0)*b.unitScale;
270
- }
271
-
272
- function mathContourBands(box, dy = 0) {
273
- if (!box.unitScale || box.extended) return null;
274
- const profile = MATH_FONT.profile(box.glyph);
275
- if (!profile) return null;
276
- const bands = [], step = MATH_FONT.edgeStep, unit = box.unitScale;
277
- const x = box.glyphX || 0, y = (box.glyphY || 0) + dy, radius = (box.stroke || 0) / 2;
278
- for (let i = profile.length - 1; i > 0; i--) if (profile[i]) {
279
- bands.push({top: y - (profile[0] + i * step) * unit - radius,
280
- bottom: y - (profile[0] + (i - 1) * step) * unit + radius,
281
- left: x + profile[i][0] * unit - radius, right: x + profile[i][1] * unit + radius});
282
- }
283
- return bands;
284
- }
285
-
286
327
  const mathScriptGap = c => c.screen ? Math.max(.035 * mathScale(c), .9 / (c.screen.fontSize * c.screen.pixelRatio)) : .025 * mathScale(c);
287
- function mathContourScript(base, script, dy, nominal, c) {
288
- const a = mathContourBands(base);
289
- if (!a) return nominal;
290
- const b = mathContourBands(script, dy) || [{top: script.inkTop + dy, bottom: script.inkBottom + dy,
291
- left: script.left, right: script.right}];
292
- const gap = mathScriptGap(c);
293
- let j = 0, edge = -Infinity;
294
- for (const left of a) {
295
- while (j < b.length && b[j].bottom + gap < left.top) j++;
296
- for (let k = j; k < b.length && b[k].top <= left.bottom + gap; k++) {
297
- if (b[k].bottom + gap >= left.top) edge = Math.max(edge, left.right - b[k].left);
298
- }
299
- }
300
- return Number.isFinite(edge) ? Math.max(base.glyphX || 0, edge + gap) : nominal;
301
- }
302
-
303
328
  function mathScripts(n,c) {
304
329
  const b=mathLayout(n.base,c), up=n.sup?mathLayout(n.sup,mathScriptStyle(c)):null,
305
330
  down=n.sub?mathLayout(n.sub,mathScriptStyle(c,true)):null;
@@ -316,8 +341,8 @@ function mathScripts(n,c) {
316
341
  }
317
342
  return mathCompose(items,w,{class:b.class});
318
343
  }
319
- const base=b.scriptBase || b,baseAscent=-base.inkTop,baseDescent=base.inkBottom,
320
- upDescent=up?.inkBottom || 0,downAscent=-(down?.inkTop || 0),boxed=base.glyph===undefined || base.extended;
344
+ const base=b.scriptBase || b,boxed=base.glyph===undefined || base.extended,baseAscent=base.h,baseDescent=base.d,
345
+ upDescent=up?.d || 0,downAscent=down?.h || 0;
321
346
  let rise=up?Math.max(mathConstant(c.cramped?'SuperscriptShiftUpCramped':'SuperscriptShiftUp',c,0.36),
322
347
  upDescent+mathConstant('SuperscriptBottomMin',c,0.1),boxed?baseAscent-mathConstant('SuperscriptBaselineDropMax',c,0.25):0):0;
323
348
  let drop=down?Math.max(mathConstant('SubscriptShiftDown',c,0.2),
@@ -331,20 +356,17 @@ function mathScripts(n,c) {
331
356
  }
332
357
  const items=[[b,0,0]]; let w=b.w;
333
358
  if (up) {
334
- const kern=Math.min(mathKern(base,0,rise-upDescent)+mathKern(up,3,-upDescent),mathKern(base,0,baseAscent)+mathKern(up,3,baseAscent-rise));
335
359
  // A large operator's italic correction moves its subscript left, not its superscript right.
336
- const nominal=b.w+(b.large?0:b.italic || 0)+kern;
337
- let x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,up,-rise,nominal,c);
360
+ const nominal=b.w+(b.large?0:b.italic || 0);
361
+ let x=nominal;
338
362
  // A superscript beside an over-accent clears the accent's ink as well as the letter's.
339
363
  const a=b.accentInk,gap=mathScriptGap(c);
340
364
  if(a && up.inkTop-rise<a.bottom+gap && up.inkBottom-rise+gap>a.top)x=Math.max(x,a.right+gap-up.left);
341
365
  items.push([up,x,-rise]);w=Math.max(w,x+up.w);
342
366
  }
343
367
  if (down) {
344
- const kern=Math.min(mathKern(base,2,downAscent-drop)+mathKern(down,1,downAscent),mathKern(base,2,-baseDescent)+mathKern(down,1,drop-baseDescent));
345
- const nominal=b.w-(b.large?b.italic || 0:0)+kern;
346
- const x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,down,drop,nominal,c);
347
- items.push([down,x,drop]);w=Math.max(w,x+down.w);
368
+ const nominal=b.w-(b.large?b.italic || 0:0);
369
+ items.push([down,nominal,drop]);w=Math.max(w,nominal+down.w);
348
370
  }
349
371
  // \prescript's scripts end together at its base.
350
372
  if (n.pre) for (const item of items.slice(1)) item[1]=w-item[0].w;
@@ -360,26 +382,31 @@ function mathFraction(n,c,width) {
360
382
  // amsmath's \cfrac opens its numerator with LaTeX's \strut: 0.7 and 0.3 of a 1.2 em baseline skip.
361
383
  if(n.strut)top={...top,h:Math.max(top.h,.84*mathScale(child)),d:Math.max(top.d,.36*mathScale(child))};
362
384
  const bottom=mathLayout(n.den,{...child,cramped:true}),axis=mathConstant('AxisHeight',c,0.25);
363
- const line=n.bar===false?0:n.barThickness===undefined?mathConstant('FractionRuleThickness',c,0.04):n.barThickness*mathScale(c);
385
+ const line=n.bar===false?0:n.barThickness===undefined?mathConstant('FractionRuleThickness',c,0.04):n.barThickness*c.size;
364
386
  let rise=mathConstant(line?(display?'FractionNumeratorDisplayStyleShiftUp':'FractionNumeratorShiftUp'):(display?'StackTopDisplayStyleShiftUp':'StackTopShiftUp'),c,display?0.68:0.4),
365
387
  drop=mathConstant(line?(display?'FractionDenominatorDisplayStyleShiftDown':'FractionDenominatorShiftDown'):(display?'StackBottomDisplayStyleShiftDown':'StackBottomShiftDown'),c,display?0.68:0.35);
366
388
  if (line) {
367
- rise=Math.max(rise,top.d+axis+line/2+mathConstant(display?'FractionNumDisplayStyleGapMin':'FractionNumeratorGapMin',c,display?0.12:0.06));
368
- drop=Math.max(drop,bottom.h-axis+line/2+mathConstant(display?'FractionDenomDisplayStyleGapMin':'FractionDenominatorGapMin',c,display?0.12:0.06));
389
+ const gap=name=>n.barThickness===undefined?mathConstant(name,c,display?0.12:0.06):line*(display?3:1);
390
+ rise=Math.max(rise,top.d+axis+line/2+gap(display?'FractionNumDisplayStyleGapMin':'FractionNumeratorGapMin'));
391
+ drop=Math.max(drop,bottom.h-axis+line/2+gap(display?'FractionDenomDisplayStyleGapMin':'FractionDenominatorGapMin'));
369
392
  } else {
370
393
  const min=mathConstant(display?'StackDisplayStyleGapMin':'StackGapMin',c,display?0.4:0.15),gap=rise+drop-top.d-bottom.h;
371
394
  if (gap<min) {rise+=(min-gap)/2;drop+=(min-gap)/2;}
372
395
  }
373
- // Null delimiter space pads only an unfenced fraction; a fence's own glyphs bound \binom.
374
- const pad=n.left || n.right?0:mathScale(c)*0.1,w=Math.max(top.w,bottom.w)+2*pad;
375
- const numeratorX=n.align==='l'?pad:n.align==='r'?w-pad-top.w:(w-top.w)/2;
376
- const items=[[top,numeratorX,-rise],[bottom,(w-bottom.w)/2,drop]];
377
- if (line) items.push([mathRule(w,line,-axis-line/2),0,0]);
396
+ // TeX's \nulldelimiterspace (1.2 pt, unscaled in scripts) flanks only an unfenced fraction, outside its rule;
397
+ // a fence's own glyphs bound \binom, and amsmath's \cfrac kerns its right one away.
398
+ const pad=n.left || n.right?0:c.size*0.12,inner=Math.max(top.w,bottom.w),w=inner+pad+(n.strut?0:pad);
399
+ const numeratorX=pad+(n.align==='l'?0:n.align==='r'?inner-top.w:(inner-top.w)/2);
400
+ const items=[[top,numeratorX,-rise],[bottom,pad+(inner-bottom.w)/2,drop]];
401
+ if (line) items.push([mathRule(inner,line,-axis-line/2),pad,0]);
378
402
  // LaTeX's \frac, \binom and \genfrac brace their fraction: an ordinary atom, not TeX's bare inner.
379
403
  const b=mathCompose(items,w,{class:'ord',innerLines:top.lines || 1,fitted:!!top.fitted});
380
404
  if(width!==undefined && c.screen)b.refit=ratio=>mathFraction(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()},width);
381
- // TeX's generalized fractions fence at least its delim1 (display) or delim2 size.
382
- if (n.left || n.right) return {...mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.39:1.01),class:'ord'};
405
+ // Generalized fractions use the fixed \Umathfractiondelsize, independent of the numerator and denominator.
406
+ if (n.left || n.right) {
407
+ const delimiters=n.textDelimiters?{...c,level:0}:c,target=(display?2.4:1.01)*mathScale(c)/mathScale(delimiters);
408
+ return {...mathFenceBoxes(n.left || '',n.right || '',b,delimiters,target),class:'ord'};
409
+ }
383
410
  return b;
384
411
  }
385
412
 
@@ -390,27 +417,68 @@ function mathRoot(n,c) {
390
417
  // TeXbook Appendix G rule 11: a sign taller than needed splits its excess evenly above and below the radicand.
391
418
  gap+=Math.max(0,sign.inkBottom-sign.inkTop-(body.h+body.d+gap+line))/2;
392
419
  const rise=-sign.inkTop-body.h-gap-line,
393
- index=n.index?mathLayout(n.index,{...c,level:2,display:false}):null;
420
+ index=n.index?mathLayout(n.index,{...c,level:2,display:false,cramped:false}):null;
394
421
  let before=0,idxX=0;
395
422
  if(index) {idxX=Math.max(0,mathConstant('RadicalKernBeforeDegree',c,0.2));before=Math.max(0,idxX+index.w+mathConstant('RadicalKernAfterDegree',c,-0.3));}
396
423
  const bodyX=before+sign.w,w=bodyX+body.w,items=[[sign,before,rise],[body,bodyX,0]];
397
424
  items.push([mathRule(body.w,line,-body.h-gap-line),bodyX,0]);
398
- if(index) {const ratio=(MATH_FONT.constants.RadicalDegreeBottomRaisePercent ?? 60)/100;items.push([index,idxX,sign.inkBottom+rise-(sign.inkBottom-sign.inkTop)*ratio-index.inkBottom]);}
399
- const b=mathCompose(items,w);b.h+=extra;return b;
425
+ const b=mathCompose(items,w);b.h+=extra;
426
+ if(!index)return b;
427
+ const ratio=(MATH_FONT.constants.RadicalDegreeBottomRaisePercent ?? 60)/100;
428
+ return mathCompose([[b,0,0],[index,idxX,sign.inkBottom+rise-(sign.inkBottom-sign.inkTop)*ratio]],w);
400
429
  }
401
430
 
402
- function mathFenceBoxes(left,right,body,c,size,least=1) {
403
- const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(body.h-axis,body.d+axis),target=size?size*mathScale(c):Math.max(least*mathScale(c),2*reach*0.901,2*reach-0.5*mathScale(c));
404
- const a=mathDelimiter(left,target,c),b=mathDelimiter(right,target,c);
431
+ function mathFenceBoxes(left,right,body,c,size,least=0,measure=body) {
432
+ const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(measure.h-axis,measure.d+axis),target=size?size*mathScale(c):Math.max(least*mathScale(c),2*reach*0.901,2*reach-0.5*mathScale(c));
433
+ // An empty side is TeX's null delimiter: \nulldelimiterspace wide.
434
+ const side=value=>!value || value==='.'?mathBox(c.size*0.12):mathDelimiter(value,target,c),a=side(left),b=side(right);
405
435
  return mathCompose([[a,0,0],[body,a.w,0],[b,a.w+body.w,0]],a.w+body.w+b.w,{class:'inner'});
406
436
  }
407
437
 
438
+ // MathML's menclose notations, drawn with the rule thickness \boxed uses around a 0.2 em padding.
439
+ function mathEnclose(n,c) {
440
+ const set=new Set(n.notation),s=mathScale(c),line=mathConstant('FractionRuleThickness',c,0.04),pad=0.2*s,
441
+ b=set.has('radical')?mathLayout({type:'root',body:n.body},c):mathLayout(n.body,c),
442
+ has=(...names)=>names.some(name=>set.has(name)),round=has('circle'),
443
+ left=has('box','roundedbox','circle','left','longdiv','phasorangle'),right=has('box','roundedbox','circle','right','actuarial','madruwb'),
444
+ top=has('box','roundedbox','circle','top','longdiv','actuarial'),bottom=has('box','roundedbox','circle','bottom','madruwb','phasorangle'),
445
+ // A circle is the ellipse through the padded box's corners; longdiv's bracket and phasorangle's slope need room at the left.
446
+ grow=round?(Math.SQRT2-1)/2:0,padL=(left?pad:0)+(has('longdiv')?0.3*s:has('phasorangle')?0.4*s:0)+grow*(b.w+2*pad),padR=(right?pad:0)+grow*(b.w+2*pad),
447
+ padT=(top?pad:0)+grow*(b.h+b.d+2*pad),padB=(bottom?pad:0)+grow*(b.h+b.d+2*pad),
448
+ w=padL+b.w+padR,y0=-b.h-padT,y1=b.d+padB,x0=has('longdiv','phasorangle')?padL-pad:0,m=mathNumber,paths=[];
449
+ const segment=(xa,ya,xb,yb)=>paths.push('M'+m(xa)+' '+m(ya)+'L'+m(xb)+' '+m(yb));
450
+ if(has('box'))paths.push('M0 '+m(y0)+'H'+m(w)+'V'+m(y1)+'H0Z');
451
+ else if(has('roundedbox')) {const r=Math.min(0.25*s,(y1-y0)/2,w/2);paths.push('M'+m(r)+' '+m(y0)+'H'+m(w-r)+'A'+m(r)+' '+m(r)+' 0 0 1 '+m(w)+' '+m(y0+r)+'V'+m(y1-r)+'A'+m(r)+' '+m(r)+' 0 0 1 '+m(w-r)+' '+m(y1)+'H'+m(r)+'A'+m(r)+' '+m(r)+' 0 0 1 0 '+m(y1-r)+'V'+m(y0+r)+'A'+m(r)+' '+m(r)+' 0 0 1 '+m(r)+' '+m(y0)+'Z');}
452
+ else if(round) {const rx=w/2,ry=(y1-y0)/2;paths.push('M0 '+m(y0+ry)+'A'+m(rx)+' '+m(ry)+' 0 1 0 '+m(w)+' '+m(y0+ry)+'A'+m(rx)+' '+m(ry)+' 0 1 0 0 '+m(y0+ry)+'Z');}
453
+ else {
454
+ if(set.has('left'))segment(0,y0,0,y1);
455
+ if(has('right','actuarial','madruwb'))segment(w,y0,w,y1);
456
+ if(has('top','longdiv','actuarial'))segment(x0,y0,w,y0);
457
+ if(has('bottom','madruwb','phasorangle'))segment(has('phasorangle')?0:0,y1,w,y1);
458
+ }
459
+ if(set.has('longdiv'))paths.push('M'+m(x0)+' '+m(y0)+'Q'+m(x0+0.3*s)+' '+m((y0+y1)/2)+' '+m(x0-0.05*s)+' '+m(y1));
460
+ if(set.has('phasorangle'))segment(0,y1,x0+0.1*s,y0);
461
+ if(set.has('horizontalstrike'))segment(0,-mathConstant('AxisHeight',c,0.25),w,-mathConstant('AxisHeight',c,0.25));
462
+ if(set.has('verticalstrike'))segment(w/2,y0,w/2,y1);
463
+ if(set.has('updiagonalstrike'))segment(0,y1,w,y0);
464
+ if(set.has('downdiagonalstrike'))segment(0,y0,w,y1);
465
+ if(set.has('updiagonalarrow')) {const tip=0.2*s;segment(0,y1,w,y0);paths.push('M'+m(w-tip)+' '+m(y0)+'H'+m(w)+'V'+m(y0+tip));}
466
+ const fill=n.background?'<path d="M0 '+m(y0)+'H'+m(w)+'V'+m(y1)+'H0Z" fill="'+mathEscape(n.background)+'" fill-opacity="1"/>':'',
467
+ stroke='<path d="'+paths.join('')+'" fill="none" stroke="currentColor" stroke-opacity="1" stroke-width="'+m(line)+'"/>';
468
+ const box=mathCompose([[b,padL,0]],w,{h:-y0,d:y1,class:b.class});
469
+ box.svg=fill+stroke+box.svg;
470
+ if(n.color)box.svg='<g fill="'+mathEscape(n.color)+'" color="'+mathEscape(n.color)+'" fill-opacity="1" stroke-opacity="1">'+box.svg+'</g>';
471
+ return box;
472
+ }
473
+
408
474
  function mathAccent(n,c) {
409
475
  const position=n.position || 'over';let nucleus=n.base;
410
476
  while(nucleus?.type==='style' || (nucleus?.type==='row' && nucleus.children.length===1))nucleus=nucleus.type==='style'?nucleus.body:nucleus.children[0];
411
477
  const b=mathLayout(n.base,position==='under'?c:{...c,cramped:true,dotless:nucleus?.type==='glyph' && !n.overlay && /^[\u0300-\u036f\u20d0-\u20ff]$/u.test(n.value)}),s=mathScale(c);
412
478
  // A brace is an operator: centred on its base, with no italic correction to shift its labels.
413
- const brace=n.limits==='always',semantics={class:n.class || b.class,limits:n.limits || b.limits,italic:brace?0:b.italic,accent:b.accent,scriptBase:b.scriptBase || b};
479
+ // TeX's rules 12 and 18a: scripts on an accented character sit by the character; a bar, or an accent over more than one character, is a box.
480
+ const brace=n.limits==='always',bar=/^(overline|underline|¯|_)$/.test(n.value) && !n.overlay,character=!bar && nucleus?.type==='glyph',
481
+ semantics={class:n.class || (brace?'op':b.class),limits:n.limits || b.limits,italic:brace || !(character || n.overlay)?0:b.italic,accent:b.accent,scriptBase:character || n.overlay?b.scriptBase || b:undefined};
414
482
  if(n.overlay) {
415
483
  const w=Math.max(b.w,0.2*s),line=mathConstant('FractionRuleThickness',c,0.04);
416
484
  const rising='M0 '+mathNumber(b.d)+'L'+mathNumber(w)+' '+mathNumber(-b.h),
@@ -423,21 +491,28 @@ function mathAccent(n,c) {
423
491
  }
424
492
  if (n.value==='overline' || n.value==='underline' || n.value==='¯' || n.value==='_') {
425
493
  const over=position!=='under',line=mathConstant(over?'OverbarRuleThickness':'UnderbarRuleThickness',c,0.04),gap=mathConstant(over?'OverbarVerticalGap':'UnderbarVerticalGap',c,0.1);
494
+ // amsmath's \varliminf underlines lim over a strut 0.2 ex@ deep.
495
+ if(n.varlim && !over)b.d=Math.max(b.d,0.02*s);
426
496
  const y=over?-b.h-gap-line:b.d+gap;
427
497
  const result=mathCompose([[b,0,0],[mathRule(b.w,line,y),0,0]],b.w,semantics);
428
498
  result[over?'h':'d']+=mathConstant(over?'OverbarExtraAscender':'UnderbarExtraDescender',c,0.04);
429
499
  return result;
430
500
  }
431
- const names={hat:'̂',widehat:'̂',tilde:'̃',widetilde:'̃',bar:'̄',vec:'⃗',dot:'̇',ddot:'̈',dddot:'⃛',ddddot:'⃜',acute:'́',grave:'̀',breve:'̆',check:'̌',overbrace:'⏞',underbrace:'⏟',overrightarrow:'→',overleftarrow:'←',overleftrightarrow:'↔'};
432
- // An under-accent (or \slashed's stroke) centres on its base, as in TeX and MathML Core: attachment points are for top accents.
433
- const value=names[n.value] || n.value,accentStyle={...c,flattenAccent:position!=='under' && b.h>mathConstant('FlattenedAccentBaseHeight',c,0.65)},
434
- a=n.stretch?mathStretch(value,Math.max(b.w,s*0.3),accentStyle,true):mathGlyph(value,accentStyle,{variant:'roman'}),
435
- x=position!=='over' || brace?(b.w-a.w)/2:(b.accent ?? b.w/2)-(a.accent ?? a.w/2),combining=/^[\u0300-\u036f\u20d0-\u20ff]$/u.test(value);
501
+ // The font's accent attachment aligns both top and bottom accents; a through stroke stays centered.
502
+ // TeX's stretchy arrows and harpoons over or under a formula are the font's combining arrows, set as accents.
503
+ const arrows=n.stretch && n.class!=='op' && (position==='over'?{'→':'⃗','←':'⃖','↔':'⃡','↼':'⃐','⇀':'⃑'}:position==='under'?{'→':'⃯','←':'⃮','↔':'͍'}:{}),
504
+ value=arrows?.[n.value] && MATH_FONT.chars[arrows[n.value].codePointAt(0)]!==undefined?arrows[n.value]:n.value,
505
+ a=n.stretch?mathStretch(value,Math.max(b.w,s*0.3),c,true,n.class!=='op'):mathGlyph(value,c,{variant:'roman'}),
506
+ x=position==='through' || brace?(b.w-a.w)/2:(b.accent ?? b.w/2)-(a.accent ?? a.w/2),combining=/^[\u0300-\u036f\u20d0-\u20ff]$/u.test(value);
436
507
  let y;
437
508
  if(position==='through')y=0;
438
- else if(position==='under')y=b.d+mathConstant('UnderbarVerticalGap',c,0.1)-a.inkTop;
439
- else if(combining)y=-Math.max(0,b.h-mathConstant('AccentBaseHeight',c,0.48));
509
+ // A glyph the font draws below the baseline hangs from the base's depth, as LuaTeX sets a bottom accent.
510
+ else if(position==='under')y=a.inkTop>=0?b.d:b.d+mathConstant('UnderbarVerticalGap',c,0.1)-a.inkTop;
511
+ // A glyph drawn above the x-height keeps its designed height, raised by the base's height above AccentBaseHeight.
512
+ else if(combining || a.inkBottom<0)y=-Math.max(0,b.h-mathConstant('AccentBaseHeight',c,0.48));
440
513
  else y=-b.h-mathConstant('OverbarVerticalGap',c,0.1)-a.inkBottom;
514
+ // amsmath's \varinjlim and \varprojlim stack lim, a 1.5 ex@ kern, the arrow and a kern of -1 ex@ (ex@ is 1 pt).
515
+ if(n.varlim && position==='under')return mathCompose([[b,0,0],[a,x,b.d+0.15*s+a.h]],b.w,{...semantics,d:b.d+0.15*s+a.h+a.d-0.1*s});
441
516
  // A combining under-accent's box is its ink: its advance box rests far below the mark.
442
517
  if(position==='under')return mathCompose([[b,0,0],[{...a,h:-a.inkTop,d:a.inkBottom},x,y]],b.w,semantics);
443
518
  if(position==='over') {
@@ -458,8 +533,10 @@ function mathTable(n,c) {
458
533
  if(paired && i%2) return mathRow([{type:'row',children:[]},...(cell.type==='row'?cell.children:[cell])],cellStyle);
459
534
  return mathLayout(cell,cellStyle);
460
535
  }));
461
- const cols=Math.max(n.align?.length || 0,n.pairs?2*n.pairs:0,...rows.map(r=>r.length)),s=mathScale(c),cs=mathScale(cellStyle),
462
- widths=Array.from({length:cols},(_,i)=>Math.max(0,...rows.map(row=>row[i]?.w || 0))),
536
+ // A cell spanning columns (\multicolumn, \hdotsfor) and an \intertext line do not set their columns' widths.
537
+ const own=(r,i)=>{const cell=n.rows[r][i];return !(cell?.span>1 || cell?.covered || cell?.intertext);};
538
+ const cols=Math.max(n.align?.length || 0,n.pairs?2*n.pairs:0,...rows.map((r,k)=>n.rows[k][0]?.intertext?0:r.length)),s=mathScale(c),cs=mathScale(cellStyle),
539
+ widths=Array.from({length:cols},(_,i)=>Math.max(0,...rows.map((row,r)=>own(r,i)?row[i]?.w || 0:0))),
463
540
  align=n.env==='eqnarray'?Array.from({length:cols},(_,i)=>['r','c','l'][i%3]):n.align || Array(cols).fill('c');
464
541
  if(rows.length*(cols+(n.columnInsertions?.length || 0))+(n.columnRules?.length || 0)+(n.rowRules?.length || 0)>100000)
465
542
  throw Object.assign(new Error('Array composition exceeds the rendering budget'),{code:'resource-limit'});
@@ -468,104 +545,169 @@ function mathTable(n,c) {
468
545
  if(insertion.before<0 || insertion.before>cols) throw Object.assign(new Error('Array insertion exceeds its columns'),{code:'invalid-alignment'});
469
546
  insertions[insertion.before].push({...insertion,box:mathLayout(insertion.body,cellStyle)});
470
547
  }
548
+ // LaTeX's array keeps half its column gap (\arraycolsep) outside the edge columns. Rules take no width;
549
+ // each further rule in a run adds \doublerulesep.
550
+ // amsmath's smallmatrix has a thin space at each side and a thick space between its columns.
551
+ const ruleRuns=Array(cols+1).fill(0),edge=/^d?array$/.test(n.env)?s/2:/smallmatrix$/.test(n.env)?s/6:0;
552
+ for(const boundary of n.columnRules || [])if(boundary>=0 && boundary<=cols)ruleRuns[boundary]++;
553
+ const ruleSep=0.2*s,ruleStarts=[];
471
554
  const gaps=Array.from({length:cols+1},(_,i)=>{
472
- 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;
555
+ let gap=i===0 || i===cols?edge:paired?(i%2?0:/^(alignat|alignedat)$/.test(n.env)?0:2*s):/smallmatrix$/.test(n.env)?5/18*s:small?cs/3:n.env==='CD'?0:s;
473
556
  if(insertions[i].some(item=>item.replaceGap))gap=0;
474
- return gap+insertions[i].reduce((sum,item)=>sum+item.box.w,0);
557
+ const content=gap+insertions[i].reduce((sum,item)=>sum+item.box.w,0);
558
+ ruleStarts.push(i===0?0:i===cols?content:content/2);
559
+ return content+Math.max(0,ruleRuns[i]-1)*ruleSep;
475
560
  });
561
+ // A spanning cell wider than its columns widens the last of them, as TeX's \multispan does.
562
+ for(const [r,row] of n.rows.entries())for(const [i,cell] of row.entries())if(cell?.span>1 && !cell.dots) {
563
+ const last=Math.min(cols,i+cell.span)-1,room=widths.slice(i,last+1).reduce((a,b)=>a+b,0)+gaps.slice(i+1,last+1).reduce((a,b)=>a+b,0);
564
+ if(rows[r][i].w>room)widths[last]+=rows[r][i].w-room;
565
+ }
476
566
  const starts=[],ends=[],boundaries=[],insertionItems=[];let w=0;
477
567
  for(let i=0;i<=cols;i++) {
478
568
  const contentWidth=insertions[i].reduce((sum,item)=>sum+item.box.w,0);
479
- boundaries.push(w+gaps[i]/2);
569
+ boundaries.push(w+ruleStarts[i]);
480
570
  let x=w+(gaps[i]-contentWidth)/2;
481
571
  for(const item of insertions[i]) {insertionItems.push([item.box,x]);x+=item.box.w;}
482
572
  w+=gaps[i];if(i<cols) {starts.push(w);w+=widths[i];ends.push(w);}
483
573
  }
484
574
  const insertionHeight=Math.max(0,...insertionItems.map(([b])=>b.h)),insertionDepth=Math.max(0,...insertionItems.map(([b])=>b.d)),
485
- heights=rows.map(row=>Math.max(0.7*cs,insertionHeight,...row.map(b=>b.h))),
486
- depths=rows.map(row=>Math.max(0.2*cs,insertionDepth,...row.map(b=>b.d))),baselines=[];
575
+ // LaTeX's array strut is 0.7 and 0.3 of a 1.2 em baseline skip (cases stretches it by 1.2); rows abut,
576
+ // and only the display alignments add \jot between them.
577
+ strut=small || n.env==='CD'?[0.7,0.2]:/cases$/.test(n.env)?[1.008,0.432]:[0.84,0.36],
578
+ rowGap=small?0.2:n.env==='CD'?0.3:/^(align|flalign|split|[lr]?gather|eqnarray|multline)/.test(n.env)?0.3:0,
579
+ heights=rows.map(row=>Math.max(strut[0]*cs,insertionHeight,...row.map(b=>b.h))),
580
+ depths=rows.map(row=>Math.max(strut[1]*cs,insertionDepth,...row.map(b=>b.d))),baselines=[];
581
+ // A full-width rule between rows takes \arrayrulewidth of height; a run of them steps by \doublerulesep.
582
+ const line=mathConstant('FractionRuleThickness',c,0.04),hlines=Array(rows.length+1).fill(0),hlineStarts=[];
583
+ for(const rule of n.rowRules || [])if(rule.from===undefined && rule.to===undefined && rule.before>=0 && rule.before<=rows.length)hlines[rule.before]++;
584
+ const hlineSpace=k=>k?line+(k-1)*ruleSep:0;
487
585
  let total=0;
488
- for(let r=0;r<rows.length;r++) {
586
+ // amsmath's subarray has no strut: its rows are a baseline skip apart (the script font's stack shifts), or a
587
+ // lineskip of three rules apart where they would come closer.
588
+ // smallmatrix's rows are 6 ex@ apart with a lineskip of 1.5 ex@ (ex@ is 1 pt).
589
+ const skip=n.env==='subarray' || n.env==='substack'?{base:(mathConstant('StackTopShiftUp',c,0.444)+mathConstant('StackBottomShiftDown',c,0.345))*cs/s,line:3*mathConstant('FractionRuleThickness',cellStyle,0.04)}:
590
+ /smallmatrix$/.test(n.env)?{base:0.6*s,line:0.15*s}:n.env==='CD'?{base:2*cs,line:0.3*cs}:null;
591
+ if(skip)for(const [r,row] of rows.entries()) {heights[r]=Math.max(0,...row.map(b=>b.h));depths[r]=Math.max(0,...row.map(b=>b.d));}
592
+ for(let r=0;r<=rows.length;r++) {
593
+ hlineStarts.push(total);total+=hlineSpace(hlines[r]);
594
+ if(r===rows.length)break;
489
595
  total+=heights[r];baselines.push(total);total+=depths[r];
490
- if(r+1<rows.length)total+=(small?0.2:0.3)*cs+(n.rowGaps?.[r] || 0)*s;
596
+ if(r+1<rows.length)total+=skip?Math.max(skip.base-depths[r]-heights[r+1],skip.line):rowGap*cs+(n.rowGaps?.[r] || 0)*s;
491
597
  }
492
598
  const offset=n.position==='t'?-(baselines[0] || 0):n.position==='b'?-(baselines.at(-1) || 0):-total/2-mathConstant('AxisHeight',c,0.25),items=[];
493
599
  for(let r=0;r<rows.length;r++) {
600
+ if(n.rows[r][0]?.intertext) {items.push([rows[r][0],0,baselines[r]+offset]);continue;}
494
601
  for(let i=0;i<cols;i++) {
495
- const b=rows[r][i] || mathBox(),a=/^multlined?$/.test(n.env) && cols===1?(r===0?'l':r===rows.length-1?'r':'c'):align[i] || 'c',
496
- dx=a==='r'?widths[i]-b.w:a==='l'?0:(widths[i]-b.w)/2;
602
+ const cell=n.rows[r][i];
603
+ if(cell?.covered)continue;
604
+ const last=cell?.span>1?Math.min(cols,i+cell.span)-1:i,width=(ends[last] ?? starts[i])-starts[i];
605
+ // amsmath's \hdotsfor: dots 3 mu apart times its spacing, spread evenly across the columns it fills.
606
+ if(cell?.dots) {
607
+ const dot=mathGlyph('.',cellStyle,{variant:'roman'}),step=dot.w+cell.dots*3/18*cs,count=Math.max(1,Math.floor(width/step)),spread=width/count;
608
+ for(let k=0;k<count;k++)items.push([dot,starts[i]+k*spread+(spread-dot.w)/2,baselines[r]+offset]);
609
+ continue;
610
+ }
611
+ const b=rows[r][i] || mathBox(),a=cell?.spanAlign || (/^multlined?$/.test(n.env) && cols===1?(r===0?'l':r===rows.length-1?'r':'c'):align[i] || 'c'),
612
+ dx=a==='r'?width-b.w:a==='l'?0:(width-b.w)/2;
497
613
  items.push([b,starts[i]+dx,baselines[r]+offset]);
498
614
  }
499
615
  for(const [b,x] of insertionItems)items.push([b,x,baselines[r]+offset]);
500
616
  }
501
- const line=mathConstant('FractionRuleThickness',c,0.04),ruleCounts=new Map();
502
- for(const boundary of n.columnRules || []) {
617
+ const ruleCounts=new Map(),band=r=>[hlineStarts[r]+hlineSpace(hlines[r]),hlineStarts[r+1]+hlineSpace(hlines[r+1])];
618
+ const vertical=(x,from,to,dashed)=>items.push([mathBox(line/2,0,to-from,'<path data-math-line="vertical" d="M0 0v'+mathNumber(to-from)+'" fill="none" stroke="currentColor" stroke-width="'+mathNumber(line)+'"'+(dashed?' stroke-dasharray="'+mathNumber(.15*s)+' '+mathNumber(.1*s)+'"':'')+'/>',{left:-line/2}),x,offset+from]);
619
+ // A \multicolumn replaces the rules of the columns it spans (the first column's left rule too) with its own.
620
+ const spans=n.rows.flatMap((row,r)=>row.flatMap((cell,i)=>cell?.span>1 || cell?.spanRules?[{r,i,last:Math.min(cols,i+(cell.span || 1))-1,rules:cell.spanRules || []}]:[]));
621
+ for(const [index,boundary] of (n.columnRules || []).entries()) {
503
622
  if(boundary<0 || boundary>cols)throw Object.assign(new Error('Array rule exceeds its columns'),{code:'invalid-rule'});
504
623
  const count=ruleCounts.get(boundary) || 0;ruleCounts.set(boundary,count+1);
505
- const x=boundaries[boundary]+count*0.15*s;
506
- items.push([mathBox(line/2,0,total,'<path data-math-line="vertical" d="M0 0v'+mathNumber(total)+'" fill="none" stroke="currentColor" stroke-width="'+mathNumber(line)+'"/>',{left:-line/2}),x,offset]);
624
+ const x=boundaries[boundary]+count*ruleSep,gaps=spans.filter(span=>span.i<boundary && boundary<=span.last+1 || span.i===0 && boundary===0).map(span=>band(span.r)).sort((a,b)=>a[0]-b[0]);
625
+ let y=0;
626
+ for(const [top,bottom] of gaps) {if(top>y)vertical(x,y,top,n.columnDashes?.[index]);y=Math.max(y,bottom);}
627
+ if(y<total)vertical(x,y,total,n.columnDashes?.[index]);
507
628
  }
629
+ for(const span of spans)for(const rule of span.rules)vertical(rule===0?boundaries[span.i]:boundaries[span.last+1],...band(span.r));
508
630
  ruleCounts.clear();
509
631
  for(const rule of n.rowRules || []) {
510
632
  const boundary=rule.before,from=rule.from ?? 0,to=rule.to ?? cols;
511
633
  if(boundary<0 || boundary>rows.length || from<0 || to>cols)throw Object.assign(new Error('Array rule exceeds its cells'),{code:'invalid-rule'});
512
634
  const count=ruleCounts.get(boundary) || 0;ruleCounts.set(boundary,count+1);
513
- const y=(boundary===0?0:boundary===rows.length?total:(baselines[boundary-1]+depths[boundary-1]+baselines[boundary]-heights[boundary])/2)+offset+count*0.15*s,
635
+ const full=rule.from===undefined && rule.to===undefined,
636
+ y=(full?hlineStarts[boundary]+line/2+count*ruleSep:boundary===0?0:boundary===rows.length?total:(baselines[boundary-1]+depths[boundary-1]+baselines[boundary]-heights[boundary])/2+count*0.15*s)+offset,
514
637
  left=from===0?0:boundaries[from],right=to===cols?w:boundaries[to];
515
638
  const stroke='<path data-math-line="horizontal" d="M0 0H'+mathNumber(right-left)+'" fill="none" stroke="currentColor" stroke-width="'+mathNumber(line)+'"'+(rule.dashed?' stroke-dasharray="'+mathNumber(.15*s)+' '+mathNumber(.1*s)+'"':'')+'/>';
516
639
  items.push([mathBox(right-left,line/2,line/2,stroke),left,y]);
517
640
  }
518
- const b=mathCompose(items,w,{class:'inner',h:Math.max(0,-offset),d:Math.max(0,total+offset)});
519
- const delimiters={pmatrix:['(',')'],bmatrix:['[',']'],Bmatrix:['{','}'],vmatrix:['|','|'],Vmatrix:['‖','‖'],
520
- psmallmatrix:['(',')'],bsmallmatrix:['[',']'],Bsmallmatrix:['{','}'],vsmallmatrix:['|','|'],Vsmallmatrix:['‖','‖'],
521
- cases:['{',''],dcases:['{',''],rcases:['','}'],drcases:['','}']};
522
- const pair=delimiters[n.env];
641
+ // An array is a \vcenter, an ordinary atom; a fenced one is an inner atom, as \left and \right make it.
642
+ const b=mathCompose(items,Math.max(w,...rows.map((row,r)=>n.rows[r][0]?.intertext?row[0].w:0)),{class:'ord',h:Math.max(0,-offset),d:Math.max(0,total+offset)});
643
+ const pair=mathTableDelimiters(n.env);
523
644
  return pair?mathFenceBoxes(pair[0],pair[1],b,c):b;
524
645
  }
525
646
 
526
647
  function mathLayout(n,c) {
648
+ c.displayMode ??= c.display;
527
649
  if(!n)return mathBox();
528
650
  // With spans, each symbol carries its source offset for the host's tap-to-place.
529
651
  if(c.spans && n.at!==undefined && (n.type==='glyph' || n.type==='text')) {
530
652
  const b=mathLayout({...n,at:undefined},c);
531
653
  return {...b,svg:'<g data-math-at="'+n.at+'">'+b.svg+'</g>'};
532
654
  }
655
+ // An empty argument shows the placeholder box a missing one does, as a place to tap.
656
+ if(c.spans && n.at!==undefined && n.type==='row' && !n.children.length)
657
+ return mathLayout({type:'glyph',value:'□',variant:'roman',at:n.at},c);
533
658
  if(c.budget && ++c.budget.nodes>100000)throw Object.assign(new Error('Mathematical layout exceeds the rendering budget'),{code:'resource-limit'});
534
659
  switch(n.type) {
535
- case 'row': return mathRow(n.children,c);
660
+ case 'row': {
661
+ const b=mathRow(n.children,c);
662
+ if(n.group) {
663
+ Object.assign(b,{class:'ord',limits:undefined});
664
+ // TeX collapses a single character before resolving choices; every other group stays a boxed nucleus.
665
+ if(!mathCharacterNode(n))Object.assign(b,{glyph:undefined,scriptBase:undefined,italic:0});
666
+ }
667
+ return b;
668
+ }
536
669
  case 'glyph': {
537
- // Latin Modern's designed \big to \Bigg parentheses are 5 to 9 units short of 1.2, 1.8, 2.4 and 3 em.
538
- 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'};
539
- if(n.stretch)return {...mathStretch(n.value,c.stretchTarget || mathScale(c),c,true),class:n.class || 'rel',limits:n.limits,stretchAxis:'horizontal'};
540
- if(n.value==='…' || n.value==='⋯') {
541
- // TeX's \ldots and \cdots are three punctuation dots with punctuation spacing, wider than the font's ellipses.
542
- const dot=mathGlyph(n.value==='…'?'.':'⋅',c,{variant:'roman'}),step=dot.w+mathSpace('punct','punct',c);
543
- return mathCompose([[dot,0,0],[dot,step,0],[dot,2*step,0]],2*step+dot.w,{class:n.class || 'inner'});
670
+ // TeX spaces a \middle as a closing atom, and a binary atom after it becomes ordinary.
671
+ const middle=n.delimiter && !n.delimiterSize?{class:'close',middle:true}:{};
672
+ // amsmath's \big to \Bigg are \left and \right around a strut 1.2 to 3 times a parenthesis's height and depth,
673
+ // so TeX's \delimiterfactor and \delimitershortfall choose the size, and the strut sets the box.
674
+ if(n.delimiterSize) {
675
+ const paren=MATH_FONT.glyph(MATH_FONT.chars[40]),s=mathScale(c),strut=n.delimiterSize*(paren[4]-paren[2])/MATH_FONT.units*s,axis=mathConstant('AxisHeight',c,0.25);
676
+ const b=mathDelimiter(n.value,Math.max(strut*0.901,strut-0.5*s),c);
677
+ return {...b,h:Math.max(b.h,axis+strut/2),d:Math.max(b.d,strut/2-axis),class:n.class || 'ord',...middle};
544
678
  }
545
- let b=mathGlyph(n.value,c,{class:n.class || 'ord',variant:n.variant || (c.variant==='normal'?n.defaultVariant || 'normal':c.variant),large:n.large,limits:n.limits});
546
- if(n.large && c.display && !c.level) {
547
- const target=mathConstant('DisplayOperatorMinHeight',c,1.3),a=mathStretch(n.value,target,c);
679
+ if(n.delimiter && c.delimiterTarget)return {...mathDelimiter(n.value,c.delimiterTarget,c),class:n.class || 'ord',...middle};
680
+ if(n.stretch)return {...mathStretch(n.value,c.stretchTarget || mathScale(c),c,true,false,!!c.stretchTarget),class:n.class || 'rel',limits:n.limits,stretchAxis:'horizontal'};
681
+ let b=mathGlyph(n.value,c,{class:n.class || 'ord',...middle,variant:n.variant || (c.variant==='normal'?n.defaultVariant || 'normal':c.variant),large:n.large,limits:n.limits});
682
+ if(n.large) {
683
+ let a=c.display && !c.level?mathStretch(n.value,mathConstant('DisplayOperatorMinHeight',c,1.3),c):b;
684
+ // LuaTeX's vertical glyph boxes use CFF control bounds; the ink keeps its exact extrema.
685
+ const bounds=MATH_FONT.verticalBounds[a.glyph];
686
+ if(bounds)a={...a,h:Math.max(0,bounds[1]*a.unitScale),d:Math.max(0,-bounds[0]*a.unitScale)};
548
687
  b=mathCompose([[a,0,(a.h-a.d)/2-mathConstant('AxisHeight',c,0.25)]],a.w,{class:n.class || 'op',italic:a.italic,limits:n.limits,large:true,glyph:a.glyph,unitScale:a.unitScale});
549
688
  }
550
689
  return b;
551
690
  }
552
- case 'text': return mathText(n.value,c,{variant:n.variant || (c.variant==='normal'?'roman':c.variant),class:n.class,limits:n.limits});
553
- case 'space': return mathBox(n.width*mathScale(c),0,0,'',{space:true});
691
+ case 'text': return mathText(n.value,c,{variant:n.variant || (c.variant==='normal'?'roman':c.variant),class:n.class,limits:n.limits,verbatim:n.verbatim});
692
+ case 'choice': return mathLayout(mathChoice(n,c),c);
693
+ case 'space': return mathBox((c.displayMode && n.displayWidth!==undefined?n.displayWidth:n.width)*mathScale(c),0,0,'',{space:true});
554
694
  case 'scripts': return mathScripts(n,c);
555
695
  case 'frac': return mathFraction(n,c);
556
696
  case 'root': return mathRoot(n,c);
697
+ case 'enclose': return mathEnclose(n,c);
557
698
  case 'fence': {
558
699
  // A nested fence does not inherit an outer \middle target. Its cached box
559
700
  // survives the outer fence's second pass, keeping nested layout linear.
560
701
  const cache=c.cache || (c.cache=new WeakMap()),key=[c.size,c.level,c.variant,c.display,c.cramped,c.stretchTarget].join('|');
561
702
  let entries=cache.get(n);if(entries?.has(key))return {...entries.get(key)};
562
- const local={...c,delimiterTarget:undefined};let b=mathLayout(n.body,local);
703
+ const local={...c,delimiterTarget:undefined};let b=mathLayout(n.body,local);const first=b;
563
704
  // Only a \middle needs the second pass, sized to the first pass's body.
564
705
  if(n.body && mathHasMiddle(n.body)) {
565
- const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(b.h-axis,b.d+axis),target=Math.max(mathScale(c),2*reach*0.901,2*reach-0.5*mathScale(c));
706
+ const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(b.h-axis,b.d+axis),target=Math.max(2*reach*0.901,2*reach-0.5*mathScale(c));
566
707
  b=mathLayout(n.body,{...local,delimiterTarget:target});
567
708
  }
568
- b=mathFenceBoxes(n.left,n.right,b,local,n.size);
709
+ // LuaTeX sizes \left and \right from the body as \middle is sized, not from the grown \middle.
710
+ b=mathFenceBoxes(n.left,n.right,b,local,n.size,0,first);if(n.class)b.class=n.class;
569
711
  if(!entries)cache.set(n,entries=new Map());entries.set(key,b);return {...b};
570
712
  }
571
713
  case 'accent': return mathAccent(n,c);
@@ -591,32 +733,64 @@ function mathLayout(n,c) {
591
733
  return b;
592
734
  }
593
735
  case 'overunder': {
594
- const over=n.over?mathLayout(n.over,mathScriptStyle(c)):null,under=n.under?mathLayout(n.under,mathScriptStyle(c,true)):null,
595
- 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))});
596
- const w=Math.max(b.w,over?.w || 0,under?.w || 0),items=[[b,(w-b.w)/2,0]],stretched=b.stretchAxis==='horizontal';
597
- if(over) {
598
- const rise=stretched?Math.max(mathConstant('StretchStackTopShiftUp',c,0.8),b.h+over.inkBottom+mathConstant('StretchStackGapAboveMin',c,0.1)):
599
- b.h+over.inkBottom+mathConstant('OverbarVerticalGap',c,0.1);
600
- items.push([over,(w-over.w)/2,-rise]);
736
+ const s=mathScale(c),ss=mathScale(mathScriptStyle(c)),kind=n.arrow || '',doubled=/^(Leftarrow|Rightarrow|Leftrightarrow)$/.test(kind),
737
+ paired=/^(rightleftharpoons|leftrightharpoons)$/.test(kind),
738
+ label=(x,cramped)=>x && !(n.base?.stretch && !n.diagram && x.type==='row' && !x.children.length)?mathLayout(x,mathScriptStyle(c,cramped)):null;
739
+ let over=label(n.over),under=label(n.under,true);
740
+ // mathtools puts a text control-space beside each double-arrow label, including an empty one.
741
+ if(doubled) {
742
+ const left=kind!=='Rightarrow'?0.333*s:0,right=kind!=='Leftarrow'?0.333*s:0,
743
+ padded=b=>mathCompose([[b || mathBox(),left,0]],(b?.w || 0)+left+right);
744
+ over=padded(over);under=padded(under);
601
745
  }
602
- if(under) {
603
- const drop=stretched?Math.max(mathConstant('StretchStackBottomShiftDown',c,0.6),b.d-under.inkTop+mathConstant('StretchStackGapBelowMin',c,0.1)):
604
- b.d-under.inkTop+mathConstant('UnderbarVerticalGap',c,0.1);
605
- items.push([under,(w-under.w)/2,drop]);
746
+ // mhchem raises its lower label to a common 1.25 ex top and smashes its height before adding limits.
747
+ if(n.unspaced && under)under={...mathCompose([[under,0,under.h-1.25*MATH_FONT.xHeight/MATH_FONT.units*s]],under.w),h:0};
748
+ const pad=(n.labelPad ?? (doubled?10:14))/18*ss,target=Math.max((n.minWidth || (/^hook/.test(kind)?10/9:1))*s,Math.max(over?.w || 0,under?.w || 0)+pad),
749
+ shift=n.unspaced && n.base.value==='→'?-2/18*ss:/^(leftarrow|rightarrow|leftrightarrow|mapsto|hookleftarrow|hookrightarrow|leftharpoonup|leftharpoondown|rightharpoonup|rightharpoondown)$/.test(kind)?(/^(left|hook)/.test(kind)?1:-1)*1.5/18*ss:0;
750
+ // These arrows, and amsmath's overset/underset/stackrel, are operators with TeX's ordinary limit gaps.
751
+ const stack=(b,above,below,dx=shift)=>{
752
+ const w=Math.max(b.w,above?.w || 0,below?.w || 0),items=[[b,(w-b.w)/2,0]];
753
+ if(above) {
754
+ const rise=n.accentGap?b.h+above.inkBottom+mathConstant('OverbarVerticalGap',c,0.1):b.h+Math.max(mathConstant('UpperLimitBaselineRiseMin',c,0.111),mathConstant('UpperLimitGapMin',c,0.2)+above.d);
755
+ items.push([above,(w-above.w)/2+dx,-rise]);
756
+ }
757
+ if(below) {
758
+ const drop=n.accentGap?b.d-below.inkTop+mathConstant('UnderbarVerticalGap',c,0.1):b.d+Math.max(mathConstant('LowerLimitBaselineDropMin',c,0.6),mathConstant('LowerLimitGapMin',c,0.167)+below.h);
759
+ items.push([below,(w-below.w)/2+dx,drop]);
760
+ }
761
+ return mathCompose(items,w,{class:n.unspaced?'ord':n.class || b.class});
762
+ };
763
+ if(paired) {
764
+ // Each half carries the opposite label as a phantom. Even an empty phantom retains its limit gap.
765
+ const right=kind==='rightleftharpoons',phantom=b=>({...b || mathBox(),svg:''}),dy=0.22*MATH_FONT.xHeight/MATH_FONT.units*s,
766
+ top=stack(mathStretch(right?'⇀':'↼',target,c,true,false,true),over,phantom(under),(right?-1:1)*1.5/18*ss),
767
+ bottom=stack(mathStretch(right?'↽':'⇁',target,c,true,false,true),phantom(over),under,(right?1:-1)*1.5/18*ss);
768
+ return mathCompose([[top,0,-dy],[bottom,top.w-bottom.w,dy]],top.w,{class:'rel'});
606
769
  }
607
- return mathCompose(items,w,{class:n.class || b.class});
770
+ let b;
771
+ if(/^hook/.test(kind)) {
772
+ // The small Latin Modern hook owns five mu; joining it to the shaft removes three mu.
773
+ const right=kind==='hookrightarrow',arrow=mathStretch(right?'→':'←',target-2/18*s,c,true,false,true),hook=mathGlyphIndex(MATH_FONT.arrowHook,c),width=arrow.w+2/18*s;
774
+ if(right)b=mathCompose([[hook,0,0],[arrow,2/18*s,0]],width);
775
+ else {
776
+ const reflected=mathBox(5/18*s,hook.h,hook.d,'<g transform="translate('+mathNumber(5/18*s)+' 0) scale(-1 1)">'+hook.svg+'</g>');
777
+ b=mathCompose([[arrow,0,0],[reflected,arrow.w-3/18*s,0]],width);
778
+ }
779
+ } else b=n.diagram && n.base.value==='='?mathCompose([[mathRule(target,0.04*s,-0.28*s),0,0],[mathRule(target,0.04*s,-0.04*s),0,0]],target):mathLayout(n.base,{...c,stretchTarget:target});
780
+ return stack(b,over,under);
608
781
  }
609
782
  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);}
610
- case 'smash': {const b=mathLayout(n.body,c);return {...b,h:n.mode==='b'?b.h:0,d:n.mode==='t'?b.d:0};}
783
+ case 'smash': {const b=mathLayout(n.body,c);return {...b,h:n.mode==='b'?b.h:0,d:n.mode==='t'?b.d:0,glyph:undefined,scriptBase:undefined};}
611
784
  // \vcenter centres its box on the maths axis.
612
785
  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})});}
613
786
  case 'rule': {const s=mathScale(c);return mathRule(n.width*s,(n.height+n.depth)*s,-n.height*s);}
614
787
  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;}
615
- default: throw Object.assign(new Error('Unsupported maths construct: '+n.type),{code:'unsupported-construct'});
788
+ default: throw Object.assign(new Error('Unsupported math construct: '+n.type),{code:'unsupported-construct'});
616
789
  }
617
790
  }
618
791
 
619
792
  import {MATH_FONT} from './font.js';
793
+ import {mathChoice,mathTableDelimiters} from './parser.js';
620
794
  import {mathStyledCodePoint} from './variants.js';
621
795
  import {mathFallbackGlyph} from './fallbacks.js';
622
796
  import {mathResponsiveLayout, mathHasMiddle} from './responsive.js';