dsh-ppt 0.23.1 → 0.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.en.md +7 -7
- package/README.md +7 -7
- package/docs/REFERENCE.en.md +3 -2
- package/docs/REFERENCE.zh.md +3 -2
- package/docs/USAGE.en.md +3 -2
- package/docs/USAGE.md +3 -2
- package/docs/VALIDATION.md +4 -0
- package/docs/WORKBENCH.md +4 -3
- package/lib/client.js +1090 -58
- package/lib/execution.d.ts +6 -5
- package/lib/execution.js +56 -1
- package/lib/tools.js +26 -1
- package/lib/types.d.ts +18 -1
- package/lib/workbench-language.js +1 -0
- package/lib/workbench.js +157 -6
- package/package.json +2 -2
- package/skills/dsh-ppt/SKILL.md +3 -3
- package/skills/dsh-ppt/package.json +1 -1
- package/skills/dsh-ppt/references/advanced.md +19 -5
- package/skills/dsh-ppt/references/data.md +1 -1
- package/skills/dsh-ppt/references/syntax.md +6 -2
- package/skills/dsh-ppt/scripts/build-deck.mjs +45 -6
- package/skills/dsh-ppt/scripts/deck-advanced.mjs +258 -14
- package/skills/dsh-ppt/scripts/deck-core.mjs +135 -14
- package/skills/dsh-ppt/scripts/deck-data.mjs +10 -1
- package/skills/dsh-ppt/scripts/deck-delivery.mjs +529 -6
- package/skills/dsh-ppt/scripts/deck-director.mjs +31 -1
- package/skills/dsh-ppt/scripts/deck-import.mjs +1193 -0
- package/skills/dsh-ppt/scripts/deck-layouts.mjs +2273 -119
- package/skills/dsh-ppt/scripts/deck-math.mjs +1735 -0
|
@@ -0,0 +1,1735 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* deck-math.mjs —— dsh-ppt 零外部依赖确定性 LaTeX 数学公式编译器。
|
|
3
|
+
*
|
|
4
|
+
* 将 LaTeX 数学表达式(行内 $...$、块级 $$...$$、\[...\]、\(...\) 以及 slide.formula)
|
|
5
|
+
* 解析为结构化 AST,并同构编译为:
|
|
6
|
+
* 1. ECMA-376 Office Math(<a14:m><m:oMathPara><m:oMath>...</m:oMath></m:oMathPara></a14:m>)
|
|
7
|
+
* 2. W3C MathML(<math xmlns="http://www.w3.org/1998/Math/MathML">...</math>)
|
|
8
|
+
* 3. 混排段落行内 DrawingML Run 描述符(兼容 LibreOffice 混排段落限制,杜绝吞公式或裸反斜杠泄漏)
|
|
9
|
+
* 4. 2D 公式自然宽高比几何估算器(确保 LibreOffice StarMath / PowerPoint 等比居中无拉伸)
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const A14_NS = 'http://schemas.microsoft.com/office/drawing/2010/main'
|
|
13
|
+
const OMML_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/math'
|
|
14
|
+
const MATHML_NS = 'http://www.w3.org/1998/Math/MathML'
|
|
15
|
+
|
|
16
|
+
function escapeXmlText(value) {
|
|
17
|
+
return String(value ?? '')
|
|
18
|
+
.replace(/[\u000B\u000C]/g, ' ')
|
|
19
|
+
.replace(/[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu, '')
|
|
20
|
+
.replace(/&/g, '&')
|
|
21
|
+
.replace(/</g, '<')
|
|
22
|
+
.replace(/>/g, '>')
|
|
23
|
+
.replace(/"/g, '"')
|
|
24
|
+
.replace(/'/g, ''')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function escapeHtmlText(value) {
|
|
28
|
+
return String(value ?? '')
|
|
29
|
+
.replace(/&/g, '&')
|
|
30
|
+
.replace(/</g, '<')
|
|
31
|
+
.replace(/>/g, '>')
|
|
32
|
+
.replace(/"/g, '"')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
// 希腊字母、数学符号、大型算子、定界符与字体映射表
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
const GREEK_MAP = Object.freeze({
|
|
40
|
+
alpha: 'α',
|
|
41
|
+
beta: 'β',
|
|
42
|
+
gamma: 'γ',
|
|
43
|
+
delta: 'δ',
|
|
44
|
+
epsilon: 'ϵ',
|
|
45
|
+
varepsilon: 'ε',
|
|
46
|
+
zeta: 'ζ',
|
|
47
|
+
eta: 'η',
|
|
48
|
+
theta: 'θ',
|
|
49
|
+
vartheta: 'ϑ',
|
|
50
|
+
iota: 'ι',
|
|
51
|
+
kappa: 'κ',
|
|
52
|
+
lambda: 'λ',
|
|
53
|
+
mu: 'μ',
|
|
54
|
+
nu: 'ν',
|
|
55
|
+
xi: 'ξ',
|
|
56
|
+
omicron: 'ο',
|
|
57
|
+
pi: 'π',
|
|
58
|
+
varpi: 'ϖ',
|
|
59
|
+
rho: 'ρ',
|
|
60
|
+
varrho: 'ϱ',
|
|
61
|
+
sigma: 'σ',
|
|
62
|
+
varsigma: 'ς',
|
|
63
|
+
tau: 'τ',
|
|
64
|
+
upsilon: 'υ',
|
|
65
|
+
phi: 'ϕ',
|
|
66
|
+
varphi: 'φ',
|
|
67
|
+
chi: 'χ',
|
|
68
|
+
psi: 'ψ',
|
|
69
|
+
omega: 'ω',
|
|
70
|
+
Gamma: 'Γ',
|
|
71
|
+
Delta: 'Δ',
|
|
72
|
+
Theta: 'Θ',
|
|
73
|
+
Lambda: 'Λ',
|
|
74
|
+
Xi: 'Ξ',
|
|
75
|
+
Pi: 'Π',
|
|
76
|
+
Sigma: 'Σ',
|
|
77
|
+
Upsilon: 'Υ',
|
|
78
|
+
Phi: 'Φ',
|
|
79
|
+
Psi: 'Ψ',
|
|
80
|
+
Omega: 'Ω',
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
const SYMBOL_MAP = Object.freeze({
|
|
84
|
+
nabla: '∇',
|
|
85
|
+
partial: '∂',
|
|
86
|
+
infty: '∞',
|
|
87
|
+
emptyset: '∅',
|
|
88
|
+
varnothing: '∅',
|
|
89
|
+
ell: 'ℓ',
|
|
90
|
+
hbar: 'ℏ',
|
|
91
|
+
Re: 'ℜ',
|
|
92
|
+
Im: 'ℑ',
|
|
93
|
+
aleph: 'ℵ',
|
|
94
|
+
wp: '℘',
|
|
95
|
+
degree: '°',
|
|
96
|
+
circ: '∘',
|
|
97
|
+
bullet: '∙',
|
|
98
|
+
cdot: '·',
|
|
99
|
+
cdots: '⋯',
|
|
100
|
+
ldots: '…',
|
|
101
|
+
dots: '…',
|
|
102
|
+
vdots: '⋮',
|
|
103
|
+
ddots: '⋱',
|
|
104
|
+
times: '×',
|
|
105
|
+
div: '÷',
|
|
106
|
+
pm: '±',
|
|
107
|
+
mp: '∓',
|
|
108
|
+
ast: '∗',
|
|
109
|
+
star: '⋆',
|
|
110
|
+
oplus: '⊕',
|
|
111
|
+
ominus: '⊖',
|
|
112
|
+
otimes: '⊗',
|
|
113
|
+
oslash: '⊘',
|
|
114
|
+
odot: '⊙',
|
|
115
|
+
dagger: '†',
|
|
116
|
+
ddagger: '‡',
|
|
117
|
+
top: '⊤',
|
|
118
|
+
bot: '⊥',
|
|
119
|
+
perp: '⊥',
|
|
120
|
+
parallel: '∥',
|
|
121
|
+
mid: '|',
|
|
122
|
+
nmid: '∤',
|
|
123
|
+
angle: '∠',
|
|
124
|
+
triangle: '△',
|
|
125
|
+
backslash: '\\',
|
|
126
|
+
forall: '∀',
|
|
127
|
+
exists: '∃',
|
|
128
|
+
nexists: '∄',
|
|
129
|
+
neg: '¬',
|
|
130
|
+
lnot: '¬',
|
|
131
|
+
land: '∧',
|
|
132
|
+
wedge: '∧',
|
|
133
|
+
lor: '∨',
|
|
134
|
+
vee: '∨',
|
|
135
|
+
in: '∈',
|
|
136
|
+
notin: '∉',
|
|
137
|
+
ni: '∋',
|
|
138
|
+
subset: '⊂',
|
|
139
|
+
supset: '⊃',
|
|
140
|
+
subseteq: '⊆',
|
|
141
|
+
supseteq: '⊇',
|
|
142
|
+
subsetneq: '⊊',
|
|
143
|
+
supsetneq: '⊋',
|
|
144
|
+
cup: '∪',
|
|
145
|
+
cap: '∩',
|
|
146
|
+
setminus: '∖',
|
|
147
|
+
leq: '≤',
|
|
148
|
+
le: '≤',
|
|
149
|
+
geq: '≥',
|
|
150
|
+
ge: '≥',
|
|
151
|
+
neq: '≠',
|
|
152
|
+
ne: '≠',
|
|
153
|
+
approx: '≈',
|
|
154
|
+
sim: '∼',
|
|
155
|
+
simeq: '≃',
|
|
156
|
+
cong: '≅',
|
|
157
|
+
equiv: '≡',
|
|
158
|
+
propto: '∝',
|
|
159
|
+
ll: '≪',
|
|
160
|
+
gg: '≫',
|
|
161
|
+
prec: '≺',
|
|
162
|
+
succ: '≻',
|
|
163
|
+
preceq: '≼',
|
|
164
|
+
succeq: '≽',
|
|
165
|
+
triangleq: '≜',
|
|
166
|
+
defeq: '≔',
|
|
167
|
+
coloneqq: '≔',
|
|
168
|
+
rightarrow: '→',
|
|
169
|
+
to: '→',
|
|
170
|
+
leftarrow: '←',
|
|
171
|
+
gets: '←',
|
|
172
|
+
leftrightarrow: '↔',
|
|
173
|
+
Rightarrow: '⇒',
|
|
174
|
+
implies: '⇒',
|
|
175
|
+
Leftarrow: '⇐',
|
|
176
|
+
Leftrightarrow: '⇔',
|
|
177
|
+
iff: '⇔',
|
|
178
|
+
mapsto: '↦',
|
|
179
|
+
longmapsto: '⟼',
|
|
180
|
+
longrightarrow: '⟶',
|
|
181
|
+
longleftarrow: '⟵',
|
|
182
|
+
Longrightarrow: '⟹',
|
|
183
|
+
Longleftarrow: '⟸',
|
|
184
|
+
Longleftrightarrow: '⟺',
|
|
185
|
+
uparrow: '↑',
|
|
186
|
+
downarrow: '↓',
|
|
187
|
+
updownarrow: '↕',
|
|
188
|
+
Uparrow: '⇑',
|
|
189
|
+
Downarrow: '⇓',
|
|
190
|
+
nearrow: '↗',
|
|
191
|
+
searrow: '↘',
|
|
192
|
+
swarrow: '↙',
|
|
193
|
+
nwarrow: '↖',
|
|
194
|
+
hookrightarrow: '↪',
|
|
195
|
+
hookleftarrow: '↩',
|
|
196
|
+
rightharpoonup: '⇀',
|
|
197
|
+
langle: '⟨',
|
|
198
|
+
rangle: '⟩',
|
|
199
|
+
lfloor: '⌊',
|
|
200
|
+
rfloor: '⌋',
|
|
201
|
+
lceil: '⌈',
|
|
202
|
+
rceil: '⌉',
|
|
203
|
+
Vert: '‖',
|
|
204
|
+
'|': '‖',
|
|
205
|
+
'{': '{',
|
|
206
|
+
'}': '}',
|
|
207
|
+
'%': '%',
|
|
208
|
+
'&': '&',
|
|
209
|
+
'#': '#',
|
|
210
|
+
'_': '_',
|
|
211
|
+
'$': '$',
|
|
212
|
+
prime: '′',
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
const NARY_OPERATORS = Object.freeze({
|
|
216
|
+
sum: { chr: '∑', limLoc: 'undOvr' },
|
|
217
|
+
prod: { chr: '∏', limLoc: 'undOvr' },
|
|
218
|
+
coprod: { chr: '∐', limLoc: 'undOvr' },
|
|
219
|
+
bigcup: { chr: '⋃', limLoc: 'undOvr' },
|
|
220
|
+
bigcap: { chr: '⋂', limLoc: 'undOvr' },
|
|
221
|
+
bigoplus: { chr: '⨁', limLoc: 'undOvr' },
|
|
222
|
+
bigotimes: { chr: '⨂', limLoc: 'undOvr' },
|
|
223
|
+
bigvee: { chr: '⋁', limLoc: 'undOvr' },
|
|
224
|
+
bigwedge: { chr: '⋀', limLoc: 'undOvr' },
|
|
225
|
+
bigsqcup: { chr: '⨆', limLoc: 'undOvr' },
|
|
226
|
+
int: { chr: '∫', limLoc: 'subSup' },
|
|
227
|
+
iint: { chr: '∬', limLoc: 'subSup' },
|
|
228
|
+
iiint: { chr: '∭', limLoc: 'subSup' },
|
|
229
|
+
oint: { chr: '∮', limLoc: 'subSup' },
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
const LIMIT_FUNCTIONS = Object.freeze({
|
|
233
|
+
lim: 'lim',
|
|
234
|
+
limsup: 'lim sup',
|
|
235
|
+
liminf: 'lim inf',
|
|
236
|
+
max: 'max',
|
|
237
|
+
min: 'min',
|
|
238
|
+
sup: 'sup',
|
|
239
|
+
inf: 'inf',
|
|
240
|
+
argmax: 'arg max',
|
|
241
|
+
argmin: 'arg min',
|
|
242
|
+
})
|
|
243
|
+
|
|
244
|
+
const UPRIGHT_FUNCTIONS = Object.freeze({
|
|
245
|
+
sin: 'sin',
|
|
246
|
+
cos: 'cos',
|
|
247
|
+
tan: 'tan',
|
|
248
|
+
cot: 'cot',
|
|
249
|
+
sec: 'sec',
|
|
250
|
+
csc: 'csc',
|
|
251
|
+
arcsin: 'arcsin',
|
|
252
|
+
arccos: 'arccos',
|
|
253
|
+
arctan: 'arctan',
|
|
254
|
+
sinh: 'sinh',
|
|
255
|
+
cosh: 'cosh',
|
|
256
|
+
tanh: 'tanh',
|
|
257
|
+
coth: 'coth',
|
|
258
|
+
log: 'log',
|
|
259
|
+
ln: 'ln',
|
|
260
|
+
lg: 'lg',
|
|
261
|
+
exp: 'exp',
|
|
262
|
+
det: 'det',
|
|
263
|
+
dim: 'dim',
|
|
264
|
+
ker: 'ker',
|
|
265
|
+
deg: 'deg',
|
|
266
|
+
gcd: 'gcd',
|
|
267
|
+
Pr: 'Pr',
|
|
268
|
+
hom: 'hom',
|
|
269
|
+
arg: 'arg',
|
|
270
|
+
Var: 'Var',
|
|
271
|
+
Cov: 'Cov',
|
|
272
|
+
tr: 'tr',
|
|
273
|
+
diag: 'diag',
|
|
274
|
+
rank: 'rank',
|
|
275
|
+
sgn: 'sgn',
|
|
276
|
+
softmax: 'softmax',
|
|
277
|
+
sigmoid: 'sigmoid',
|
|
278
|
+
ReLU: 'ReLU',
|
|
279
|
+
GELU: 'GELU',
|
|
280
|
+
mod: 'mod',
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
const ACCENT_COMMANDS = Object.freeze({
|
|
284
|
+
hat: { omml: '\u0302', mathml: '^' },
|
|
285
|
+
widehat: { omml: '\u0302', mathml: '^' },
|
|
286
|
+
check: { omml: '\u030C', mathml: 'ˇ' },
|
|
287
|
+
tilde: { omml: '\u0303', mathml: '~' },
|
|
288
|
+
widetilde: { omml: '\u0303', mathml: '~' },
|
|
289
|
+
acute: { omml: '\u0301', mathml: '´' },
|
|
290
|
+
grave: { omml: '\u0300', mathml: '`' },
|
|
291
|
+
dot: { omml: '\u0307', mathml: '˙' },
|
|
292
|
+
ddot: { omml: '\u0308', mathml: '¨' },
|
|
293
|
+
breve: { omml: '\u0306', mathml: '˘' },
|
|
294
|
+
bar: { omml: '\u0304', mathml: '¯' },
|
|
295
|
+
vec: { omml: '\u20D7', mathml: '→' },
|
|
296
|
+
overrightarrow: { omml: '\u20D7', mathml: '→' },
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
const SPACING_MODIFIER_ACCENT = Object.freeze({
|
|
300
|
+
hat: { glyph: 'ˆ', baseline: 12000 },
|
|
301
|
+
widehat: { glyph: 'ˆ', baseline: 12000 },
|
|
302
|
+
check: { glyph: 'ˇ', baseline: 12000 },
|
|
303
|
+
tilde: { glyph: '˜', baseline: 12000 },
|
|
304
|
+
widetilde: { glyph: '˜', baseline: 12000 },
|
|
305
|
+
acute: { glyph: 'ˊ', baseline: 12000 },
|
|
306
|
+
grave: { glyph: 'ˋ', baseline: 12000 },
|
|
307
|
+
dot: { glyph: '˙', baseline: 14000 },
|
|
308
|
+
ddot: { glyph: '¨', baseline: 14000 },
|
|
309
|
+
breve: { glyph: '˘', baseline: 12000 },
|
|
310
|
+
bar: { glyph: '¯', baseline: 14000 },
|
|
311
|
+
vec: { glyph: '¯', baseline: 14000 },
|
|
312
|
+
})
|
|
313
|
+
|
|
314
|
+
const DELIM_COMMANDS = Object.freeze({
|
|
315
|
+
'(': '(',
|
|
316
|
+
')': ')',
|
|
317
|
+
'[': '[',
|
|
318
|
+
']': ']',
|
|
319
|
+
'\\{': '{',
|
|
320
|
+
'\\}': '}',
|
|
321
|
+
'{': '{',
|
|
322
|
+
'}': '}',
|
|
323
|
+
'|': '|',
|
|
324
|
+
'\\|': '‖',
|
|
325
|
+
'\\Vert': '‖',
|
|
326
|
+
'\\vert': '|',
|
|
327
|
+
'\\langle': '⟨',
|
|
328
|
+
'\\rangle': '⟩',
|
|
329
|
+
'\\lfloor': '⌊',
|
|
330
|
+
'\\rfloor': '⌋',
|
|
331
|
+
'\\lceil': '⌈',
|
|
332
|
+
'\\rceil': '⌉',
|
|
333
|
+
'/': '/',
|
|
334
|
+
'.': '',
|
|
335
|
+
})
|
|
336
|
+
|
|
337
|
+
// 严格限定在标准字体均具备字形的 BMP 类字母符号区 (U+2100..U+214F),彻底杜绝 SMP (U+1D400..U+1D7FF) 在无头 LibreOffice 渲染为 □ 豆腐块
|
|
338
|
+
const SAFE_BMP_CAL = Object.freeze({
|
|
339
|
+
B: 'ℬ', E: 'ℰ', F: 'ℱ', H: 'ℋ', I: 'ℐ', L: 'ℒ', M: 'ℳ', R: 'ℛ',
|
|
340
|
+
})
|
|
341
|
+
|
|
342
|
+
const SAFE_BMP_BB = Object.freeze({
|
|
343
|
+
C: 'ℂ', H: 'ℍ', N: 'ℕ', P: 'ℙ', Q: 'ℚ', R: 'ℝ', Z: 'ℤ',
|
|
344
|
+
})
|
|
345
|
+
|
|
346
|
+
const SPACE_COMMANDS = Object.freeze({
|
|
347
|
+
',': '\u2009',
|
|
348
|
+
':': '\u2005',
|
|
349
|
+
';': '\u2004',
|
|
350
|
+
'!': '',
|
|
351
|
+
' ': ' ',
|
|
352
|
+
quad: '\u2003',
|
|
353
|
+
qquad: '\u2003\u2003',
|
|
354
|
+
enspace: '\u2002',
|
|
355
|
+
})
|
|
356
|
+
|
|
357
|
+
const BINARY_OR_REL_OPS = new Set([
|
|
358
|
+
'+', '-', '−', '=', '<', '>', '±', '∓', '×', '÷', '·', '∗', '⊕', '⊖', '⊗', '⊙',
|
|
359
|
+
'≤', '≥', '≠', '≈', '∼', '≃', '≅', '≡', '∝', '≪', '≫', '≺', '≻', '≼', '≽', '≜', '≔',
|
|
360
|
+
'∈', '∉', '∋', '⊂', '⊃', '⊆', '⊇', '∪', '∩', '∖', '∧', '∨', '∥', '∤',
|
|
361
|
+
'→', '←', '↔', '⇒', '⇐', '⇔', '↦', '⟼', '⟶', '⟵', '⟹', '⟸', '⟺', '↪', '↩',
|
|
362
|
+
])
|
|
363
|
+
|
|
364
|
+
// ---------------------------------------------------------------------------
|
|
365
|
+
// 文本中的数学定界检测与货币误判防护(保护 "$120B ... $45B" 绝不误判为公式)
|
|
366
|
+
// ---------------------------------------------------------------------------
|
|
367
|
+
|
|
368
|
+
function isLikelyCurrencySpan(inner) {
|
|
369
|
+
const trimmed = inner.trim()
|
|
370
|
+
if (trimmed === '') return true
|
|
371
|
+
// 若以纯数字开头且内部包含未在 \text{...} 中的中文或空格分隔普通词组(如 "10M 增长至 "),判定为两处货币符号
|
|
372
|
+
const withoutTextCmd = trimmed.replace(/\\(?:text|textrm|textbf|mbox|operatorname)\s*\{[^}]*\}/g, '')
|
|
373
|
+
if (/^\d[\d,.]*\s*(?:[kKmMbBtT]|万|亿|元|美元|万元|亿元)?(?:\s|$|[\u4E00-\u9FFF])/.test(withoutTextCmd)) {
|
|
374
|
+
if (/[\u4E00-\u9FFF]/.test(withoutTextCmd) || /\s+[a-zA-Z]{2,}\s+/.test(withoutTextCmd)) {
|
|
375
|
+
return true
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return false
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* 将混合文本拆分为普通文本段与数学公式段。
|
|
383
|
+
* 支持 $$...$$, \[...\], \(...\), 以及带货币防护的行内 $...$。
|
|
384
|
+
*/
|
|
385
|
+
export function splitMathSegments(input) {
|
|
386
|
+
const str = String(input ?? '')
|
|
387
|
+
if (str === '' || (!str.includes('$') && !str.includes('\\[') && !str.includes('\\('))) {
|
|
388
|
+
return str === '' ? [] : [{ type: 'text', value: str }]
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const segments = []
|
|
392
|
+
let cursor = 0
|
|
393
|
+
let textStart = 0
|
|
394
|
+
const len = str.length
|
|
395
|
+
|
|
396
|
+
const pushText = (endIdx) => {
|
|
397
|
+
if (endIdx > textStart) {
|
|
398
|
+
segments.push({ type: 'text', value: str.slice(textStart, endIdx).replace(/\\\$/g, '$') })
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
while (cursor < len) {
|
|
403
|
+
// 跳过转义 \$
|
|
404
|
+
if (str[cursor] === '\\' && str[cursor + 1] === '$') {
|
|
405
|
+
cursor += 2
|
|
406
|
+
continue
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// 1. $$...$$ 块级公式
|
|
410
|
+
if (str[cursor] === '$' && str[cursor + 1] === '$') {
|
|
411
|
+
const close = str.indexOf('$$', cursor + 2)
|
|
412
|
+
if (close > cursor + 2) {
|
|
413
|
+
const inner = str.slice(cursor + 2, close).trim()
|
|
414
|
+
if (inner !== '') {
|
|
415
|
+
pushText(cursor)
|
|
416
|
+
segments.push({ type: 'math', latex: inner, display: true })
|
|
417
|
+
cursor = close + 2
|
|
418
|
+
textStart = cursor
|
|
419
|
+
continue
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
cursor += 2
|
|
423
|
+
continue
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// 2. \[...\] 块级公式
|
|
427
|
+
if (str[cursor] === '\\' && str[cursor + 1] === '[') {
|
|
428
|
+
const close = str.indexOf('\\]', cursor + 2)
|
|
429
|
+
if (close > cursor + 2) {
|
|
430
|
+
const inner = str.slice(cursor + 2, close).trim()
|
|
431
|
+
if (inner !== '') {
|
|
432
|
+
pushText(cursor)
|
|
433
|
+
segments.push({ type: 'math', latex: inner, display: true })
|
|
434
|
+
cursor = close + 2
|
|
435
|
+
textStart = cursor
|
|
436
|
+
continue
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// 3. \(...\) 行内公式
|
|
442
|
+
if (str[cursor] === '\\' && str[cursor + 1] === '(') {
|
|
443
|
+
const close = str.indexOf('\\)', cursor + 2)
|
|
444
|
+
if (close > cursor + 2) {
|
|
445
|
+
const inner = str.slice(cursor + 2, close).trim()
|
|
446
|
+
if (inner !== '') {
|
|
447
|
+
pushText(cursor)
|
|
448
|
+
segments.push({ type: 'math', latex: inner, display: false })
|
|
449
|
+
cursor = close + 2
|
|
450
|
+
textStart = cursor
|
|
451
|
+
continue
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// 4. $...$ 行内公式(严格遵循非空白紧贴与货币防护规则)
|
|
457
|
+
if (str[cursor] === '$') {
|
|
458
|
+
const nextCh = str[cursor + 1] ?? ''
|
|
459
|
+
if (nextCh !== '' && nextCh !== '$' && !/\s/.test(nextCh)) {
|
|
460
|
+
let close = cursor + 1
|
|
461
|
+
let found = -1
|
|
462
|
+
while (close < len) {
|
|
463
|
+
if (str[close] === '\\') {
|
|
464
|
+
close += 2
|
|
465
|
+
continue
|
|
466
|
+
}
|
|
467
|
+
if (str[close] === '\n') break
|
|
468
|
+
if (str[close] === '$') {
|
|
469
|
+
const prevCh = str[close - 1] ?? ''
|
|
470
|
+
const afterCh = str[close + 1] ?? ''
|
|
471
|
+
if (!/\s/.test(prevCh) && !/\d/.test(afterCh) && afterCh !== '$') {
|
|
472
|
+
found = close
|
|
473
|
+
break
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
close += 1
|
|
477
|
+
}
|
|
478
|
+
if (found > cursor + 1) {
|
|
479
|
+
const inner = str.slice(cursor + 1, found)
|
|
480
|
+
if (!isLikelyCurrencySpan(inner)) {
|
|
481
|
+
pushText(cursor)
|
|
482
|
+
segments.push({ type: 'math', latex: inner.trim(), display: false })
|
|
483
|
+
cursor = found + 1
|
|
484
|
+
textStart = cursor
|
|
485
|
+
continue
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
cursor += 1
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
pushText(len)
|
|
495
|
+
return segments
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
export function containsLatexMath(input) {
|
|
499
|
+
return splitMathSegments(input).some((seg) => seg.type === 'math')
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
export function looksLikeRawLatex(input) {
|
|
503
|
+
const s = String(input ?? '').trim()
|
|
504
|
+
if (!s) return false
|
|
505
|
+
if (containsLatexMath(s)) return true
|
|
506
|
+
return /\\(?:frac|dfrac|tfrac|binom|sqrt|sum|prod|int|oint|bigcup|bigcap|left|right|begin|alpha|beta|gamma|delta|epsilon|varepsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|pi|rho|sigma|tau|upsilon|phi|varphi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Phi|Psi|Omega|nabla|partial|infty|leq|geq|neq|approx|equiv|pm|times|cdot|in|notin|subset|subseteq|forall|exists|rightarrow|Rightarrow|leftrightarrow|mapsto|ldots|cdots|hat|bar|vec|tilde|dot|ddot|overline|underline|sin|cos|tan|log|ln|exp|max|min|lim|arg|text|mathbf|mathrm|mathcal|mathbb|boldsymbol)\b/.test(s)
|
|
507
|
+
|| /[A-Za-z0-9)\]}]\s*[_^]\s*(?:\{[^}]+\}|[A-Za-z0-9\\])/.test(s)
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
export function unwrapOuterMathDelimiters(input) {
|
|
511
|
+
const s = String(input ?? '').trim()
|
|
512
|
+
if (s.startsWith('$$') && s.endsWith('$$') && s.length > 4) return s.slice(2, -2).trim()
|
|
513
|
+
if (s.startsWith('\\[') && s.endsWith('\\]') && s.length > 4) return s.slice(2, -2).trim()
|
|
514
|
+
if (s.startsWith('\\(') && s.endsWith('\\)') && s.length > 4) return s.slice(2, -2).trim()
|
|
515
|
+
if (s.startsWith('$') && s.endsWith('$') && s.length > 2 && !s.slice(1, -1).includes('$')) {
|
|
516
|
+
return s.slice(1, -1).trim()
|
|
517
|
+
}
|
|
518
|
+
return s
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* 在 Markdown / HTML 清洗前遮罩公式片段,避免 `$0 < \alpha_i < 1$` 中的 `<...>` 或 `_` 被误删。
|
|
523
|
+
*/
|
|
524
|
+
export function maskMathSpans(input) {
|
|
525
|
+
const raw = String(input ?? '')
|
|
526
|
+
if (!raw.includes('$') && !raw.includes('\\[') && !raw.includes('\\(') && !raw.includes('`')) {
|
|
527
|
+
return { masked: raw, stash: [] }
|
|
528
|
+
}
|
|
529
|
+
const stash = []
|
|
530
|
+
// 先遮罩反引号行内代码 `...`(如 `<m:oMath>`),防止其中的尖括号在清洗时被误剥离;输出时仍经 escapeHtml/escapeXml 严格转义
|
|
531
|
+
const codeMasked = raw.replace(/`[^`\n]+`/g, (m) => {
|
|
532
|
+
const idx = stash.length
|
|
533
|
+
stash.push(m)
|
|
534
|
+
return '\uE010MATH' + idx + '\uE011'
|
|
535
|
+
})
|
|
536
|
+
const segs = splitMathSegments(codeMasked)
|
|
537
|
+
if (!segs.some((s) => s.type === 'math')) {
|
|
538
|
+
return { masked: codeMasked, stash }
|
|
539
|
+
}
|
|
540
|
+
const masked = segs.map((seg) => {
|
|
541
|
+
if (seg.type !== 'math') return seg.value
|
|
542
|
+
const idx = stash.length
|
|
543
|
+
stash.push(seg.display ? ('$$' + seg.latex + '$$') : ('$' + seg.latex + '$'))
|
|
544
|
+
return '\uE010MATH' + idx + '\uE011'
|
|
545
|
+
}).join('')
|
|
546
|
+
return { masked, stash }
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
export function unmaskMathSpans(masked, stash) {
|
|
550
|
+
if (!stash || stash.length === 0) return masked
|
|
551
|
+
return String(masked).replace(/\uE010MATH(\d+)\uE011/g, (_, idx) => stash[Number(idx)] ?? '')
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// ---------------------------------------------------------------------------
|
|
555
|
+
// LaTeX 词法分词器(Tokenizer)
|
|
556
|
+
// ---------------------------------------------------------------------------
|
|
557
|
+
|
|
558
|
+
function tokenizeLatex(latex) {
|
|
559
|
+
// 仅剥离未转义的 % 行尾注释,保留转义百分号 \%(兼容 \\% 行分隔符后紧跟注释)
|
|
560
|
+
const src = String(latex ?? '').replace(/((?:^|[^\\])(?:\\\\)*)%[^\n]*/g, '$1')
|
|
561
|
+
const tokens = []
|
|
562
|
+
let i = 0
|
|
563
|
+
const n = src.length
|
|
564
|
+
|
|
565
|
+
while (i < n) {
|
|
566
|
+
const ch = src[i]
|
|
567
|
+
if (/\s/.test(ch)) {
|
|
568
|
+
i += 1
|
|
569
|
+
continue
|
|
570
|
+
}
|
|
571
|
+
if (ch === '\\') {
|
|
572
|
+
if (i + 1 >= n) break
|
|
573
|
+
const next = src[i + 1]
|
|
574
|
+
if (next === '\\') {
|
|
575
|
+
tokens.push({ type: 'rowSep', value: '\\\\' })
|
|
576
|
+
i += 2
|
|
577
|
+
// 跳过可选行距参数 \\[4pt]
|
|
578
|
+
if (src[i] === '[') {
|
|
579
|
+
const endBr = src.indexOf(']', i + 1)
|
|
580
|
+
if (endBr > i) i = endBr + 1
|
|
581
|
+
}
|
|
582
|
+
continue
|
|
583
|
+
}
|
|
584
|
+
if (/[a-zA-Z]/.test(next)) {
|
|
585
|
+
let j = i + 1
|
|
586
|
+
while (j < n && /[a-zA-Z]/.test(src[j])) j += 1
|
|
587
|
+
const cmd = src.slice(i + 1, j)
|
|
588
|
+
// 对 \text / \textrm / \textbf / \mathrm / \mathbf / \mathcal / \mathbb / \operatorname 直接捕获原始花括号文本
|
|
589
|
+
if (['text', 'textrm', 'textup', 'textbf', 'mbox', 'operatorname'].includes(cmd)) {
|
|
590
|
+
while (j < n && /\s/.test(src[j])) j += 1
|
|
591
|
+
if (src[j] === '{') {
|
|
592
|
+
let depth = 1
|
|
593
|
+
let k = j + 1
|
|
594
|
+
while (k < n && depth > 0) {
|
|
595
|
+
if (src[k] === '\\' && k + 1 < n) { k += 2; continue }
|
|
596
|
+
if (src[k] === '{') depth += 1
|
|
597
|
+
else if (src[k] === '}') depth -= 1
|
|
598
|
+
k += 1
|
|
599
|
+
}
|
|
600
|
+
const content = src.slice(j + 1, Math.max(j + 1, k - 1))
|
|
601
|
+
.replace(/\\([#$%&_{}])/g, '$1')
|
|
602
|
+
.replace(/~/g, ' ')
|
|
603
|
+
tokens.push({ type: 'textGroup', cmd, value: content })
|
|
604
|
+
i = k
|
|
605
|
+
continue
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
tokens.push({ type: 'cmd', value: cmd })
|
|
609
|
+
i = j
|
|
610
|
+
continue
|
|
611
|
+
}
|
|
612
|
+
// 单字符转义命令(\, \; \! \{ \} \| \% \_ 等)
|
|
613
|
+
tokens.push({ type: 'cmd', value: next })
|
|
614
|
+
i += 2
|
|
615
|
+
continue
|
|
616
|
+
}
|
|
617
|
+
if (ch === '{') { tokens.push({ type: 'lbrace', value: '{' }); i += 1; continue }
|
|
618
|
+
if (ch === '}') { tokens.push({ type: 'rbrace', value: '}' }); i += 1; continue }
|
|
619
|
+
if (ch === '[') { tokens.push({ type: 'lbrack', value: '[' }); i += 1; continue }
|
|
620
|
+
if (ch === ']') { tokens.push({ type: 'rbrack', value: ']' }); i += 1; continue }
|
|
621
|
+
if (ch === '^') { tokens.push({ type: 'sup', value: '^' }); i += 1; continue }
|
|
622
|
+
if (ch === '_') { tokens.push({ type: 'sub', value: '_' }); i += 1; continue }
|
|
623
|
+
if (ch === '&') { tokens.push({ type: 'colSep', value: '&' }); i += 1; continue }
|
|
624
|
+
if (ch === '~') { tokens.push({ type: 'space', value: '\u00A0' }); i += 1; continue }
|
|
625
|
+
if (ch === '\'') {
|
|
626
|
+
let j = i
|
|
627
|
+
while (j < n && src[j] === '\'') j += 1
|
|
628
|
+
tokens.push({ type: 'prime', count: j - i })
|
|
629
|
+
i = j
|
|
630
|
+
continue
|
|
631
|
+
}
|
|
632
|
+
if (/[0-9]/.test(ch)) {
|
|
633
|
+
let j = i
|
|
634
|
+
while (j < n && (/[0-9]/.test(src[j]) || (src[j] === '.' && /[0-9]/.test(src[j + 1] ?? '')))) j += 1
|
|
635
|
+
tokens.push({ type: 'num', value: src.slice(i, j) })
|
|
636
|
+
i = j
|
|
637
|
+
continue
|
|
638
|
+
}
|
|
639
|
+
if (/[a-zA-Z]/.test(ch)) {
|
|
640
|
+
tokens.push({ type: 'ident', value: ch })
|
|
641
|
+
i += 1
|
|
642
|
+
continue
|
|
643
|
+
}
|
|
644
|
+
tokens.push({ type: 'char', value: ch === '-' ? '−' : ch })
|
|
645
|
+
i += 1
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
return tokens
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ---------------------------------------------------------------------------
|
|
652
|
+
// 递归下降 AST 语法分析器(Parser)
|
|
653
|
+
// ---------------------------------------------------------------------------
|
|
654
|
+
|
|
655
|
+
export function parseLatexMath(latex) {
|
|
656
|
+
const clean = unwrapOuterMathDelimiters(latex)
|
|
657
|
+
const tokens = tokenizeLatex(clean)
|
|
658
|
+
let pos = 0
|
|
659
|
+
|
|
660
|
+
const peek = (offset = 0) => tokens[pos + offset] ?? null
|
|
661
|
+
const next = () => tokens[pos++] ?? null
|
|
662
|
+
|
|
663
|
+
function makeRow(children) {
|
|
664
|
+
if (!children || children.length === 0) return { type: 'row', children: [] }
|
|
665
|
+
if (children.length === 1) return children[0]
|
|
666
|
+
return { type: 'row', children }
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
function readEnvName() {
|
|
670
|
+
if (peek()?.type === 'lbrace') {
|
|
671
|
+
next()
|
|
672
|
+
let name = ''
|
|
673
|
+
while (peek() && peek().type !== 'rbrace') {
|
|
674
|
+
name += next().value ?? ''
|
|
675
|
+
}
|
|
676
|
+
if (peek()?.type === 'rbrace') next()
|
|
677
|
+
return name.trim()
|
|
678
|
+
}
|
|
679
|
+
return ''
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function readDelimiterChar() {
|
|
683
|
+
const tok = peek()
|
|
684
|
+
if (!tok) return ''
|
|
685
|
+
if (tok.type === 'cmd') {
|
|
686
|
+
next()
|
|
687
|
+
return DELIM_COMMANDS['\\' + tok.value] ?? DELIM_COMMANDS[tok.value] ?? SYMBOL_MAP[tok.value] ?? tok.value
|
|
688
|
+
}
|
|
689
|
+
if (tok.type === 'char' || tok.type === 'lbrack' || tok.type === 'rbrack') {
|
|
690
|
+
next()
|
|
691
|
+
const v = tok.value === '−' ? '-' : tok.value
|
|
692
|
+
return DELIM_COMMANDS[v] ?? v
|
|
693
|
+
}
|
|
694
|
+
return ''
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
function parseArg() {
|
|
698
|
+
const tok = peek()
|
|
699
|
+
if (!tok) return { type: 'row', children: [] }
|
|
700
|
+
if (tok.type === 'lbrace') {
|
|
701
|
+
next()
|
|
702
|
+
const expr = parseExpression((t) => t.type === 'rbrace')
|
|
703
|
+
if (peek()?.type === 'rbrace') next()
|
|
704
|
+
return expr
|
|
705
|
+
}
|
|
706
|
+
return parseBaseAtom() ?? { type: 'row', children: [] }
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function parseOptionalBracketArg() {
|
|
710
|
+
if (peek()?.type !== 'lbrack') return null
|
|
711
|
+
next()
|
|
712
|
+
const expr = parseExpression((t) => t.type === 'rbrack')
|
|
713
|
+
if (peek()?.type === 'rbrack') next()
|
|
714
|
+
return expr
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function parseMatrix(envName) {
|
|
718
|
+
const rows = []
|
|
719
|
+
let currentRow = []
|
|
720
|
+
let currentCell = []
|
|
721
|
+
|
|
722
|
+
const flushCell = () => {
|
|
723
|
+
currentRow.push(makeRow(currentCell))
|
|
724
|
+
currentCell = []
|
|
725
|
+
}
|
|
726
|
+
const flushRow = () => {
|
|
727
|
+
flushCell()
|
|
728
|
+
if (currentRow.length > 0) rows.push(currentRow)
|
|
729
|
+
currentRow = []
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
while (pos < tokens.length) {
|
|
733
|
+
const tok = peek()
|
|
734
|
+
if (tok.type === 'cmd' && tok.value === 'end') {
|
|
735
|
+
next()
|
|
736
|
+
readEnvName()
|
|
737
|
+
break
|
|
738
|
+
}
|
|
739
|
+
if (tok.type === 'colSep') {
|
|
740
|
+
next()
|
|
741
|
+
flushCell()
|
|
742
|
+
continue
|
|
743
|
+
}
|
|
744
|
+
if (tok.type === 'rowSep') {
|
|
745
|
+
next()
|
|
746
|
+
flushRow()
|
|
747
|
+
continue
|
|
748
|
+
}
|
|
749
|
+
const item = parseScriptedItem((t) =>
|
|
750
|
+
t.type === 'colSep' || t.type === 'rowSep' || (t.type === 'cmd' && t.value === 'end'),
|
|
751
|
+
)
|
|
752
|
+
if (item) currentCell.push(item)
|
|
753
|
+
else next()
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
if (currentCell.length > 0 || currentRow.length > 0) {
|
|
757
|
+
flushRow()
|
|
758
|
+
}
|
|
759
|
+
if (rows.length === 0) rows.push([{ type: 'row', children: [] }])
|
|
760
|
+
|
|
761
|
+
const matrixNode = { type: 'matrix', env: envName, rows }
|
|
762
|
+
if (envName === 'pmatrix') return { type: 'delim', open: '(', close: ')', body: matrixNode }
|
|
763
|
+
if (envName === 'bmatrix') return { type: 'delim', open: '[', close: ']', body: matrixNode }
|
|
764
|
+
if (envName === 'Bmatrix') return { type: 'delim', open: '{', close: '}', body: matrixNode }
|
|
765
|
+
if (envName === 'vmatrix') return { type: 'delim', open: '|', close: '|', body: matrixNode }
|
|
766
|
+
if (envName === 'Vmatrix') return { type: 'delim', open: '‖', close: '‖', body: matrixNode }
|
|
767
|
+
if (envName === 'cases') return { type: 'delim', open: '{', close: '', body: matrixNode }
|
|
768
|
+
return matrixNode
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function applyStyleTransform(ast, styleKind) {
|
|
772
|
+
if (!ast) return ast
|
|
773
|
+
if (ast.type === 'ident' || ast.type === 'num') {
|
|
774
|
+
if (styleKind === 'cal' || styleKind === 'bb') {
|
|
775
|
+
const bmpMap = styleKind === 'cal' ? SAFE_BMP_CAL : SAFE_BMP_BB
|
|
776
|
+
const isBb = styleKind === 'bb'
|
|
777
|
+
const chars = [...ast.value]
|
|
778
|
+
if (chars.length > 1) {
|
|
779
|
+
return makeRow(chars.map((ch) => (
|
|
780
|
+
ch in bmpMap
|
|
781
|
+
? { type: 'sym', value: bmpMap[ch], variant: styleKind, bmp: true, upright: isBb }
|
|
782
|
+
: { type: 'sym', value: ch, variant: styleKind, bmp: false, upright: isBb }
|
|
783
|
+
)))
|
|
784
|
+
}
|
|
785
|
+
const ch = chars[0] ?? ast.value
|
|
786
|
+
return ch in bmpMap
|
|
787
|
+
? { type: 'sym', value: bmpMap[ch], variant: styleKind, bmp: true, upright: isBb }
|
|
788
|
+
: { type: 'sym', value: ch, variant: styleKind, bmp: false, upright: isBb }
|
|
789
|
+
}
|
|
790
|
+
return { ...ast, style: styleKind }
|
|
791
|
+
}
|
|
792
|
+
if (ast.type === 'sym') {
|
|
793
|
+
return { ...ast, style: styleKind }
|
|
794
|
+
}
|
|
795
|
+
if (ast.type === 'row') {
|
|
796
|
+
return { ...ast, children: ast.children.map((ch) => applyStyleTransform(ch, styleKind)) }
|
|
797
|
+
}
|
|
798
|
+
return { type: 'style', style: styleKind, body: ast }
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function parseBaseAtom() {
|
|
802
|
+
const tok = peek()
|
|
803
|
+
if (!tok) return null
|
|
804
|
+
|
|
805
|
+
if (tok.type === 'lbrace') {
|
|
806
|
+
next()
|
|
807
|
+
const inner = parseExpression((t) => t.type === 'rbrace')
|
|
808
|
+
if (peek()?.type === 'rbrace') next()
|
|
809
|
+
return inner
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
if (tok.type === 'textGroup') {
|
|
813
|
+
next()
|
|
814
|
+
return { type: 'text', value: tok.value, bold: tok.cmd === 'textbf' }
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
if (tok.type === 'num') {
|
|
818
|
+
next()
|
|
819
|
+
return { type: 'num', value: tok.value }
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
if (tok.type === 'ident') {
|
|
823
|
+
next()
|
|
824
|
+
return { type: 'ident', value: tok.value }
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
if (tok.type === 'space') {
|
|
828
|
+
next()
|
|
829
|
+
return { type: 'space', value: tok.value }
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
if (tok.type === 'lbrack' || tok.type === 'rbrack') {
|
|
833
|
+
next()
|
|
834
|
+
return { type: 'op', value: tok.value }
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
if (tok.type === 'char') {
|
|
838
|
+
next()
|
|
839
|
+
return { type: 'op', value: tok.value }
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
if (tok.type === 'cmd') {
|
|
843
|
+
const cmd = tok.value
|
|
844
|
+
next()
|
|
845
|
+
|
|
846
|
+
if (cmd === 'displaystyle' || cmd === 'textstyle' || cmd === 'scriptstyle' || cmd === 'limits' || cmd === 'nolimits' || cmd === 'big' || cmd === 'Big' || cmd === 'bigg' || cmd === 'Bigg' || cmd === 'bigl' || cmd === 'bigr' || cmd === 'Bigl' || cmd === 'Bigr') {
|
|
847
|
+
return parseBaseAtom()
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
if (cmd in SPACE_COMMANDS) {
|
|
851
|
+
return SPACE_COMMANDS[cmd] ? { type: 'space', value: SPACE_COMMANDS[cmd] } : { type: 'row', children: [] }
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
if (cmd === 'frac' || cmd === 'dfrac' || cmd === 'tfrac' || cmd === 'cfrac') {
|
|
855
|
+
const num = parseArg()
|
|
856
|
+
const den = parseArg()
|
|
857
|
+
return { type: 'frac', bar: true, num, den }
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
if (cmd === 'binom' || cmd === 'tbinom' || cmd === 'dbinom') {
|
|
861
|
+
const num = parseArg()
|
|
862
|
+
const den = parseArg()
|
|
863
|
+
return { type: 'delim', open: '(', close: ')', body: { type: 'frac', bar: false, num, den } }
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
if (cmd === 'sqrt') {
|
|
867
|
+
const deg = parseOptionalBracketArg()
|
|
868
|
+
const body = parseArg()
|
|
869
|
+
return deg ? { type: 'root', deg, body } : { type: 'sqrt', body }
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
if (cmd === 'left') {
|
|
873
|
+
const open = readDelimiterChar()
|
|
874
|
+
const body = parseExpression((t) => t.type === 'cmd' && t.value === 'right')
|
|
875
|
+
let close = ''
|
|
876
|
+
if (peek()?.type === 'cmd' && peek().value === 'right') {
|
|
877
|
+
next()
|
|
878
|
+
close = readDelimiterChar()
|
|
879
|
+
}
|
|
880
|
+
return { type: 'delim', open, close, body }
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
if (cmd === 'begin') {
|
|
884
|
+
const envName = readEnvName()
|
|
885
|
+
return parseMatrix(envName)
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
if (cmd in ACCENT_COMMANDS) {
|
|
889
|
+
const body = parseArg()
|
|
890
|
+
return { type: 'acc', cmd, chr: ACCENT_COMMANDS[cmd].omml, mathmlChr: ACCENT_COMMANDS[cmd].mathml, body }
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
if (cmd === 'overline') {
|
|
894
|
+
return { type: 'bar', pos: 'top', body: parseArg() }
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
if (cmd === 'underline') {
|
|
898
|
+
return { type: 'bar', pos: 'bot', body: parseArg() }
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
if (cmd === 'overbrace') {
|
|
902
|
+
const body = parseArg()
|
|
903
|
+
if (peek()?.type === 'sup') {
|
|
904
|
+
next()
|
|
905
|
+
const label = parseArg()
|
|
906
|
+
return { type: 'limUpp', base: { type: 'bar', pos: 'top', body }, lim: label }
|
|
907
|
+
}
|
|
908
|
+
return { type: 'bar', pos: 'top', body }
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
if (cmd === 'underbrace') {
|
|
912
|
+
const body = parseArg()
|
|
913
|
+
if (peek()?.type === 'sub') {
|
|
914
|
+
next()
|
|
915
|
+
const label = parseArg()
|
|
916
|
+
return { type: 'limLow', base: { type: 'bar', pos: 'bot', body }, lim: label }
|
|
917
|
+
}
|
|
918
|
+
return { type: 'bar', pos: 'bot', body }
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
if (cmd === 'overset' || cmd === 'stackrel') {
|
|
922
|
+
const topExpr = parseArg()
|
|
923
|
+
const baseExpr = parseArg()
|
|
924
|
+
return { type: 'limUpp', base: baseExpr, lim: topExpr }
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
if (cmd === 'underset') {
|
|
928
|
+
const botExpr = parseArg()
|
|
929
|
+
const baseExpr = parseArg()
|
|
930
|
+
return { type: 'limLow', base: baseExpr, lim: botExpr }
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
if (cmd === 'mathbf' || cmd === 'bm' || cmd === 'boldsymbol') {
|
|
934
|
+
return applyStyleTransform(parseArg(), 'bold')
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
if (cmd === 'mathrm') {
|
|
938
|
+
return applyStyleTransform(parseArg(), 'roman')
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
if (cmd === 'mathcal') {
|
|
942
|
+
return applyStyleTransform(parseArg(), 'cal')
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
if (cmd === 'mathbb') {
|
|
946
|
+
return applyStyleTransform(parseArg(), 'bb')
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
if (cmd === 'mathit') {
|
|
950
|
+
return applyStyleTransform(parseArg(), 'italic')
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
if (cmd in NARY_OPERATORS) {
|
|
954
|
+
const spec = NARY_OPERATORS[cmd]
|
|
955
|
+
let sub = null
|
|
956
|
+
let sup = null
|
|
957
|
+
let limLoc = spec.limLoc
|
|
958
|
+
// 读取任意顺序的 _sub / ^sup / \limits
|
|
959
|
+
while (peek()) {
|
|
960
|
+
if (peek().type === 'cmd' && peek().value === 'limits') {
|
|
961
|
+
next()
|
|
962
|
+
limLoc = 'undOvr'
|
|
963
|
+
continue
|
|
964
|
+
}
|
|
965
|
+
if (peek().type === 'cmd' && peek().value === 'nolimits') {
|
|
966
|
+
next()
|
|
967
|
+
limLoc = 'subSup'
|
|
968
|
+
continue
|
|
969
|
+
}
|
|
970
|
+
if (peek().type === 'sub' && sub === null) {
|
|
971
|
+
next()
|
|
972
|
+
sub = parseArg()
|
|
973
|
+
continue
|
|
974
|
+
}
|
|
975
|
+
if (peek().type === 'sup' && sup === null) {
|
|
976
|
+
next()
|
|
977
|
+
sup = parseArg()
|
|
978
|
+
continue
|
|
979
|
+
}
|
|
980
|
+
break
|
|
981
|
+
}
|
|
982
|
+
// 大型算子收集紧随其后的被积/被求和项(遇到顶层加减或等号关系符停止)
|
|
983
|
+
const bodyParts = []
|
|
984
|
+
while (pos < tokens.length) {
|
|
985
|
+
const t = peek()
|
|
986
|
+
if (!t || t.type === 'rbrace' || t.type === 'rbrack' || t.type === 'colSep' || t.type === 'rowSep') break
|
|
987
|
+
if (t.type === 'cmd' && (t.value === 'right' || t.value === 'end')) break
|
|
988
|
+
if (bodyParts.length > 0 && t.type === 'char' && ['+', '−', '-', '=', '<', '>'].includes(t.value)) break
|
|
989
|
+
if (bodyParts.length > 0 && t.type === 'cmd' && ['leq', 'le', 'geq', 'ge', 'neq', 'ne', 'approx', 'equiv', 'rightarrow', 'to', 'Rightarrow', 'iff'].includes(t.value)) break
|
|
990
|
+
const nextPart = parseScriptedItem()
|
|
991
|
+
if (!nextPart) break
|
|
992
|
+
bodyParts.push(nextPart)
|
|
993
|
+
}
|
|
994
|
+
return {
|
|
995
|
+
type: 'nary',
|
|
996
|
+
cmd,
|
|
997
|
+
chr: spec.chr,
|
|
998
|
+
limLoc,
|
|
999
|
+
sub,
|
|
1000
|
+
sup,
|
|
1001
|
+
body: makeRow(bodyParts),
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// \arg\max / \arg\min 组合识别为极限型算子
|
|
1006
|
+
if (cmd === 'arg' && peek()?.type === 'cmd' && (peek().value === 'max' || peek().value === 'min')) {
|
|
1007
|
+
const subCmd = next().value
|
|
1008
|
+
return { type: 'func', name: 'arg ' + subCmd, limitOp: true }
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
if (cmd in LIMIT_FUNCTIONS) {
|
|
1012
|
+
return { type: 'func', name: LIMIT_FUNCTIONS[cmd], limitOp: true }
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
if (cmd in UPRIGHT_FUNCTIONS) {
|
|
1016
|
+
return { type: 'func', name: UPRIGHT_FUNCTIONS[cmd], limitOp: false }
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
if (cmd in GREEK_MAP) {
|
|
1020
|
+
const isUpper = cmd[0] === cmd[0].toUpperCase()
|
|
1021
|
+
return { type: 'sym', value: GREEK_MAP[cmd], greek: true, upright: isUpper }
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
if (cmd in SYMBOL_MAP) {
|
|
1025
|
+
const sym = SYMBOL_MAP[cmd]
|
|
1026
|
+
return BINARY_OR_REL_OPS.has(sym)
|
|
1027
|
+
? { type: 'op', value: sym }
|
|
1028
|
+
: { type: 'sym', value: sym, upright: sym === '|' || sym === '‖' }
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// 未知命令兜底:绝不泄露裸反斜杠,转为正体函数名
|
|
1032
|
+
return { type: 'func', name: cmd, limitOp: false }
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
next()
|
|
1036
|
+
return null
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
function parseScriptedItem(stopPredicate) {
|
|
1040
|
+
if (pos >= tokens.length) return null
|
|
1041
|
+
if (stopPredicate && stopPredicate(peek())) return null
|
|
1042
|
+
|
|
1043
|
+
let base = parseBaseAtom()
|
|
1044
|
+
if (!base) return null
|
|
1045
|
+
|
|
1046
|
+
// 支持紧随其后的撇号 f' / f''
|
|
1047
|
+
let primeText = ''
|
|
1048
|
+
while (peek()?.type === 'prime') {
|
|
1049
|
+
const p = next()
|
|
1050
|
+
primeText += p.count === 1 ? '′' : p.count === 2 ? '″' : '′'.repeat(p.count)
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
let sub = null
|
|
1054
|
+
let sup = primeText ? { type: 'sym', value: primeText } : null
|
|
1055
|
+
|
|
1056
|
+
while (peek()) {
|
|
1057
|
+
if (peek().type === 'sub' && sub === null) {
|
|
1058
|
+
next()
|
|
1059
|
+
sub = parseArg()
|
|
1060
|
+
continue
|
|
1061
|
+
}
|
|
1062
|
+
if (peek().type === 'sup') {
|
|
1063
|
+
next()
|
|
1064
|
+
const supArg = parseArg()
|
|
1065
|
+
sup = sup ? makeRow([sup, supArg]) : supArg
|
|
1066
|
+
continue
|
|
1067
|
+
}
|
|
1068
|
+
break
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
if (base.type === 'func' && base.limitOp && sub && !sup) {
|
|
1072
|
+
return { type: 'limLow', base, lim: sub }
|
|
1073
|
+
}
|
|
1074
|
+
if (sub && sup) return { type: 'subsup', base, sub, sup }
|
|
1075
|
+
if (sub) return { type: 'sub', base, sub }
|
|
1076
|
+
if (sup) return { type: 'sup', base, sup }
|
|
1077
|
+
return base
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
function parseExpression(stopPredicate) {
|
|
1081
|
+
const items = []
|
|
1082
|
+
while (pos < tokens.length) {
|
|
1083
|
+
const tok = peek()
|
|
1084
|
+
if (!tok) break
|
|
1085
|
+
if (stopPredicate && stopPredicate(tok)) break
|
|
1086
|
+
if (tok.type === 'rbrace') break
|
|
1087
|
+
const item = parseScriptedItem(stopPredicate)
|
|
1088
|
+
if (item) {
|
|
1089
|
+
if (!(item.type === 'row' && item.children.length === 0)) {
|
|
1090
|
+
items.push(item)
|
|
1091
|
+
}
|
|
1092
|
+
} else {
|
|
1093
|
+
break
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
return makeRow(items)
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
return parseExpression()
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// ---------------------------------------------------------------------------
|
|
1103
|
+
// W3C MathML 编译器(100% 浏览器原生渲染、零脚本注入)
|
|
1104
|
+
// ---------------------------------------------------------------------------
|
|
1105
|
+
|
|
1106
|
+
export function astToMathMl(ast, options = {}) {
|
|
1107
|
+
function emit(node) {
|
|
1108
|
+
if (!node) return '<mrow></mrow>'
|
|
1109
|
+
switch (node.type) {
|
|
1110
|
+
case 'row':
|
|
1111
|
+
if (node.children.length === 0) return '<mrow></mrow>'
|
|
1112
|
+
return '<mrow>' + node.children.map(emit).join('') + '</mrow>'
|
|
1113
|
+
case 'num':
|
|
1114
|
+
return '<mn' + (node.style === 'bold' ? ' mathvariant="bold"' : '') + '>' + escapeHtmlText(node.value) + '</mn>'
|
|
1115
|
+
case 'ident': {
|
|
1116
|
+
const attr = node.style === 'bold'
|
|
1117
|
+
? ' mathvariant="bold"'
|
|
1118
|
+
: node.style === 'roman'
|
|
1119
|
+
? ' mathvariant="normal"'
|
|
1120
|
+
: ''
|
|
1121
|
+
return '<mi' + attr + '>' + escapeHtmlText(node.value) + '</mi>'
|
|
1122
|
+
}
|
|
1123
|
+
case 'sym': {
|
|
1124
|
+
let attr = ''
|
|
1125
|
+
if (node.variant === 'bb' && !node.bmp) attr = ' mathvariant="double-struck"'
|
|
1126
|
+
else if (node.variant === 'cal' && !node.bmp) attr = ' mathvariant="script"'
|
|
1127
|
+
else if (node.style === 'bold') attr = ' mathvariant="bold"'
|
|
1128
|
+
else if (node.upright || node.style === 'roman') attr = ' mathvariant="normal"'
|
|
1129
|
+
return '<mi' + attr + '>' + escapeHtmlText(node.value) + '</mi>'
|
|
1130
|
+
}
|
|
1131
|
+
case 'op':
|
|
1132
|
+
return '<mo>' + escapeHtmlText(node.value) + '</mo>'
|
|
1133
|
+
case 'text':
|
|
1134
|
+
return '<mtext' + (node.bold ? ' style="font-weight:700"' : '') + '>' + escapeHtmlText(node.value) + '</mtext>'
|
|
1135
|
+
case 'space':
|
|
1136
|
+
return '<mtext>' + escapeHtmlText(node.value) + '</mtext>'
|
|
1137
|
+
case 'func':
|
|
1138
|
+
return '<mi mathvariant="normal">' + escapeHtmlText(node.name) + '</mi>'
|
|
1139
|
+
case 'style': {
|
|
1140
|
+
const mv = node.style === 'bold' ? 'bold' : node.style === 'roman' ? 'normal' : 'italic'
|
|
1141
|
+
return '<mstyle mathvariant="' + mv + '">' + emit(node.body) + '</mstyle>'
|
|
1142
|
+
}
|
|
1143
|
+
case 'frac':
|
|
1144
|
+
return '<mfrac' + (node.bar === false ? ' linethickness="0"' : '') + '>' +
|
|
1145
|
+
'<mrow>' + emit(node.num) + '</mrow>' +
|
|
1146
|
+
'<mrow>' + emit(node.den) + '</mrow>' +
|
|
1147
|
+
'</mfrac>'
|
|
1148
|
+
case 'sqrt':
|
|
1149
|
+
return '<msqrt>' + emit(node.body) + '</msqrt>'
|
|
1150
|
+
case 'root':
|
|
1151
|
+
return '<mroot><mrow>' + emit(node.body) + '</mrow><mrow>' + emit(node.deg) + '</mrow></mroot>'
|
|
1152
|
+
case 'sub':
|
|
1153
|
+
return '<msub><mrow>' + emit(node.base) + '</mrow><mrow>' + emit(node.sub) + '</mrow></msub>'
|
|
1154
|
+
case 'sup':
|
|
1155
|
+
return '<msup><mrow>' + emit(node.base) + '</mrow><mrow>' + emit(node.sup) + '</mrow></msup>'
|
|
1156
|
+
case 'subsup':
|
|
1157
|
+
return '<msubsup><mrow>' + emit(node.base) + '</mrow><mrow>' + emit(node.sub) + '</mrow><mrow>' + emit(node.sup) + '</mrow></msubsup>'
|
|
1158
|
+
case 'limLow':
|
|
1159
|
+
return '<munder><mrow>' + emit(node.base) + '</mrow><mrow>' + emit(node.lim) + '</mrow></munder>'
|
|
1160
|
+
case 'limUpp':
|
|
1161
|
+
return '<mover><mrow>' + emit(node.base) + '</mrow><mrow>' + emit(node.lim) + '</mrow></mover>'
|
|
1162
|
+
case 'nary': {
|
|
1163
|
+
const opXml = '<mo largeop="true" movablelimits="false">' + escapeHtmlText(node.chr) + '</mo>'
|
|
1164
|
+
const limitsUnderOver = node.limLoc === 'undOvr'
|
|
1165
|
+
let header = opXml
|
|
1166
|
+
if (node.sub && node.sup) {
|
|
1167
|
+
header = limitsUnderOver
|
|
1168
|
+
? '<munderover>' + opXml + '<mrow>' + emit(node.sub) + '</mrow><mrow>' + emit(node.sup) + '</mrow></munderover>'
|
|
1169
|
+
: '<msubsup>' + opXml + '<mrow>' + emit(node.sub) + '</mrow><mrow>' + emit(node.sup) + '</mrow></msubsup>'
|
|
1170
|
+
} else if (node.sub) {
|
|
1171
|
+
header = limitsUnderOver
|
|
1172
|
+
? '<munder>' + opXml + '<mrow>' + emit(node.sub) + '</mrow></munder>'
|
|
1173
|
+
: '<msub>' + opXml + '<mrow>' + emit(node.sub) + '</mrow></msub>'
|
|
1174
|
+
} else if (node.sup) {
|
|
1175
|
+
header = limitsUnderOver
|
|
1176
|
+
? '<mover>' + opXml + '<mrow>' + emit(node.sup) + '</mrow></mover>'
|
|
1177
|
+
: '<msup>' + opXml + '<mrow>' + emit(node.sup) + '</mrow></msup>'
|
|
1178
|
+
}
|
|
1179
|
+
return '<mrow>' + header + emit(node.body) + '</mrow>'
|
|
1180
|
+
}
|
|
1181
|
+
case 'delim':
|
|
1182
|
+
return '<mrow>' +
|
|
1183
|
+
(node.open ? '<mo stretchy="true">' + escapeHtmlText(node.open) + '</mo>' : '') +
|
|
1184
|
+
emit(node.body) +
|
|
1185
|
+
(node.close ? '<mo stretchy="true">' + escapeHtmlText(node.close) + '</mo>' : '') +
|
|
1186
|
+
'</mrow>'
|
|
1187
|
+
case 'matrix':
|
|
1188
|
+
return '<mtable class="math-matrix">' +
|
|
1189
|
+
node.rows.map((row) => '<mtr>' + row.map((cell) => '<mtd>' + emit(cell) + '</mtd>').join('') + '</mtr>').join('') +
|
|
1190
|
+
'</mtable>'
|
|
1191
|
+
case 'acc':
|
|
1192
|
+
return '<mover accent="true"><mrow>' + emit(node.body) + '</mrow><mo>' + escapeHtmlText(node.mathmlChr) + '</mo></mover>'
|
|
1193
|
+
case 'bar':
|
|
1194
|
+
return node.pos === 'bot'
|
|
1195
|
+
? '<munder><mrow>' + emit(node.body) + '</mrow><mo stretchy="true">_</mo></munder>'
|
|
1196
|
+
: '<mover><mrow>' + emit(node.body) + '</mrow><mo stretchy="true">¯</mo></mover>'
|
|
1197
|
+
default:
|
|
1198
|
+
return '<mrow></mrow>'
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
const displayAttr = options.display ? ' display="block"' : ' display="inline"'
|
|
1203
|
+
const classAttr = options.className ? ' class="' + escapeHtmlText(options.className) + '"' : ''
|
|
1204
|
+
return '<math xmlns="' + MATHML_NS + '"' + displayAttr + classAttr + '>' + emit(ast) + '</math>'
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
export function latexToMathMl(latex, options = {}) {
|
|
1208
|
+
return astToMathMl(parseLatexMath(latex), options)
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// ---------------------------------------------------------------------------
|
|
1212
|
+
// ECMA-376 Office Math (<m:oMath>) 编译器
|
|
1213
|
+
// ---------------------------------------------------------------------------
|
|
1214
|
+
|
|
1215
|
+
function ommlRun(text, opts = {}) {
|
|
1216
|
+
const val = String(text ?? '')
|
|
1217
|
+
if (val === '') return ''
|
|
1218
|
+
const rPrParts = []
|
|
1219
|
+
if (opts.nor) rPrParts.push('<m:nor/>')
|
|
1220
|
+
if (opts.scr) rPrParts.push('<m:scr m:val="' + opts.scr + '"/>')
|
|
1221
|
+
if (!opts.nor && opts.sty) rPrParts.push('<m:sty m:val="' + opts.sty + '"/>')
|
|
1222
|
+
|
|
1223
|
+
const mRPr = rPrParts.length > 0 ? '<m:rPr>' + rPrParts.join('') + '</m:rPr>' : ''
|
|
1224
|
+
let aRPr = ''
|
|
1225
|
+
if (opts.sizePt || opts.color) {
|
|
1226
|
+
const szAttr = opts.sizePt ? ' sz="' + Math.round(opts.sizePt * 100) + '"' : ''
|
|
1227
|
+
const bAttr = opts.sty === 'b' || opts.bold ? ' b="1"' : ''
|
|
1228
|
+
const fill = opts.color
|
|
1229
|
+
? '<a:solidFill><a:srgbClr val="' + String(opts.color).replace(/^#/, '').slice(0, 6).toUpperCase() + '"/></a:solidFill>'
|
|
1230
|
+
: ''
|
|
1231
|
+
aRPr = '<a:rPr' + szAttr + bAttr + '>' + fill + '</a:rPr>'
|
|
1232
|
+
}
|
|
1233
|
+
const preserve = /^\s|\s$/.test(val) ? ' xml:space="preserve"' : ''
|
|
1234
|
+
return '<m:r>' + mRPr + aRPr + '<m:t' + preserve + '>' + escapeXmlText(val) + '</m:t></m:r>'
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
function ensureNonEmptyOmml(innerXml, runDefaults) {
|
|
1238
|
+
return innerXml && innerXml.trim() !== '' ? innerXml : ommlRun('\u200B', { ...runDefaults, nor: true })
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
export function astToOmml(ast, options = {}) {
|
|
1242
|
+
const runDefaults = {
|
|
1243
|
+
sizePt: options.sizePt,
|
|
1244
|
+
color: options.color,
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
function emit(node, inheritedStyle = '') {
|
|
1248
|
+
if (!node) return ''
|
|
1249
|
+
switch (node.type) {
|
|
1250
|
+
case 'row':
|
|
1251
|
+
return node.children.map((ch) => emit(ch, inheritedStyle)).join('')
|
|
1252
|
+
case 'num':
|
|
1253
|
+
return ommlRun(node.value, {
|
|
1254
|
+
...runDefaults,
|
|
1255
|
+
sty: (node.style === 'bold' || inheritedStyle === 'bold') ? 'b' : undefined,
|
|
1256
|
+
})
|
|
1257
|
+
case 'ident': {
|
|
1258
|
+
const eff = node.style || inheritedStyle
|
|
1259
|
+
const sty = eff === 'bold' ? 'b' : eff === 'roman' ? 'p' : undefined
|
|
1260
|
+
return ommlRun(node.value, { ...runDefaults, sty })
|
|
1261
|
+
}
|
|
1262
|
+
case 'sym': {
|
|
1263
|
+
if (node.variant === 'bb' && !node.bmp) {
|
|
1264
|
+
return ommlRun(node.value, { ...runDefaults, scr: 'double-struck', sty: 'b' })
|
|
1265
|
+
}
|
|
1266
|
+
if (node.variant === 'cal' && !node.bmp) {
|
|
1267
|
+
return ommlRun(node.value, { ...runDefaults, scr: 'script' })
|
|
1268
|
+
}
|
|
1269
|
+
const eff = node.style || inheritedStyle
|
|
1270
|
+
const sty = eff === 'bold' ? 'b' : (node.upright || eff === 'roman') ? 'p' : undefined
|
|
1271
|
+
return ommlRun(node.value, { ...runDefaults, sty })
|
|
1272
|
+
}
|
|
1273
|
+
case 'op': {
|
|
1274
|
+
const padded = BINARY_OR_REL_OPS.has(node.value) && node.value !== '′' && node.value !== '″'
|
|
1275
|
+
? ' ' + node.value + ' '
|
|
1276
|
+
: node.value
|
|
1277
|
+
return ommlRun(padded, { ...runDefaults, sty: 'p' })
|
|
1278
|
+
}
|
|
1279
|
+
case 'text':
|
|
1280
|
+
return ommlRun(node.value, { ...runDefaults, nor: true, bold: node.bold })
|
|
1281
|
+
case 'space':
|
|
1282
|
+
return ommlRun(node.value, { ...runDefaults, nor: true })
|
|
1283
|
+
case 'func': {
|
|
1284
|
+
const needTrailSpace = !node.limitOp && /^[a-zA-Z]/.test(node.name)
|
|
1285
|
+
return ommlRun(node.name + (needTrailSpace ? ' ' : ''), { ...runDefaults, nor: true })
|
|
1286
|
+
}
|
|
1287
|
+
case 'style':
|
|
1288
|
+
return emit(node.body, node.style)
|
|
1289
|
+
case 'frac': {
|
|
1290
|
+
const fPr = node.bar === false ? '<m:fPr><m:type m:val="noBar"/></m:fPr>' : ''
|
|
1291
|
+
const numXml = ensureNonEmptyOmml(emit(node.num, inheritedStyle), runDefaults)
|
|
1292
|
+
const denXml = ensureNonEmptyOmml(emit(node.den, inheritedStyle), runDefaults)
|
|
1293
|
+
return '<m:f>' + fPr + '<m:num>' + numXml + '</m:num><m:den>' + denXml + '</m:den></m:f>'
|
|
1294
|
+
}
|
|
1295
|
+
case 'sqrt': {
|
|
1296
|
+
const eXml = ensureNonEmptyOmml(emit(node.body, inheritedStyle), runDefaults)
|
|
1297
|
+
return '<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/><m:e>' + eXml + '</m:e></m:rad>'
|
|
1298
|
+
}
|
|
1299
|
+
case 'root': {
|
|
1300
|
+
const degXml = ensureNonEmptyOmml(emit(node.deg, inheritedStyle), runDefaults)
|
|
1301
|
+
const eXml = ensureNonEmptyOmml(emit(node.body, inheritedStyle), runDefaults)
|
|
1302
|
+
return '<m:rad><m:radPr><m:degHide m:val="0"/></m:radPr><m:deg>' + degXml + '</m:deg><m:e>' + eXml + '</m:e></m:rad>'
|
|
1303
|
+
}
|
|
1304
|
+
case 'sub':
|
|
1305
|
+
return '<m:sSub>' +
|
|
1306
|
+
'<m:e>' + ensureNonEmptyOmml(emit(node.base, inheritedStyle), runDefaults) + '</m:e>' +
|
|
1307
|
+
'<m:sub>' + ensureNonEmptyOmml(emit(node.sub, inheritedStyle), runDefaults) + '</m:sub>' +
|
|
1308
|
+
'</m:sSub>'
|
|
1309
|
+
case 'sup':
|
|
1310
|
+
return '<m:sSup>' +
|
|
1311
|
+
'<m:e>' + ensureNonEmptyOmml(emit(node.base, inheritedStyle), runDefaults) + '</m:e>' +
|
|
1312
|
+
'<m:sup>' + ensureNonEmptyOmml(emit(node.sup, inheritedStyle), runDefaults) + '</m:sup>' +
|
|
1313
|
+
'</m:sSup>'
|
|
1314
|
+
case 'subsup':
|
|
1315
|
+
return '<m:sSubSup>' +
|
|
1316
|
+
'<m:e>' + ensureNonEmptyOmml(emit(node.base, inheritedStyle), runDefaults) + '</m:e>' +
|
|
1317
|
+
'<m:sub>' + ensureNonEmptyOmml(emit(node.sub, inheritedStyle), runDefaults) + '</m:sub>' +
|
|
1318
|
+
'<m:sup>' + ensureNonEmptyOmml(emit(node.sup, inheritedStyle), runDefaults) + '</m:sup>' +
|
|
1319
|
+
'</m:sSubSup>'
|
|
1320
|
+
case 'limLow':
|
|
1321
|
+
return '<m:limLow>' +
|
|
1322
|
+
'<m:e>' + ensureNonEmptyOmml(emit(node.base, inheritedStyle), runDefaults) + '</m:e>' +
|
|
1323
|
+
'<m:lim>' + ensureNonEmptyOmml(emit(node.lim, inheritedStyle), runDefaults) + '</m:lim>' +
|
|
1324
|
+
'</m:limLow>'
|
|
1325
|
+
case 'limUpp':
|
|
1326
|
+
return '<m:limUpp>' +
|
|
1327
|
+
'<m:e>' + ensureNonEmptyOmml(emit(node.base, inheritedStyle), runDefaults) + '</m:e>' +
|
|
1328
|
+
'<m:lim>' + ensureNonEmptyOmml(emit(node.lim, inheritedStyle), runDefaults) + '</m:lim>' +
|
|
1329
|
+
'</m:limUpp>'
|
|
1330
|
+
case 'nary': {
|
|
1331
|
+
const hasSub = Boolean(node.sub && !(node.sub.type === 'row' && node.sub.children.length === 0))
|
|
1332
|
+
const hasSup = Boolean(node.sup && !(node.sup.type === 'row' && node.sup.children.length === 0))
|
|
1333
|
+
const naryPr =
|
|
1334
|
+
'<m:naryPr>' +
|
|
1335
|
+
'<m:chr m:val="' + escapeXmlText(node.chr) + '"/>' +
|
|
1336
|
+
'<m:limLoc m:val="' + (node.limLoc === 'subSup' ? 'subSup' : 'undOvr') + '"/>' +
|
|
1337
|
+
(!hasSub ? '<m:subHide m:val="1"/>' : '') +
|
|
1338
|
+
(!hasSup ? '<m:supHide m:val="1"/>' : '') +
|
|
1339
|
+
'</m:naryPr>'
|
|
1340
|
+
const subXml = hasSub ? '<m:sub>' + ensureNonEmptyOmml(emit(node.sub, inheritedStyle), runDefaults) + '</m:sub>' : '<m:sub/>'
|
|
1341
|
+
const supXml = hasSup ? '<m:sup>' + ensureNonEmptyOmml(emit(node.sup, inheritedStyle), runDefaults) + '</m:sup>' : '<m:sup/>'
|
|
1342
|
+
const eXml = '<m:e>' + ensureNonEmptyOmml(emit(node.body, inheritedStyle), runDefaults) + '</m:e>'
|
|
1343
|
+
return '<m:nary>' + naryPr + subXml + supXml + eXml + '</m:nary>'
|
|
1344
|
+
}
|
|
1345
|
+
case 'delim':
|
|
1346
|
+
return '<m:d>' +
|
|
1347
|
+
'<m:dPr>' +
|
|
1348
|
+
'<m:begChr m:val="' + escapeXmlText(node.open ?? '') + '"/>' +
|
|
1349
|
+
'<m:endChr m:val="' + escapeXmlText(node.close ?? '') + '"/>' +
|
|
1350
|
+
'</m:dPr>' +
|
|
1351
|
+
'<m:e>' + ensureNonEmptyOmml(emit(node.body, inheritedStyle), runDefaults) + '</m:e>' +
|
|
1352
|
+
'</m:d>'
|
|
1353
|
+
case 'matrix': {
|
|
1354
|
+
const colCount = Math.max(1, ...node.rows.map((r) => r.length))
|
|
1355
|
+
const mrXml = node.rows.map((r) => {
|
|
1356
|
+
const cells = Array.from({ length: colCount }, (_, c) =>
|
|
1357
|
+
'<m:e>' + ensureNonEmptyOmml(emit(r[c], inheritedStyle), runDefaults) + '</m:e>',
|
|
1358
|
+
).join('')
|
|
1359
|
+
return '<m:mr>' + cells + '</m:mr>'
|
|
1360
|
+
}).join('')
|
|
1361
|
+
return '<m:m>' + mrXml + '</m:m>'
|
|
1362
|
+
}
|
|
1363
|
+
case 'acc':
|
|
1364
|
+
return '<m:acc>' +
|
|
1365
|
+
'<m:accPr><m:chr m:val="' + escapeXmlText(node.chr) + '"/></m:accPr>' +
|
|
1366
|
+
'<m:e>' + ensureNonEmptyOmml(emit(node.body, inheritedStyle), runDefaults) + '</m:e>' +
|
|
1367
|
+
'</m:acc>'
|
|
1368
|
+
case 'bar':
|
|
1369
|
+
return '<m:bar>' +
|
|
1370
|
+
'<m:barPr><m:pos m:val="' + (node.pos === 'bot' ? 'bot' : 'top') + '"/></m:barPr>' +
|
|
1371
|
+
'<m:e>' + ensureNonEmptyOmml(emit(node.body, inheritedStyle), runDefaults) + '</m:e>' +
|
|
1372
|
+
'</m:bar>'
|
|
1373
|
+
default:
|
|
1374
|
+
return ''
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
const inner = ensureNonEmptyOmml(emit(ast), runDefaults)
|
|
1379
|
+
if (options.wrapDrawingMl !== false) {
|
|
1380
|
+
return (
|
|
1381
|
+
'<a14:m xmlns:a14="' + A14_NS + '">' +
|
|
1382
|
+
'<m:oMathPara xmlns:m="' + OMML_NS + '">' +
|
|
1383
|
+
'<m:oMath>' + inner + '</m:oMath>' +
|
|
1384
|
+
'</m:oMathPara>' +
|
|
1385
|
+
'</a14:m>'
|
|
1386
|
+
)
|
|
1387
|
+
}
|
|
1388
|
+
if (options.para) {
|
|
1389
|
+
return '<m:oMathPara xmlns:m="' + OMML_NS + '"><m:oMath>' + inner + '</m:oMath></m:oMathPara>'
|
|
1390
|
+
}
|
|
1391
|
+
return '<m:oMath xmlns:m="' + OMML_NS + '">' + inner + '</m:oMath>'
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
export function latexToOmml(latex, options = {}) {
|
|
1395
|
+
return astToOmml(parseLatexMath(latex), options)
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
// ---------------------------------------------------------------------------
|
|
1399
|
+
// 混排段落行内 DrawingML Run 编译(支持真上下标 baseline,杜绝 LibreOffice 吞行内公式)
|
|
1400
|
+
// ---------------------------------------------------------------------------
|
|
1401
|
+
|
|
1402
|
+
export function astToOoxmlInlineRuns(ast) {
|
|
1403
|
+
const runs = []
|
|
1404
|
+
|
|
1405
|
+
function pushRun(text, mods = {}) {
|
|
1406
|
+
if (!text) return
|
|
1407
|
+
runs.push({
|
|
1408
|
+
text,
|
|
1409
|
+
italic: Boolean(mods.italic),
|
|
1410
|
+
bold: Boolean(mods.bold),
|
|
1411
|
+
baseline: mods.baseline ?? 0,
|
|
1412
|
+
spcEm: mods.spcEm ?? 0,
|
|
1413
|
+
math: mods.isText ? false : true,
|
|
1414
|
+
})
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
function flattenPlain(node) {
|
|
1418
|
+
const subRuns = astToOoxmlInlineRuns(node)
|
|
1419
|
+
return subRuns.map((r) => r.text).join('')
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
function walk(node, mods = {}) {
|
|
1423
|
+
if (!node) return
|
|
1424
|
+
switch (node.type) {
|
|
1425
|
+
case 'row':
|
|
1426
|
+
node.children.forEach((ch) => walk(ch, mods))
|
|
1427
|
+
break
|
|
1428
|
+
case 'num':
|
|
1429
|
+
pushRun(node.value, { ...mods, italic: false, bold: mods.bold || node.style === 'bold' })
|
|
1430
|
+
break
|
|
1431
|
+
case 'ident':
|
|
1432
|
+
pushRun(node.value, {
|
|
1433
|
+
...mods,
|
|
1434
|
+
italic: node.style !== 'roman' && node.style !== 'bold',
|
|
1435
|
+
bold: mods.bold || node.style === 'bold',
|
|
1436
|
+
})
|
|
1437
|
+
break
|
|
1438
|
+
case 'sym':
|
|
1439
|
+
if (node.variant === 'bb' && !node.bmp) {
|
|
1440
|
+
pushRun(node.value, { ...mods, italic: false, bold: true })
|
|
1441
|
+
break
|
|
1442
|
+
}
|
|
1443
|
+
if (node.variant === 'cal' && !node.bmp) {
|
|
1444
|
+
pushRun(node.value, { ...mods, italic: true, bold: true })
|
|
1445
|
+
break
|
|
1446
|
+
}
|
|
1447
|
+
pushRun(node.value, {
|
|
1448
|
+
...mods,
|
|
1449
|
+
italic: !node.upright && node.style !== 'roman',
|
|
1450
|
+
bold: mods.bold || node.style === 'bold',
|
|
1451
|
+
})
|
|
1452
|
+
break
|
|
1453
|
+
case 'op': {
|
|
1454
|
+
const sp = BINARY_OR_REL_OPS.has(node.value) && !mods.baseline ? ' ' + node.value + ' ' : node.value
|
|
1455
|
+
pushRun(sp, { ...mods, italic: false })
|
|
1456
|
+
break
|
|
1457
|
+
}
|
|
1458
|
+
case 'text':
|
|
1459
|
+
pushRun(node.value, { ...mods, italic: false, bold: mods.bold || node.bold, isText: true })
|
|
1460
|
+
break
|
|
1461
|
+
case 'space':
|
|
1462
|
+
pushRun(node.value, { ...mods, italic: false })
|
|
1463
|
+
break
|
|
1464
|
+
case 'func':
|
|
1465
|
+
pushRun(node.name + (!node.limitOp ? ' ' : ''), { ...mods, italic: false })
|
|
1466
|
+
break
|
|
1467
|
+
case 'style':
|
|
1468
|
+
walk(node.body, { ...mods, bold: mods.bold || node.style === 'bold' })
|
|
1469
|
+
break
|
|
1470
|
+
case 'frac': {
|
|
1471
|
+
const needNumParen = node.num?.type === 'row' && node.num.children.length > 1
|
|
1472
|
+
const needDenParen = node.den?.type === 'row' && node.den.children.length > 1
|
|
1473
|
+
if (needNumParen) pushRun('(', { ...mods, italic: false })
|
|
1474
|
+
walk(node.num, mods)
|
|
1475
|
+
if (needNumParen) pushRun(')', { ...mods, italic: false })
|
|
1476
|
+
pushRun(node.bar === false ? ' ¦ ' : '/', { ...mods, italic: false })
|
|
1477
|
+
if (needDenParen) pushRun('(', { ...mods, italic: false })
|
|
1478
|
+
walk(node.den, mods)
|
|
1479
|
+
if (needDenParen) pushRun(')', { ...mods, italic: false })
|
|
1480
|
+
break
|
|
1481
|
+
}
|
|
1482
|
+
case 'sqrt':
|
|
1483
|
+
pushRun('√(', { ...mods, italic: false })
|
|
1484
|
+
walk(node.body, mods)
|
|
1485
|
+
pushRun(')', { ...mods, italic: false })
|
|
1486
|
+
break
|
|
1487
|
+
case 'root':
|
|
1488
|
+
walk(node.deg, { ...mods, baseline: 35000 })
|
|
1489
|
+
pushRun('√(', { ...mods, italic: false })
|
|
1490
|
+
walk(node.body, mods)
|
|
1491
|
+
pushRun(')', { ...mods, italic: false })
|
|
1492
|
+
break
|
|
1493
|
+
case 'sub':
|
|
1494
|
+
case 'limLow':
|
|
1495
|
+
walk(node.base, mods)
|
|
1496
|
+
walk(node.sub ?? node.lim, { ...mods, baseline: -25000 })
|
|
1497
|
+
break
|
|
1498
|
+
case 'sup':
|
|
1499
|
+
case 'limUpp': {
|
|
1500
|
+
walk(node.base, mods)
|
|
1501
|
+
if (node.base?.type === 'sym' && node.base.bmp) {
|
|
1502
|
+
pushRun('\u2009', { ...mods, italic: false })
|
|
1503
|
+
}
|
|
1504
|
+
walk(node.sup ?? node.lim, { ...mods, baseline: 35000 })
|
|
1505
|
+
break
|
|
1506
|
+
}
|
|
1507
|
+
case 'subsup': {
|
|
1508
|
+
walk(node.base, mods)
|
|
1509
|
+
if (node.base?.type === 'sym' && node.base.bmp) {
|
|
1510
|
+
pushRun('\u2009', { ...mods, italic: false })
|
|
1511
|
+
}
|
|
1512
|
+
walk(node.sub, { ...mods, baseline: -25000 })
|
|
1513
|
+
walk(node.sup, { ...mods, baseline: 35000 })
|
|
1514
|
+
break
|
|
1515
|
+
}
|
|
1516
|
+
case 'nary':
|
|
1517
|
+
pushRun(node.chr, { ...mods, italic: false })
|
|
1518
|
+
if (node.sub) walk(node.sub, { ...mods, baseline: -25000 })
|
|
1519
|
+
if (node.sup) walk(node.sup, { ...mods, baseline: 35000 })
|
|
1520
|
+
pushRun(' ', { ...mods, italic: false })
|
|
1521
|
+
walk(node.body, mods)
|
|
1522
|
+
break
|
|
1523
|
+
case 'delim':
|
|
1524
|
+
if (node.open) pushRun(node.open, { ...mods, italic: false })
|
|
1525
|
+
walk(node.body, mods)
|
|
1526
|
+
if (node.close) pushRun(node.close, { ...mods, italic: false })
|
|
1527
|
+
break
|
|
1528
|
+
case 'matrix': {
|
|
1529
|
+
const rowStrs = node.rows.map((r) => r.map(flattenPlain).join(', '))
|
|
1530
|
+
pushRun(rowStrs.join('; '), { ...mods, italic: false })
|
|
1531
|
+
break
|
|
1532
|
+
}
|
|
1533
|
+
case 'acc': {
|
|
1534
|
+
const baseStr = flattenPlain(node.body)
|
|
1535
|
+
const isVec = node.cmd === 'vec' || node.cmd === 'overrightarrow'
|
|
1536
|
+
const targetComb = isVec ? '\u0304' : node.chr
|
|
1537
|
+
const precomposed = (baseStr + targetComb).normalize('NFC')
|
|
1538
|
+
// 1. 若存在单码位 NFC 预组字形(如 â, ê, î, ô, û, ā, ū, ã, ñ),直接输出单码位零组合符
|
|
1539
|
+
if ([...precomposed].length === 1 && precomposed !== baseStr) {
|
|
1540
|
+
pushRun(precomposed, { ...mods, italic: true, bold: mods.bold || isVec })
|
|
1541
|
+
break
|
|
1542
|
+
}
|
|
1543
|
+
// 2. 若基底是纯 ASCII 拉丁单字母且为上横线(如 \bar{x} / \vec{x}),Liberation Serif 原生 GPOS 居中锚定完美
|
|
1544
|
+
if (/^[a-zA-Z]$/.test(baseStr) && targetComb === '\u0304') {
|
|
1545
|
+
pushRun(baseStr + '\u0304', { ...mods, italic: true, bold: mods.bold || isVec })
|
|
1546
|
+
break
|
|
1547
|
+
}
|
|
1548
|
+
// 3. 对无 NFC 预组的希腊字母或任意字符(如 \hat{\omega}_i, \tilde{\theta}_m),在同一 <a:r> 内利用负字距回退叠印顶标修饰符,随后插入细空隙与下标自然衔接
|
|
1549
|
+
const modSpec = SPACING_MODIFIER_ACCENT[node.cmd] ?? { glyph: 'ˆ', baseline: 12000 }
|
|
1550
|
+
pushRun(baseStr + modSpec.glyph, { ...mods, italic: true, bold: mods.bold || isVec, spcEm: -0.44 })
|
|
1551
|
+
pushRun('\u2009', { ...mods, italic: false })
|
|
1552
|
+
break
|
|
1553
|
+
}
|
|
1554
|
+
case 'bar': {
|
|
1555
|
+
const baseStr = flattenPlain(node.body)
|
|
1556
|
+
const comb = node.pos === 'bot' ? '\u0332' : '\u0304'
|
|
1557
|
+
const composed = [...baseStr].map((c) => (c + comb).normalize('NFC')).join('')
|
|
1558
|
+
pushRun(composed, { ...mods, italic: true })
|
|
1559
|
+
break
|
|
1560
|
+
}
|
|
1561
|
+
default:
|
|
1562
|
+
break
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
walk(ast)
|
|
1567
|
+
return runs
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
// ---------------------------------------------------------------------------
|
|
1571
|
+
// 2D 结构判定与自然宽高比几何估算器(确保 LibreOffice StarMath 1:1 等比无畸变)
|
|
1572
|
+
// ---------------------------------------------------------------------------
|
|
1573
|
+
|
|
1574
|
+
export function has2dMathConstruct(ast) {
|
|
1575
|
+
if (!ast) return false
|
|
1576
|
+
if (['frac', 'sqrt', 'root', 'nary', 'matrix', 'limLow', 'limUpp'].includes(ast.type)) return true
|
|
1577
|
+
if (ast.type === 'row') return ast.children.some(has2dMathConstruct)
|
|
1578
|
+
return Boolean(
|
|
1579
|
+
has2dMathConstruct(ast.body) ||
|
|
1580
|
+
has2dMathConstruct(ast.base) ||
|
|
1581
|
+
has2dMathConstruct(ast.num) ||
|
|
1582
|
+
has2dMathConstruct(ast.den) ||
|
|
1583
|
+
has2dMathConstruct(ast.sub) ||
|
|
1584
|
+
has2dMathConstruct(ast.sup),
|
|
1585
|
+
)
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
export function measureMathAst(ast) {
|
|
1589
|
+
if (!ast) return { widthEm: 0.6, heightEm: 1.0 }
|
|
1590
|
+
switch (ast.type) {
|
|
1591
|
+
case 'row': {
|
|
1592
|
+
if (ast.children.length === 0) return { widthEm: 0.4, heightEm: 1.0 }
|
|
1593
|
+
let w = 0
|
|
1594
|
+
let h = 1.0
|
|
1595
|
+
for (const ch of ast.children) {
|
|
1596
|
+
const m = measureMathAst(ch)
|
|
1597
|
+
w += m.widthEm
|
|
1598
|
+
h = Math.max(h, m.heightEm)
|
|
1599
|
+
}
|
|
1600
|
+
return { widthEm: w, heightEm: h }
|
|
1601
|
+
}
|
|
1602
|
+
case 'num':
|
|
1603
|
+
return { widthEm: Math.max(0.55, ast.value.length * 0.56), heightEm: 1.0 }
|
|
1604
|
+
case 'ident':
|
|
1605
|
+
case 'sym':
|
|
1606
|
+
return { widthEm: 0.62, heightEm: 1.0 }
|
|
1607
|
+
case 'op':
|
|
1608
|
+
return { widthEm: BINARY_OR_REL_OPS.has(ast.value) ? 1.15 : 0.48, heightEm: 1.0 }
|
|
1609
|
+
case 'text': {
|
|
1610
|
+
let w = 0
|
|
1611
|
+
for (const ch of ast.value) {
|
|
1612
|
+
w += (ch.codePointAt(0) ?? 0) > 0x2E80 ? 1.0 : 0.54
|
|
1613
|
+
}
|
|
1614
|
+
return { widthEm: Math.max(0.5, w), heightEm: 1.05 }
|
|
1615
|
+
}
|
|
1616
|
+
case 'space':
|
|
1617
|
+
return { widthEm: 0.35 * ast.value.length, heightEm: 1.0 }
|
|
1618
|
+
case 'func':
|
|
1619
|
+
return { widthEm: ast.name.length * 0.54 + 0.25, heightEm: 1.05 }
|
|
1620
|
+
case 'style':
|
|
1621
|
+
return measureMathAst(ast.body)
|
|
1622
|
+
case 'frac': {
|
|
1623
|
+
const n = measureMathAst(ast.num)
|
|
1624
|
+
const d = measureMathAst(ast.den)
|
|
1625
|
+
return {
|
|
1626
|
+
widthEm: Math.max(n.widthEm, d.widthEm) + 0.52,
|
|
1627
|
+
heightEm: n.heightEm * 0.86 + d.heightEm * 0.86 + 0.54,
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
case 'sqrt': {
|
|
1631
|
+
const b = measureMathAst(ast.body)
|
|
1632
|
+
return { widthEm: b.widthEm + 0.72, heightEm: b.heightEm + 0.32 }
|
|
1633
|
+
}
|
|
1634
|
+
case 'root': {
|
|
1635
|
+
const deg = measureMathAst(ast.deg)
|
|
1636
|
+
const b = measureMathAst(ast.body)
|
|
1637
|
+
return { widthEm: deg.widthEm * 0.6 + b.widthEm + 0.78, heightEm: b.heightEm + 0.36 }
|
|
1638
|
+
}
|
|
1639
|
+
case 'sub': {
|
|
1640
|
+
const b = measureMathAst(ast.base)
|
|
1641
|
+
const s = measureMathAst(ast.sub)
|
|
1642
|
+
return { widthEm: b.widthEm + s.widthEm * 0.68, heightEm: Math.max(1.22, b.heightEm + 0.22) }
|
|
1643
|
+
}
|
|
1644
|
+
case 'sup': {
|
|
1645
|
+
const b = measureMathAst(ast.base)
|
|
1646
|
+
const s = measureMathAst(ast.sup)
|
|
1647
|
+
return { widthEm: b.widthEm + s.widthEm * 0.68, heightEm: Math.max(1.28, b.heightEm + 0.30) }
|
|
1648
|
+
}
|
|
1649
|
+
case 'subsup': {
|
|
1650
|
+
const b = measureMathAst(ast.base)
|
|
1651
|
+
const sub = measureMathAst(ast.sub)
|
|
1652
|
+
const sup = measureMathAst(ast.sup)
|
|
1653
|
+
return {
|
|
1654
|
+
widthEm: b.widthEm + Math.max(sub.widthEm, sup.widthEm) * 0.68,
|
|
1655
|
+
heightEm: Math.max(1.42, b.heightEm + 0.42),
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
case 'limLow':
|
|
1659
|
+
case 'limUpp': {
|
|
1660
|
+
const b = measureMathAst(ast.base)
|
|
1661
|
+
const l = measureMathAst(ast.lim)
|
|
1662
|
+
return { widthEm: Math.max(b.widthEm, l.widthEm * 0.74) + 0.2, heightEm: b.heightEm + 0.62 }
|
|
1663
|
+
}
|
|
1664
|
+
case 'nary': {
|
|
1665
|
+
const sub = ast.sub ? measureMathAst(ast.sub) : { widthEm: 0, heightEm: 0 }
|
|
1666
|
+
const sup = ast.sup ? measureMathAst(ast.sup) : { widthEm: 0, heightEm: 0 }
|
|
1667
|
+
const b = measureMathAst(ast.body)
|
|
1668
|
+
const opW = ast.limLoc === 'undOvr'
|
|
1669
|
+
? Math.max(1.25, sub.widthEm * 0.68, sup.widthEm * 0.68)
|
|
1670
|
+
: 1.05 + Math.max(sub.widthEm, sup.widthEm) * 0.65
|
|
1671
|
+
const opH = ast.limLoc === 'undOvr'
|
|
1672
|
+
? 1.55 + (ast.sub ? 0.42 : 0) + (ast.sup ? 0.42 : 0)
|
|
1673
|
+
: 1.75
|
|
1674
|
+
return { widthEm: opW + 0.22 + b.widthEm, heightEm: Math.max(opH, b.heightEm) }
|
|
1675
|
+
}
|
|
1676
|
+
case 'delim': {
|
|
1677
|
+
const b = measureMathAst(ast.body)
|
|
1678
|
+
const delimCount = (ast.open ? 1 : 0) + (ast.close ? 1 : 0)
|
|
1679
|
+
return { widthEm: b.widthEm + delimCount * 0.46, heightEm: Math.max(1.18, b.heightEm * 1.06) }
|
|
1680
|
+
}
|
|
1681
|
+
case 'matrix': {
|
|
1682
|
+
const cols = Math.max(1, ...ast.rows.map((r) => r.length))
|
|
1683
|
+
const colWidths = Array.from({ length: cols }, () => 0.6)
|
|
1684
|
+
let totalH = 0
|
|
1685
|
+
for (const r of ast.rows) {
|
|
1686
|
+
let rowH = 1.0
|
|
1687
|
+
r.forEach((cell, cIdx) => {
|
|
1688
|
+
const m = measureMathAst(cell)
|
|
1689
|
+
colWidths[cIdx] = Math.max(colWidths[cIdx], m.widthEm)
|
|
1690
|
+
rowH = Math.max(rowH, m.heightEm)
|
|
1691
|
+
})
|
|
1692
|
+
totalH += rowH
|
|
1693
|
+
}
|
|
1694
|
+
return {
|
|
1695
|
+
widthEm: colWidths.reduce((a, b) => a + b, 0) + (cols - 1) * 0.92 + 0.5,
|
|
1696
|
+
heightEm: totalH + Math.max(0, ast.rows.length - 1) * 0.34 + 0.36,
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
case 'acc':
|
|
1700
|
+
case 'bar': {
|
|
1701
|
+
const b = measureMathAst(ast.body)
|
|
1702
|
+
return { widthEm: b.widthEm, heightEm: b.heightEm + 0.28 }
|
|
1703
|
+
}
|
|
1704
|
+
default:
|
|
1705
|
+
return { widthEm: 0.8, heightEm: 1.0 }
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/**
|
|
1710
|
+
* 在给定容器框内,按公式自然宽高比求解 1:1 无拉伸的 <p:sp> 几何框。
|
|
1711
|
+
*/
|
|
1712
|
+
export function fitFormulaBoxIn(ast, containerBoxIn, options = {}) {
|
|
1713
|
+
const {
|
|
1714
|
+
padXIn = 0.28,
|
|
1715
|
+
padYIn = 0.14,
|
|
1716
|
+
emIn = 0.31,
|
|
1717
|
+
align = 'ctr',
|
|
1718
|
+
} = options
|
|
1719
|
+
const metrics = measureMathAst(ast)
|
|
1720
|
+
const maxW = Math.max(0.8, containerBoxIn.w - padXIn * 2)
|
|
1721
|
+
const maxH = Math.max(0.36, containerBoxIn.h - padYIn * 2)
|
|
1722
|
+
|
|
1723
|
+
let naturalW = Math.max(0.9, metrics.widthEm * emIn)
|
|
1724
|
+
let naturalH = Math.max(0.40, metrics.heightEm * emIn * 1.06)
|
|
1725
|
+
|
|
1726
|
+
const scale = Math.min(1, maxW / naturalW, maxH / naturalH)
|
|
1727
|
+
const w = +(naturalW * scale).toFixed(4)
|
|
1728
|
+
const h = +(naturalH * scale).toFixed(4)
|
|
1729
|
+
const x = align === 'l'
|
|
1730
|
+
? +(containerBoxIn.x + padXIn).toFixed(4)
|
|
1731
|
+
: +(containerBoxIn.x + (containerBoxIn.w - w) / 2).toFixed(4)
|
|
1732
|
+
const y = +(containerBoxIn.y + (containerBoxIn.h - h) / 2).toFixed(4)
|
|
1733
|
+
|
|
1734
|
+
return { x, y, w, h, widthEm: metrics.widthEm, heightEm: metrics.heightEm }
|
|
1735
|
+
}
|