mathtex-editor-core 0.3.0

Headless core of the mathtex structural math editor: model, operations, navigation, selection, IR matching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! The editable tree: sequences of nodes with stable slotmap ids and parent links.

use serde::{Deserialize, Serialize};
use slotmap::{new_key_type, SlotMap};

new_key_type! {
    /// Stable identity of a node.
    pub(crate) struct NodeId;
    /// Stable identity of an editable sequence.
    pub(crate) struct SeqId;
}

/// The editable math tree.
#[derive(Debug, Clone)]
pub(crate) struct Tree {
    pub(crate) nodes: SlotMap<NodeId, Node>,
    pub(crate) seqs: SlotMap<SeqId, Seq>,
    pub(crate) root: SeqId,
    // Bumped by every primitive that changes content, so callers detect no-op commands.
    pub(crate) edits: u64,
}

impl Tree {
    pub(crate) fn new() -> Self {
        let mut seqs: SlotMap<SeqId, Seq> = SlotMap::with_key();
        let root = seqs.insert(Seq { parent: None, items: Vec::new() });
        Self { nodes: SlotMap::with_key(), seqs, root, edits: 0 }
    }

    pub(crate) fn root(&self) -> SeqId {
        self.root
    }

    pub(crate) fn kind(&self, id: NodeId) -> Option<&Kind> {
        self.nodes.get(id).map(|n| &n.kind)
    }

    pub(crate) fn items(&self, id: SeqId) -> &[NodeId] {
        self.seqs.get(id).map_or(&[], |s| s.items.as_slice())
    }

    pub(crate) fn len(&self, id: SeqId) -> usize {
        self.items(id).len()
    }

    pub(crate) fn is_empty(&self, id: SeqId) -> bool {
        self.items(id).is_empty()
    }

    pub(crate) fn touch(&mut self) {
        self.edits += 1;
    }

    /// The node that owns this sequence as a slot, or `None` for the root.
    pub(crate) fn seq_parent(&self, id: SeqId) -> Option<NodeId> {
        self.seqs.get(id).and_then(|s| s.parent)
    }

    /// If `seq` is the base slot of a Script, the owning Script node.
    pub(crate) fn script_base_node(&self, seq: SeqId) -> Option<NodeId> {
        let parent = self.seq_parent(seq)?;
        match self.kind(parent) {
            Some(Kind::Script { base, .. }) if *base == seq => Some(parent),
            _ => None,
        }
    }

    /// Whether `seq` is the content of a `\text{}` node, where only atoms may live.
    pub(crate) fn is_text_slot(&self, seq: SeqId) -> bool {
        let Some(parent) = self.seq_parent(seq) else {
            return false;
        };
        matches!(self.kind(parent), Some(Kind::Styled { variant: Variant::Text, .. }))
    }

    /// The sequence and index where this node currently lives.
    pub(crate) fn index_in_parent(&self, node: NodeId) -> Option<(SeqId, usize)> {
        let parent = self.nodes.get(node)?.parent;
        let idx = self.seqs.get(parent)?.items.iter().position(|&n| n == node)?;
        Some((parent, idx))
    }

    /// The gap just before the node that owns `seq`, or `None` for the root.
    pub(crate) fn before_parent(&self, seq: SeqId) -> Option<Cursor> {
        let node = self.seq_parent(seq)?;
        let (seq, index) = self.index_in_parent(node)?;
        Some(Cursor { seq, index })
    }

    /// Number of slots enclosing `seq`, zero for the root.
    pub(crate) fn seq_depth(&self, seq: SeqId) -> usize {
        let mut depth = 0;
        let mut cur = seq;
        while let Some(node) = self.seq_parent(cur) {
            depth += 1;
            let Some(n) = self.nodes.get(node) else { break };
            cur = n.parent;
        }
        depth
    }

