@zyro-sec/latex 0.0.0-stage → 1.0.2

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/src/parser.ts ADDED
@@ -0,0 +1,598 @@
1
+ import {
2
+ LatexParseError,
3
+ type AccentKind,
4
+ type MathNode,
5
+ type MathVariant,
6
+ type MatrixEnvironment,
7
+ type ParseOptions,
8
+ } from "./types"
9
+ import {
10
+ assertNestingDepth,
11
+ assertSourceLength,
12
+ DEFAULT_MAX_NESTING_DEPTH,
13
+ DEFAULT_MAX_SOURCE_LENGTH,
14
+ resolvePositiveInteger,
15
+ } from "./limits"
16
+ import { delimiterTable, largeOperators, namedOperators, spacingCommands, symbolTable } from "./symbols"
17
+
18
+ const matrixEnvironments: MatrixEnvironment[] = [
19
+ "matrix",
20
+ "pmatrix",
21
+ "bmatrix",
22
+ "Bmatrix",
23
+ "vmatrix",
24
+ "Vmatrix",
25
+ "cases",
26
+ "aligned",
27
+ "align",
28
+ "gathered",
29
+ "gather",
30
+ "smallmatrix",
31
+ "array",
32
+ ]
33
+
34
+ const accents: Readonly<Record<string, AccentKind>> = {
35
+ hat: "hat",
36
+ widehat: "widehat",
37
+ bar: "bar",
38
+ overline: "overline",
39
+ underline: "underline",
40
+ vec: "vec",
41
+ tilde: "tilde",
42
+ widetilde: "tilde",
43
+ dot: "dot",
44
+ ddot: "ddot",
45
+ }
46
+
47
+ const variants: Readonly<Record<string, MathVariant>> = {
48
+ mathrm: "normal",
49
+ textrm: "normal",
50
+ mathnormal: "normal",
51
+ mathbf: "bold",
52
+ boldsymbol: "bold",
53
+ bm: "bold",
54
+ mathit: "italic",
55
+ mathsf: "sans",
56
+ mathtt: "monospace",
57
+ mathbb: "double-struck",
58
+ mathcal: "script",
59
+ mathscr: "script",
60
+ mathfrak: "fraktur",
61
+ }
62
+
63
+ export function parseLatex(source: string, options: ParseOptions = {}): MathNode {
64
+ const expanded = expandLatexMacros(source, options)
65
+ const maxDepth = resolvePositiveInteger(options.maxDepth, DEFAULT_MAX_NESTING_DEPTH, "maxDepth")
66
+ return new Parser(expanded, options.strict ?? false, maxDepth).parse()
67
+ }
68
+
69
+ export function expandLatexMacros(source: string, options: ParseOptions = {}): string {
70
+ const maxSourceLength = resolvePositiveInteger(options.maxSourceLength, DEFAULT_MAX_SOURCE_LENGTH, "maxSourceLength")
71
+ const maxExpandedLength = resolvePositiveInteger(options.maxExpandedLength, maxSourceLength, "maxExpandedLength")
72
+ const maxExpand = resolvePositiveInteger(options.maxExpand, 100, "maxExpand")
73
+ const maxDepth = resolvePositiveInteger(options.maxDepth, DEFAULT_MAX_NESTING_DEPTH, "maxDepth")
74
+ assertSourceLength(source, maxSourceLength)
75
+ assertNestingDepth(source, maxDepth)
76
+ const expanded = expandMacros(source, options.macros, maxExpand, maxExpandedLength)
77
+ if (expanded !== source) assertNestingDepth(expanded, maxDepth)
78
+ return expanded
79
+ }
80
+
81
+ function expandMacros(
82
+ source: string,
83
+ macros: ParseOptions["macros"],
84
+ maxExpand: number,
85
+ maxExpandedLength: number,
86
+ ): string {
87
+ assertSourceLength(source, maxExpandedLength, "Expanded LaTeX source")
88
+ if (!macros || Object.keys(macros).length === 0) return source
89
+
90
+ let result = source
91
+ for (let pass = 0; pass < maxExpand; pass++) {
92
+ let changed = false
93
+ let cursor = 0
94
+ let outputLength = 0
95
+ const output: string[] = []
96
+ const commands = /\\[A-Za-z@]+|\\./g
97
+
98
+ for (const match of result.matchAll(commands)) {
99
+ const command = match[0]
100
+ const index = match.index
101
+ const replacement = macros[command] ?? macros[command.slice(1)]
102
+ if (replacement === undefined) continue
103
+ if (typeof replacement !== "string") {
104
+ throw new TypeError(`Macro ${command} must expand to a string`)
105
+ }
106
+
107
+ appendWithinLimit(output, result.slice(cursor, index), outputLength, maxExpandedLength)
108
+ outputLength += index - cursor
109
+ appendWithinLimit(output, replacement, outputLength, maxExpandedLength)
110
+ outputLength += replacement.length
111
+ cursor = index + command.length
112
+ changed = true
113
+ }
114
+
115
+ if (!changed) return result
116
+ appendWithinLimit(output, result.slice(cursor), outputLength, maxExpandedLength)
117
+ result = output.join("")
118
+ }
119
+
120
+ throw new LatexParseError(`Macro expansion exceeded ${maxExpand} passes`, 0)
121
+ }
122
+
123
+ function appendWithinLimit(output: string[], value: string, currentLength: number, maximum: number): void {
124
+ if (currentLength + value.length > maximum) {
125
+ throw new LatexParseError(`Expanded LaTeX source exceeds the ${maximum}-character limit`, maximum)
126
+ }
127
+ output.push(value)
128
+ }
129
+
130
+ class Parser {
131
+ private position = 0
132
+ private depth = 0
133
+
134
+ constructor(
135
+ private readonly source: string,
136
+ private readonly strict: boolean,
137
+ private readonly maxDepth: number,
138
+ ) {}
139
+
140
+ public parse(): MathNode {
141
+ const body = this.parseRow()
142
+ this.skipMathWhitespace()
143
+ if (!this.done()) this.fail(`Unexpected "${this.peek()}"`)
144
+ return row(body)
145
+ }
146
+
147
+ private parseRow(stop?: () => boolean): MathNode[] {
148
+ const body: MathNode[] = []
149
+
150
+ while (!this.done()) {
151
+ this.skipMathWhitespace()
152
+ if (this.done() || stop?.()) break
153
+
154
+ const current = this.peek()
155
+ if (current === "}") break
156
+
157
+ if (current === "^" || current === "_") {
158
+ this.position++
159
+ const script = this.parseArgument()
160
+ const previous = body.pop() ?? { type: "row", body: [] }
161
+ const existing = previous.type === "scripts" ? previous : { type: "scripts" as const, base: previous }
162
+ if (current === "^") existing.superscript = script
163
+ else existing.subscript = script
164
+ body.push(existing)
165
+ continue
166
+ }
167
+
168
+ if (current === "\\" && this.applyLimitsModifier(body)) continue
169
+ body.push(this.parseAtom())
170
+ }
171
+
172
+ return body
173
+ }
174
+
175
+ private parseAtom(): MathNode {
176
+ this.depth++
177
+ if (this.depth > this.maxDepth) {
178
+ this.depth--
179
+ this.fail(`LaTeX nesting exceeds the ${this.maxDepth}-level limit`)
180
+ }
181
+ try {
182
+ return this.parseAtomInner()
183
+ } finally {
184
+ this.depth--
185
+ }
186
+ }
187
+
188
+ private parseAtomInner(): MathNode {
189
+ const current = this.peek()
190
+ if (current === "{") return this.parseGroup()
191
+ if (current === "\\") return this.parseCommand()
192
+ if (current === "~") {
193
+ this.position++
194
+ return { type: "space", width: 1 }
195
+ }
196
+
197
+ this.position++
198
+ return { type: "symbol", value: current, role: inferRole(current) }
199
+ }
200
+
201
+ private parseCommand(): MathNode {
202
+ const start = this.position
203
+ const command = this.readCommand()
204
+
205
+ if (command === "\\") return { type: "row", body: [] }
206
+ if (command === "begin") return this.parseEnvironment()
207
+ if (command === "frac" || command === "dfrac" || command === "tfrac" || command === "cfrac") {
208
+ this.skipMathWhitespace()
209
+ const alignment =
210
+ command === "cfrac" && this.peek() === "[" ? /^\[([lr]?)\]/.exec(this.source.slice(this.position)) : undefined
211
+ if (alignment === null) this.fail("Unsupported \\cfrac alignment; expected [l], [r], or []")
212
+ if (alignment) this.position += alignment[0].length
213
+ return {
214
+ type: "fraction",
215
+ numerator: this.parseArgument(),
216
+ denominator: this.parseArgument(),
217
+ bar: true,
218
+ ...(alignment?.[1] ? { numeratorAlign: alignment[1] === "l" ? "left" : "right" } : {}),
219
+ }
220
+ }
221
+ if (command === "binom" || command === "dbinom" || command === "tbinom") {
222
+ const fraction: MathNode = {
223
+ type: "fraction",
224
+ numerator: this.parseArgument(),
225
+ denominator: this.parseArgument(),
226
+ bar: false,
227
+ }
228
+ return { type: "delimited", left: "(", body: fraction, right: ")" }
229
+ }
230
+ if (command === "sqrt") {
231
+ const index = this.parseOptionalArgument()
232
+ const result: MathNode = { type: "root", body: this.parseArgument() }
233
+ if (index) result.index = index
234
+ return result
235
+ }
236
+ if (command === "left") return this.parseLeftRight()
237
+ if (command === "middle") return { type: "symbol", value: this.readDelimiter() }
238
+ if (command === "right") {
239
+ this.position = start
240
+ this.fail("Unexpected \\right")
241
+ }
242
+ if (command in accents) {
243
+ return { type: "accent", accent: accents[command], body: this.parseArgument() }
244
+ }
245
+ if (command in variants) {
246
+ return {
247
+ type: "variant",
248
+ variant: variants[command],
249
+ body: command === "textrm" ? { type: "text", value: this.readTextGroup() } : this.parseArgument(),
250
+ }
251
+ }
252
+ if (command === "text" || command === "mbox") return { type: "text", value: this.readTextGroup() }
253
+ if (command === "operatorname") {
254
+ const limits = this.peek() === "*"
255
+ if (limits) this.position++
256
+ return { type: "operator", value: this.readTextGroup(), limits }
257
+ }
258
+ if (command === "overset" || command === "stackrel") {
259
+ const over = this.parseArgument()
260
+ const base = this.parseArgument()
261
+ return { type: "overunder", base, over }
262
+ }
263
+ if (command === "underset") {
264
+ const under = this.parseArgument()
265
+ const base = this.parseArgument()
266
+ return { type: "overunder", base, under }
267
+ }
268
+ if (command === "overbrace" || command === "underbrace") {
269
+ return { type: "brace", body: this.parseArgument(), position: command === "overbrace" ? "over" : "under" }
270
+ }
271
+ if (command === "textcolor") {
272
+ const color = this.readRawGroup()
273
+ return { type: "color", color, body: this.parseArgument() }
274
+ }
275
+ if (command === "color") {
276
+ const color = this.readRawGroup()
277
+ return { type: "color", color, body: row(this.parseRow()) }
278
+ }
279
+ if (command === "not") {
280
+ const target = this.parseAtom()
281
+ if (target.type === "symbol") return { ...target, value: negateSymbol(target.value) }
282
+ return { type: "row", body: [{ type: "symbol", value: "¬" }, target] }
283
+ }
284
+ if (command === "pmod") {
285
+ return {
286
+ type: "row",
287
+ body: [
288
+ { type: "space", width: 1 },
289
+ { type: "text", value: "(mod " },
290
+ this.parseArgument(),
291
+ { type: "text", value: ")" },
292
+ ],
293
+ }
294
+ }
295
+ if (command === "mod" || command === "bmod") return { type: "operator", value: "mod", limits: false }
296
+ if (command === "displaylines") {
297
+ this.skipMathWhitespace()
298
+ this.expect("{")
299
+ return this.parseMatrix("gathered", "}")
300
+ }
301
+ if (
302
+ command === "limits" ||
303
+ command === "nolimits" ||
304
+ command === "displaystyle" ||
305
+ command === "textstyle" ||
306
+ command === "scriptstyle" ||
307
+ command === "scriptscriptstyle"
308
+ ) {
309
+ return { type: "row", body: [] }
310
+ }
311
+ if (/^(?:big|Big|bigg|Bigg)[lrm]?$/.test(command)) {
312
+ return { type: "symbol", value: this.readDelimiter() }
313
+ }
314
+ if (command in spacingCommands) return { type: "space", width: spacingCommands[command] }
315
+ if (command in symbolTable) {
316
+ const symbol = symbolTable[command]
317
+ return { type: "symbol", value: symbol.value, ...(symbol.role ? { role: symbol.role } : {}) }
318
+ }
319
+ if (command in largeOperators) {
320
+ return { type: "operator", value: largeOperators[command], limits: !command.includes("int") }
321
+ }
322
+ if (namedOperators.has(command)) {
323
+ return {
324
+ type: "operator",
325
+ value: command,
326
+ limits: command.startsWith("lim") || command === "min" || command === "max",
327
+ }
328
+ }
329
+ if (command === "backslash") return { type: "symbol", value: "\\" }
330
+ const delimiter = delimiterTable[`\\${command}`] ?? delimiterTable[command]
331
+ if (delimiter !== undefined) return { type: "symbol", value: delimiter }
332
+ if (command === "{" || command === "}") return { type: "symbol", value: command }
333
+ if (command === "%" || command === "#" || command === "$" || command === "&" || command === "_") {
334
+ return { type: "symbol", value: command }
335
+ }
336
+
337
+ if (this.strict) this.fail(`Unsupported command \\${command}`, start)
338
+ return { type: "text", value: `\\${command}` }
339
+ }
340
+
341
+ private parseEnvironment(): MathNode {
342
+ const rawEnvironment = this.readRawGroup()
343
+ const unstarredEnvironment = rawEnvironment.endsWith("*") ? rawEnvironment.slice(0, -1) : rawEnvironment
344
+ const environment = matrixEnvironments.find((name) => name === unstarredEnvironment)
345
+ if (!environment) {
346
+ if (this.strict) this.fail(`Unsupported environment ${unstarredEnvironment}`)
347
+ const content = this.readUntilEnd(rawEnvironment)
348
+ return { type: "text", value: content }
349
+ }
350
+ const columns = environment === "array" ? this.readRawGroup().replace(/\s/g, "") : undefined
351
+ if (columns !== undefined && (!/^[lcr|]+$/.test(columns) || !/[lcr]/.test(columns))) {
352
+ this.fail("Unsupported array columns; expected l, c, r, and |")
353
+ }
354
+ return this.parseMatrix(environment, `\\end{${rawEnvironment}}`, columns)
355
+ }
356
+
357
+ private parseMatrix(environment: MatrixEnvironment, end: string, columns?: string): MathNode {
358
+ const rows: MathNode[][] = []
359
+ let cells: MathNode[] = []
360
+
361
+ while (!this.done()) {
362
+ this.skipMathWhitespace()
363
+ if (this.source.startsWith(end, this.position) && cells.length === 0) break
364
+
365
+ const cellStart = this.position
366
+ const cell = row(
367
+ this.parseRow(
368
+ () =>
369
+ this.peek() === "&" ||
370
+ this.source.startsWith("\\\\", this.position) ||
371
+ this.source.startsWith(end, this.position),
372
+ ),
373
+ )
374
+ cells.push(cell)
375
+ this.skipMathWhitespace()
376
+
377
+ if (this.peek() === "&") {
378
+ this.position++
379
+ continue
380
+ }
381
+ if (this.source.startsWith("\\\\", this.position)) {
382
+ this.position += 2
383
+ this.consumeOptionalBracket()
384
+ rows.push(cells)
385
+ cells = []
386
+ continue
387
+ }
388
+ if (this.source.startsWith(end, this.position)) break
389
+ // Empty cells are valid only when a cell, row, or closing delimiter advances the parser.
390
+ if (this.position === cellStart) this.fail(`Unexpected "${this.peek()}" in ${environment}`)
391
+ }
392
+
393
+ if (!this.source.startsWith(end, this.position)) this.fail(`Missing ${end}`)
394
+ this.expect(end)
395
+ if (cells.length > 0 || rows.length === 0) rows.push(cells)
396
+ return { type: "matrix", rows, environment, ...(columns !== undefined ? { columns } : {}) }
397
+ }
398
+
399
+ private parseLeftRight(): MathNode {
400
+ const left = this.readDelimiter()
401
+ const atRight = () =>
402
+ this.source.startsWith("\\right", this.position) && !/[A-Za-z@]/.test(this.source[this.position + 6] ?? "")
403
+ const body = row(this.parseRow(atRight))
404
+ if (!atRight()) this.fail("Missing \\right")
405
+ this.readCommand()
406
+ const right = this.readDelimiter()
407
+ return { type: "delimited", left, body, right }
408
+ }
409
+
410
+ private parseArgument(): MathNode {
411
+ this.skipMathWhitespace()
412
+ if (this.peek() === "{") return this.parseGroup()
413
+ if (this.done()) this.fail("Expected an argument")
414
+ return this.parseAtom()
415
+ }
416
+
417
+ private parseGroup(): MathNode {
418
+ this.expect("{")
419
+ const body = row(this.parseRow())
420
+ this.expect("}")
421
+ return body
422
+ }
423
+
424
+ private parseOptionalArgument(): MathNode | undefined {
425
+ this.skipMathWhitespace()
426
+ if (this.peek() !== "[") return undefined
427
+ this.position++
428
+ const body = row(this.parseRow(() => this.peek() === "]"))
429
+ this.expect("]")
430
+ return body
431
+ }
432
+
433
+ private consumeOptionalBracket(): void {
434
+ this.skipMathWhitespace()
435
+ if (this.peek() !== "[") return
436
+ let depth = 0
437
+ while (!this.done()) {
438
+ const char = this.source[this.position++]
439
+ if (char === "[") depth++
440
+ if (char === "]" && --depth === 0) return
441
+ }
442
+ }
443
+
444
+ private readDelimiter(): string {
445
+ this.skipMathWhitespace()
446
+ if (this.done()) this.fail("Expected a delimiter")
447
+ const start = this.position
448
+ if (this.peek() === "\\") {
449
+ const command = this.readCommand()
450
+ const delimiter = delimiterTable[`\\${command}`] ?? delimiterTable[command]
451
+ if (delimiter !== undefined) return delimiter
452
+ if (this.strict) this.fail(`Unsupported delimiter \\${command}`, start)
453
+ return `\\${command}`
454
+ }
455
+ const token = this.source[this.position++]
456
+ return delimiterTable[token] ?? token
457
+ }
458
+
459
+ private readCommand(): string {
460
+ this.expect("\\")
461
+ if (this.done()) return "\\"
462
+ const next = this.peek()
463
+ if (!/[A-Za-z@]/.test(next)) {
464
+ this.position++
465
+ return next
466
+ }
467
+
468
+ const start = this.position
469
+ while (!this.done() && /[A-Za-z@]/.test(this.peek())) this.position++
470
+ const command = this.source.slice(start, this.position)
471
+ if (this.peek() === " ") this.position++
472
+ return command
473
+ }
474
+
475
+ private readRawGroup(): string {
476
+ this.skipMathWhitespace()
477
+ this.expect("{")
478
+ const start = this.position
479
+ let depth = 1
480
+ while (!this.done()) {
481
+ const char = this.source[this.position++]
482
+ const escaped = (char === "{" || char === "}") && this.isEscaped(this.position - 1)
483
+ if (char === "{" && !escaped) depth++
484
+ if (char === "}" && !escaped && --depth === 0) return this.source.slice(start, this.position - 1)
485
+ }
486
+ return this.fail("Unterminated group", start)
487
+ }
488
+
489
+ private applyLimitsModifier(body: MathNode[]): boolean {
490
+ const match = /^\\(limits|nolimits)(?![A-Za-z@])/.exec(this.source.slice(this.position))
491
+ if (!match) return false
492
+ this.position += match[0].length
493
+
494
+ const target = body.at(-1)
495
+ const operator =
496
+ target?.type === "operator"
497
+ ? target
498
+ : target?.type === "scripts" && target.base.type === "operator"
499
+ ? target.base
500
+ : undefined
501
+ if (operator) operator.limits = match[1] === "limits"
502
+ return true
503
+ }
504
+
505
+ private isEscaped(index: number): boolean {
506
+ let slashCount = 0
507
+ for (let cursor = index - 1; cursor >= 0 && this.source[cursor] === "\\"; cursor--) slashCount++
508
+ return slashCount % 2 === 1
509
+ }
510
+
511
+ private readTextGroup(): string {
512
+ return this.readRawGroup()
513
+ .replace(/\\([A-Za-z@]+|.)/g, (match, command: string) => {
514
+ if ("{}%#$&_ ".includes(command)) return command
515
+ if (command === "textbackslash") return "\\"
516
+ if (command === "!") return ""
517
+ if (command in spacingCommands) return " ".repeat(Math.max(1, spacingCommands[command]))
518
+ return match
519
+ })
520
+ .replace(/~/g, " ")
521
+ }
522
+
523
+ private readUntilEnd(environment: string): string {
524
+ const marker = `\\end{${environment}}`
525
+ const end = this.source.indexOf(marker, this.position)
526
+ if (end < 0) this.fail(`Missing ${marker}`)
527
+ const content = this.source.slice(this.position, end)
528
+ this.position = end + marker.length
529
+ return content
530
+ }
531
+
532
+ private skipMathWhitespace(): void {
533
+ while (!this.done()) {
534
+ if (/\s/.test(this.peek())) {
535
+ this.position++
536
+ continue
537
+ }
538
+ if (this.peek() === "%") {
539
+ while (!this.done() && this.peek() !== "\n") this.position++
540
+ continue
541
+ }
542
+ break
543
+ }
544
+ }
545
+
546
+ private expect(value: string): void {
547
+ if (!this.source.startsWith(value, this.position)) this.fail(`Expected "${value}"`)
548
+ this.position += value.length
549
+ }
550
+
551
+ private peek(): string {
552
+ return this.source[this.position] ?? ""
553
+ }
554
+
555
+ private done(): boolean {
556
+ return this.position >= this.source.length
557
+ }
558
+
559
+ private fail(message: string, position = this.position): never {
560
+ throw new LatexParseError(message, position)
561
+ }
562
+ }
563
+
564
+ function row(body: MathNode[]): MathNode {
565
+ if (body.length === 1) return body[0]
566
+ return { type: "row", body }
567
+ }
568
+
569
+ function inferRole(value: string): "binary" | "relation" | "punctuation" | "opening" | "closing" | "ordinary" {
570
+ if ("+-*/×÷±∓".includes(value)) return "binary"
571
+ if ("=<>≤≥≠≈∈∉⊂⊃".includes(value)) return "relation"
572
+ if (",;:".includes(value)) return "punctuation"
573
+ if ("([{".includes(value)) return "opening"
574
+ if (")]}".includes(value)) return "closing"
575
+ return "ordinary"
576
+ }
577
+
578
+ function negateSymbol(value: string): string {
579
+ const negated: Record<string, string> = {
580
+ "=": "≠",
581
+ "∈": "∉",
582
+ "∋": "∌",
583
+ "≡": "≢",
584
+ "≈": "≉",
585
+ "∼": "≁",
586
+ "<": "≮",
587
+ ">": "≯",
588
+ "≤": "≰",
589
+ "≥": "≱",
590
+ "⊂": "⊄",
591
+ "⊃": "⊅",
592
+ "⊆": "⊈",
593
+ "⊇": "⊉",
594
+ "∣": "∤",
595
+ "∥": "∦",
596
+ }
597
+ return negated[value] ?? `${value}̸`
598
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { Plugin } from "@zyro-sec/plugin/tui"
2
+ import { createLatexCodeBlockRenderer } from "./markdown"
3
+
4
+ export default Plugin.define({
5
+ id: "opencode.latex",
6
+ setup(context) {
7
+ const render = createLatexCodeBlockRenderer(context.renderer, () => ({
8
+ text: context.theme.text.base,
9
+ subdued: context.theme.text.muted,
10
+ }))
11
+ context.markdown.registerCodeBlockRenderer("latex", render)
12
+ context.markdown.registerCodeBlockRenderer("math", render)
13
+ },
14
+ })
@@ -0,0 +1,87 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { renderLatex, renderLatexToString } from "./render"
3
+
4
+ describe("renderLatexToString", () => {
5
+ test("renders a fraction with a centered rule", () => {
6
+ expect(renderLatexToString(String.raw`\frac{x+1}{y-1}`)).toBe([" x + 1", "───────", " y - 1"].join("\n"))
7
+ })
8
+
9
+ test.each([
10
+ [String.raw`E = mc^2`, "E = mc²"],
11
+ [String.raw`a_n`, "aₙ"],
12
+ [String.raw`x_i^2`, "x²ᵢ"],
13
+ [String.raw`x^{}`, "x"],
14
+ [String.raw`x_{}`, "x"],
15
+ [String.raw`x^{}_{}`, "x"],
16
+ [String.raw`x^m_1`, " m\nx\n 1"],
17
+ [String.raw`x^2_q`, " 2\nx\n q"],
18
+ [String.raw`x^{\frac{1}{2}}_1`, " 1\n ───\n 2\nx\n 1"],
19
+ ])("compacts scripts only when every script is supported: %s", (source, expected) => {
20
+ expect(renderLatexToString(source)).toBe(expected)
21
+ })
22
+
23
+ test("respects script and display mode options", () => {
24
+ expect(renderLatexToString(String.raw`x_i^2`, { compactScripts: false })).toBe(" 2\nx\n i")
25
+ expect(renderLatexToString(String.raw`\sum_1^n`, { displayMode: false })).toBe("∑ⁿ₁")
26
+ expect(renderLatexToString(String.raw`\sum_1^n`, { compactScripts: false })).toBe("n\n∑\n1")
27
+ })
28
+
29
+ test("centers binomials around an empty math-axis row", () => {
30
+ expect(renderLatexToString(String.raw`P = \binom{n}{k}`)).toBe([" ⎛ n ⎞", "P = ⎜ ⎟", " ⎝ k ⎠"].join("\n"))
31
+ })
32
+
33
+ test("renders roots with a vinculum", () => {
34
+ expect(renderLatexToString(String.raw`\sqrt{x^2+y^2}`)).toBe([" ╭───────", "╰╯x² + y²"].join("\n"))
35
+ })
36
+
37
+ test("renders matrices with stretching delimiters", () => {
38
+ expect(renderLatexToString(String.raw`\begin{pmatrix}a & b \\ c & d\end{pmatrix}`)).toBe(
39
+ ["⎛a b⎞", "⎜ ⎟", "⎝c d⎠"].join("\n"),
40
+ )
41
+ })
42
+
43
+ test("places display operator limits above and below", () => {
44
+ expect(renderLatexToString(String.raw`\sum_{i=1}^{n} i^2`)).toBe([" n", " ∑ i²", "i = 1"].join("\n"))
45
+ })
46
+
47
+ test("returns intrinsic geometry and baseline", () => {
48
+ const layout = renderLatex(String.raw`\frac{1}{2}`)
49
+ expect(layout.width).toBe(3)
50
+ expect(layout.height).toBe(3)
51
+ expect(layout.baseline).toBe(1)
52
+ })
53
+
54
+ test("renders blackboard, calligraphic, and fraktur alphabets", () => {
55
+ expect(renderLatexToString(String.raw`\mathbb{R} \to \mathcal{C} \times \mathfrak{g}`)).toBe("ℝ → 𝒞 × 𝔤")
56
+ })
57
+
58
+ test("preserves inherited styles through nested variants and colors", () => {
59
+ const layout = renderLatex(String.raw`\mathbf{\mathsf{\textcolor{red}{\mathit{x}}}}`)
60
+ expect(layout.cells[0][0]).toEqual({ char: "x", style: { bold: true, italic: true, color: "red" } })
61
+ })
62
+
63
+ test("renders nested fractions without flattening their structure", () => {
64
+ const result = renderLatexToString(String.raw`\frac{1}{1+\frac{1}{x}}`)
65
+ expect(result.split("\n")).toHaveLength(5)
66
+ expect(result.match(/─/g)?.length).toBeGreaterThanOrEqual(10)
67
+ })
68
+
69
+ test("renders common textbook structures", () => {
70
+ const result = renderLatexToString(String.raw`\left[\frac{-b \pm \sqrt{b^2-4ac}}{2a}\right]`)
71
+ expect(result).toContain("±")
72
+ expect(result).toContain("╰╯")
73
+ expect(result).toContain("─")
74
+ expect(result).toContain("⎡")
75
+ expect(result).toContain("⎦")
76
+ })
77
+
78
+ test("places fallback combining negation after the base symbol", () => {
79
+ const result = renderLatexToString(String.raw`\not\rightarrow`)
80
+ expect(Array.from(result)).toEqual(["→", "̸"])
81
+ })
82
+
83
+ test("treats square brackets as ordinary interval delimiters", () => {
84
+ expect(renderLatexToString(String.raw`x\in[0,1]`)).toBe("x ∈ [0,1]")
85
+ expect(renderLatexToString(String.raw`[-1,1]`)).toBe("[-1,1]")
86
+ })
87
+ })