mathtex-editor-core 0.1.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
446
447
448
//! The editable data model uses a `Seq` and `Node` tree backed by stable slotmap ids.

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

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

/// The editable math tree.
#[derive(Debug, Clone)]
pub struct Tree {
    pub(crate) nodes: SlotMap<NodeId, Node>,
    pub(crate) seqs: SlotMap<SeqId, Seq>,
    pub(crate) root: SeqId,
}

impl Default for Tree {
    fn default() -> Self {
        Self::new()
    }
}

impl Tree {
    /// A new tree with an empty root sequence.
    pub 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,
        }
    }

    /// Return the root sequence id.
    pub fn root(&self) -> SeqId {
        self.root
    }
    /// Return a node by id.
    pub fn node(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(id)
    }
    /// Return a sequence by id.
    pub fn seq(&self, id: SeqId) -> Option<&Seq> {
        self.seqs.get(id)
    }
    /// Return a node payload by id.
    pub fn kind(&self, id: NodeId) -> Option<&Kind> {
        self.nodes.get(id).map(|n| &n.kind)
    }
    /// Return the node ids stored in a sequence.
    pub fn items(&self, id: SeqId) -> &[NodeId] {
        self.seqs.get(id).map_or(&[], |s| s.items.as_slice())
    }
    /// Return the number of nodes in a sequence.
    pub fn len(&self, id: SeqId) -> usize {
        self.items(id).len()
    }
    /// An empty sequence is a structural placeholder.
    pub fn is_empty(&self, id: SeqId) -> bool {
        self.items(id).is_empty()
    }

    /// The node that owns this sequence as a slot, or `None` for the root.
    pub 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,
        }
    }

    /// The sequence and index where this node currently lives.
    pub 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))
    }

    /// All present slot sequences of a node in canonical navigation and ownership order.
    pub fn child_seqs(&self, node: NodeId) -> Vec<SeqId> {
        let Some(n) = self.nodes.get(node) else {
            return Vec::new();
        };
        match &n.kind {
            Kind::Atom(_) => 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 struct Seq {
    /// The node that owns this sequence, or `None` for the root sequence.
    pub parent: Option<NodeId>,
    /// The ordered nodes stored in this sequence.
    pub items: Vec<NodeId>,
}

/// A node, which always lives inside a sequence.
#[derive(Debug, Clone)]
pub struct Node {
    /// The sequence that contains this node.
    pub parent: SeqId,
    /// The payload carried by this node.
    pub kind: Kind,
}

/// Node payloads. Every editable slot is a `SeqId`.
#[derive(Debug, Clone)]
pub enum Kind {
    /// A single leaf token.
    Atom(Symbol),
    /// A fraction with numerator and denominator slots.
    Frac {
        /// The numerator slot.
        num: SeqId,
        /// The denominator slot.
        den: SeqId,
        /// The visual fraction style.
        style: FracStyle,
    },
    /// Subscripts and superscripts on an editable base.
    Script {
        /// The base slot.
        base: SeqId,
        /// The optional subscript slot.
        sub: Option<SeqId>,
        /// The optional superscript slot.
        sup: Option<SeqId>,
    },
    /// A fixed big operator with editable lower and upper limit slots.
    BigOp {
        /// The operator nucleus.
        op: Symbol,
        /// The lower limit slot.
        lower: SeqId,
        /// The upper limit slot.
        upper: SeqId,
    },
    /// A radical with degree and radicand slots.
    Sqrt {
        /// The degree slot.
        index: SeqId,
        /// The radicand slot.
        radicand: SeqId,
    },
    /// A delimited expression.
    Delim {
        /// The opening delimiter.
        open: char,
        /// The closing delimiter.
        close: char,
        /// The delimited body slot.
        body: SeqId,
    },
    /// A fixed accent mark attached to an editable base.
    Accent {
        /// The accent mark.
        mark: Mark,
        /// The accented base slot.
        base: SeqId,
    },
    /// An editable base with optional over and under labels.
    UnderOver {
        /// The base slot.
        base: SeqId,
        /// The optional over slot.
        over: Option<SeqId>,
        /// The optional under slot.
        under: Option<SeqId>,
        /// The over decoration.
        over_deco: Deco,
        /// The under decoration.
        under_deco: Deco,
    },
    /// A styled content slot.
    Styled {
        /// The style variant.
        variant: Variant,
        /// The styled content slot.
        content: SeqId,
    },
    /// A rectangular grid of editable cell slots.
    Matrix {
        /// The matrix environment.
        env: MatrixEnv,
        /// The matrix cell slots by row.
        rows: Vec<Vec<SeqId>>,
    },
}

/// A leaf token plus its math class for editing heuristics.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Symbol {
    /// The 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 while escaping TeX special characters.
    pub fn from_char(c: char) -> Self {
        let latex = match c {
            '%' => "\\%".to_string(),
            '#' => "\\#".to_string(),
            '&' => "\\&".to_string(),
            '$' => "\\$".to_string(),
            '_' => "\\_".to_string(),
            '{' => "\\{".to_string(),
            '}' => "\\}".to_string(),
            '~' => "\\sim".to_string(),
            '\\' => "\\backslash".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(),
        };
        Symbol {
            latex,
            class: char_class(c),
        }
    }
}

/// 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);
    c.is_alphabetic() && !c.is_ascii() && !greek
}

/// Default math class for a typed character.
pub(crate) fn char_class(c: char) -> MathClass {
    match c {
        '+' | '-' | '*' => MathClass::Bin,
        '=' | '<' | '>' => MathClass::Rel,
        ',' | ';' | '.' | ':' => MathClass::Punct,
        '(' | '[' => MathClass::Open,
        ')' | ']' => MathClass::Close,
        _ => MathClass::Ord,
    }
}

/// Math atom classification used by editing heuristics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, 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, 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, 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, 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 used by under and over constructs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Deco {
    /// No decoration.
    None,
    /// Brace decoration.
    Brace,
    /// Arrow decoration.
    Arrow,
    /// Line decoration.
    Line,
}

/// Font or text variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, 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 style.
    Text,
    /// Operator name style.
    OperatorName,
}

/// Matrix environment type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, 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.
    Array,
}

/// Spec for inserting an under/over construct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, 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 cursor is a gap in a sequence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cursor {
    /// The sequence containing the cursor.
    pub seq: SeqId,
    /// The gap index inside the sequence.
    pub index: usize,
}

/// A selection is a contiguous run within one sequence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Selection {
    /// The selected sequence.
    pub seq: SeqId,
    /// The anchor gap index.
    pub anchor: usize,
    /// The focus gap index.
    pub focus: usize,
}