formula-composer 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +122 -2
- package/angular/esm2020/formula-composer-tinymce-angular.mjs +4 -0
- package/angular/esm2020/lib/formula-composer.directive.mjs +52 -0
- package/angular/esm2020/lib/formula-composer.module.mjs +21 -0
- package/angular/esm2020/lib/init.mjs +9 -0
- package/angular/esm2020/lib/provide.mjs +11 -0
- package/angular/esm2020/public-api.mjs +8 -0
- package/angular/fesm2015/formula-composer-tinymce-angular.mjs +99 -0
- package/angular/fesm2020/formula-composer-tinymce-angular.mjs +101 -0
- package/angular/formula-composer-tinymce-angular.d.ts +5 -0
- package/angular/lib/formula-composer.directive.d.ts +22 -0
- package/angular/lib/formula-composer.module.d.ts +15 -0
- package/angular/lib/init.d.ts +23 -0
- package/angular/lib/provide.d.ts +10 -0
- package/angular/package.json +10 -0
- package/angular/public-api.d.ts +5 -0
- package/dist/editor-ui/catalog-types.d.ts +30 -0
- package/dist/editor-ui/catalog.generated.d.ts +2 -0
- package/dist/editor-ui/commands.d.ts +44 -0
- package/dist/editor-ui/dom.d.ts +8 -0
- package/dist/editor-ui/editor.d.ts +86 -0
- package/dist/editor-ui/icons.d.ts +5 -0
- package/dist/editor-ui/index.d.ts +9 -0
- package/dist/editor-ui/index.js +119 -0
- package/dist/editor-ui/modal.d.ts +81 -0
- package/dist/editor-ui/periodic.d.ts +8 -0
- package/dist/editor-ui/pickers.d.ts +23 -0
- package/dist/editor-ui/popover.d.ts +24 -0
- package/dist/editor-ui/special-chars.generated.d.ts +10 -0
- package/dist/editor-ui/strings.d.ts +48 -0
- package/dist/editor-ui/styles.d.ts +3 -0
- package/dist/editor-ui/toolbar.d.ts +47 -0
- package/dist/integration/content.d.ts +52 -0
- package/dist/integration/controller.d.ts +76 -0
- package/dist/integration/index.d.ts +3 -0
- package/dist/integration/index.js +1 -0
- package/dist/integration/options.d.ts +46 -0
- package/dist/math-core/a11y.d.ts +3 -0
- package/dist/math-core/caret-speech.d.ts +3 -0
- package/dist/math-core/editor.d.ts +212 -0
- package/dist/math-core/functions.d.ts +8 -0
- package/dist/math-core/history.d.ts +16 -0
- package/dist/math-core/index.d.ts +17 -0
- package/dist/math-core/index.js +3 -0
- package/dist/math-core/latex/parse.d.ts +11 -0
- package/dist/math-core/latex/serialize.d.ts +4 -0
- package/dist/math-core/latex/symbols.d.ts +32 -0
- package/dist/math-core/mathml.d.ts +33 -0
- package/dist/math-core/model.d.ts +69 -0
- package/dist/math-core/safe-xml.d.ts +7 -0
- package/dist/math-core/sanitize.d.ts +6 -0
- package/dist/math-core/tree-index.d.ts +26 -0
- package/dist/math-core/xml.d.ts +21 -0
- package/dist/renderer/alphanumerics.d.ts +3 -0
- package/dist/renderer/attributes.d.ts +10 -0
- package/dist/renderer/core.d.ts +13 -0
- package/dist/renderer/image.d.ts +29 -0
- package/dist/renderer/index.d.ts +22 -0
- package/dist/renderer/index.js +9 -0
- package/dist/renderer/layout.d.ts +14 -0
- package/dist/renderer/styles.d.ts +9 -0
- package/dist/renderer/view.d.ts +30 -0
- package/dist/renderer/vnode.d.ts +25 -0
- package/dist/tinymce/browser/plugin.min.js +129 -0
- package/dist/tinymce/compat.d.ts +24 -0
- package/dist/tinymce/index.d.ts +5 -0
- package/dist/tinymce/index.js +1 -0
- package/dist/tinymce/init.d.ts +22 -0
- package/dist/tinymce/plugin.d.ts +30 -0
- package/dist/tinymce/tinymce-types.d.ts +127 -0
- package/dist/tinymce-react/editor.d.ts +19 -0
- package/dist/tinymce-react/index.d.ts +3 -0
- package/dist/tinymce-react/index.js +1 -0
- package/dist/tinymce-react/init.d.ts +23 -0
- package/editor-ui/package.json +6 -0
- package/images/edit-formula.png +0 -0
- package/images/editor-content.png +0 -0
- package/integration/package.json +6 -0
- package/math-core/package.json +6 -0
- package/package.json +101 -4
- package/react/package.json +6 -0
- package/renderer/package.json +6 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { type ElementNode, type MathDocument, type MathNode, type RowNode } from './model.js';
|
|
2
|
+
import { type TreeIndex } from './tree-index.js';
|
|
3
|
+
export interface Caret {
|
|
4
|
+
rowId: number;
|
|
5
|
+
offset: number;
|
|
6
|
+
}
|
|
7
|
+
export interface SelectionRange {
|
|
8
|
+
row: RowNode;
|
|
9
|
+
start: number;
|
|
10
|
+
end: number;
|
|
11
|
+
}
|
|
12
|
+
export interface InputStyle {
|
|
13
|
+
bold: boolean;
|
|
14
|
+
/** `null` means automatic italic (single-letter identifiers italic, everything else upright). */
|
|
15
|
+
italic: boolean | null;
|
|
16
|
+
color: string | null;
|
|
17
|
+
textMode: boolean;
|
|
18
|
+
}
|
|
19
|
+
export type LineStyle = 'solid' | 'dashed';
|
|
20
|
+
export type VerticalDirection = 'up' | 'down';
|
|
21
|
+
export type MatrixKind = 'table' | 'parentheses' | 'brackets' | 'bars';
|
|
22
|
+
export type ContextKind = 'table' | 'fence' | 'operator' | 'number' | 'space' | 'stack' | 'none';
|
|
23
|
+
export interface TableContext {
|
|
24
|
+
table: ElementNode;
|
|
25
|
+
rowIndex: number;
|
|
26
|
+
columnIndex: number;
|
|
27
|
+
rowCount: number;
|
|
28
|
+
columnCount: number;
|
|
29
|
+
}
|
|
30
|
+
/** The token a character is inserted as, when it is not the one typing it would give (PU-002). */
|
|
31
|
+
export interface CharacterToken {
|
|
32
|
+
readonly tag: 'mi' | 'mn' | 'mo';
|
|
33
|
+
/** Text of the token when it differs from the character, e.g. `A` with `mathvariant="monospace"` for U+1D670. */
|
|
34
|
+
readonly text?: string;
|
|
35
|
+
readonly mathvariant?: string;
|
|
36
|
+
}
|
|
37
|
+
export interface MathEditorModelOptions {
|
|
38
|
+
historyLimit?: number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Editing model for one formula: document, caret/selection, commands and undo history.
|
|
42
|
+
* Pure TypeScript with no DOM dependency.
|
|
43
|
+
*/
|
|
44
|
+
export declare class MathEditorModel {
|
|
45
|
+
private doc;
|
|
46
|
+
private index;
|
|
47
|
+
private caret;
|
|
48
|
+
private anchor;
|
|
49
|
+
private readonly history;
|
|
50
|
+
private style;
|
|
51
|
+
private lineStyle;
|
|
52
|
+
private docRevision;
|
|
53
|
+
private readonly listeners;
|
|
54
|
+
constructor(options?: MathEditorModelOptions);
|
|
55
|
+
onChange(listener: () => void): () => void;
|
|
56
|
+
private emit;
|
|
57
|
+
get document(): Readonly<MathDocument>;
|
|
58
|
+
getMathML(): string;
|
|
59
|
+
/** Replaces the content. History is cleared unless `keepHistory` is set. */
|
|
60
|
+
setMathML(mathml: string, keepHistory?: boolean): void;
|
|
61
|
+
setDocument(doc: MathDocument): void;
|
|
62
|
+
isEmpty(): boolean;
|
|
63
|
+
get treeIndex(): TreeIndex;
|
|
64
|
+
getCaret(): Caret;
|
|
65
|
+
getAnchor(): Caret | null;
|
|
66
|
+
getInputStyle(): Readonly<InputStyle>;
|
|
67
|
+
getLineStyle(): LineStyle;
|
|
68
|
+
currentRow(): RowNode;
|
|
69
|
+
setCaret(caret: Caret, extend?: boolean): void;
|
|
70
|
+
select(anchor: Caret, focus: Caret): void;
|
|
71
|
+
selectAll(): void;
|
|
72
|
+
/** Selects the atom at `index` in `rowId`. */
|
|
73
|
+
selectAtom(rowId: number, index: number): void;
|
|
74
|
+
clearSelection(): void;
|
|
75
|
+
/** Selection normalised to a contiguous range of one row; `null` when collapsed. */
|
|
76
|
+
getSelection(): SelectionRange | null;
|
|
77
|
+
hasSelection(): boolean;
|
|
78
|
+
moveRight(extend?: boolean): void;
|
|
79
|
+
moveLeft(extend?: boolean): void;
|
|
80
|
+
private exitRow;
|
|
81
|
+
/** Home/End leave nested slots for the start/end of the current line; with Shift they stay in the row. */
|
|
82
|
+
moveHome(extend?: boolean): void;
|
|
83
|
+
moveEnd(extend?: boolean): void;
|
|
84
|
+
/** Caret position projected onto the root row (the index of the top-level atom holding the caret). */
|
|
85
|
+
private rootOffset;
|
|
86
|
+
/** Structural vertical move (numerator/denominator, scripts, table rows). Returns false if nothing above/below. */
|
|
87
|
+
moveVertical(direction: VerticalDirection): boolean;
|
|
88
|
+
private verticalTarget;
|
|
89
|
+
/** Moves to the next/previous empty slot (Tab-like navigation used by the UI when configured). */
|
|
90
|
+
moveToSlot(forward: boolean): boolean;
|
|
91
|
+
private snapshot;
|
|
92
|
+
private restore;
|
|
93
|
+
private reindex;
|
|
94
|
+
/** Increases whenever the document structure may have changed (not on caret moves). */
|
|
95
|
+
get revision(): number;
|
|
96
|
+
/** Runs a mutation as one undo step. `fn` returns false when nothing changed. */
|
|
97
|
+
private mutate;
|
|
98
|
+
private removeSelection;
|
|
99
|
+
/** Inserts at the caret; content typed into or next to an empty argument placeholder replaces it. */
|
|
100
|
+
private insertAtCaret;
|
|
101
|
+
/** The negate template followed by a relation yields the precomposed negated symbol (`=` → `≠`). */
|
|
102
|
+
private negateInPlace;
|
|
103
|
+
private tokenAttrs;
|
|
104
|
+
private classify;
|
|
105
|
+
/**
|
|
106
|
+
* Types one character with MathType rules (digits → mn, letters → mi, others → mo, space → NBSP operator).
|
|
107
|
+
* `as` gives the token MathType's special-characters popup inserts for `ch` when it differs from those rules.
|
|
108
|
+
*/
|
|
109
|
+
typeCharacter(ch: string, as?: CharacterToken): void;
|
|
110
|
+
typeText(text: string): void;
|
|
111
|
+
private mergeFunctionName;
|
|
112
|
+
insertNewline(): void;
|
|
113
|
+
private canBeScriptBase;
|
|
114
|
+
/** Index of the opening fence that matches the closing fence at `close`, or -1. */
|
|
115
|
+
private matchingOpen;
|
|
116
|
+
/** Removes and returns the element before the caret that should become a script base. */
|
|
117
|
+
private takePreviousBase;
|
|
118
|
+
/**
|
|
119
|
+
* Inserts MathML at the caret. Template semantics: a non-empty selection goes into the argument
|
|
120
|
+
* slot (`maction actiontype="argument"`) or the first slot; a script template with an argument base
|
|
121
|
+
* takes the previous element. The caret lands in the first empty slot.
|
|
122
|
+
*/
|
|
123
|
+
insertMathML(mathml: string): boolean;
|
|
124
|
+
/** A plain fraction template typed inside another fraction keeps display size, like MathType's editor. */
|
|
125
|
+
private isNestedFraction;
|
|
126
|
+
insertMatrix(rows: number, columns: number, kind?: MatrixKind): boolean;
|
|
127
|
+
deleteBackward(): void;
|
|
128
|
+
deleteForward(): void;
|
|
129
|
+
/** At the edge of a slot: empty templates are removed, otherwise the template gets selected. */
|
|
130
|
+
private deleteAtSlotBoundary;
|
|
131
|
+
clear(): void;
|
|
132
|
+
/** MathML of the selection, or `null` when nothing is selected. */
|
|
133
|
+
copySelection(): string | null;
|
|
134
|
+
cutSelection(): string | null;
|
|
135
|
+
/** Pastes MathML (or plain text typed character by character). */
|
|
136
|
+
paste(content: string): boolean;
|
|
137
|
+
/** Inserts already-parsed nodes (e.g. from the LaTeX parser). */
|
|
138
|
+
insertNodes(nodes: MathNode[]): boolean;
|
|
139
|
+
undo(): boolean;
|
|
140
|
+
redo(): boolean;
|
|
141
|
+
canUndo(): boolean;
|
|
142
|
+
canRedo(): boolean;
|
|
143
|
+
private selectedTokens;
|
|
144
|
+
toggleBold(): void;
|
|
145
|
+
toggleItalic(): void;
|
|
146
|
+
/** Restores automatic italic: single-letter identifiers italic, the rest upright. */
|
|
147
|
+
setAutoItalic(): void;
|
|
148
|
+
/** Regular text mode: typed characters become `mtext`. Applied to a selection, tokens become upright. */
|
|
149
|
+
setTextMode(enabled: boolean): void;
|
|
150
|
+
setColor(color: string | null): void;
|
|
151
|
+
/** Wraps the selection in `<mstyle mathsize>`; without a selection, sizes the whole formula as MathType does. */
|
|
152
|
+
setFontSize(size: string | null): void;
|
|
153
|
+
/** Size of the whole formula, or `null` when it has none. */
|
|
154
|
+
getFontSize(): string | null;
|
|
155
|
+
setFontFamily(family: string | null): void;
|
|
156
|
+
getFontFamily(): string | null;
|
|
157
|
+
/** Sets (or removes) an attribute of the `<math>` element, e.g. `indentalign` for multi-line formulas. */
|
|
158
|
+
setDocumentAttribute(name: string, value: string | null): boolean;
|
|
159
|
+
hasLineBreaks(): boolean;
|
|
160
|
+
isRtl(): boolean;
|
|
161
|
+
toggleRtl(): void;
|
|
162
|
+
/** Sets (or removes) an attribute on every token of the selection, or on the atom before the caret. */
|
|
163
|
+
setTokenAttribute(name: string, value: string | null): boolean;
|
|
164
|
+
/** Atom immediately before the caret, if any. */
|
|
165
|
+
previousAtom(): MathNode | null;
|
|
166
|
+
contextKind(): ContextKind;
|
|
167
|
+
fenceContext(): ElementNode | null;
|
|
168
|
+
setFence(attrs: {
|
|
169
|
+
open?: string;
|
|
170
|
+
close?: string;
|
|
171
|
+
separators?: string;
|
|
172
|
+
}): boolean;
|
|
173
|
+
tableContext(): TableContext | null;
|
|
174
|
+
private newCell;
|
|
175
|
+
tableInsertRow(position: 'above' | 'below'): boolean;
|
|
176
|
+
tableInsertColumn(position: 'left' | 'right'): boolean;
|
|
177
|
+
tableRemoveRow(): boolean;
|
|
178
|
+
tableRemoveColumn(): boolean;
|
|
179
|
+
private adjustList;
|
|
180
|
+
private adjustLines;
|
|
181
|
+
setLineStyle(style: LineStyle): void;
|
|
182
|
+
/** Adds or removes the line below the current row (`rowlines`) or right of the current column (`columnlines`). */
|
|
183
|
+
setTableLine(kind: 'row' | 'column', present: boolean): boolean;
|
|
184
|
+
setTableFrame(present: boolean): boolean;
|
|
185
|
+
/** Sets the alignment of the current column (`columnalign` list). */
|
|
186
|
+
setColumnAlign(align: string): boolean;
|
|
187
|
+
/** Sets the vertical alignment of the current row (`rowalign` on `mtr`). */
|
|
188
|
+
setRowAlign(align: string): boolean;
|
|
189
|
+
/** Sets or removes an `mtable` attribute (e.g. `equalrows`, `columnspacing`, `align`). */
|
|
190
|
+
setTableAttribute(name: string, value: string | null): boolean;
|
|
191
|
+
private stackContext;
|
|
192
|
+
stackInsertRow(position: 'before' | 'after'): boolean;
|
|
193
|
+
stackInsertLine(): boolean;
|
|
194
|
+
/** Shifts the current stack row left (+1) or right (-1) via `position`. */
|
|
195
|
+
stackShiftRow(delta: number): boolean;
|
|
196
|
+
setStackAttribute(name: string, value: string | null): boolean;
|
|
197
|
+
/** `mscarries` that applies to the current stack row (the one just above it), or the one holding the caret. */
|
|
198
|
+
private carriesContext;
|
|
199
|
+
hasCarries(): boolean;
|
|
200
|
+
/** Inserts an `mscarries` row above the current stack row, one carry per column. */
|
|
201
|
+
stackInsertCarries(): boolean;
|
|
202
|
+
/** Sets `location`, `crossout` or `scriptsizemultiplier` on the carries of the current row. */
|
|
203
|
+
setCarriesAttribute(name: string, value: string | null): boolean;
|
|
204
|
+
/** Sets (or removes) `width`/`height`/`depth` on the `mspace` before the caret. */
|
|
205
|
+
setSpaceAttribute(name: 'width' | 'height' | 'depth', value: string | null): boolean;
|
|
206
|
+
/** Merges `mn . mn` / `mn , mn` around the caret into one number, or splits a merged number. */
|
|
207
|
+
toggleNumberSeparators(): boolean;
|
|
208
|
+
/** Wraps the selection or previous atom in `mpadded` and nudges it by `em` steps. */
|
|
209
|
+
nudge(dx: number, dy: number): boolean;
|
|
210
|
+
/** Normalised children of the current row (merged numbers), used by renderers that need token runs. */
|
|
211
|
+
static merged(children: readonly MathNode[]): MathNode[];
|
|
212
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Function names recognised while typing; they become a single upright `<mi>` (e.g. `<mi>sin</mi>`).
|
|
3
|
+
* Observed in the reference: sin, cos, log are recognised and `lim` is not. The remaining trigonometric,
|
|
4
|
+
* hyperbolic and logarithmic names are inferred from the same family.
|
|
5
|
+
*/
|
|
6
|
+
export declare const FUNCTION_NAMES: readonly string[];
|
|
7
|
+
export declare const MAX_FUNCTION_NAME_LENGTH: number;
|
|
8
|
+
export declare function isFunctionName(text: string): boolean;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const DEFAULT_HISTORY_LIMIT = 200;
|
|
2
|
+
/** Bounded undo/redo stack of immutable snapshots. */
|
|
3
|
+
export declare class History<T> {
|
|
4
|
+
private readonly limit;
|
|
5
|
+
private undoStack;
|
|
6
|
+
private redoStack;
|
|
7
|
+
constructor(limit?: number);
|
|
8
|
+
push(snapshot: T): void;
|
|
9
|
+
/** Removes the most recent snapshot (used when a command turned out to be a no-op). */
|
|
10
|
+
discardLast(): void;
|
|
11
|
+
undo(current: T): T | null;
|
|
12
|
+
redo(current: T): T | null;
|
|
13
|
+
canUndo(): boolean;
|
|
14
|
+
canRedo(): boolean;
|
|
15
|
+
clear(): void;
|
|
16
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export * from './model.js';
|
|
2
|
+
export * from './xml.js';
|
|
3
|
+
export * from './safe-xml.js';
|
|
4
|
+
export * from './mathml.js';
|
|
5
|
+
export * from './editor.js';
|
|
6
|
+
export * from './history.js';
|
|
7
|
+
export * from './tree-index.js';
|
|
8
|
+
export * from './functions.js';
|
|
9
|
+
export * from './a11y.js';
|
|
10
|
+
export * from './caret-speech.js';
|
|
11
|
+
export * from './sanitize.js';
|
|
12
|
+
export { parseLatex, parseLatexNodes, LatexParseError, colorToHex } from './latex/parse.js';
|
|
13
|
+
export { serializeLatex, nodesToLatexString } from './latex/serialize.js';
|
|
14
|
+
/** LaTeX → MathType-compatible MathML. */
|
|
15
|
+
export declare function latexToMathML(latex: string): string;
|
|
16
|
+
/** MathML → compact LaTeX. */
|
|
17
|
+
export declare function mathMLToLatex(mathml: string): string;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var Cn=Object.defineProperty;var Mn=(e,t,n)=>t in e?Cn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var E=(e,t,n)=>Mn(e,typeof t!="symbol"?t+"":t,n);var me=1;function nt(){return me+=1,me}function h(e=[],t="mrow",n={}){return{kind:"row",id:nt(),tag:t,attrs:{...n},children:e}}function p(e,t,n={}){return{kind:"token",id:nt(),tag:e,attrs:{...n},text:t}}function I(e,t={}){return{kind:"leaf",id:nt(),tag:e,attrs:{...t}}}function c(e,t,n={}){return{kind:"element",id:nt(),tag:e,attrs:{...n},children:t}}function fe(){return{attrs:{},root:h()}}function W(e,t=!1){let n=t?nt():e.id;switch(e.kind){case"row":{let r={...e,id:n,attrs:{...e.attrs},children:e.children.map(o=>W(o,t))};return e.tokenHint&&(r.tokenHint={tag:e.tokenHint.tag,attrs:{...e.tokenHint.attrs}}),r}case"token":case"leaf":return{...e,id:n,attrs:{...e.attrs}};case"element":return{...e,id:n,attrs:{...e.attrs},children:e.children.map(r=>W(r,t))}}}function rt(e,t=!1){return{attrs:{...e.attrs},root:W(e.root,t)}}function So(e){return e?.kind==="row"}var Xt=new Set(["mrow","msqrt","mstyle","menclose","mphantom","mpadded","merror","mtd","maction","mscarry"]),pe={mfrac:2,mroot:2,msub:2,msup:2,msubsup:3,munder:2,mover:2,munderover:3,mfenced:1,msqrt:1,mstyle:1,menclose:1,mphantom:1,mpadded:1,merror:1,mtd:1,maction:1};function To(e){return e.children.length===0}function ct(e,t,n=null){if(t(e,n)!==!1&&(e.kind==="row"||e.kind==="element"))for(let r of e.children)ct(r,t,e)}function Co(e,t){let n=null;return ct(e,(r,o)=>n?!1:r.id===t?(n={node:r,parent:o},!1):!0),n}var L=class extends Error{constructor(n,r){super(`${n} at ${r}`);E(this,"position",r);this.name="XmlParseError"}},In={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",InvisibleTimes:"\u2062",ApplyFunction:"\u2061",InvisibleComma:"\u2063",it:"\u2062",af:"\u2061",ic:"\u2063",minus:"\u2212",plus:"+",times:"\xD7",divide:"\xF7",PlusMinus:"\xB1",pm:"\xB1",infin:"\u221E",int:"\u222B",sum:"\u2211",prod:"\u220F",rarr:"\u2192",larr:"\u2190",le:"\u2264",ge:"\u2265",ne:"\u2260",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",pi:"\u03C0",theta:"\u03B8",lambda:"\u03BB",mu:"\u03BC",sigma:"\u03C3",omega:"\u03C9",middot:"\xB7",sdot:"\u22C5",deg:"\xB0",ThinSpace:"\u2009",VeryThinSpace:"\u200A",NegativeThinSpace:"\u200B",laquo:"\xAB",raquo:"\xBB",uml:"\xA8",sect:"\xA7"};function ge(e){return e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);/g,(t,n)=>{if(n.startsWith("#x")||n.startsWith("#X")){let r=Number.parseInt(n.slice(2),16);return Number.isFinite(r)?String.fromCodePoint(r):t}if(n.startsWith("#")){let r=Number.parseInt(n.slice(1),10);return Number.isFinite(r)?String.fromCodePoint(r):t}return In[n]??t})}var Ln=127;function dt(e,t=!1){let n="";for(let r of e){let o=r.codePointAt(0)??0;r==="&"?n+="&":r==="<"?n+="<":r===">"?n+=">":t&&r==='"'?n+=""":o>Ln?n+=`&#x${o.toString(16).toUpperCase()};`:n+=r}return n}var Gt=/[A-Za-z_:][-A-Za-z0-9_:.]*/y,Ut=/\s*/y;function we(e){let t=0,n=e.length,r=()=>{Ut.lastIndex=t,Ut.exec(e),t=Ut.lastIndex},o=()=>{Gt.lastIndex=t;let l=Gt.exec(e);if(!l)throw new L("Expected name",t);return t=Gt.lastIndex,l[0]},i=l=>{let u=l.indexOf(":");return u>=0?l.slice(u+1):l},s=l=>{let u=[];for(;t<n;){if(e.startsWith("</",t)){t+=2;let m=i(o());if(r(),e[t]!==">")throw new L("Expected >",t);if(t+=1,l===null||m!==l)throw new L(`Unexpected closing tag ${m}`,t);return u}if(e.startsWith("<!--",t)){let m=e.indexOf("-->",t+4);if(m<0)throw new L("Unterminated comment",t);t=m+3;continue}if(e.startsWith("<![CDATA[",t)){let m=e.indexOf("]]>",t+9);if(m<0)throw new L("Unterminated CDATA",t);u.push({type:"text",text:e.slice(t+9,m)}),t=m+3;continue}if(e.startsWith("<?",t)||e.startsWith("<!",t)){let m=e.indexOf(">",t);if(m<0)throw new L("Unterminated declaration",t);t=m+1;continue}if(e[t]==="<"){t+=1;let m=i(o()),R={};for(;;){r();let M=e[t];if(M==="/"&&e[t+1]===">"){t+=2,u.push({type:"element",name:m,attrs:R,children:[]});break}if(M===">"){t+=1;let U=s(m);u.push({type:"element",name:m,attrs:R,children:U});break}if(t>=n)throw new L("Unterminated tag",t);let d=o();if(r(),e[t]!=="="){R[d]="";continue}t+=1,r();let x=e[t];if(x!=='"'&&x!=="'")throw new L("Expected quoted attribute value",t);let S=e.indexOf(x,t+1);if(S<0)throw new L("Unterminated attribute value",t);R[d]=ge(e.slice(t+1,S)),t=S+1}continue}let f=e.indexOf("<",t),b=f<0?n:f;u.push({type:"text",text:ge(e.slice(t,b))}),t=b}if(l!==null)throw new L(`Missing closing tag ${l}`,t);return u};return s(null).filter(l=>l.type==="element")}function ht(e){return e.type==="text"?e.text:e.children.map(ht).join("")}var be=[["<","\xAB"],[">","\xBB"],['"',"\xA8"],["&","\xA7"],["'","`"]],On=/[\u00AB\u00BB\u00A8\u00A7`]/;function xe(e){return e.trimStart().startsWith("\xABmath")}function Oo(e){let t=e;On.test(t)&&(t=t.replace(/[\u00AB\u00BB\u00A8\u00A7`]/g,n=>`&#x${(n.codePointAt(0)??0).toString(16).toUpperCase()};`));for(let[n,r]of be)t=t.split(n).join(r);return t}function ke(e){let t=e;for(let[n,r]of be)t=t.split(r).join(n);return t}var ot={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",Alpha:"A",Beta:"B",Epsilon:"E",Zeta:"Z",Eta:"H",Iota:"I",Kappa:"K",Mu:"M",Nu:"N",Omicron:"O",Rho:"P",Tau:"T",Chi:"X",digamma:"\u03DD",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",hbar:"\u210F",hslash:"\u210F",ell:"\u2113",wp:"\u2118",imath:"\u0131",jmath:"\u0237",i:"\u0131"},Ht={infty:"\u221E",partial:"\u2202",nabla:"\u2207",emptyset:"\u2205",varnothing:"\u2205",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",cap:"\u2229",cup:"\u222A",setminus:"\u2216",smallsetminus:"\u2216",wedge:"\u2227",land:"\u2227",vee:"\u2228",lor:"\u2228",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",triangleleft:"\u25C1",triangleright:"\u25B7",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",diamond:"\u22C4",bigtriangleup:"\u25B3",bigtriangledown:"\u25BD",wr:"\u2240",boxplus:"\u229E",boxminus:"\u229F",boxtimes:"\u22A0",centerdot:"\u22C5",leq:"\u2264",le:"\u2264",geq:"\u2265",ge:"\u2265",neq:"\u2260",ne:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",propto:"\u221D",ll:"\u226A",gg:"\u226B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",subsetneq:"\u228A",supsetneq:"\u228B",nsubseteq:"\u2288",nsupseteq:"\u2289",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",in:"\u2208",notin:"\u2209",ni:"\u220B",owns:"\u220B",perp:"\u22A5",parallel:"\u2225",nparallel:"\u2226",mid:"\u2223",nmid:"\u2224",models:"\u22A8",vdash:"\u22A2",dashv:"\u22A3",prec:"\u227A",succ:"\u227B",preceq:"\u2AAF",succeq:"\u2AB0",doteq:"\u2250",asymp:"\u224D",bowtie:"\u22C8",lessgtr:"\u2276",leqslant:"\u2A7D",geqslant:"\u2A7E",lesssim:"\u2272",gtrsim:"\u2273",nless:"\u226E",ngtr:"\u226F",nleq:"\u2270",ngeq:"\u2271",ncong:"\u2247",nsim:"\u2241",approxeq:"\u224A",triangleq:"\u225C",to:"\u2192",rightarrow:"\u2192",leftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",Rightarrow:"\u21D2",Leftarrow:"\u21D0",Leftrightarrow:"\u21D4",uparrow:"\u2191",downarrow:"\u2193",updownarrow:"\u2195",Uparrow:"\u21D1",Downarrow:"\u21D3",Updownarrow:"\u21D5",mapsto:"\u21A6",longrightarrow:"\u27F6",longleftarrow:"\u27F5",longleftrightarrow:"\u27F7",Longrightarrow:"\u27F9",Longleftarrow:"\u27F8",Longleftrightarrow:"\u27FA",iff:"\u21D4",implies:"\u21D2",impliedby:"\u21D0",longmapsto:"\u27FC",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",hookrightarrow:"\u21AA",hookleftarrow:"\u21A9",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightleftarrows:"\u21C4",leftrightarrows:"\u21C6",twoheadrightarrow:"\u21A0",curvearrowright:"\u21B7",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",lnot:"\xAC",angle:"\u2220",measuredangle:"\u2221",sphericalangle:"\u2222",triangle:"\u2206",square:"\u25A1",Box:"\u25A1",prime:"'",Re:"\u211C",Im:"\u2111",therefore:"\u2234",because:"\u2235",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",degree:"\xB0",top:"\u22A4",bot:"\u22A5",surd:"\u221A",complement:"\u2201",clubsuit:"\u2663",diamondsuit:"\u2662",heartsuit:"\u2661",spadesuit:"\u2660",flat:"\u266D",natural:"\u266E",sharp:"\u266F",checkmark:"\u2713",S:"\xA7",P:"\xB6",colon:":",vert:"|",Vert:"\u2016",Arrowvert:"\u2016",lbrace:"{",rbrace:"}",lbrack:"[",rbrack:"]",langle:"\u27E8",rangle:"\u27E9",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",lvert:"|",rvert:"|",lVert:"\u2016",rVert:"\u2016",backslash:"\\","|":"\u2016","{":"{","}":"}","#":"#",$:"$","%":"%","&":"&",_:"_"},mt={sum:"\u2211",prod:"\u220F",coprod:"\u2210",bigcup:"\u22C3",bigcap:"\u22C2",bigvee:"\u22C1",bigwedge:"\u22C0",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",biguplus:"\u2A04",bigsqcup:"\u2A06",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",oiint:"\u222F",oiiint:"\u2230"},ft={bigcup:"\u222A",bigcap:"\u2229"},Z={B:"\u212C",E:"\u2130",F:"\u2131",H:"\u210B",I:"\u2110",L:"\u2112",M:"\u2133",R:"\u211B"},Re=new Set(["\u222B","\u222C","\u222D","\u222E","\u222F","\u2230","\u2232","\u2233"]),Ne=new Set(Object.values(mt).filter(e=>!Re.has(e))),pt=["sin","cos","tan","cot","sec","csc","sinh","cosh","tanh","coth","arcsin","arccos","arctan","log","ln","lg","exp","lim","limsup","liminf","max","min","sup","inf","det","gcd","Pr","deg","dim","ker","hom","arg"],Ae=new Set(["lim","limsup","liminf","max","min","sup","inf","det","gcd","Pr"]),gt={",":{char:"\u200A"},":":{char:"\u2009"},">":{char:"\u2009"},";":{char:"\xA0"}," ":{char:"\xA0"},quad:{char:"\xA0\xA0"},qquad:{char:"\xA0\xA0\xA0\xA0"},"!":{width:"-0.2em"},enspace:{char:"\u2002"},thinspace:{char:"\u2009"}},wt={hat:"^",widehat:"^",check:"\u02C7",tilde:"~",widetilde:"~",acute:"\xB4",grave:"`",dot:"\u02D9",ddot:"\u2025",dddot:"\u20DB",breve:"\u02D8",bar:"\xAF",vec:"\u2192",mathring:"\u02DA"},ye=new Set(["vec"]),bt={overline:"\xAF",overrightarrow:"\u2192",overleftarrow:"\u2190",overleftrightarrow:"\u2194",overbrace:"\u23DE",overparen:"\u23DC"},xt={underline:"\xAF",underbrace:"\u23DF",underparen:"\u23DD",underrightarrow:"\u2192",underleftarrow:"\u2190"},kt={mathbf:"bold",mathit:"italic",mathrm:"normal",mathbb:"double-struck",mathcal:"script",mathscr:"script",mathfrak:"fraktur",mathsf:"sans-serif",mathtt:"monospace",boldsymbol:"bold-italic",bm:"bold-italic",textbf:"bold",textit:"italic",textrm:"normal",textsf:"sans-serif",texttt:"monospace",mathbfit:"bold-italic",mathsfit:"sans-serif-italic"},it={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},Ee={"(":"(",")":")","[":"[","]":"]","\\{":"{","\\}":"}","|":"|","\\|":"||",".":"","\\langle":"<","\\rangle":">","\\lfloor":"\u230A","\\rfloor":"\u230B","\\lceil":"\u2308","\\rceil":"\u2309","\\vert":"|","\\Vert":"||","\\lvert":"|","\\rvert":"|","\\lVert":"||","\\rVert":"||","<":"<",">":">","\\lbrace":"{","\\rbrace":"}","\\lbrack":"[","\\rbrack":"]","\\llbracket":"\u27E6","\\rrbracket":"\u27E7","/":"/","\\backslash":"\\"},Rt={black:"#000000",white:"#FFFFFF",red:"#FF0000",green:"#00FF00",blue:"#0000FF",cyan:"#00FFFF",magenta:"#FF00FF",yellow:"#FFFF00",gray:"#808080",grey:"#808080",orange:"#FF8000",purple:"#800080",brown:"#A52A2A",pink:"#FFC0CB",lime:"#BFFF00",olive:"#808000",teal:"#008080",violet:"#800080",darkgray:"#404040",lightgray:"#BFBFBF"};function zt(e){let t=new Map;for(let[n,r]of Object.entries(e))r.length>0&&!t.has(r)&&/^[A-Za-z]+$/.test(n)&&t.set(r,n);return t}var st=(()=>{let e=zt(ot);for(let[t,n]of zt(mt))e.has(t)||e.set(t,n);for(let[t,n]of zt(Ht))e.has(t)||e.set(t,n);for(let t of["A","B","E","Z","H","I","K","M","N","O","P","T","X",":","'"])e.delete(t);return e.set("|","vert"),e.set("[","lbrack"),e.set("]","rbrack"),e.set("\u2016","Arrowvert"),e.set("\u210F","hslash"),e.set("\u0131","i"),e.set("\u2209","not\\in"),e.set("\u2192","rightarrow"),e.set("\u2190","leftarrow"),e.set("\u2264","leq"),e.set("\u2265","geq"),e.set("\u2260","neq"),e.set("\xAC","neg"),e.set("\u2205","varnothing"),e.set("\u2227","wedge"),e.set("\u2228","vee"),e.set("\u220B","ni"),e.set("\u27FA","Longleftrightarrow"),e.set("\u27F9","Longrightarrow"),e.set("\u27F8","Longleftarrow"),e.set("\u2026","dots"),e.set("\xA7","S"),e})();var Nt="http://www.w3.org/1998/Math/MathML",Te=new Set(["mi","mn","mo","mtext","ms"]),_n=new Set(["mspace","none","mprescripts","msline","malignmark","maligngroup","mglyph"]),Ce=new Set(["mn","mtext"]),Wt=new Set(["mstack","mlongdiv","msgroup","mscarries"]),Dn=new Set(["mtr","mlabeledtr"]),Me=/^[ \t\n\r]+|[ \t\n\r]+$/g,Vt=2,at="mathsize",Fn={"\u223C":"~","\u2025":"\xA8"},Bn={...Object.fromEntries(Object.entries(Z).map(([e,t])=>[t,{base:e,variant:"script"}])),\u211C:{base:"R",variant:"fraktur"},\u2111:{base:"I",variant:"fraktur"}},Kt=class extends Error{constructor(t){super(t),this.name="MathMLParseError"}};function _(e){return e.children.filter(t=>t.type==="element")}function Ie(e){return ht(e).replace(Me,"")}function $n(e){if(e.type!=="text")return[];let t=e.text.replace(Me,"");return t?[...t].map(n=>p("mtext",n)):[]}function Pn(e){let t=e.name,n=Ie(e);return Ce.has(t)&&n.length>0?[...n].map(r=>p(t,r,e.attrs)):[p(t,n,e.attrs)]}function ve(e){let t=e.mathcolor?Rt[e.mathcolor.toLowerCase()]:void 0;t&&(e.mathcolor=t)}function Le(e){let t=n=>{if(n.kind==="token"){if(ve(n.attrs),n.tag!=="mo")return;let r=Bn[n.text];r&&!n.attrs.mathvariant?(n.text=r.base,n.attrs.mathvariant=r.variant):n.text=Fn[n.text]??n.text;return}if(n.kind!=="leaf"){n.kind==="element"&&ve(n.attrs);for(let r of n.children)t(r)}};t(e.root),qn(e)}function qn(e){let t=e.root.children.length===1?e.root.children[0]:void 0;if(t?.kind!=="element"||t.tag!=="mstyle"||e.attrs[at]!==void 0)return;let n=t.attrs[at],r=t.children[0];n===void 0||Object.keys(t.attrs).length!==1||t.children.length!==1||r?.kind!=="row"||(e.attrs[at]=n,e.root.children=r.children)}function jn(e){if(!Te.has(e.name)||Ie(e)!=="")return null;let t=h();return t.tokenHint={tag:e.name,attrs:{...e.attrs}},t}var yt=null;function Oe(e){return e.name==="maction"&&e.attrs.actiontype==="argument"}function j(e){if(e.name==="mrow"&&Object.keys(e.attrs).length===0)return h(O(e.children));if(Oe(e)){let n=_(e),r=n[0],o=n.length===1&&r?j(r):h(O(e.children));return yt?.add(o.id),o}if(e.name==="none")return h();let t=jn(e);return t||h(H(e))}function Xn(e,t){let n=_(e),r=[];for(let i=0;i<t;i+=1){let s=n[i];r.push(s?j(s):h())}let o=r[t-1];if(o&&n.length>t)for(let i of n.slice(t))o.children.push(...H(i));return c(e.name,r,e.attrs)}function At(e){return c(e.name,[h(O(e.children))],e.attrs)}function Gn(e){let t=_(e),n={...e.attrs};if(t.length<=1){let i=t[0];return c("mfenced",[i?j(i):h()],n)}let r=(n.separators??",").replace(/\s+/g,""),o=[];return t.forEach((i,s)=>{if(s>0&&r.length>0){let a=r[Math.min(s-1,r.length-1)]??",";o.push(p("mo",a))}o.push(...H(i))}),delete n.separators,c("mfenced",[h(o)],n)}function Un(e){let t=[];for(let n of _(e))if(Dn.has(n.name)){let r=_(n).map(o=>o.name==="mtd"?At(o):c("mtd",[h(H(o))]));t.push(c(n.name,r,n.attrs))}else t.push(c("mtr",[c("mtd",[h(H(n))])]));return c("mtable",t,e.attrs)}function Se(e){return e.name==="msrow"?h(O(e.children),"msrow",e.attrs):e.name==="mscarry"?h(O(e.children),"mscarry",e.attrs):e.name==="msline"?I("msline",e.attrs):e.name==="none"?I("none",e.attrs):Wt.has(e.name)?_e(e):j(e)}function _e(e){let t=_(e);if(e.name==="mlongdiv"){let n=t.slice(0,Vt).map(j);for(;n.length<Vt;)n.push(h());return c("mlongdiv",[...n,...t.slice(Vt).map(Se)],e.attrs)}return c(e.name,t.map(Se),e.attrs)}function zn(e){let t=_(e).map(n=>n.name==="mprescripts"||n.name==="none"?I(n.name==="none"?"none":"mprescripts"):j(n));return t.length===0&&t.push(h()),c("mmultiscripts",t,e.attrs)}function H(e){let t=e.name;if(Te.has(t))return Pn(e);if(_n.has(t))return[I(t,e.attrs)];if(t==="mrow"){if(Object.keys(e.attrs).length>0)return[At(e)];let r=O(e.children);return r.length>0?r:[c("mrow",[h()])]}if(t==="semantics"){let r=_(e).find(o=>o.name!=="annotation"&&o.name!=="annotation-xml");return r?H(r):[]}if(t==="annotation"||t==="annotation-xml")return[];if(t==="maction"){if(Oe(e)){if(!yt)return O(e.children);let o=j(e);return[c("mrow",[o])]}let r=_(e)[0];return[c("maction",[r?j(r):h()],e.attrs)]}if(t==="mfenced")return[Gn(e)];if(t==="mtable")return[Un(e)];if(t==="mmultiscripts")return[zn(e)];if(Wt.has(t))return[_e(e)];if(Xt.has(t))return[At(e)];let n=pe[t];return n!==void 0?[Xn(e,n)]:t==="math"?O(e.children):[At(e)]}function Hn(e){let t=e&&Fe(e)?e.children[0]:void 0;return t?.kind==="row"&&t.children.length===0}function O(e){let t=[];for(let n of e)n.type==="text"?t.push(...$n(n)):t.push(...H(n));return t.length===1&&Hn(t[0])?[]:t}function De(e){if(e.name==="annotation"&&(e.attrs.encoding??"").toLowerCase()==="latex")return ht(e).trim();for(let t of _(e)){let n=De(t);if(n!==null)return n}return null}function Y(e,t={}){yt=t.argumentRows??null;try{return Vn(e)}finally{yt=null}}function Vn(e){let t=xe(e)?ke(e):e,n;try{n=we(t.trim())}catch(i){throw new Kt(i instanceof Error?i.message:"Invalid MathML")}let r=n.find(i=>i.name==="math");if(!r)return n.length===0?{doc:{attrs:{},root:h()},latex:null}:{doc:{attrs:{},root:h(O(n))},latex:null};let o={};for(let[i,s]of Object.entries(r.attrs))i!=="xmlns"&&!i.startsWith("xmlns:")&&(o[i]=s);return{doc:{attrs:o,root:h(O(r.children))},latex:De(r)}}function q(e){return Object.entries(e).map(([t,n])=>` ${t}="${dt(n,!0)}"`).join("")}function Kn(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(o=>e[o]===t[o])}function Fe(e){return e.kind==="element"&&e.tag==="mrow"&&Object.keys(e.attrs).length===0}function Be(e){let t=[];for(let n of e){let r=Fe(n)?n.children[0]:void 0;r?.kind==="row"&&r.children.length>0?t.push(...Be(r.children)):t.push(n)}return t}function T(e){let t=[];for(let n of Be(e)){let r=t[t.length-1];n.kind==="token"&&r?.kind==="token"&&Ce.has(n.tag)&&r.tag===n.tag&&Kn(r.attrs,n.attrs)?t[t.length-1]={...r,text:r.text+n.text}:t.push(n)}return t}function Wn(e){return`<${e.tag}${q(e.attrs)}>${dt(e.text)}</${e.tag}>`}function Zt(e){return T(e.children).map(St).join("")}function Et(e){if(e.children.length===0&&e.tokenHint)return`<${e.tokenHint.tag}${q(e.tokenHint.attrs)}></${e.tokenHint.tag}>`;let t=T(e.children),n=Object.keys(e.attrs).length>0;if(t.length===0)return`<mrow${q(e.attrs)}/>`;let r=t[0];return t.length===1&&r&&!n?St(r):`<mrow${q(e.attrs)}>${t.map(St).join("")}</mrow>`}function z(e,t,n){return n?`<${e}${q(t)}>${n}</${e}>`:`<${e}${q(t)}/>`}function Zn(e){return e.kind==="row"?e.tag==="msrow"&&Object.keys(e.attrs).length===0&&T(e.children).length===1?Et(e):e.tag==="msrow"||e.tag==="mscarry"?z(e.tag,e.attrs,Zt(e)):Et(e):e.kind==="leaf"?vt(e):lt(e)}function vt(e){return`<${e.tag}${q(e.attrs)}/>`}function lt(e){let{tag:t,attrs:n,children:r}=e;if(Xt.has(t)){let i=r[0],s=i?.kind==="row"?Zt(i):"";return z(t,n,s)}if(t==="mtable"||t==="mtr"||t==="mlabeledtr")return z(t,n,r.map(i=>i.kind==="element"?lt(i):"").join(""));if(Wt.has(t))return z(t,n,r.map(Zn).join(""));if(t==="mmultiscripts")return z(t,n,r.map(i=>i.kind==="row"?Et(i):i.kind==="leaf"?vt(i):lt(i)).join(""));let o=r.map(i=>i.kind==="row"?Et(i):i.kind==="leaf"?vt(i):lt(i)).join("");return z(t,n,o)}function St(e){switch(e.kind){case"token":return Wn(e);case"leaf":return vt(e);case"element":return lt(e)}}function Q(e,t={}){let{[at]:n,...r}=e.attrs,o=q(r),i=Zt(e.root),s=n!==void 0&&i?z("mstyle",{[at]:n},i):i;return t.latexAnnotation!==void 0?`<math${o} xmlns="${Nt}"><semantics><mrow>${s}</mrow><annotation encoding="LaTeX">${dt(t.latexAnnotation)}</annotation></semantics></math>`:s?`<math${o} xmlns="${Nt}">${s}</math>`:`<math${o} xmlns="${Nt}"/>`}function $e(e){return`<math xmlns="${Nt}">${T(e).map(St).join("")}</math>`}var Pe=["sin","cos","tan","cot","sec","csc","sinh","cosh","tanh","coth","sech","csch","arcsin","arccos","arctan","arccot","arcsec","arccsc","log","ln","lg","exp"],Yn=new Set(Pe),qe=Math.max(...Pe.map(e=>e.length));function je(e){return Yn.has(e)}var Xo=200,Tt=class{constructor(t=200){E(this,"limit",t);E(this,"undoStack",[]);E(this,"redoStack",[])}push(t){this.undoStack.push(t),this.undoStack.length>this.limit&&this.undoStack.shift(),this.redoStack=[]}discardLast(){this.undoStack.pop()}undo(t){let n=this.undoStack.pop();return n===void 0?null:(this.redoStack.push(t),n)}redo(t){let n=this.redoStack.pop();return n===void 0?null:(this.undoStack.push(t),n)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[]}};function V(e){if(e.kind!=="element")return[];let t=[],n=e.tag==="mroot"?[1,0]:e.children.map((r,o)=>o);for(let r of n){let o=e.children[r];o&&(o.kind==="row"?t.push(o):o.kind==="element"&&t.push(...V(o)))}return t}function Yt(e){let t=new Map,n=new Map,r=new Map,o=new Map,i=new Map,s=l=>{t.set(l.id,l),l.children.forEach((u,f)=>{r.set(u.id,l),i.set(u.id,{row:l,index:f});let b=V(u);o.set(u.id,b);for(let m of b)n.set(m.id,{atom:u,parentRow:l,index:f});a(u)})},a=l=>{if(l.kind==="row"){s(l);return}if(l.kind==="element")for(let u of l.children)r.set(u.id,l),a(u)};return s(e),{rows:t,owners:n,parents:r,atomRows:o,atomParent:i}}function Ct(e,t){let n=[],r=e.rows.get(t);for(;r;)n.unshift(r),r=e.owners.get(r.id)?.parentRow;return n}function $(e,t,n){let r=e.rows.get(t);for(;r;){let o=e.parents.get(r.id)??e.owners.get(r.id)?.atom;if(!o)return null;if(o.kind==="element"&&o.tag===n)return o;r=o}return null}var Qn="\xA0",Xe={bold:!1,italic:null,color:null,textMode:!1},Jn=/^\p{L}$/u,tr=/^\p{Nd}$/u,er=new Set(["_"]),nr=new Set([")","]","}","|","\u2016","\u232A","\u27E9","\u2309","\u230B"]),rr={")":"(","]":"[","}":"{","|":"|","\u2016":"\u2016","\u232A":"\u2329","\u27E9":"\u27E8","\u2309":"\u2308","\u230B":"\u230A"},Ke=new Set(["msub","msup","msubsup","mmultiscripts","munder","mover","munderover"]),We=new Set([..."\u2211\u220F\u2210\u222B\u222C\u222D\u222E\u222F\u2230\u2231\u2232\u2233\u22C0\u22C1\u22C2\u22C3\u2A00\u2A01\u2A02\u2A04\u2A06"]),or=new Set(["lim"]),ir={mover:1,munderover:2},sr={mroot:[0,1],munderover:[0,2,1]},ar={"=":"\u2260","<":"\u226E",">":"\u226F","\u2264":"\u2270","\u2265":"\u2271","\u2261":"\u2262","\u223C":"\u2241","~":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2208":"\u2209","\u220B":"\u220C","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u2203":"\u2204","\u2223":"\u2224","\u2225":"\u2226"},lr={parentheses:{},brackets:{open:"[",close:"]"},bars:{open:"|",close:"|"}},ur={mfrac:{0:[null,1],1:[0,null]},msup:{0:[1,null],1:[null,0]},msub:{0:[null,1],1:[0,null]},msubsup:{0:[2,1],1:[2,null],2:[null,1]},mover:{0:[1,null],1:[null,0]},munder:{0:[null,1],1:[0,null]},munderover:{0:[2,1],1:[0,null],2:[null,0]},mroot:{0:[1,null],1:[null,0]}};function Ge(e){let t=new Map;for(let n of(e??"").split(";")){let r=n.indexOf(":");r>0&&t.set(n.slice(0,r).trim(),n.slice(r+1).trim())}return t}function cr(e){return[...e.entries()].map(([t,n])=>`${t}:${n}`).join(";")}function ut(e,t){return e==="mi"&&[...t].length===1?"italic":"normal"}function Ze(e,t){return e?t?"bold-italic":"bold":t?"italic":"normal"}function Mt(e){return(e.attrs.mathvariant??"").startsWith("bold")}function Ue(e){let t=e.attrs.mathvariant;return t===void 0?ut(e.tag,e.text)==="italic":t.includes("italic")}function It(e,t,n){let r=Ze(t,n);r===ut(e.tag,e.text)?delete e.attrs.mathvariant:e.attrs.mathvariant=r}function dr(e){let t=[],n=r=>{if(r.kind==="token")t.push(r);else if(r.kind==="row"||r.kind==="element")for(let o of r.children)n(o)};for(let r of e)n(r);return t}function _t(e){let t=[];for(let n of e)for(let r of V(n))t.push(r),t.push(..._t(r.children));return t}function Ye(e){return e?.kind==="element"&&e.tag==="mrow"&&Object.keys(e.attrs).length===0&&e.children.length===1&&e.children[0]?.kind==="row"}function ze(e){return e?.kind==="leaf"&&e.tag==="mspace"&&e.attrs.linebreak==="newline"}function He(e){return Ye(e)&&e.children[0]?.kind==="row"&&e.children[0].children.length===0}function Jt(e){if(e.kind!=="element"||!Ke.has(e.tag))return!1;let t=e.children[0],n=t?.kind==="row"&&t.children.length===1?t.children[0]:void 0;return n?.kind!=="token"?!1:n.tag==="mo"?We.has(n.text)||n.attrs.largeop==="true":n.tag==="mi"&&or.has(n.text)}function Qt(e){if(e.kind!=="element")return[];if(e.tag==="mmultiscripts"){let o=e.children.findIndex(s=>s.kind==="leaf"&&s.tag==="mprescripts"),i=s=>s.filter(a=>a.kind==="row");return o<0?i(e.children):[...i(e.children.slice(o+1)),...i(e.children.slice(0,o))]}let t=ir[e.tag],n=V(e);if(t===void 0)return n;let r=e.children[t];return n.filter(o=>o!==r)}function Qe(e,t){let n=[];for(let r of e){if(t&&Jt(r))continue;let o=r.kind==="element"&&!Jt(r)?sr[r.tag]:void 0,i=o&&r.kind==="element"?o.map(s=>r.children[s]).filter(s=>s?.kind==="row"):V(r);for(let s of i)n.push(s,...Qe(s.children,!1))}return n}function Lt(e,t,n){let r=(e??"").trim().split(/\s+/).filter(Boolean),o=[];for(let i=0;i<t;i+=1)o.push(r[i]??r[r.length-1]??n);return o}function Ot(e,t){if(e.every(r=>r===t))return null;let n=e[0];return e.every(r=>r===n)&&n!==void 0?n:e.join(" ")}var Ve=class{constructor(t={}){E(this,"doc",fe());E(this,"index",Yt(this.doc.root));E(this,"caret",{rowId:this.doc.root.id,offset:0});E(this,"anchor",null);E(this,"history");E(this,"style",{...Xe});E(this,"lineStyle","solid");E(this,"docRevision",0);E(this,"listeners",new Set);this.history=new Tt(t.historyLimit)}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}emit(){for(let t of this.listeners)t()}get document(){return this.doc}getMathML(){return Q(this.doc)}setMathML(t,n=!1){let r=Y(t);Le(r.doc),n?this.history.push(this.snapshot()):this.history.clear(),this.doc=r.doc,this.reindex(),this.caret={rowId:this.doc.root.id,offset:this.doc.root.children.length},this.anchor=null,this.style={...Xe},this.emit()}setDocument(t){this.history.clear(),this.doc=rt(t,!0),this.reindex(),this.caret={rowId:this.doc.root.id,offset:this.doc.root.children.length},this.anchor=null,this.emit()}isEmpty(){return this.doc.root.children.length===0}get treeIndex(){return this.index}getCaret(){return{...this.caret}}getAnchor(){return this.anchor?{...this.anchor}:null}getInputStyle(){return this.style}getLineStyle(){return this.lineStyle}currentRow(){return this.index.rows.get(this.caret.rowId)??this.doc.root}setCaret(t,n=!1){let r=this.index.rows.get(t.rowId);if(!r)return;let o={rowId:r.id,offset:Math.max(0,Math.min(t.offset,r.children.length))};n?this.anchor||(this.anchor={...this.caret}):this.anchor=null,this.caret=o,this.anchor&&this.anchor.rowId===o.rowId&&this.anchor.offset===o.offset&&(this.anchor=null),this.emit()}select(t,n){!this.index.rows.has(t.rowId)||!this.index.rows.has(n.rowId)||(this.anchor={...t},this.caret={...n},t.rowId===n.rowId&&t.offset===n.offset&&(this.anchor=null),this.emit())}selectAll(){let t=this.doc.root;t.children.length!==0&&this.select({rowId:t.id,offset:0},{rowId:t.id,offset:t.children.length})}selectAtom(t,n){this.select({rowId:t,offset:n},{rowId:t,offset:n+1})}clearSelection(){this.anchor&&(this.anchor=null,this.emit())}getSelection(){if(!this.anchor)return null;let t=Ct(this.index,this.anchor.rowId),n=Ct(this.index,this.caret.rowId),r=0;for(;r+1<t.length&&r+1<n.length&&t[r+1]?.id===n[r+1]?.id;)r+=1;let o=t[r];if(!o)return null;let i=(m,R)=>{if(R.length-1===r)return[m.offset,m.offset];let M=R[r+1],x=(M?this.index.owners.get(M.id):void 0)?.index??0;return[x,x+1]},[s,a]=i(this.anchor,t),[l,u]=i(this.caret,n),f=Math.min(s,l),b=Math.max(a,u);return f===b?null:{row:o,start:f,end:b}}hasSelection(){return this.getSelection()!==null}moveRight(t=!1){let n=this.currentRow(),r=this.caret.offset;if(t){r<n.children.length?this.setCaret({rowId:n.id,offset:r+1},!0):this.exitRow(n,"after",!0);return}let o=this.getSelection();if(o){this.setCaret({rowId:o.row.id,offset:o.end});return}let i=n.children[r];if(i){let s=Qt(i)[0];s?this.setCaret({rowId:s.id,offset:0}):this.setCaret({rowId:n.id,offset:r+1});return}this.exitRow(n,"after",!1)}moveLeft(t=!1){let n=this.currentRow(),r=this.caret.offset;if(t){r>0?this.setCaret({rowId:n.id,offset:r-1},!0):this.exitRow(n,"before",!0);return}let o=this.getSelection();if(o){this.setCaret({rowId:o.row.id,offset:o.start});return}let i=n.children[r-1];if(i){let s=Qt(i),a=s[s.length-1];a?this.setCaret({rowId:a.id,offset:a.children.length}):this.setCaret({rowId:n.id,offset:r-1});return}this.exitRow(n,"before",!1)}exitRow(t,n,r){let o=this.index.owners.get(t.id);if(!o)return;let i=n==="after"&&Jt(o.atom)&&o.atom.kind==="element"&&o.atom.children[0]===t;if(!r&&!i){let f=Qt(o.atom),b=f.findIndex(R=>R.id===t.id),m=n==="after"?f[b+1]:b<0?void 0:f[b-1];if(m){this.setCaret({rowId:m.id,offset:n==="after"?0:m.children.length});return}}let s=o.parentRow,a=n==="after"?o.index+1:o.index,l=this.index.owners.get(s.id)?.atom,u=n==="after"?a===s.children.length:a===0;if(!r&&u&&l?.kind==="element"&&l.tag==="mstyle"){this.exitRow(s,n,!1);return}this.setCaret({rowId:s.id,offset:a},r)}moveHome(t=!1){if(t){this.setCaret({rowId:this.caret.rowId,offset:0},!0);return}let n=this.doc.root,r=this.rootOffset();for(;r>0&&!ze(n.children[r-1]);)r-=1;this.setCaret({rowId:n.id,offset:r})}moveEnd(t=!1){if(t){this.setCaret({rowId:this.caret.rowId,offset:this.currentRow().children.length},!0);return}let n=this.doc.root,r=this.rootOffset();for(this.caret.rowId!==n.id&&(r+=1);r<n.children.length&&!ze(n.children[r]);)r+=1;this.setCaret({rowId:n.id,offset:r})}rootOffset(){let n=Ct(this.index,this.caret.rowId)[1];return n?this.index.owners.get(n.id)?.index??0:this.caret.offset}moveVertical(t){let n=this.currentRow(),r=n.children.length===0?0:this.caret.offset/n.children.length;for(;;){let o=this.verticalTarget(n,t);if(o)return this.setCaret({rowId:o.id,offset:Math.round(r*o.children.length)}),!0;let i=this.index.owners.get(n.id);if(!i)return!1;n=i.parentRow,r=n.children.length===0?0:i.index/n.children.length}}verticalTarget(t,n){let r=this.index.parents.get(t.id);if(!r||r.kind!=="element")return null;let o=ur[r.tag];if(o){let i=r.children.findIndex(u=>u.id===t.id),s=o[i],a=s?s[n==="up"?0:1]:null,l=a===null?void 0:r.children[a];return l?.kind==="row"?l:null}if(r.tag==="mtd"){let i=this.tableContext();if(!i)return null;let s=i.rowIndex+(n==="up"?-1:1),a=i.table.children[s],l=a?.kind==="element"?a.children[i.columnIndex]:void 0,u=l?.kind==="element"?l.children[0]:void 0;return u?.kind==="row"?u:null}if(r.tag==="mstack"||r.tag==="mlongdiv"||r.tag==="msgroup"){let i=V(r),s=i.findIndex(a=>a.id===t.id);return i[s+(n==="up"?-1:1)]??null}return null}moveToSlot(t){let n=_t(this.doc.root.children),r=[this.doc.root,...n],o=r.findIndex(a=>a.id===this.caret.rowId),s=(t?r.slice(o+1):r.slice(0,Math.max(o,0)).reverse()).find(a=>a.children.length===0);return s?(this.setCaret({rowId:s.id,offset:0}),!0):!1}snapshot(){return{doc:rt(this.doc),caret:{...this.caret},anchor:this.anchor?{...this.anchor}:null}}restore(t){this.doc=t.doc,this.reindex(),this.caret=t.caret,this.anchor=t.anchor}reindex(){this.index=Yt(this.doc.root),this.docRevision+=1}get revision(){return this.docRevision}mutate(t){let n=this.snapshot(),r=Q(n.doc),o=t();return this.reindex(),o===!1||Q(this.doc)===r?(o===!1&&this.restore(n),this.emit(),!1):(this.history.push(n),this.emit(),!0)}removeSelection(){let t=this.getSelection();if(!t)return null;let n=t.row.children.splice(t.start,t.end-t.start);return this.anchor=null,this.caret={rowId:t.row.id,offset:t.start},this.reindex(),{row:t.row,offset:t.start,removed:n}}insertAtCaret(t){let n=this.currentRow(),r=this.caret.offset,o=this.index.owners.get(n.id);n.children.length===0&&o&&Ye(o.atom)?(n=o.parentRow,r=o.index,n.children.splice(r,1)):He(n.children[r])?n.children.splice(r,1):r>0&&He(n.children[r-1])&&(r-=1,n.children.splice(r,1)),n.children.splice(r,0,...t),this.caret={rowId:n.id,offset:r+t.length},this.reindex()}negateInPlace(t){let n=this.currentRow(),r=ar[t],o=this.index.owners.get(n.id),i=o?.atom;return!r||!o||n.children.length>0||i?.kind!=="element"||i.tag!=="menclose"||i.attrs.notation!=="updiagonalstrike"?!1:(o.parentRow.children.splice(o.index,1,p("mo",r,this.tokenAttrs("mo",r))),this.caret={rowId:o.parentRow.id,offset:o.index+1},this.reindex(),!0)}tokenAttrs(t,n,r){let o={...r??{}},i=this.style.italic??ut(t,n)==="italic",s=Ze(this.style.bold,i);return s!==ut(t,n)&&(o.mathvariant=s),this.style.color&&(o.mathcolor=this.style.color),o}classify(t){return this.style.textMode?"mtext":tr.test(t)?"mn":Jn.test(t)||er.has(t)?"mi":"mo"}typeCharacter(t,n){t&&this.mutate(()=>{if(this.removeSelection(),!this.style.textMode&&this.negateInPlace(t))return;let r=this.currentRow();if(r.tokenHint&&r.children.length===0){let{largeop:l,...u}=r.tokenHint.attrs;this.insertAtCaret([p(r.tokenHint.tag,t,We.has(t)||l===void 0?u:r.tokenHint.attrs)]);return}let o=this.style.textMode?void 0:n,i=o?.text??(t===" "?Qn:t),s=o?.tag??(t===" "&&!this.style.textMode?"mo":this.classify(t)),a=this.tokenAttrs(s,i);o?.mathvariant&&(a.mathvariant=o.mathvariant),this.insertAtCaret([p(s,i,a)]),s==="mi"&&this.mergeFunctionName()})}typeText(t){for(let n of t)n===`
|
|
2
|
+
`?this.insertNewline():this.typeCharacter(n)}mergeFunctionName(){let t=this.currentRow(),n=this.caret.offset,r=t.children[n-1];if(r?.kind!=="token"||r.tag!=="mi")return;let o=n,i=0;for(;o>0;){let s=t.children[o-1];if(s?.kind!=="token"||s.tag!=="mi"||!/^\p{L}+$/u.test(s.text)||s.attrs.mathvariant==="normal")break;let a=Object.keys(s.attrs).filter(l=>l!=="mathvariant");if(a.length>0&&a.some(l=>s.attrs[l]!==r.attrs[l])||(i+=s.text.length,i>qe))break;o-=1}for(let s=o;s<n;s+=1){let a=t.children.slice(s,n).map(l=>l.kind==="token"?l.text:"").join("");if(je(a)&&n-s>1){let l={},u=r.attrs.mathcolor;u&&(l.mathcolor=u),this.style.bold&&(l.mathvariant="bold"),t.children.splice(s,n-s,p("mi",a,l)),this.caret={rowId:t.id,offset:s+1},this.reindex();return}}}insertNewline(){this.mutate(()=>{this.removeSelection(),this.insertAtCaret([I("mspace",{linebreak:"newline"})])})}canBeScriptBase(t){return t.kind==="token"&&t.tag==="mo"?nr.has(t.text)||t.attrs.largeop==="true":t.kind!=="leaf"}matchingOpen(t,n,r,o){let i=0;for(let s=n-1;s>=0;s-=1){let a=t[s];if(!(a?.kind!=="token"||a.tag!=="mo")){if(a.text===r&&i===0)return s;a.text===o&&r!==o?i+=1:a.text===r&&(i-=1)}}return-1}takePreviousBase(){let t=this.currentRow(),n=this.caret.offset,r=t.children[n-1];if(!r||!this.canBeScriptBase(r))return[];n-=1;let o=r.kind==="token"&&r.tag==="mo"?rr[r.text]:void 0;if(o!==void 0&&r.kind==="token"){let s=this.matchingOpen(t.children,n,o,r.text);s>=0&&(n=s)}if(r.kind==="token"&&r.tag==="mn")for(;n>0;){let s=t.children[n-1];if(s?.kind!=="token"||s.tag!=="mn")break;n-=1}let i=t.children.splice(n,this.caret.offset-n);return this.caret={rowId:t.id,offset:n},this.reindex(),i}insertMathML(t){return this.mutate(()=>{let n=new Set,o=Y(t,{argumentRows:n}).doc.root.children;if(o.length===0)return!1;let i=_t(o),s=i.find(m=>n.has(m.id)),l=this.removeSelection()?.removed??[],u=o[0];if(l.length===0&&s&&u?.kind==="element"&&Ke.has(u.tag)&&u.children[0]?.id===s.id&&!s.tokenHint&&(l=this.takePreviousBase()),l.length>0){let m=s??i[0];m&&(m.children=l,delete m.tokenHint)}let f=this.isNestedFraction(o)?[c("mstyle",[h(o)],{displaystyle:"true"})]:o;this.insertAtCaret(f);let b=Qe(f,!0).find(m=>m.children.length===0);return b&&(this.caret={rowId:b.id,offset:0}),!0})}isNestedFraction(t){let n=t.length===1?t[0]:void 0;return n?.kind!=="element"||n.tag!=="mfrac"||Object.keys(n.attrs).length>0||!n.children.every(r=>r.kind==="row"&&r.children.length===0)?!1:$(this.index,this.caret.rowId,"mfrac")!==null}insertMatrix(t,n,r="parentheses"){if(t<1||n<1)return!1;let o=c("mtable",Array.from({length:t},()=>c("mtr",Array.from({length:n},()=>c("mtd",[h()]))))),i=r==="table"?o:c("mfenced",[h([o])],lr[r]);return this.mutate(()=>{let s=this.removeSelection(),a=o.children[0]?.kind==="element"?o.children[0].children[0]:void 0,l=a?.kind==="element"?a.children[0]:void 0;s&&s.removed.length>0&&l?.kind==="row"&&(l.children=s.removed),this.insertAtCaret([i]);let u=_t([i]).find(f=>f.children.length===0);u&&(this.caret={rowId:u.id,offset:0})})}deleteBackward(){if(this.hasSelection()){this.mutate(()=>{this.removeSelection()});return}let t=this.currentRow(),n=this.caret.offset,r=t.children[n-1];if(r){if(r.kind==="element"&&(this.index.atomRows.get(r.id)?.length??0)>0){this.selectAtom(t.id,n-1);return}this.mutate(()=>{t.children.splice(n-1,1),this.caret={rowId:t.id,offset:n-1}});return}this.deleteAtSlotBoundary(t,"before")}deleteForward(){if(this.hasSelection()){this.mutate(()=>{this.removeSelection()});return}let t=this.currentRow(),n=this.caret.offset,r=t.children[n];if(r){if(r.kind==="element"&&(this.index.atomRows.get(r.id)?.length??0)>0){this.selectAtom(t.id,n);return}this.mutate(()=>{t.children.splice(n,1)});return}this.deleteAtSlotBoundary(t,"after")}deleteAtSlotBoundary(t,n){let r=this.index.owners.get(t.id);if(!r)return;let o=this.index.atomRows.get(r.atom.id)??[];if(o.every(a=>a.children.length===0)){this.mutate(()=>{r.parentRow.children.splice(r.index,1),this.caret={rowId:r.parentRow.id,offset:r.index}});return}let i=o.findIndex(a=>a.id===t.id),s=n==="before"?o[i-1]:o[i+1];if(s){this.setCaret({rowId:s.id,offset:n==="before"?s.children.length:0});return}this.selectAtom(r.parentRow.id,r.index)}clear(){this.mutate(()=>{this.doc.root.children=[],this.caret={rowId:this.doc.root.id,offset:0},this.anchor=null})}copySelection(){let t=this.getSelection();return t?$e(t.row.children.slice(t.start,t.end)):null}cutSelection(){let t=this.copySelection();return t===null?null:(this.mutate(()=>{this.removeSelection()}),t)}paste(t){let n=t.trim();if(!n)return!1;if(n.startsWith("<")||n.startsWith("\xAB"))try{let o=Y(n).doc.root.children.map(i=>W(i,!0));return this.mutate(()=>{this.removeSelection(),this.insertAtCaret(o)})}catch{return!1}return this.typeText(n),!0}insertNodes(t){let n=t.map(r=>W(r,!0));return this.mutate(()=>{this.removeSelection(),this.insertAtCaret(n)})}undo(){let t=this.history.undo(this.snapshot());return t?(this.restore(t),this.emit(),!0):!1}redo(){let t=this.history.redo(this.snapshot());return t?(this.restore(t),this.emit(),!0):!1}canUndo(){return this.history.canUndo()}canRedo(){return this.history.canRedo()}selectedTokens(){let t=this.getSelection();return t?dr(t.row.children.slice(t.start,t.end)):[]}toggleBold(){let t=this.selectedTokens();if(t.length===0){this.style={...this.style,bold:!this.style.bold},this.emit();return}let n=!t.every(Mt);this.mutate(()=>{for(let r of t)It(r,n,Ue(r))})}toggleItalic(){let t=this.selectedTokens();if(t.length===0){let r=this.style.italic;this.style={...this.style,italic:r===null?!0:!r},this.emit();return}let n=!t.every(Ue);this.mutate(()=>{for(let r of t)It(r,Mt(r),n)})}setAutoItalic(){let t=this.selectedTokens();if(this.style={...this.style,italic:null,textMode:!1},t.length===0){this.emit();return}this.mutate(()=>{for(let n of t)It(n,Mt(n),ut(n.tag,n.text)==="italic")})}setTextMode(t){let n=this.selectedTokens();if(this.style={...this.style,textMode:t},n.length===0||!t){this.emit();return}this.mutate(()=>{for(let r of n)It(r,Mt(r),!1)})}setColor(t){let n=this.selectedTokens();if(this.style={...this.style,color:t},n.length===0){this.emit();return}this.mutate(()=>{for(let r of n)t?r.attrs.mathcolor=t:delete r.attrs.mathcolor})}setFontSize(t){let n=this.getSelection();if(!n){this.setDocumentAttribute("mathsize",t);return}this.mutate(()=>{let r=n.end-n.start===1?n.row.children[n.start]:void 0;if(r?.kind==="element"&&r.tag==="mstyle"){t?r.attrs.mathsize=t:delete r.attrs.mathsize;return}if(!t)return!1;let o=this.removeSelection();return this.insertAtCaret([c("mstyle",[h(o?.removed??[])],{mathsize:t})]),!0})}getFontSize(){return this.doc.attrs.mathsize??null}setFontFamily(t){this.mutate(()=>{let n=Ge(this.doc.attrs.style);t?n.set("font-family",t):n.delete("font-family");let r=cr(n);r?this.doc.attrs.style=r:delete this.doc.attrs.style})}getFontFamily(){return Ge(this.doc.attrs.style).get("font-family")??null}setDocumentAttribute(t,n){return(this.doc.attrs[t]??null)===n?!1:this.mutate(()=>{n===null?delete this.doc.attrs[t]:this.doc.attrs[t]=n})}hasLineBreaks(){return this.doc.root.children.some(t=>t.kind==="leaf"&&t.attrs.linebreak==="newline")}isRtl(){return this.doc.attrs.dir==="rtl"}toggleRtl(){this.mutate(()=>{this.doc.attrs.dir==="rtl"?delete this.doc.attrs.dir:this.doc.attrs.dir="rtl"})}setTokenAttribute(t,n){let r=this.selectedTokens(),i=this.currentRow().children[this.caret.offset-1],s=r.length>0?r:i?.kind==="token"?[i]:[];return s.length===0?!1:this.mutate(()=>{for(let a of s)n===null?delete a.attrs[t]:a.attrs[t]=n})}previousAtom(){return this.currentRow().children[this.caret.offset-1]??null}contextKind(){if(this.tableContext())return"table";let t=this.previousAtom();return $(this.index,this.caret.rowId,"mstack")||$(this.index,this.caret.rowId,"mlongdiv")?"stack":t?.kind==="leaf"&&t.tag==="mspace"?"space":t?.kind==="token"&&t.tag==="mo"?"operator":t?.kind==="token"&&t.tag==="mn"?"number":this.fenceContext()?"fence":"none"}fenceContext(){return $(this.index,this.caret.rowId,"mfenced")}setFence(t){let n=this.fenceContext();return n?this.mutate(()=>{for(let[r,o]of Object.entries(t)){if(o===void 0)continue;r==="open"&&o==="("||r==="close"&&o===")"||r==="separators"&&o===","?delete n.attrs[r]:n.attrs[r]=o}}):!1}tableContext(){let t=$(this.index,this.caret.rowId,"mtd");if(!t)return null;let n=this.index.parents.get(t.id),r=n?this.index.parents.get(n.id):void 0;if(n?.kind!=="element"||r?.kind!=="element"||r.tag!=="mtable")return null;let o=r.children.findIndex(a=>a.id===n.id),i=n.children.findIndex(a=>a.id===t.id),s=Math.max(...r.children.map(a=>a.kind==="element"?a.children.length:0));return{table:r,rowIndex:o,columnIndex:i,rowCount:r.children.length,columnCount:s}}newCell(){return c("mtd",[h()])}tableInsertRow(t){let n=this.tableContext();return n?this.mutate(()=>{let r=c("mtr",Array.from({length:n.columnCount},()=>this.newCell())),o=n.rowIndex+(t==="below"?1:0);n.table.children.splice(o,0,r),this.adjustLines(n.table,"rowlines",n.rowCount,o,"insert");let i=r.children[n.columnIndex]?.children[0];i?.kind==="row"&&(this.caret={rowId:i.id,offset:0}),this.anchor=null}):!1}tableInsertColumn(t){let n=this.tableContext();return n?this.mutate(()=>{let r=n.columnIndex+(t==="right"?1:0),o=null;n.table.children.forEach((s,a)=>{if(s.kind!=="element")return;let l=this.newCell();s.children.splice(Math.min(r,s.children.length),0,l);let u=l.children[0];a===n.rowIndex&&u?.kind==="row"&&(o=u)}),this.adjustLines(n.table,"columnlines",n.columnCount,r,"insert"),this.adjustList(n.table,"columnalign",n.columnCount,r,"insert","center");let i=o;i&&(this.caret={rowId:i.id,offset:0}),this.anchor=null}):!1}tableRemoveRow(){let t=this.tableContext();return!t||t.rowCount<=1?!1:this.mutate(()=>{t.table.children.splice(t.rowIndex,1),this.adjustLines(t.table,"rowlines",t.rowCount,t.rowIndex,"remove");let n=t.table.children[Math.min(t.rowIndex,t.table.children.length-1)],r=n?.kind==="element"?n.children[Math.min(t.columnIndex,n.children.length-1)]:void 0,o=r?.kind==="element"?r.children[0]:void 0;o?.kind==="row"&&(this.caret={rowId:o.id,offset:o.children.length}),this.anchor=null})}tableRemoveColumn(){let t=this.tableContext();return!t||t.columnCount<=1?!1:this.mutate(()=>{for(let i of t.table.children)i.kind==="element"&&i.children.length>t.columnIndex&&i.children.splice(t.columnIndex,1);this.adjustLines(t.table,"columnlines",t.columnCount,t.columnIndex,"remove"),this.adjustList(t.table,"columnalign",t.columnCount,t.columnIndex,"remove","center");let n=t.table.children[t.rowIndex],r=n?.kind==="element"?n.children[Math.min(t.columnIndex,n.children.length-1)]:void 0,o=r?.kind==="element"?r.children[0]:void 0;o?.kind==="row"&&(this.caret={rowId:o.id,offset:o.children.length}),this.anchor=null})}adjustList(t,n,r,o,i,s){if(t.attrs[n]===void 0)return;let a=Lt(t.attrs[n],r,s);i==="insert"?a.splice(o,0,s):a.splice(o,1);let l=Ot(a,s);l===null?delete t.attrs[n]:t.attrs[n]=l}adjustLines(t,n,r,o,i){if(t.attrs[n]===void 0||r<1)return;let s=Lt(t.attrs[n],Math.max(r-1,0),"none");i==="insert"?s.splice(Math.min(o,s.length),0,"none"):s.splice(Math.min(o,s.length-1),1);let a=Ot(s,"none");a===null?delete t.attrs[n]:t.attrs[n]=a}setLineStyle(t){this.lineStyle=t,this.emit()}setTableLine(t,n){let r=this.tableContext();if(!r)return!1;let o=t==="row"?"rowlines":"columnlines",i=(t==="row"?r.rowCount:r.columnCount)-1,s=t==="row"?r.rowIndex:r.columnIndex;return i<1||s>=i?!1:this.mutate(()=>{let a=Lt(r.table.attrs[o],i,"none");a[s]=n?this.lineStyle:"none";let l=Ot(a,"none");l===null?delete r.table.attrs[o]:r.table.attrs[o]=l})}setTableFrame(t){let n=this.tableContext();return n?this.mutate(()=>{t?n.table.attrs.frame=this.lineStyle:delete n.table.attrs.frame}):!1}setColumnAlign(t){let n=this.tableContext();return n?this.mutate(()=>{let r=Lt(n.table.attrs.columnalign,n.columnCount,"center");r[n.columnIndex]=t;let o=Ot(r,"center");o===null?delete n.table.attrs.columnalign:n.table.attrs.columnalign=o}):!1}setRowAlign(t){let n=this.tableContext(),r=n?.table.children[n.rowIndex];return!n||r?.kind!=="element"?!1:this.mutate(()=>{t==="baseline"?delete r.attrs.rowalign:r.attrs.rowalign=t})}setTableAttribute(t,n){let r=this.tableContext();return r?this.mutate(()=>{n===null?delete r.table.attrs[t]:r.table.attrs[t]=n}):!1}stackContext(){let t=this.currentRow(),n=this.index.parents.get(t.id);return n?.kind!=="element"||n.tag!=="mstack"&&n.tag!=="mlongdiv"&&n.tag!=="msgroup"?null:{stack:n,row:t,index:n.children.findIndex(r=>r.id===t.id)}}stackInsertRow(t){let n=this.stackContext();return n?this.mutate(()=>{let r=h([],"msrow");n.stack.children.splice(n.index+(t==="after"?1:0),0,r),this.caret={rowId:r.id,offset:0},this.anchor=null}):!1}stackInsertLine(){let t=this.stackContext();return t?this.mutate(()=>{t.stack.children.splice(t.index+1,0,I("msline"))}):!1}stackShiftRow(t){let n=this.stackContext();return n?this.mutate(()=>{let o=(Number.parseInt(n.row.attrs.position??"0",10)||0)+t;o===0?delete n.row.attrs.position:n.row.attrs.position=String(o)}):!1}setStackAttribute(t,n){let r=$(this.index,this.caret.rowId,"mstack")??$(this.index,this.caret.rowId,"mlongdiv");return r?this.mutate(()=>{n===null?delete r.attrs[t]:r.attrs[t]=n}):!1}carriesContext(){let t=$(this.index,this.caret.rowId,"mscarries");if(t)return t;let n=this.stackContext(),r=n?n.stack.children[n.index-1]:void 0;return r?.kind==="element"&&r.tag==="mscarries"?r:null}hasCarries(){return this.carriesContext()!==null}stackInsertCarries(){let t=this.stackContext();if(!t||this.carriesContext())return!1;let n=Math.max(1,t.row.children.length);return this.mutate(()=>{let r=c("mscarries",Array.from({length:n},()=>h([],"mscarry")));t.stack.children.splice(t.index,0,r);let o=r.children[0];o?.kind==="row"&&(this.caret={rowId:o.id,offset:0}),this.anchor=null})}setCarriesAttribute(t,n){let r=this.carriesContext();return r?this.mutate(()=>{n===null?delete r.attrs[t]:r.attrs[t]=n}):!1}setSpaceAttribute(t,n){let r=this.previousAtom();return r?.kind!=="leaf"||r.tag!=="mspace"?!1:this.mutate(()=>{n===null?delete r.attrs[t]:r.attrs[t]=n})}toggleNumberSeparators(){let t=this.currentRow();return this.mutate(()=>{let n=!1;for(let r=1;r+1<t.children.length;r+=1){let o=t.children[r-1],i=t.children[r],s=t.children[r+1];o?.kind==="token"&&o.tag==="mn"&&i?.kind==="token"&&i.tag==="mo"&&(i.text==="."||i.text===",")&&s?.kind==="token"&&s.tag==="mn"&&(t.children[r]=p("mn",i.text,o.attrs),n=!0)}if(!n)for(let r=1;r+1<t.children.length;r+=1){let o=t.children[r];o?.kind==="token"&&o.tag==="mn"&&(o.text==="."||o.text===",")&&(t.children[r]=p("mo",o.text),n=!0)}return n})}nudge(t,n){let r=this.getSelection(),o=r?.row??this.currentRow(),i=r?r.start:this.caret.offset-1,s=r?r.end:this.caret.offset;return i<0||s<=i?!1:this.mutate(()=>{let a=s-i===1?o.children[i]:void 0,l;if(a?.kind==="element"&&a.tag==="mpadded")l=a;else{let f=o.children.splice(i,s-i);l=c("mpadded",[h(f)]),o.children.splice(i,0,l)}let u=(f,b)=>{let m=Number.parseFloat(l.attrs[f]??"0")||0,R=Math.round((m+b)*10)/10;R===0?delete l.attrs[f]:l.attrs[f]=`${R}em`};t!==0&&u("lspace",t),n!==0&&u("voffset",n),this.anchor=null,this.caret={rowId:o.id,offset:i+1}})}static merged(t){return T(t)}};var hr="\xA0",mr="\u200A",fr="\u2009",ln=".",pr=new Set(["-0.2em","-0.1667em"]),Je={"+":"plus","-":"minus","\u2212":"minus","=":"equals","\xB1":"plus-or-minus","\u2213":"minus-or-plus","\xD7":"cross times","\xB7":"times","\u22C5":"times","*":"times","\u2217":"times","\xF7":"divided by","/":"divided by","<":"less than",">":"greater than","\u2264":"less or equal than","\u2265":"greater or equal than","\u2260":"not equal to","\u2248":"almost equal to","\u2261":"identical to","\u223C":"tilde operator","\u221D":"proportional to","\u2192":"rightwards arrow","\u2190":"leftwards arrow","\u2194":"left right arrow","\u21D2":"rightwards double arrow","\u21D0":"leftwards double arrow","\u21D4":"left right double arrow","\u2208":"element of","\u2209":"not an element of","\u2282":"subset of","\u2283":"superset of","\u2286":"subset of or equal to","\u2287":"superset of or equal to","\u222A":"union","\u2229":"intersection","\u2205":"empty set","\u221E":"infinity","\u2202":"partial differential","\u2207":"nabla","\u2200":"for all","\u2203":"there exists","\xAC":"not","\u2227":"logical and","\u2228":"logical or","\u2220":"angle","\u22A5":"perpendicular","\u2225":"parallel to","\xB0":"degree","!":"factorial",",":"comma",";":"semicolon",":":"colon",".":"dot","\u2026":"horizontal ellipsis","\u22EF":"midline horizontal ellipsis","%":"percent sign","(":"left parenthesis",")":"right parenthesis","[":"left square bracket","]":"right square bracket","{":"left curly bracket","}":"right curly bracket","|":"vertical line","'":"apostrophe","\u2032":"prime","\u222B":"integral","\u222C":"double integral","\u222D":"triple integral","\u222E":"contour integral","\u2211":"sum","\u220F":"product","\u2210":"coproduct","\u2206":"increment","\u2234":"therefore","\u2235":"because","\u2218":"ring operator","\u2295":"circled plus","\u2297":"circled times","\u27E8":"left angle bracket","\u27E9":"right angle bracket","\u230A":"left floor","\u230B":"right floor","\u2308":"left ceiling","\u2309":"right ceiling","\u2243":"asymptotically equal to","\u2245":"approximately equal to","\u226A":"much less-than","\u226B":"much greater-than","\u227A":"precedes","\u227B":"succeeds","\u2204":"there does not exist","\u2216":"set minus","\u21A6":"rightwards arrow from bar","\u2191":"upwards arrow","\u2193":"downwards arrow","\u2195":"up down arrow","\u2197":"north east arrow","\u2198":"south east arrow","\u21AA":"rightwards arrow with hook","\u22EE":"vertical ellipsis","\u22F1":"down right diagonal ellipsis",\u2112:"script capital l","\u2118":"script capital p",\u2113:"ell",\u211C:"real part",\u2111:"imaginary part",\u2135:"alef",\u2102:"complex numbers",\u2115:"natural numbers",\u211A:"rational numbers",\u211D:"real numbers",\u2124:"integer numbers",\u2119:"double-struck capital p"},gr={"-":"negative","\u2212":"negative","\u2213":"negative-or-plus"},tn={"\u222A":"large union","\u2229":"large intersection"},wr={normal:"straight",bold:"bold",italic:"italic","bold-italic":"bold italic",fraktur:"fraktur",script:"calligraphic","double-struck":"double-struck"},br={longdiv:"long division",updiagonalstrike:"up diagonal",downdiagonalstrike:"down diagonal",horizontalstrike:"horizontal",verticalstrike:"vertical"},xr=["columnalign","rowalign"],en={"(":"parentheses",")":"parentheses","[":"square brackets","]":"square brackets","{":"curly brackets","}":"curly brackets","|":"vertical bar","\u2016":"double vertical bar","||":"double vertical bar","<":"angle brackets",">":"angle brackets","\u27E8":"angle brackets","\u27E9":"angle brackets","\u2308":"ceiling","\u2309":"ceiling","\u230A":"floor","\u230B":"floor"},nn={"\u2192":"rightwards arrow","\u21C0":"rightwards harpoon with barb upwards","\u2194":"left right arrow","\xAF":"bar","^":"hat","~":"tilde","\xA8":"diaeresis","\u2025":"two dots","\u02D9":"dot","\u23DE":"overbrace","\u23DF":"underbrace","\u23DC":"top parenthesis","\u23DD":"bottom parenthesis","\u02C7":"caron","\u02D8":"breve"},kr={2:"half",3:"third",4:"fourth",5:"fifth"},Rr={2:"square",3:"cube"},Nr=new Set(["\u2211","\u220F","\u2210","\u22C3","\u22C2","\u22C1","\u22C0","\u2A01","\u2A02"]),un="lim",Ar=new Set(["msub","msup"]),yr=(()=>{let e=new Map([["\u03C2","final sigma"]]);for(let[t,n]of Object.entries(ot)){if(!/^[\u0391-\u03A9\u03B1-\u03C9]$/.test(n)||e.has(n))continue;let r=(t.startsWith("var")?t.slice(3):t).toLowerCase();e.set(n,/[\u0391-\u03A9]/.test(n)?`capital ${r}`:r)}return e})();function w(e){return e.filter(t=>t.length>0).join(" ")}function X(e){if(!e)return null;let t=T(e.children);return t.length===1?t[0]??null:null}function G(e){let t=X(e);return t?.kind==="token"&&t.tag!=="mtext"}function ne(e){return!e||T(e.children).length===0}function rn(e){let t=X(e);return G(e)||t?.kind==="element"&&Ar.has(t.tag)}function Ft(e,t){return w([e,N(t),G(t)?"":`end ${e}`])}function g(e,t){let n=e.children[t];return n?.kind==="row"?n:void 0}function te(e){let t=e.attrs.mathvariant;return!t||t==="italic"&&e.tag==="mi"&&[...e.text].length===1?"":wr[t]??""}function Er(e){if(e===mr)return e;if(e===fr)return"thin space";if(e===hr)return"space";if(/^\u00A0+$/.test(e))return e;if(/^[\u2000-\u200B]$/.test(e))return""}function vr(e,t){if(e.tag==="mtext")return w(["text",te(e),e.text,"end text"]);if(e.tag==="mn")return w([te(e),e.text]);if(e.tag==="mi"){let o=[...e.text].length>1?e.text:yr.get(e.text)??Je[e.text]??e.text;return w([te(e),o])}let n=Er(e.text);if(n!==void 0)return n;if(e.attrs.largeop==="true"&&tn[e.text])return tn[e.text]??"";let r=gr[e.text];return r&&Sr(t)?r:Je[e.text]??e.text}function Sr(e){return e?e.kind==="token"&&e.tag==="mo"&&!")]}|".includes(e.text):!0}function Tr(e){return e?.kind==="token"&&e.tag==="mo"&&e.text===ln}function N(e){if(!e)return"";let t=T(e.children),n=[];for(let r=0;r<t.length;r++){let o=t[r];if(!o)continue;let i=t[r+1],s=n.length-1;if(Tr(o)&&r>0&&i?.kind==="token"&&t[r-1]?.kind==="token"&&s>=0){n[s]=`${n[s]??""}${ln}${an(i,o)}`,r++;continue}n.push(an(o,t[r-1]??null))}return w(n)}function Cr(e){let t=X(g(e,0)),n=X(g(e,1));if(t?.kind==="token"&&t.tag==="mn"&&t.text==="1"&&n?.kind==="token"&&n.tag==="mn"){let r=kr[n.text];if(r)return`1 ${r}`}return rn(g(e,0))&&rn(g(e,1))?w([N(g(e,0)),"over",N(g(e,1))]):w(["fraction numerator",N(g(e,0)),"over denominator",N(g(e,1)),"end fraction"])}function Mr(e,t){let n=X(t);return n?.kind==="token"&&n.tag==="mn"&&n.text==="2"?w([e,"squared"]):n?.kind==="token"&&n.tag==="mn"&&n.text==="3"?w([e,"cubed"]):G(t)?w([e,"to the power of",N(t)]):w([e,"to the power of",N(t),"end exponent"])}function J(e){let t=g(e,0);return ne(t)?"blank":N(t)}function ee(e){return G(g(e,0))?J(e):w(["stack",J(e)])}function on(e){let t=X(e);return t?.kind!=="token"?!1:t.tag==="mo"?Nr.has(t.text)||t.attrs.largeop==="true":t.tag==="mi"&&t.text===un}function sn(e){let t=X(e);return t?.kind==="token"&&t.tag==="mi"&&t.text===un?"limit":N(e)}function Ir(e){let t=e.kind==="element"?g(e,0):void 0;return ne(t)?"blank":G(t)?N(t):w(["cell",N(t),"end cell"])}function Lr(e){let t=xr.flatMap(r=>{let o=e.attrs[r];return o?[`${r} ${o}`]:[]}),n=e.children.filter(r=>r.kind==="element").map(r=>w(["row",...r.children.map(Ir)]));return w(["table",t.length?w(["attributes",...t,"end attributes"]):"",...n,"end table"])}function Or(e){let t=(e.attrs.notation??"longdiv").trim().split(/\s+/),n=t.every(o=>o.endsWith("strike"))?"strike":"enclose",r=t.map(o=>br[o]??o);return w([...r,n,N(g(e,0)),G(g(e,0))?"":`end ${n}`])}function _r(e){let t=e.children,n=t.findIndex(s=>s.kind==="leaf"&&s.tag==="mprescripts"),r=(s,a,l)=>s.flatMap((u,f)=>u.kind==="row"&&!ne(u)?[Ft(f%2===0?a:l,u)]:[]),o=t.slice(1,n<0?void 0:n),i=n<0?[]:t.slice(n+1);return w([J(e),...r(i,"presubscript","presuperscript"),...r(o,"subscript","superscript")])}function Dr(e){let t=N(g(e,0)),n=e.attrs.displaystyle;return n==="true"?w(["begin display style",t,"end style"]):n==="false"?w(["begin inline style",t,"end style"]):t}function Fr(e){let t=e.attrs.open??"(",n=e.attrs.close??")";return w([w(["open",en[t]??t]),N(g(e,0)),w(["close",en[n]??n])])}function cn(e){switch(e.tag){case"mfrac":return Cr(e);case"msqrt":return G(g(e,0))?w(["square root of",N(g(e,0))]):w(["square root of",N(g(e,0)),"end root"]);case"mroot":{let t=N(g(e,1)),n=Rr[t]??`${t}-th`;return w([`${n} root of`,N(g(e,0)),G(g(e,0))?"":"end root"])}case"msup":return Mr(J(e),g(e,1));case"msub":return w([J(e),Ft("subscript",g(e,1))]);case"msubsup":return w([J(e),Ft("subscript",g(e,1)),Ft("superscript",g(e,2))]);case"munderover":return on(g(e,0))?w([sn(g(e,0)),"from",N(g(e,1)),"to",N(g(e,2)),"of"]):w([ee(e),"with",Dt(g(e,1)),"below and",Dt(g(e,2)),"on top"]);case"munder":if(on(g(e,0))){let t=sn(g(e,0));return w([t,t==="limit"?"as":"for",N(g(e,1)),"of"])}return w([ee(e),"with",Dt(g(e,1)),"below"]);case"mover":return w([ee(e),"with",Dt(g(e,1)),"on top"]);case"mfenced":return Fr(e);case"mtable":return Lr(e);case"menclose":return Or(e);case"mphantom":return"";case"mmultiscripts":return _r(e);case"mstyle":return Dr(e);default:return w(e.children.map(t=>t.kind==="row"?N(t):t.kind==="element"?cn(t):""))}}function Dt(e){let t=X(e);return t?.kind==="token"&&nn[t.text]?nn[t.text]??"":N(e)}function an(e,t){switch(e.kind){case"token":return vr(e,t);case"leaf":return e.tag!=="mspace"?"":e.attrs.linebreak==="newline"?"new line":pr.has(e.attrs.width??"")?"back space":"";case"element":return cn(e)}}function dn(e){return N(e.root).trim()}var hn={mfrac:["numerator","denominator"],msqrt:["square root"],mroot:["root","index"],msup:["base","superscript"],msub:["base","subscript"],msubsup:["base","subscript","superscript"],mover:["base","overscript"],munder:["base","underscript"],munderover:["base","underscript","overscript"],mfenced:["fence"],menclose:["enclosure"],mtd:["cell"],mstyle:["style"],mmultiscripts:["base"]};function Bt(e){return e?dn({attrs:{},root:{kind:"row",id:-1,tag:"mrow",attrs:{},children:[e]}}):""}function ri(e){let t=e.getCaret(),n=e.treeIndex,r=n.rows.get(t.rowId);if(!r)return"";let o=n.owners.get(r.id),i=t.offset===r.children.length;if(!o)return r.children.length===0?"empty expression":i?"end expression":t.offset===0?`begin expression ${Bt(r.children[0])}`.trim():Bt(r.children[t.offset-1]);let s=n.parents.get(r.id),a=s?.kind==="element"?s.tag:o.atom.kind==="element"?o.atom.tag:"",l=s?.kind==="element"?s.children.findIndex(f=>f.id===r.id):0,u=hn[a]?.[l]??hn[a]?.[0]??"slot";return t.offset===0?`${u} begin ${Bt(r.children[0])}`.trim():i?`${u} end`:Bt(r.children[t.offset-1])}var Br=new Set(["mrow","mfrac","msqrt","mroot","mstyle","merror","mpadded","mphantom","mfenced","menclose","msub","msup","msubsup","munder","mover","munderover","mmultiscripts","mtable","mlabeledtr","mtr","mtd","mstack","mlongdiv","msgroup","msrow","mscarries","mscarry","maction"]),$r=/^[A-Za-z][A-Za-z0-9_.-]*(?::[A-Za-z][A-Za-z0-9_.-]*)?$/,Pr=/^on/i,qr=new Set(["href","xlink:href","src","definitionurl","altimg"]),jr=/^(?:https?:|mailto:|[^:]*$)/i,Xr=/url\s*\(|expression\s*\(|javascript\s*:|@import|behavior\s*:/i;function mn(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase();!$r.test(n)||Pr.test(n)||o==="xmlns"||o.startsWith("xmlns:")||qr.has(o)&&!jr.test(r.trim())||o==="style"&&Xr.test(r)||(t[n]=r)}return t}function si(e){let t=rt(e);return t.attrs=mn(t.attrs),ct(t.root,n=>{n.attrs=mn(n.attrs),n.kind==="element"&&!Br.has(n.tag)&&(n.tag="mrow")}),t}var C=class extends Error{constructor(n,r){super(`${n} at ${r}`);E(this,"position",r);this.name="LatexParseError"}};function Gr(e){let t=[],n=0,r=[...e];for(;n<r.length;){let o=r[n]??"";if(o==="\\"){let i=r[n+1];if(i===void 0)throw new C("Trailing backslash",n);if(i==="\\"){t.push({t:"newline",p:n}),n+=2;continue}if(/[A-Za-z]/.test(i)){let s=n+1;for(;s<r.length&&/[A-Za-z]/.test(r[s]??"");)s+=1;t.push({t:"cmd",v:r.slice(n+1,s).join(""),p:n}),n=s;continue}t.push({t:"cmd",v:i,p:n}),n+=2;continue}if(o==="%"){for(;n<r.length&&r[n]!==`
|
|
3
|
+
`;)n+=1;continue}o==="{"?t.push({t:"open",p:n}):o==="}"?t.push({t:"close",p:n}):o==="^"?t.push({t:"sup",p:n}):o==="_"?t.push({t:"sub",p:n}):o==="&"?t.push({t:"amp",p:n}):/\s/.test(o)?t.push({t:"space",p:n}):o==="~"?t.push({t:"cmd",v:" ",p:n}):t.push({t:"char",v:o,p:n}),n+=1}return t}var fn="\xA0",$t=/^[0-9]$/,pn=/^\p{L}$/u,Ur={matrix:null,smallmatrix:null,pmatrix:{},bmatrix:{open:"[",close:"]"},Bmatrix:{open:"{",close:"}"},vmatrix:{open:"|",close:"|"},Vmatrix:{open:"||",close:"||"}},zr={textbf:"bold",textit:"italic",textrm:"normal",textsf:"sans-serif",texttt:"monospace"},gn={l:"left",c:"center",r:"right"},Hr={boxed:"box",fbox:"box",cancel:"updiagonalstrike",bcancel:"downdiagonalstrike",xcancel:"downdiagonalstrike updiagonalstrike",sout:"horizontalstrike"},Vr=new Set(["left","right","big","Big","bigg","Bigg","bigl","bigr","Bigl","Bigr","biggl","biggr","Biggl","Biggr","displaylimits","nonumber","notag"]),Kr=new Set(["big","Big","bigg","Bigg","bigl","bigr","Bigl","Bigr","biggl","biggr","Biggl","Biggr","bigm","Bigm"]),oe=class{constructor(t){E(this,"toks",t);E(this,"pos",0);E(this,"limitsOverride",null)}peek(){return this.toks[this.pos]}next(){let t=this.toks[this.pos];return this.pos+=1,t}skipSpaces(){for(;this.peek()?.t==="space";)this.pos+=1}position(){return this.peek()?.p??-1}parseSequence(t,n=!1){let r=[];for(;;){let o=this.peek();if(!o||o.t==="close"||n&&(o.t==="amp"||o.t==="newline")||o.t==="cmd"&&(o.v==="right"||o.v==="end"||o.v==="middle"))return r;if(o.t==="space"){this.pos+=1;continue}if(o.t==="sup"||o.t==="sub"){this.attachScripts(r,t);continue}if(o.t==="amp"){this.pos+=1,r.push(p("mo","&"));continue}if(o.t==="newline"){this.pos+=1,r.push(I("mspace",{linebreak:"newline"}));continue}if(o.t==="cmd"&&(o.v==="displaystyle"||o.v==="textstyle")){this.pos+=1;let i=this.parseSequence(t,n);return r.push(c("mstyle",[h(i)],{displaystyle:o.v==="displaystyle"?"true":"false"})),r}if(o.t==="cmd"&&o.v==="color"){this.pos+=1;let{spec:i,model:s}=this.parseColorParts(),a=this.parseSequence(t,n),l=a.length===1?a[0]:void 0;return l?.kind==="token"?l.attrs.mathcolor=qt(i,s):a.length>0&&r.push(c("mstyle",[h(a)],{mathcolor:s?qt(i,s):i})),l?.kind==="token"&&r.push(l),r}r.push(...this.parseAtom(t))}}parseColorParts(){let t=null;this.skipSpaces();let n=this.peek();return n?.t==="char"&&n.v==="["&&(this.pos+=1,t=this.readRawUntil("]")),{spec:this.readRawGroup().trim(),model:t}}parseColorSpec(){let{spec:t,model:n}=this.parseColorParts();return qt(t,n)}readRawUntil(t){let n="";for(;;){let r=this.next();if(!r)throw new C(`Expected ${t}`,this.position());if(r.t==="char"&&r.v===t)return n;n+=re(r)}}readRawGroup(){this.skipSpaces();let t=this.next();if(!t)throw new C("Expected {",this.position());if(t.t!=="open")return re(t);let n=1,r="";for(;;){let o=this.next();if(!o)throw new C("Unclosed {",t.p);if(o.t==="open"&&(n+=1),o.t==="close"&&(n-=1,n===0))return r;r+=re(o)}}parseArgument(t){this.skipSpaces();let n=this.peek();if(!n)return h();if(n.t==="open"){this.pos+=1;let r=this.parseSequence(t);return this.expect("close"),h(r)}return n.t==="close"||n.t==="amp"||n.t==="newline"?h():n.t==="char"&&$t.test(n.v)?(this.pos+=1,h([this.makeToken("mn",n.v,t)])):h(this.parseAtom(t))}parseOptional(t){this.skipSpaces();let n=this.peek();if(n?.t!=="char"||n.v!=="[")return null;this.pos+=1;let r=[],o=0;for(;;){let i=this.peek();if(!i)throw new C("Unclosed [",n.p);if(i.t==="char"&&i.v==="]"&&o===0)return this.pos+=1,h(r);if(i.t==="open"&&(o+=1),i.t==="close"&&(o-=1),i.t==="sup"||i.t==="sub"){this.attachScripts(r,t);continue}if(i.t==="space"){this.pos+=1;continue}r.push(...this.parseAtom(t))}}expect(t){let n=this.next();if(n?.t!==t)throw new C(`Expected ${t==="close"?"}":t}`,n?.p??-1)}makeToken(t,n,r,o={}){let i={...o};if(r.variant&&t!=="mo"){let s=t==="mi"&&[...n].length===1;s&&r.variant==="italic"||!s&&r.variant==="normal"||(i.mathvariant=r.variant)}return r.color&&(i.mathcolor=r.color),p(t,n,i)}readScripts(t){let n=null,r=null;for(;;){this.skipSpaces();let o=this.peek();if(o?.t==="sub"&&!n)this.pos+=1,n=this.parseArgument(t);else if(o?.t==="sup"&&!r)this.pos+=1,r=this.parseArgument(t);else return{sub:n,sup:r}}}attachScripts(t,n){let r=t.pop(),o=r?[r]:[];for(;r?.kind==="token"&&r.tag==="mn";){let b=t[t.length-1];if(b?.kind!=="token"||b.tag!=="mn")break;o.unshift(b),t.pop()}let i=this.limitsOverride;this.limitsOverride=null;let{sub:s,sup:a}=this.readScripts(n);if(r&&Yr(r)&&this.startsAtom()){t.push(...this.prescripted(s,a,n));return}if(a?.children.length===1&&a.children[0]?.kind==="token"&&a.children[0].text==="\u2218"&&!s){t.push(...o,p("mo","\xB0"));return}let u=h(o),f=i??(r!==void 0&&Qr(r));s&&a?t.push(c(f?"munderover":"msubsup",[u,s,a])):s?t.push(c(f?"munder":"msub",[u,s])):a?t.push(c(f?"mover":"msup",[u,a])):t.push(...o)}startsAtom(){let t=this.peek();return t!==void 0&&(t.t==="char"||t.t==="cmd"||t.t==="open")}prescripted(t,n,r){let[o,...i]=this.parseAtom(r),s=i.length===0?this.readScripts(r):{sub:null,sup:null},a=u=>u??I("none"),l=[h(o?[o]:[])];return(s.sub||s.sup)&&l.push(a(s.sub),a(s.sup)),l.push(I("mprescripts"),a(t),a(n)),[c("mmultiscripts",l),...i]}parseAtom(t){let n=this.next();if(!n)return[];switch(n.t){case"open":{let r=this.parseSequence(t);return this.expect("close"),r.length===1?r:[c("mrow",[h(r)])]}case"char":return this.parseChar(n.v,t);case"cmd":return this.parseCommand(n.v,t,n.p);default:return[]}}parseChar(t,n){if($t.test(t)){let r=[this.makeToken("mn",t,n)];for(;;){let o=this.peek(),i=this.toks[this.pos+1];if(o?.t==="char"&&$t.test(o.v))r.push(this.makeToken("mn",o.v,n)),this.pos+=1;else if(o?.t==="char"&&o.v==="."&&i?.t==="char"&&$t.test(i.v))r.push(this.makeToken("mo",".",n)),this.pos+=1;else return r}}if(pn.test(t)){if(n.variant==="double-struck"&&it[t]){let r={mathvariant:"normal"};return n.color&&(r.mathcolor=n.color),[p("mi",it[t]??t,r)]}return[this.makeToken("mi",t,n)]}return[this.makeToken("mo",t,n)]}parseFence(){this.skipSpaces();let t=this.next();if(!t)throw new C("Missing delimiter",-1);let n=t.t==="cmd"?`\\${t.v}`:t.t==="char"?t.v:"",r=Ee[n];if(r===void 0)throw new C(`Unknown delimiter ${n}`,t.p);return r}parseCommand(t,n,r){let o=gt[t];if(o)return o.char?[p("mo",o.char)]:[I("mspace",{width:o.width??"0em"})];if(t==="left"){let d=this.parseFence(),S=[...this.parseSequence(n)];for(;this.peek()?.t==="cmd"&&this.peek().v==="middle";)this.pos+=1,S.push(p("mo",this.parseFence(),{stretchy:"true"})),S.push(...this.parseSequence(n));let U=this.next();if(U?.t!=="cmd"||U.v!=="right")throw new C("Missing \\right",r);let B=this.parseFence(),K={};return d!=="("&&(K.open=d),B!==")"&&(K.close=B),[c("mfenced",[h(S)],K)]}if(Kr.has(t))return[p("mo",this.parseFence())];if(t==="limits"||t==="nolimits")return this.limitsOverride=t==="limits",[];if(t==="frac"||t==="dfrac"||t==="tfrac"||t==="cfrac"){let d=this.parseArgument(n),x=this.parseArgument(n),S=c("mfrac",[d,x]);return t==="dfrac"||t==="cfrac"?[c("mstyle",[h([S])],{displaystyle:"true"})]:t==="tfrac"?[c("mstyle",[h([S])],{displaystyle:"false"})]:[S]}if(t==="binom"||t==="dbinom"||t==="tbinom"){let d=this.parseArgument(n),x=this.parseArgument(n);return[c("mfenced",[h([c("mfrac",[d,x],{linethickness:"0"})])])]}if(t==="sqrt"){let d=this.parseOptional(n),x=this.parseArgument(n);return d&&d.children.length>0?[c("mroot",[x,d])]:[c("msqrt",[x])]}if(t==="text"||t==="textnormal"||t==="mbox"||t==="textup"||t==="hbox"){let d=this.readRawGroup().replace(/ /g,fn),x={};return n.color&&(x.mathcolor=n.color),d?[...d].map(S=>p("mtext",S,x)):[]}let i=zr[t];if(i){let d=this.readRawGroup().replace(/ /g,fn),x={mathvariant:i};return n.color&&(x.mathcolor=n.color),d?[p("mtext",d,x)]:[]}if(t==="operatorname"){let d=this.readRawGroup();return[p("mo",d,n.color?{mathcolor:n.color}:{})]}if(t==="pmod"){let d=this.parseArgument(n);return[p("mo","("),p("mi","mod"),...d.children,p("mo",")")]}if(t==="bmod"||t==="mod")return[p("mi","mod")];if(t==="substack")return this.parseArgument(n).children;let s=kt[t];if(s){let d=this.parseArgument({...n,variant:s}),x=d.children.every(B=>B.kind==="token"&&B.tag==="mi"&&[...B.text].length===1&&pn.test(B.text)),S=d.children.length===1?d.children[0]:void 0,U=t==="mathcal"&&S?.kind==="token"?Z[S.text]:void 0;if(U)return[p("mo",U,n.color?{mathcolor:n.color}:{})];if(t==="mathit"&&x&&d.children.length>1){let B=d.children.map(K=>K.kind==="token"?K.text:"").join("");return[this.makeToken("mi",B,{...n,variant:s},{mathvariant:s})]}return d.children}if(t==="color"||t==="textcolor"){let d=this.parseColorSpec();return this.parseArgument({...n,color:d}).children}let a=wt[t];if(a!==void 0){let d=this.parseArgument(n);return[c("mover",[d,h([p("mo",a)])],ye.has(t)?{accent:"true"}:{})]}let l=bt[t];if(l!==void 0){let d=this.parseArgument(n);return[c("mover",[d,h([p("mo",l)])])]}let u=xt[t];if(u!==void 0){let d=this.parseArgument(n);return[c("munder",[d,h([p("mo",u)])])]}if(t==="overset"||t==="stackrel"){let d=this.parseArgument(n),x=this.parseArgument(n);return[c("mover",[x,d])]}if(t==="underset"){let d=this.parseArgument(n),x=this.parseArgument(n);return[c("munder",[x,d])]}if(t==="xrightarrow"||t==="xleftarrow"){let d=this.parseOptional(n),x=this.parseArgument(n),S=h([p("mo",t==="xrightarrow"?"\u2192":"\u2190")]);return d&&d.children.length>0?[c("munderover",[S,d,x])]:[c("mover",[S,x])]}let f=Hr[t];if(f)return[c("menclose",[this.parseArgument(n)],{notation:f})];if(t==="enclose"){let d=this.readRawGroup();return[c("menclose",[this.parseArgument(n)],{notation:d.replace(/,/g," ")})]}if(t==="phantom")return[c("mphantom",[this.parseArgument(n)])];if(t==="not"){this.skipSpaces();let d=this.parseAtom(n)[0];return d?.kind==="token"?[p("mo",{"=":"\u2260","\u2208":"\u2209","\u2282":"\u2284","\u2286":"\u2288","<":"\u226E",">":"\u226F","\u2261":"\u2262"}[d.text]??`${d.text}\u0338`)]:d?[d]:[]}if(t==="begin")return[this.parseEnvironment(n,r)];if(t==="mathstrut"||t==="strut"||Vr.has(t))return[];let b=ft[t];if(b)return[p("mo",b,{largeop:"true"})];let m=mt[t];if(m)return[p("mo",m)];if(pt.includes(t))return[p("mi",t,n.color?{mathcolor:n.color}:{})];let R=ot[t];if(R)return[this.makeToken("mi",R,n)];let M=Ht[t];if(M)return[this.makeToken("mo",M,n)];throw new C(`Unknown command \\${t}`,r)}parseEnvironment(t,n){let r=this.readRawGroup().trim(),o=null,i=null;if(r==="array"){let b=this.readRawGroup(),R=[...b.replace(/[^lcr]/g,"")].map(d=>gn[d]??"center");R.some(d=>d!=="center")&&(o=R.join(" "));let M=Zr(b);M.includes("solid")&&(i=M.join(" "))}let s=[],a=[];for(;;){let b=this.parseSequence(t,!0);a.push(c("mtd",[h(b)]));let m=this.next();if(!m)throw new C(`Missing \\end{${r}}`,n);if(m.t!=="amp"){if(m.t==="newline"){s.push(c("mtr",a)),a=[];continue}if(m.t==="cmd"&&m.v==="end"){let R=this.readRawGroup().trim();if(R!==r)throw new C(`Mismatched \\end{${R}}`,m.p);a.length===1&&a[0]?.children[0]?.kind==="row"&&a[0].children[0].children.length===0&&s.length>0||s.push(c("mtr",a));break}throw new C("Unexpected token in environment",m.p)}}let l={};o&&(l.columnalign=o),i&&(l.columnlines=i),(r==="cases"||r==="dcases")&&(l.columnalign="left"),(r==="aligned"||r==="align"||r==="align*"||r==="split"||r==="eqnarray"||r==="alignat")&&(l.columnalign="right left",l.columnspacing="0em"),(r==="gathered"||r==="gather")&&(l.columnalign="center");let u=c("mtable",s,l);if(r==="cases"||r==="dcases")return c("mfenced",[h([u])],{open:"{",close:""});if(r==="rcases")return c("mfenced",[h([u])],{open:"",close:"}"});let f=Ur[r];if(f)return c("mfenced",[h([u])],f);if(f===null||r==="array"||l.columnalign)return u;throw new C(`Unknown environment ${r}`,n)}atEnd(){return this.skipSpaces(),this.pos>=this.toks.length}rest(){return this.peek()}};function re(e){switch(e.t){case"cmd":return`\\${e.v}`;case"char":return e.v;case"open":return"{";case"close":return"}";case"sup":return"^";case"sub":return"_";case"amp":return"&";case"newline":return"\\\\";case"space":return" "}}var Wr=16,Pt=255;function tt(e){return Math.max(0,Math.min(Pt,Math.round(e))).toString(Wr).padStart(2,"0").toUpperCase()}function qt(e,t){let n=e.trim();if(t==="rgb"){let[o=0,i=0,s=0]=n.split(",").map(a=>Number.parseFloat(a));return`#${tt(o*Pt)}${tt(i*Pt)}${tt(s*Pt)}`}if(t==="RGB"){let[o=0,i=0,s=0]=n.split(",").map(a=>Number.parseFloat(a));return`#${tt(o)}${tt(i)}${tt(s)}`}if(t==="HTML"||/^#?[0-9a-fA-F]{6}$/.test(n))return`#${n.replace("#","").toUpperCase()}`;let r=Rt[n.toLowerCase()];return r||n}function Zr(e){let t=[],n=!1,r=!1;for(let o of e)o==="|"?r=n:gn[o]&&(n&&t.push(r?"solid":"none"),n=!0,r=!1);return t}function Yr(e){return e.kind==="element"&&e.tag==="mrow"&&e.children.length===1&&e.children[0]?.kind==="row"&&e.children[0].children.length===0}function Qr(e){return!!(e.kind==="token"&&e.tag==="mo"&&(Ne.has(e.text)||e.attrs.largeop==="true")||e.kind==="element"&&e.tag==="munder"&&Jr(e.children[1],"\u23DF")||e.kind==="token"&&e.tag==="mi"&&Ae.has(e.text))}function Jr(e,t){let n=e?.kind==="row"&&e.children.length===1?e.children[0]:void 0;return n?.kind==="token"&&n.text===t}function wn(e){let t=new oe(Gr(e)),n=t.parseSequence({variant:null,color:null});if(!t.atEnd()){let r=t.rest();throw new C("Unexpected token",r?.p??-1)}return n}function ie(e){return{attrs:{},root:h(wn(e))}}var to=255,eo=/^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,no={"{":"\\{","}":"\\}","#":"\\#",$:"\\$","%":"\\%","&":"\\&",_:"\\_","\\":"\\backslash","~":"\\sim","^":"\\hat{}","\xB0":"^\\circ"},ro={bold:"textbf",italic:"textit",normal:"textrm","sans-serif":"textsf",monospace:"texttt"},ue=new Map(Object.entries(ft).map(([e,t])=>[t,e])),bn=new Map(Object.entries(Z).map(([e,t])=>[t,e])),oo=/^\p{L}{2,}$/u,io=(()=>{let e=new Map;for(let[t,n]of Object.entries(kt))t.startsWith("math")&&!e.has(n)&&e.set(n,t);return e.set("bold-italic","boldsymbol"),e})(),se=new Map(Object.entries(it).map(([e,t])=>[t,e])),jt=new Map([...Object.entries(wt).filter(([e])=>!e.startsWith("wide")).map(([e,t])=>[t,e]),["\xA8","ddot"]]),so=new Map(Object.entries(bt).map(([e,t])=>[t,e])),ao=new Map(Object.entries(xt).map(([e,t])=>[t,e])),yn=(()=>{let e=new Map;for(let[t,n]of Object.entries(gt))n.char&&!e.has(n.char)&&e.set(n.char,/^[a-z]+$/.test(t)?`\\${t} `:`\\${t}`);return e})(),lo={"(":"(",")":")","[":"[","]":"]","{":"\\{","}":"\\}","|":"|","\u2016":"\\|","":".","\u27E8":"\\langle","\u27E9":"\\rangle","\u2329":"\\langle","\u232A":"\\rangle","<":"\\langle",">":"\\rangle","\u230A":"\\lfloor","\u230B":"\\rfloor","\u2308":"\\lceil","\u2309":"\\rceil","||":"\\|","\u27E6":"\\llbracket","\u27E7":"\\rrbracket"},uo={"()":"pmatrix","[]":"bmatrix","{}":"Bmatrix","||":"vmatrix","\u2016\u2016":"Vmatrix","||||":"Vmatrix"},co={left:"l",center:"c",right:"r"},ho={box:"boxed",updiagonalstrike:"cancel",downdiagonalstrike:"bcancel","updiagonalstrike downdiagonalstrike":"xcancel","downdiagonalstrike updiagonalstrike":"xcancel"},En=new Set(pt);function k(e){let t="";for(let n of e)n&&(/\\[A-Za-z]+$/.test(t)&&/^[A-Za-z]/.test(n)&&(t+=" "),t+=n);return t}function ae(e){let t=Number.parseInt(e,16)/to,n=Math.round(t*1e3)/1e3;return Number.isInteger(n)?n.toFixed(1):String(n)}function vn(e){let t=eo.exec(e);return t?`\\color[rgb]{${ae(t[1]??"00")}, ${ae(t[2]??"00")}, ${ae(t[3]??"00")}}`:`\\color{${e}}`}function mo(e){return`{${vn(e)}`}function fo(e){return[...e].length===1&&e!==" "&&e!=="\\"}function P(e){return`{${e}}`}function y(e){return fo(e)||/^\\[A-Za-z]+$/.test(e)?e:P(e)}function D(e){let t=e?F(e):"",n=e?T(e.children):[],r=n.length===1?n[0]:void 0;return r?.kind==="element"&&r.tag==="mfrac"&&Object.keys(r.attrs).length===0||r?.kind==="token"&&r.tag==="mtext"&&Object.keys(r.attrs).length===0?t:y(t)}function po(e){let t=no[e];if(t)return t;let n=st.get(e);if(n)return`\\${n}`;let r=yn.get(e);return r||e}function xn(e){return[...e].map(po).join("")}function go(e){let t,n=e.attrs.mathvariant,r=n?io.get(n):void 0,o=e.tag==="mi"&&[...e.text].length>1;if(e.tag==="mtext"){let i=n?ro[n]??"text":"text";return kn(e,`\\${i}{${e.text.replace(/[{}\\]/g,s=>`\\${s}`)}}`)}else e.tag==="mn"?t=e.text:o&&r&&n!=="normal"?t=xn(e.text):o?t=e.text==="mod"?"\\mod":En.has(e.text)?`\\${e.text}`:`\\operatorname{${e.text}}`:e.tag==="mi"&&se.has(e.text)?t=`\\mathbb{${se.get(e.text)??""}}`:e.tag==="mo"&&e.attrs.largeop==="true"&&ue.has(e.text)?t=`\\${ue.get(e.text)??""}`:bn.has(e.text)?t=`\\mathcal{${bn.get(e.text)??""}}`:e.tag==="mo"&&oo.test(e.text)?t=`\\operatorname{${e.text}}`:t=(e.tag==="mo"?yn.get(e.text):void 0)??xn(e.text);return r&&!se.has(e.text)&&!(n==="italic"&&e.tag==="mi"&&!o)&&!(n==="normal"&&e.tag!=="mi")&&(t=e.tag==="mo"?`\\${r}${P(t)}`:k([`\\${r}`,y(t)])),kn(e,t)}function kn(e,t){let n=e.attrs.mathcolor;return n?`${mo(n)}${t}}`:t}function F(e){return Sn(e.children)}function Sn(e){return k(T(e).map(yo))}function v(e,t){let n=e.children[t];return n?.kind==="row"?n:null}function A(e,t){let n=v(e,t);return n?F(n):""}function et(e){if(!e)return null;let t=T(e.children),n=t[0];return t.length===1&&n?.kind==="token"?n:null}function Rn(e){let t=v(e,0),n=t?F(t):"";if(!n)return"{}";let r=t?T(t.children):[],o=r[0],i=o?.kind==="element"&&o.tag==="mfenced"&&(o.attrs.open??"(")==="("&&(o.attrs.close??")")===")";return r.length===1&&o&&(o.kind==="token"||o.kind==="element"&&!["msub","msup","msubsup","mfenced"].includes(o.tag)||i)?n:P(n)}function Nn(e,t){let n=e??t;return lo[n]??n}function An(e){return e.children.filter(t=>t.kind==="element").map(t=>t.children.map(n=>n.kind==="element"?A(n,0):"").join("&")).join("\\\\")}function ce(e,t){if(!t){let n=Math.max(...e.children.map(s=>s.kind==="element"?s.children.length:0),1),r=(e.attrs.columnalign??"center").split(/\s+/),o=(e.attrs.columnlines??"none").split(/\s+/);return`\\begin{array}{${Array.from({length:n},(s,a)=>{let l=co[r[a]??r[r.length-1]??"center"]??"c",u=a<n-1&&(o[a]??o[o.length-1])==="solid"?"|":"";return`${l}${u}`}).join("")}}${An(e)}\\end{array}`}return`\\begin{${t}}${An(e)}\\end{${t}}`}function wo(e){let t=e.attrs.open??"(",n=e.attrs.close??")",r=v(e,0),o=r?T(r.children):[],i=o[0];if(o.length===1&&i?.kind==="element"&&i.tag==="mtable"){let s=uo[`${t}${n}`];if(s)return ce(i,s);if(t==="{"&&n==="")return ce(i,"cases")}return o.length===1&&i?.kind==="element"&&i.tag==="mfrac"&&i.attrs.linethickness==="0"&&t==="("&&n===")"?k(["\\binom",y(A(i,0)),y(A(i,1))]):k([`\\left${Nn(t,"(")}`,r?F(r):"",`\\right${Nn(n,")")}`])}function bo(e){let t=et(v(e,1)),n=v(e,0),r=A(e,0);if(t?.tag==="mo"){let i=t.text;if(e.attrs.accent==="true"||i==="\u21C0"){let a=i==="\u21C0"?"vec":jt.get(i);if(a)return k([`\\${a}`,y(r)])}let s=so.get(i)??(jt.get(i)==="hat"?"widehat":jt.get(i)==="tilde"?"widetilde":jt.get(i));if(s)return k([`\\${s}`,y(r)])}let o=et(n);return o?.tag==="mo"&&o.text==="\u2192"?k(["\\xrightarrow",y(A(e,1))]):o?.tag==="mo"&&o.text==="\u2190"?k(["\\xleftarrow",y(A(e,1))]):de(n)?k([r,`^${D(v(e,1))}`]):k(["\\overset",y(A(e,1)),y(r)])}function xo(e){let t=et(v(e,1)),n=v(e,0),r=A(e,0);if(de(n)||ko(n))return k([r,`_${D(v(e,1))}`]);if(t?.tag==="mo"){let o=ao.get(t.text);if(o)return k([`\\${o}`,y(r)])}return k(["\\underset",y(A(e,1)),y(r)])}function ko(e){let t=e?T(e.children):[],n=t.length===1?t[0]:void 0;return n?.kind==="element"&&n.tag==="munder"&&et(v(n,1))?.text==="\u23DF"}function Ro(e){let t=et(e);return t?.tag==="mo"&&/^(sum|prod|coprod|big)/.test(st.get(t.text)??ue.get(t.text)??"")}function le(e){return Ro(v(e,0))?k([Rn(e),"\\nolimits"]):Rn(e)}function Tn(e,t){let n=A(e,0),r=e.attrs.displaystyle,o=e.attrs.mathcolor;if(!r&&!o)return n;let i=n;return r==="true"&&(i=k(["\\displaystyle",n])),r==="false"&&(i=k(["\\textstyle",n])),o&&(i=k([vn(o),i])),t?i:P(i)}function de(e){let t=et(e);return t?t.tag==="mo"?t.attrs.largeop==="true"||st.has(t.text)&&/^(sum|prod|coprod|big|int|iint|iiint|oint)/.test(st.get(t.text)??""):t.tag==="mi"&&En.has(t.text):!1}function No(e){switch(e.tag){case"mfrac":return e.attrs.linethickness==="0"?`\\genfrac{}{}{0pt}{}${P(A(e,0))}${P(A(e,1))}`:e.attrs.bevelled==="true"?k([`{}^${D(v(e,0))}`,"/",`{}_${D(v(e,1))}`]):k(["\\frac",y(A(e,0)),y(A(e,1))]);case"msqrt":return k(["\\sqrt",y(A(e,0))]);case"mroot":return k([`\\sqrt[${A(e,1)}]`,y(A(e,0))]);case"msup":return k([le(e),`^${D(v(e,1))}`]);case"msub":return k([le(e),`_${D(v(e,1))}`]);case"msubsup":return k([le(e),`_${D(v(e,1))}`,`^${D(v(e,2))}`]);case"munderover":return de(v(e,0))?k([A(e,0),`_${D(v(e,1))}`,`^${D(v(e,2))}`]):k(["\\underset",y(A(e,1)),P(k(["\\overset",y(A(e,2)),y(A(e,0))]))]);case"mover":return bo(e);case"munder":return xo(e);case"mfenced":return wo(e);case"mtable":return ce(e);case"menclose":{let t=(e.attrs.notation??"longdiv").trim(),n=ho[t],r=A(e,0);return n?k([`\\${n}`,y(r)]):`\\enclose{${t.replace(/\s+/g,",")}}${P(r)}`}case"mphantom":return`\\phantom${P(A(e,0))}`;case"mstyle":return Tn(e,!1);case"mmultiscripts":{let t=e.children,n=t[0]?.kind==="row"?F(t[0]):"",r=t.findIndex(l=>l.kind==="leaf"&&l.tag==="mprescripts"),o=t.slice(1,r<0?void 0:r),i=r<0?[]:t.slice(r+1),s=l=>{let u="";for(let f=0;f+1<l.length;f+=2){let b=l[f],m=l[f+1],R=b?.kind==="row"?F(b):"",M=m?.kind==="row"?F(m):"";R&&(u+=`_${y(R)}`),M&&(u+=`^${y(M)}`)}return u},a=s(i);return k([a?`{}${a}`:"",n?y(n):"{}",s(o)])}case"mrow":case"mpadded":case"merror":case"maction":case"mtd":return A(e,0);case"mstack":case"mlongdiv":case"msgroup":return e.children.filter(t=>t.kind==="row").map(F).join("\\\\");default:return e.children.map(t=>t.kind==="row"?F(t):"").join("")}}function Ao(e){if(e.tag==="mspace"){if(e.attrs.linebreak==="newline")return"\\\\";let t=e.attrs.width;return t==="-0.2em"||t==="-0.1667em"?"\\!":t==="2em"?"\\qquad ":t==="1em"?"\\quad ":t?`\\hspace{${t}}`:""}return""}function yo(e){switch(e.kind){case"token":return go(e);case"leaf":return Ao(e);case"element":return No(e)}}function he(e){let t=T(e.root.children),n=t.length===1?t[0]:void 0;return n?.kind==="element"&&n.tag==="mstyle"?Tn(n,!0).trim():F(e.root).trim()}function Eo(e){return Sn(e).trim()}function bi(e){return Q(ie(e))}function xi(e){return he(Y(e).doc)}export{Xo as DEFAULT_HISTORY_LIMIT,Pe as FUNCTION_NAMES,Tt as History,Xt as INFERRED_ROW_TAGS,C as LatexParseError,Nt as MATHML_NS,qe as MAX_FUNCTION_NAME_LENGTH,Ve as MathEditorModel,Kt as MathMLParseError,pe as SLOT_COUNT,L as XmlParseError,Yt as buildIndex,rt as cloneDocument,W as cloneNode,qt as colorToHex,ge as decodeEntities,ke as decodeSafeXml,ri as describeCaret,c as element,fe as emptyDocument,$ as enclosingElement,Oo as encodeSafeXml,dt as escapeXml,Co as findById,To as isEmptyRow,je as isFunctionName,So as isRow,xe as isSafeXml,bi as latexToMathML,I as leaf,xi as mathMLToLatex,T as mergeAtoms,nt as newId,Eo as nodesToLatexString,Le as normalizeForEditing,V as ownRows,ie as parseLatex,wn as parseLatexNodes,Y as parseMathML,we as parseXml,h as row,Ct as rowPath,si as sanitizeMathDocument,$e as serializeFragment,he as serializeLatex,Q as serializeMathML,St as serializeNode,ht as textContent,dn as toAccessibleText,p as token,ct as walk};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type MathDocument, type MathNode } from '../model.js';
|
|
2
|
+
import { INTEGRALS } from './symbols.js';
|
|
3
|
+
export declare class LatexParseError extends Error {
|
|
4
|
+
readonly position: number;
|
|
5
|
+
constructor(message: string, position: number);
|
|
6
|
+
}
|
|
7
|
+
export declare function colorToHex(spec: string, model: string | null): string;
|
|
8
|
+
/** Parses LaTeX math into nodes. Throws {@link LatexParseError}. */
|
|
9
|
+
export declare function parseLatexNodes(latex: string): MathNode[];
|
|
10
|
+
export declare function parseLatex(latex: string): MathDocument;
|
|
11
|
+
export { INTEGRALS };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { MathDocument, MathNode } from '../model.js';
|
|
2
|
+
/** Serializes a document to LaTeX in MathType's compact style (e.g. `\frac12+\sqrt x`). */
|
|
3
|
+
export declare function serializeLatex(doc: MathDocument): string;
|
|
4
|
+
export declare function nodesToLatexString(nodes: readonly MathNode[]): string;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** LaTeX control words that map to a single character. `mi` entries are identifiers, the rest operators. */
|
|
2
|
+
export declare const GREEK: Readonly<Record<string, string>>;
|
|
3
|
+
export declare const OPERATORS: Readonly<Record<string, string>>;
|
|
4
|
+
/** Large operators: limits go under/over (`munderover`), except integrals (`msubsup`). */
|
|
5
|
+
export declare const BIG_OPERATORS: Readonly<Record<string, string>>;
|
|
6
|
+
/** Large forms MathType writes as the ordinary operator with `largeop="true"`. */
|
|
7
|
+
export declare const LARGEOP_COMMANDS: Readonly<Record<string, string>>;
|
|
8
|
+
/** Script capitals with letterlike code points; `\mathcal` writes them as operators. */
|
|
9
|
+
export declare const SCRIPT_LETTERLIKE: Readonly<Record<string, string>>;
|
|
10
|
+
export declare const INTEGRALS: ReadonlySet<string>;
|
|
11
|
+
export declare const LIMIT_OPERATOR_CHARS: ReadonlySet<string>;
|
|
12
|
+
/** Function-like names (`\sin`, `\lim`); limits of the `LIMIT_FUNCTIONS` go under the name. */
|
|
13
|
+
export declare const FUNCTION_COMMANDS: readonly string[];
|
|
14
|
+
export declare const LIMIT_FUNCTIONS: ReadonlySet<string>;
|
|
15
|
+
/** Spacing commands as MathType emits them. */
|
|
16
|
+
export declare const SPACES: Readonly<Record<string, {
|
|
17
|
+
char?: string;
|
|
18
|
+
width?: string;
|
|
19
|
+
}>>;
|
|
20
|
+
/** Accents written with `\cmd{x}` → `<mover>`; only `\vec` carries `accent="true"` in MathType. */
|
|
21
|
+
export declare const ACCENTS: Readonly<Record<string, string>>;
|
|
22
|
+
export declare const FLAGGED_ACCENTS: ReadonlySet<string>;
|
|
23
|
+
/** Wide over/under constructions without the accent flag. */
|
|
24
|
+
export declare const OVER_COMMANDS: Readonly<Record<string, string>>;
|
|
25
|
+
export declare const UNDER_COMMANDS: Readonly<Record<string, string>>;
|
|
26
|
+
export declare const MATHVARIANT_COMMANDS: Readonly<Record<string, string>>;
|
|
27
|
+
/** Double-struck letters with dedicated code points (written as `<mi mathvariant="normal">`). */
|
|
28
|
+
export declare const DOUBLE_STRUCK: Readonly<Record<string, string>>;
|
|
29
|
+
export declare const FENCE_COMMANDS: Readonly<Record<string, string>>;
|
|
30
|
+
export declare const NAMED_COLORS: Readonly<Record<string, string>>;
|
|
31
|
+
/** Preferred LaTeX command for a character (first entry wins, e.g. `≤` → `leq`). */
|
|
32
|
+
export declare const CHAR_TO_COMMAND: ReadonlyMap<string, string>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type MathDocument, type MathNode } from './model.js';
|
|
2
|
+
export declare const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
|
|
3
|
+
export interface ParsedMathML {
|
|
4
|
+
doc: MathDocument;
|
|
5
|
+
/** LaTeX from `<annotation encoding="LaTeX">` when present. */
|
|
6
|
+
latex: string | null;
|
|
7
|
+
}
|
|
8
|
+
export declare class MathMLParseError extends Error {
|
|
9
|
+
constructor(message: string);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Rewrites MathType's editor applies when it opens a formula, all rendering-equivalent: named colours
|
|
13
|
+
* become hex, letterlike operators (`ℒ`, `ℜ`) become a letter with a mathvariant, `∼` becomes `~` and
|
|
14
|
+
* `‥` becomes `¨`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function normalizeForEditing(doc: MathDocument): void;
|
|
17
|
+
export interface ParseOptions {
|
|
18
|
+
/** Receives the ids of rows that came from `<maction actiontype="argument">` (template slots). */
|
|
19
|
+
argumentRows?: Set<number>;
|
|
20
|
+
}
|
|
21
|
+
/** Parses MathML (plain or safeXml-encoded). Throws {@link MathMLParseError} on malformed input. */
|
|
22
|
+
export declare function parseMathML(source: string, options?: ParseOptions): ParsedMathML;
|
|
23
|
+
/** Inlines placeholder groups and merges consecutive single-character `mn`/`mtext` atoms with equal attributes. */
|
|
24
|
+
export declare function mergeAtoms(children: readonly MathNode[]): MathNode[];
|
|
25
|
+
export declare function serializeNode(node: MathNode): string;
|
|
26
|
+
export interface SerializeOptions {
|
|
27
|
+
/** Adds `<semantics>` with a LaTeX annotation. */
|
|
28
|
+
latexAnnotation?: string;
|
|
29
|
+
}
|
|
30
|
+
/** Serializes in MathType-compatible form: `<math xmlns=...>`, `&#xHEX;` entities, `<mrow/>` for empty slots. */
|
|
31
|
+
export declare function serializeMathML(doc: MathDocument, options?: SerializeOptions): string;
|
|
32
|
+
/** Serializes a row fragment (used by clipboard and templates). */
|
|
33
|
+
export declare function serializeFragment(nodes: readonly MathNode[]): string;
|