    /// Slot levels a node adds below its own sequence, zero for leaves.
    pub(crate) fn node_height(&self, node: NodeId) -> usize {
        self.child_seqs(node)
            .into_iter()
            .map(|s| 1 + self.seq_height(s))
            .max()
            .unwrap_or(0)
    }

    pub(crate) fn seq_height(&self, seq: SeqId) -> usize {
        self.items(seq).iter().map(|&n| self.node_height(n)).max().unwrap_or(0)
    }

    /// All present slot sequences of a node in canonical navigation and ownership order.
    pub(crate) fn child_seqs(&self, node: NodeId) -> Vec<SeqId> {
        let Some(n) = self.nodes.get(node) else {
            return Vec::new();
        };
        match &n.kind {
            Kind::Atom(_) | Kind::HostBox { .. } => Vec::new(),
            Kind::Frac { num, den, .. } => vec![*num, *den],
            Kind::Script { base, sub, sup } => {
                let mut v = vec![*base];
                v.extend(sub.iter().copied());
                v.extend(sup.iter().copied());
                v
            }
            // Upper first so leftward navigation enters the lower limit before the upper one.
            Kind::BigOp { upper, lower, .. } => vec![*upper, *lower],
            Kind::Sqrt { index, radicand } => vec![*index, *radicand],
            Kind::Delim { body, .. } => vec![*body],
            Kind::Accent { base, .. } => vec![*base],
            Kind::UnderOver { base, over, under, .. } => {
                let mut v = Vec::new();
                v.extend(over.iter().copied());
                v.push(*base);
                v.extend(under.iter().copied());
                v
            }
            Kind::Styled { content, .. } => vec![*content],
            Kind::Matrix { rows, .. } => rows.iter().flatten().copied().collect(),
        }
    }
}

/// An ordered run of nodes with an optional owning node.
#[derive(Debug, Clone)]
pub(crate) struct Seq {
    pub(crate) parent: Option<NodeId>,
    pub(crate) items: Vec<NodeId>,
}

/// A node, which always lives inside a sequence.
#[derive(Debug, Clone)]
pub(crate) struct Node {
    pub(crate) parent: SeqId,
    pub(crate) kind: Kind,
}

/// Node payloads, every editable slot is a `SeqId`.
#[derive(Debug, Clone)]
pub(crate) enum Kind {
    Atom(Symbol),
    HostBox { token: u32 },
    Frac { num: SeqId, den: SeqId, style: FracStyle },
    Script { base: SeqId, sub: Option<SeqId>, sup: Option<SeqId> },
    BigOp { op: Symbol, lower: SeqId, upper: SeqId },
    Sqrt { index: SeqId, radicand: SeqId },
    Delim { open: char, close: char, body: SeqId },
    Accent { mark: Mark, base: SeqId },
    UnderOver { base: SeqId, over: Option<SeqId>, under: Option<SeqId>, over_deco: Deco, under_deco: Deco },
    Styled { variant: Variant, content: SeqId },
    Matrix { env: MatrixEnv, rows: Vec<Vec<SeqId>> },
}

/// A leaf token plus its math class for editing heuristics.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Symbol {
    /// The math mode LaTeX emitted for this symbol.
    pub latex: String,
    /// The math class used by editing heuristics.
    pub class: MathClass,
}

impl Symbol {
    /// Build a symbol from a typed character, escaping TeX specials, `None` for control characters.
    pub fn from_char(c: char) -> Option<Self> {
        if c.is_control() {
            return None;
        }
        let latex = match c {
            '%' | '#' | '&' | '$' | '_' | '{' | '}' => format!("\\{c}"),
            '~' => "\\sim".to_string(),
            '\\' => "\\backslash".to_string(),
            '^' => "\\text{\\textasciicircum}".to_string(),
            '\'' => "\\prime".to_string(),
            ' ' => "\\ ".to_string(),
            // Text mode carries letters that XeTeX math mode will not render directly.
            other if needs_text_mode(other) => format!("\\text{{{other}}}"),
            other => other.to_string(),
        };
        let class = latex_class(&latex);
        Some(Symbol { latex, class })
    }

    /// A symbol for LaTeX such as `\leq`, classed by the same table as [`Symbol::from_char`].
    pub fn from_latex(latex: &str) -> Self {
        Symbol { latex: latex.to_string(), class: latex_class(latex) }
    }
}

/// A letter that XeTeX math mode won't render directly.
fn needs_text_mode(c: char) -> bool {
    let greek = ('\u{0370}'..='\u{03FF}').contains(&c) || ('\u{1F00}'..='\u{1FFF}').contains(&c);
    // Letterlike symbols such as ℝ and the math alphanumerics such as 𝑥 are math characters already.
    let letterlike = ('\u{2100}'..='\u{214F}').contains(&c);
    let math_alnum = ('\u{1D400}'..='\u{1D7FF}').contains(&c);
    c.is_alphabetic() && !c.is_ascii() && !greek && !letterlike && !math_alnum
}

/// Default math class for a typed character.
fn char_class(c: char) -> MathClass {
    match c {
        '+' | '-' | '*' | '\u{2212}' | '±' | '∓' | '×' | '÷' | '·' | '∘' | '∙' => MathClass::Bin,
        '=' | '<' | '>' | '≤' | '≥' | '≠' | '≈' | '≡' | '∼' | '≅' | '∝' | '→' | '←' | '⇒' | '⇐' | '⇔'
        | '∈' | '∉' | '⊂' | '⊆' | '⊃' | '⊇' => MathClass::Rel,
        ',' | ';' | '.' | ':' => MathClass::Punct,
        '(' | '[' | '{' | '⟨' | '⌈' | '⌊' => MathClass::Open,
        ')' | ']' | '}' | '⟩' | '⌉' | '⌋' => MathClass::Close,
        _ => MathClass::Ord,
    }
}

/// Default class of a symbol's LaTeX, the one table behind every `Symbol` constructor.
fn latex_class(latex: &str) -> MathClass {
    let mut chars = latex.chars();
    if let (Some(c), None) = (chars.next(), chars.next()) {
        return char_class(c);
    }
    let Some(name) = latex.strip_prefix('\\') else {
        return MathClass::Ord;
    };
    if OPERATOR_NAMES.contains(&name) {
        return MathClass::Op;
    }
    match name {
        "{" | "langle" | "lceil" | "lfloor" => MathClass::Open,
        "}" | "rangle" | "rceil" | "rfloor" => MathClass::Close,
        "leq" | "le" | "geq" | "ge" | "neq" | "ne" | "equiv" | "approx" | "cong" | "sim" | "simeq" | "propto"
        | "to" | "gets" | "mapsto" | "implies" | "iff" | "in" | "notin" | "ni" | "subset" | "subseteq"
        | "supset" | "supseteq" | "rightarrow" | "leftarrow" | "leftrightarrow" | "Rightarrow" | "Leftarrow"
        | "Leftrightarrow" | "Longrightarrow" | "Longleftarrow" | "perp" | "parallel" | "mid" | "ll" | "gg" => {
            MathClass::Rel
        }
        "pm" | "mp" | "times" | "div" | "cdot" | "ast" | "star" | "cup" | "cap" | "setminus" | "circ" | "oplus"
        | "otimes" | "wedge" | "vee" | "land" | "lor" => MathClass::Bin,
        "cdots" | "ldots" | "dots" | "vdots" | "ddots" => MathClass::Inner,
        "sum" | "prod" | "coprod" | "int" | "iint" | "iiint" | "oint" | "bigcup" | "bigcap" | "bigsqcup" | "biguplus"
        | "bigoplus" | "bigotimes" | "bigodot" | "bigvee" | "bigwedge" => MathClass::Op,
        _ => MathClass::Ord,
    }
}

/// Operator names that typeset upright, such as `\sin`, classed `Op`.
const OPERATOR_NAMES: &[&str] = &[
    "sin", "cos", "tan", "cot", "sec", "csc", "sinh", "cosh", "tanh", "arcsin", "arccos", "arctan", "log", "ln",
    "exp", "lim", "max", "min", "sup", "inf", "gcd", "det", "dim", "ker", "arg", "deg", "hom",
];

/// Math atom classification used by editing heuristics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MathClass {
    /// Ordinary math atom.
    Ord,
    /// Operator atom.
    Op,
    /// Binary operator atom.
    Bin,
    /// Relation atom.
    Rel,
    /// Opening delimiter atom.
    Open,
    /// Closing delimiter atom.
    Close,
    /// Punctuation atom.
    Punct,
    /// Inner atom.
    Inner,
}

/// Fraction rendering style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FracStyle {
    /// Standard fraction bar style.
    Bar,
    /// Display fraction style.
    Display,
    /// Text fraction style.
    Text,
    /// Binomial fraction style.
    Binom,
    /// Fraction layout without a bar.
    Atop,
}

/// Script slot selector.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ScriptSlot {
    /// Subscript slot.
    Sub,
    /// Superscript slot.
    Sup,
}

/// Accent mark type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mark {
    /// Hat accent.
    Hat,
    /// Vector accent.
    Vec,
    /// Bar accent.
    Bar,
    /// Tilde accent.
    Tilde,
    /// Dot accent.
    Dot,
    /// Double dot accent.
    Ddot,
    /// Wide hat accent.
    Widehat,
    /// Wide tilde accent.
    Widetilde,
    /// Overline accent.
    Overline,
    /// Underline accent.
    Underline,
    /// Check accent.
    Check,
    /// Breve accent.
    Breve,
}

/// Decoration drawn between an under or over label and its base.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Deco {
    /// No decoration, the label sits directly above or below.
    None,
    /// A horizontal brace.
    Brace,
    /// A rightward arrow.
    Arrow,
    /// A horizontal line.
    Line,
}

/// Font or text variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Variant {
    /// Normal math style.
    Normal,
    /// Bold math style.
    Bold,
    /// Blackboard bold math style.
    Blackboard,
    /// Calligraphic math style.
    Calligraphic,
    /// Fraktur math style.
    Fraktur,
    /// Roman math style.
    Roman,
    /// Sans serif math style.
    SansSerif,
    /// Typewriter math style.
    Typewriter,
    /// Text mode, whose slot holds only atoms.
    Text,
    /// Operator name style.
    OperatorName,
}

/// Matrix environment type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MatrixEnv {
    /// Plain matrix environment.
    Matrix,
    /// Parenthesized matrix environment.
    Pmatrix,
    /// Bracketed matrix environment.
    Bmatrix,
    /// Vertically barred matrix environment.
    Vmatrix,
    /// Cases environment.
    Cases,
    /// Aligned environment.
    Aligned,
    /// Array environment with centered columns.
    Array,
}

/// Spec for inserting an under or over construct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UnderOverSpec {
    /// Whether to include an over slot.
    pub over: bool,
    /// Whether to include an under slot.
    pub under: bool,
    /// The over decoration to apply.
    pub over_deco: Deco,
    /// The under decoration to apply.
    pub under_deco: Deco,
}

/// A caret is a gap in a sequence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Cursor {
    pub(crate) seq: SeqId,
    pub(crate) index: usize,
}

/// A contiguous run within one sequence between two gaps.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SeqRange {
    pub(crate) seq: SeqId,
    pub(crate) anchor: usize,
    pub(crate) focus: usize,
}

impl SeqRange {
    pub(crate) fn lo(&self) -> usize {
        self.anchor.min(self.focus)
    }

    pub(crate) fn hi(&self) -> usize {
        self.anchor.max(self.focus)
    }
}