Skip to main content

mt_core/
ast.rs

1//! The equation tree shared by the parsers, the editor and the renderers.
2//!
3//! The model follows the shape of an equation as an author sees it rather than a TeX token
4//! stream: an equation is a [`Row`] of items, templates such as fractions or radicals own their
5//! argument slots, and every node exposes a fixed, ordered list of slots. Editing code can
6//! therefore walk and mutate any construct without knowing what the construct is, and layout can
7//! recurse over the same slot list.
8
9/// A complete equation together with the size preset it is laid out at.
10#[derive(Clone, Debug, Default, PartialEq, Eq)]
11pub struct Math {
12    pub body: Node,
13    pub style: MathStyle,
14}
15
16impl Math {
17    /// An equation wrapping `body` at full size.
18    pub fn new(body: impl Into<Node>) -> Self {
19        Self {
20            body: body.into(),
21            style: MathStyle::Full,
22        }
23    }
24
25    pub fn node_at(&self, path: &Path) -> Option<&Node> {
26        self.body.node_at(path)
27    }
28
29    pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
30        self.body.node_at_mut(path)
31    }
32}
33
34/// Size preset an equation is laid out at, matching the size classes an author picks from.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
36pub enum MathStyle {
37    /// Inline text size.
38    Text,
39    /// Smaller than text, one step down in the nesting hierarchy.
40    Script,
41    /// Smallest supported size, two steps down in the nesting hierarchy.
42    ScriptScript,
43    /// Full size.
44    #[default]
45    Full,
46}
47
48impl MathStyle {
49    /// The next smaller preset, saturating at [`MathStyle::ScriptScript`].
50    pub fn smaller(self) -> Self {
51        match self {
52            MathStyle::Full => MathStyle::Script,
53            MathStyle::Text => MathStyle::Script,
54            MathStyle::Script => MathStyle::ScriptScript,
55            MathStyle::ScriptScript => MathStyle::ScriptScript,
56        }
57    }
58}
59
60/// Horizontal sequence of items.
61pub type Row = Vec<Node>;
62
63/// One item of an equation.
64///
65/// Template variants are boxed so that a `Node` stays pointer sized.
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub enum Node {
68    /// Horizontal sequence of items; an empty row is an empty argument slot.
69    Row(Row),
70    /// A single character with its atom class and font.
71    Char(Char),
72    /// Literal text set upright (`\text{...}` and friends).
73    Text(Box<TextRun>),
74    /// Explicit horizontal spacing.
75    Space(Space),
76    /// Fraction, with or without a rule.
77    Frac(Box<Frac>),
78    /// Radical with an optional index.
79    Sqrt(Box<Sqrt>),
80    /// Subscript and/or superscript attached to a base.
81    Scripts(Box<Scripts>),
82    /// Over/under material that is not an accent (`\overset`, `\stackrel`, limits).
83    Limits(Box<Limits>),
84    /// Delimiters around a body.
85    Fence(Box<Fence>),
86    /// Table of cells with optional delimiters and alignment.
87    Matrix(Box<Matrix>),
88    /// Accent over or under a base.
89    Accent(Box<Accent>),
90    /// Large operator with optional limits.
91    Big(Box<BigOp>),
92    /// Style, font or class applied to a subtree.
93    Styled(Box<Styled>),
94    /// Alignment point (`&` inside aligned environments).
95    Align,
96    /// Construct kept verbatim because it could not be represented.
97    Error(String),
98}
99
100impl Node {
101    /// An empty row, i.e. an empty slot.
102    pub fn empty() -> Self {
103        Node::Row(Row::new())
104    }
105
106    pub fn row(items: impl IntoIterator<Item = Node>) -> Self {
107        Node::Row(items.into_iter().collect())
108    }
109
110    /// A character carrying `class` and `font`.
111    pub fn char_with(ch: char, class: Class, font: Font) -> Self {
112        Node::Char(Char { ch, class, font })
113    }
114
115    /// A default-class italic variable.
116    pub fn variable(ch: char) -> Self {
117        Node::Char(Char {
118            ch,
119            class: Class::Ord,
120            font: Font::Italic,
121        })
122    }
123
124    /// A default-class upright operator or symbol.
125    pub fn symbol(ch: char, class: Class) -> Self {
126        Node::Char(Char {
127            ch,
128            class,
129            font: Font::Upright,
130        })
131    }
132
133    pub fn text(text: impl Into<String>) -> Self {
134        Node::Text(Box::new(TextRun {
135            text: text.into(),
136            font: Font::Upright,
137        }))
138    }
139
140    /// True when the node is an empty row, which renderers draw as an empty slot.
141    pub fn is_empty_slot(&self) -> bool {
142        matches!(self, Node::Row(row) if row.is_empty())
143    }
144
145    /// Whether the node is a row and can therefore accept siblings.
146    pub fn is_row(&self) -> bool {
147        matches!(self, Node::Row(_))
148    }
149
150    /// Number of child slots the node exposes, in visual order.
151    pub fn slot_count(&self) -> usize {
152        match self {
153            Node::Row(row) => row.len(),
154            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => 0,
155            Node::Frac(_) => 2,
156            Node::Sqrt(sqrt) => 1 + usize::from(sqrt.index.is_some()),
157            Node::Scripts(_) => 3,
158            Node::Limits(_) => 3,
159            Node::Fence(_) => 1,
160            Node::Matrix(matrix) => matrix.rows.iter().map(Row::len).sum(),
161            Node::Accent(_) => 1,
162            Node::Big(_) => 3,
163            Node::Styled(_) => 1,
164        }
165    }
166
167    /// Read-only access to slot `index`, in the order defined by [`Node::slot_count`].
168    pub fn slot(&self, index: usize) -> Option<&Node> {
169        match self {
170            Node::Row(row) => row.get(index),
171            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
172            Node::Frac(frac) => match index {
173                0 => Some(&frac.num),
174                1 => Some(&frac.den),
175                _ => None,
176            },
177            Node::Sqrt(sqrt) => match (index, &sqrt.index) {
178                (0, Some(radicand)) => Some(radicand),
179                (0, None) => Some(&sqrt.radicand),
180                (1, Some(_)) => Some(&sqrt.radicand),
181                _ => None,
182            },
183            Node::Scripts(scripts) => match index {
184                0 => Some(&scripts.base),
185                1 => scripts.sub.as_ref(),
186                2 => scripts.sup.as_ref(),
187                _ => None,
188            },
189            Node::Limits(limits) => match index {
190                0 => Some(&limits.base),
191                1 => limits.under.as_ref(),
192                2 => limits.over.as_ref(),
193                _ => None,
194            },
195            Node::Fence(fence) => (index == 0).then_some(&fence.body),
196            Node::Matrix(matrix) => matrix.cell_at(index),
197            Node::Accent(accent) => (index == 0).then_some(&accent.base),
198            Node::Big(big) => match index {
199                0 => Some(&big.base),
200                1 => big.sub.as_ref(),
201                2 => big.sup.as_ref(),
202                _ => None,
203            },
204            Node::Styled(styled) => (index == 0).then_some(&styled.body),
205        }
206    }
207
208    /// Mutable access to slot `index`, in the order defined by [`Node::slot_count`].
209    pub fn slot_mut(&mut self, index: usize) -> Option<&mut Node> {
210        match self {
211            Node::Row(row) => row.get_mut(index),
212            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
213            Node::Frac(frac) => match index {
214                0 => Some(&mut frac.num),
215                1 => Some(&mut frac.den),
216                _ => None,
217            },
218            Node::Sqrt(sqrt) => match (index, &mut sqrt.index) {
219                (0, Some(radicand)) => Some(radicand),
220                (0, None) => Some(&mut sqrt.radicand),
221                (1, Some(_)) => Some(&mut sqrt.radicand),
222                _ => None,
223            },
224            Node::Scripts(scripts) => match index {
225                0 => Some(&mut scripts.base),
226                1 => scripts.sub.as_mut(),
227                2 => scripts.sup.as_mut(),
228                _ => None,
229            },
230            Node::Limits(limits) => match index {
231                0 => Some(&mut limits.base),
232                1 => limits.under.as_mut(),
233                2 => limits.over.as_mut(),
234                _ => None,
235            },
236            Node::Fence(fence) => (index == 0).then_some(&mut fence.body),
237            Node::Matrix(matrix) => matrix.cell_at_mut(index),
238            Node::Accent(accent) => (index == 0).then_some(&mut accent.base),
239            Node::Big(big) => match index {
240                0 => Some(&mut big.base),
241                1 => big.sub.as_mut(),
242                2 => big.sup.as_mut(),
243                _ => None,
244            },
245            Node::Styled(styled) => (index == 0).then_some(&mut styled.body),
246        }
247    }
248
249    /// Slots in visual order. Allocates; use [`Node::slot_count`] plus [`Node::slot`] in hot paths.
250    pub fn slots(&self) -> Vec<&Node> {
251        (0..self.slot_count())
252            .filter_map(|i| self.slot(i))
253            .collect()
254    }
255
256    /// Depth-first walk over the node and every node reachable through its slots.
257    pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Node)) {
258        visit(self);
259        for index in 0..self.slot_count() {
260            if let Some(slot) = self.slot(index) {
261                slot.walk(visit);
262            }
263        }
264    }
265
266    /// Node reached by following `path` from here.
267    pub fn node_at(&self, path: &Path) -> Option<&Node> {
268        let mut current = self;
269        for &index in path.as_slice() {
270            current = current.slot(index)?;
271        }
272        Some(current)
273    }
274
275    /// Mutable node reached by following `path` from here.
276    pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
277        let mut current = self;
278        for &index in path.as_slice() {
279            current = current.slot_mut(index)?;
280        }
281        Some(current)
282    }
283
284    /// Replace the node at `path`, returning the replaced node.
285    ///
286    /// The root cannot be replaced: pass a non-empty path.
287    pub fn replace_at(&mut self, path: &Path, node: Node) -> Option<Node> {
288        let (parent_path, index) = path.split_last()?;
289        let parent = self.node_at_mut(&parent_path)?;
290        match parent {
291            Node::Row(row) => {
292                let target = row.get_mut(index)?;
293                Some(std::mem::replace(target, node))
294            }
295            other => {
296                let target = other.slot_mut(index)?;
297                Some(std::mem::replace(target, node))
298            }
299        }
300    }
301
302    /// Insert `node` into the row at `path`, directly before the item at `path` or appended when
303    /// the path names a row itself.
304    pub fn insert_at(&mut self, path: &Path, node: Node) -> bool {
305        match self.node_at_mut(path) {
306            Some(Node::Row(row)) => {
307                row.push(node);
308                true
309            }
310            Some(_) => match path.split_last() {
311                Some((parent_path, index)) => match self.node_at_mut(&parent_path) {
312                    Some(parent) => parent.insert_sibling(index, node),
313                    None => false,
314                },
315                None => false,
316            },
317            None => false,
318        }
319    }
320
321    /// Insert `node` before slot `index` of a row-like parent.
322    fn insert_sibling(&mut self, index: usize, node: Node) -> bool {
323        match self {
324            Node::Row(row) => {
325                let index = index.min(row.len());
326                row.insert(index, node);
327                true
328            }
329            _ => false,
330        }
331    }
332
333    /// Remove the node at `path`, returning it. The root cannot be removed.
334    pub fn remove_at(&mut self, path: &Path) -> Option<Node> {
335        let (parent_path, index) = path.split_last()?;
336        match self.node_at_mut(&parent_path)? {
337            Node::Row(row) => (index < row.len()).then(|| row.remove(index)),
338            _ => None,
339        }
340    }
341
342    /// Flatten rows nested directly inside a row and drop empty nested rows.
343    ///
344    /// Template slots are untouched, so this only removes row nesting that carries no meaning and
345    /// keeps parse-then-serialise round trips stable.
346    pub fn normalize(&mut self) {
347        for index in 0..self.slot_count() {
348            if let Some(slot) = self.slot_mut(index) {
349                slot.normalize();
350            }
351        }
352        if let Node::Row(row) = self {
353            let mut flat = Row::with_capacity(row.len());
354            for node in row.drain(..) {
355                match node {
356                    Node::Row(inner) => flat.extend(inner),
357                    other => flat.push(other),
358                }
359            }
360            *row = flat;
361        }
362    }
363}
364
365impl From<char> for Node {
366    fn from(ch: char) -> Self {
367        Node::variable(ch)
368    }
369}
370
371impl From<&str> for Node {
372    fn from(text: &str) -> Self {
373        Node::Text(Box::new(TextRun {
374            text: text.to_owned(),
375            font: Font::Upright,
376        }))
377    }
378}
379
380impl From<String> for Node {
381    fn from(text: String) -> Self {
382        Node::Text(Box::new(TextRun {
383            text,
384            font: Font::Upright,
385        }))
386    }
387}
388
389impl From<Vec<Node>> for Node {
390    fn from(items: Vec<Node>) -> Self {
391        Node::Row(items)
392    }
393}
394
395impl Default for Node {
396    /// An empty slot.
397    fn default() -> Self {
398        Node::empty()
399    }
400}
401
402/// A character together with the atom class that drives spacing and the font it is set in.
403#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
404pub struct Char {
405    pub ch: char,
406    pub class: Class,
407    pub font: Font,
408}
409
410/// Atom class, used for operator spacing between neighbouring atoms.
411#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
412pub enum Class {
413    /// Ordinary atom: variables, numbers, most symbols.
414    #[default]
415    Ord,
416    /// Large operator or function name taking limits.
417    Op,
418    /// Binary operator.
419    Bin,
420    /// Relation.
421    Rel,
422    /// Opening delimiter.
423    Open,
424    /// Closing delimiter.
425    Close,
426    /// Punctuation.
427    Punct,
428    /// Inner atom, e.g. a fraction or matrix.
429    Inner,
430}
431
432/// Typeface a run is set in.
433#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
434pub enum Font {
435    /// Italic math variable, the default for letters.
436    #[default]
437    Italic,
438    /// Upright roman.
439    Upright,
440    Bold,
441    BoldItalic,
442    SansSerif,
443    SansSerifBold,
444    SansSerifItalic,
445    SansSerifBoldItalic,
446    Monospace,
447    Script,
448    BoldScript,
449    Fraktur,
450    BoldFraktur,
451    DoubleStruck,
452    /// Symbols drawn from the symbol font rather than the text face.
453    Symbol,
454    /// Glyphs from the extra symbol face.
455    Extra,
456    /// Fences, the face MathType draws the characters decorating a template with.
457    Fences,
458    /// Euclid, the text face MathType names in an explicit font definition.
459    Euclid,
460    EuclidItalic,
461    EuclidBold,
462    EuclidBoldItalic,
463    /// Euclid Symbol, a symbol-encoded face MathType names in an explicit font definition.
464    EuclidSymbol,
465    EuclidSymbolItalic,
466    EuclidSymbolBold,
467    EuclidSymbolBoldItalic,
468    /// Euclid Extra, the extra face MathType names in an explicit font definition.
469    EuclidExtra,
470    EuclidExtraBold,
471}
472
473impl Font {
474    /// Whether the face is set in italics, which layout needs for metric selection.
475    pub fn is_italic(self) -> bool {
476        matches!(
477            self,
478            Font::Italic
479                | Font::BoldItalic
480                | Font::SansSerifItalic
481                | Font::SansSerifBoldItalic
482                | Font::EuclidItalic
483                | Font::EuclidBoldItalic
484                | Font::EuclidSymbolItalic
485                | Font::EuclidSymbolBoldItalic
486        )
487    }
488
489    /// Whether the face is bold.
490    pub fn is_bold(self) -> bool {
491        matches!(
492            self,
493            Font::Bold
494                | Font::BoldItalic
495                | Font::SansSerifBold
496                | Font::SansSerifBoldItalic
497                | Font::BoldScript
498                | Font::BoldFraktur
499                | Font::EuclidBold
500                | Font::EuclidBoldItalic
501                | Font::EuclidSymbolBold
502                | Font::EuclidSymbolBoldItalic
503                | Font::EuclidExtraBold
504        )
505    }
506}
507
508/// Literal text set upright, optionally in a specific face.
509#[derive(Clone, Debug, PartialEq, Eq)]
510pub struct TextRun {
511    pub text: String,
512    pub font: Font,
513}
514
515/// Explicit horizontal space.
516#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
517pub enum Space {
518    /// 3/18 em.
519    Thin,
520    /// 4/18 em.
521    Medium,
522    /// 5/18 em.
523    Thick,
524    /// 6/18 em.
525    Sixteenth,
526    /// 1 em.
527    Quad,
528    /// 2 em.
529    DoubleQuad,
530    /// -3/18 em.
531    NegativeThin,
532    /// -4/18 em.
533    NegativeMedium,
534    /// -5/18 em.
535    NegativeThick,
536}
537
538impl Space {
539    /// Width in em units, negative for backspacing.
540    pub fn em(self) -> f64 {
541        match self {
542            Space::Thin => 3.0 / 18.0,
543            Space::Medium => 4.0 / 18.0,
544            Space::Thick => 5.0 / 18.0,
545            Space::Sixteenth => 6.0 / 18.0,
546            Space::Quad => 1.0,
547            Space::DoubleQuad => 2.0,
548            Space::NegativeThin => -3.0 / 18.0,
549            Space::NegativeMedium => -4.0 / 18.0,
550            Space::NegativeThick => -5.0 / 18.0,
551        }
552    }
553}
554
555/// Fraction, with or without a rule, drawn stacked or inline.
556#[derive(Clone, Debug, PartialEq, Eq)]
557pub struct Frac {
558    pub num: Node,
559    pub den: Node,
560    pub kind: FracKind,
561}
562
563impl Frac {
564    pub fn new(num: Node, den: Node) -> Self {
565        Self {
566            num,
567            den,
568            kind: FracKind::Bar,
569        }
570    }
571}
572
573/// How a fraction is drawn.
574#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
575pub enum FracKind {
576    /// Stacked with a horizontal rule.
577    #[default]
578    Bar,
579    /// Stacked with a slash instead of a rule.
580    Slash,
581    /// Stacked without a rule, e.g. binomial coefficients.
582    NoBar,
583    /// Written inline as `a/b`.
584    Linear,
585}
586
587/// Radical, with an optional index for higher roots.
588#[derive(Clone, Debug, PartialEq, Eq)]
589pub struct Sqrt {
590    /// Root index; `None` is a square root.
591    pub index: Option<Node>,
592    pub radicand: Node,
593}
594
595impl Sqrt {
596    pub fn square(radicand: Node) -> Self {
597        Self {
598            index: None,
599            radicand,
600        }
601    }
602
603    pub fn nth(index: Node, radicand: Node) -> Self {
604        Self {
605            index: Some(index),
606            radicand,
607        }
608    }
609}
610
611/// Subscript and superscript attached to a base.
612#[derive(Clone, Debug, PartialEq, Eq)]
613pub struct Scripts {
614    pub base: Node,
615    pub sub: Option<Node>,
616    pub sup: Option<Node>,
617}
618
619impl Scripts {
620    /// Attach `sub`/`sup` to `base`.
621    ///
622    /// Merging into an existing [`Node::Scripts`] node is up to the caller, which knows whether
623    /// the new scripts belong inside or outside the existing ones.
624    pub fn attach(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
625        Self { base, sub, sup }
626    }
627}
628
629/// Over/under material that is not an accent.
630#[derive(Clone, Debug, PartialEq, Eq)]
631pub struct Limits {
632    pub base: Node,
633    pub under: Option<Node>,
634    pub over: Option<Node>,
635    pub align: Side,
636}
637
638/// Horizontal alignment of over/under material.
639#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
640pub enum Side {
641    #[default]
642    Center,
643    Left,
644    Right,
645}
646
647/// Delimiter shape.
648#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
649pub enum Delim {
650    Paren,
651    Bracket,
652    Brace,
653    Abs,
654    Norm,
655    Angle,
656    Floor,
657    Ceil,
658    /// No delimiter drawn.
659    None,
660    /// A specific character, drawn from a font that provides it.
661    Custom(char),
662    /// An arrow delimiter.
663    Arrow,
664    /// A double bar delimiter.
665    DoubleBar,
666}
667
668impl Delim {
669    /// The opening character, or `None` when nothing is drawn.
670    pub fn open(self) -> Option<char> {
671        Some(match self {
672            Delim::Paren => '(',
673            Delim::Bracket => '[',
674            Delim::Brace => '{',
675            Delim::Abs => '|',
676            Delim::Norm => '\u{2016}',
677            Delim::Angle => '\u{27E8}',
678            Delim::Floor => '\u{230A}',
679            Delim::Ceil => '\u{2308}',
680            Delim::None => return None,
681            Delim::Custom(ch) => ch,
682            Delim::Arrow => '\u{27E8}',
683            Delim::DoubleBar => '\u{2016}',
684        })
685    }
686
687    /// The closing character, or `None` when nothing is drawn.
688    pub fn close(self) -> Option<char> {
689        Some(match self {
690            Delim::Paren => ')',
691            Delim::Bracket => ']',
692            Delim::Brace => '}',
693            Delim::Abs => '|',
694            Delim::Norm => '\u{2016}',
695            Delim::Angle => '\u{27E9}',
696            Delim::Floor => '\u{230B}',
697            Delim::Ceil => '\u{2309}',
698            Delim::None => return None,
699            Delim::Custom(ch) => ch,
700            Delim::Arrow => '\u{27E9}',
701            Delim::DoubleBar => '\u{2016}',
702        })
703    }
704}
705
706/// Delimiters around a body.
707#[derive(Clone, Debug, PartialEq, Eq)]
708pub struct Fence {
709    pub open: Delim,
710    pub close: Delim,
711    pub body: Node,
712}
713
714/// Table of cells with optional delimiters.
715#[derive(Clone, Debug, PartialEq, Eq)]
716pub struct Matrix {
717    pub rows: Vec<Row>,
718    pub delims: Option<(Delim, Delim)>,
719    pub kind: MatrixKind,
720    /// Alignment applied to every column; per-column rules come from [`Matrix::columns`].
721    pub align: Side,
722    /// Optional per-column alignment overriding [`Matrix::align`].
723    pub columns: Vec<Side>,
724    /// Draws the horizontal and vertical cell rules of an array.
725    pub rules: bool,
726}
727
728impl Matrix {
729    /// A matrix of `rows` rows and `cols` columns, each cell an empty slot.
730    pub fn empty(rows: usize, cols: usize) -> Self {
731        Self {
732            rows: vec![vec![Node::empty(); cols]; rows],
733            delims: None,
734            kind: MatrixKind::Matrix,
735            align: Side::Center,
736            columns: Vec::new(),
737            rules: false,
738        }
739    }
740
741    /// Number of rows.
742    pub fn row_count(&self) -> usize {
743        self.rows.len()
744    }
745
746    /// Number of columns, taken from the widest row.
747    pub fn col_count(&self) -> usize {
748        self.rows.iter().map(Row::len).max().unwrap_or(0)
749    }
750
751    fn cell_position(&self, index: usize) -> Option<(usize, usize)> {
752        let mut remaining = index;
753        for (row, cells) in self.rows.iter().enumerate() {
754            if remaining < cells.len() {
755                return Some((row, remaining));
756            }
757            remaining -= cells.len();
758        }
759        None
760    }
761
762    /// Cell addressed by a flat slot index, row-major.
763    pub fn cell_at(&self, index: usize) -> Option<&Node> {
764        let (row, col) = self.cell_position(index)?;
765        self.rows[row].get(col)
766    }
767
768    /// Mutable cell addressed by a flat slot index, row-major.
769    pub fn cell_at_mut(&mut self, index: usize) -> Option<&mut Node> {
770        let (row, col) = self.cell_position(index)?;
771        self.rows[row].get_mut(col)
772    }
773}
774
775/// Kind of table, which decides delimiter defaults and column alignment.
776#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
777pub enum MatrixKind {
778    #[default]
779    Matrix,
780    /// Piecewise definitions: left brace, left aligned columns.
781    Cases,
782    /// Aligned equations on the alignment points.
783    Aligned,
784    /// Plain array.
785    Array,
786    /// Vertically stacked material.
787    Pile,
788    /// Long division layout.
789    LongDivision,
790}
791
792/// Accent drawn over or under a base.
793#[derive(Clone, Debug, PartialEq, Eq)]
794pub struct Accent {
795    pub kind: AccentKind,
796    pub base: Node,
797    /// Draws the accent under the base instead of over it.
798    pub under: bool,
799}
800
801/// Accent shapes.
802#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
803pub enum AccentKind {
804    Hat,
805    WideHat,
806    Tilde,
807    WideTilde,
808    /// A single horizontal rule over the base, or under it when the accent says so.
809    Bar,
810    Vector,
811    Dot,
812    DoubleDot,
813    TripleDot,
814    Breve,
815    Check,
816    Acute,
817    Grave,
818    Circle,
819    OverBrace,
820    UnderBrace,
821    OverBracket,
822    UnderBracket,
823    OverParen,
824    UnderParen,
825    ArrowRight,
826    ArrowLeft,
827    /// A doubled horizontal rule, as MathType's doubled bar template draws it. Only a doubled
828    /// overline character in markup, or that template in MTEF, produces it.
829    Line,
830    Strike,
831}
832
833impl AccentKind {
834    /// The character used when the accent is drawn from a font rather than as a rule or path.
835    pub fn glyph(self) -> Option<char> {
836        Some(match self {
837            AccentKind::Hat => '\u{02C6}',
838            AccentKind::WideHat => '\u{0302}',
839            AccentKind::Tilde => '~',
840            AccentKind::WideTilde => '\u{0303}',
841            AccentKind::Dot => '\u{02D9}',
842            AccentKind::DoubleDot => '\u{00A8}',
843            AccentKind::TripleDot => '\u{20DB}',
844            AccentKind::Breve => '\u{02D8}',
845            AccentKind::Check => '\u{02C7}',
846            AccentKind::Acute => '\u{00B4}',
847            AccentKind::Grave => '`',
848            AccentKind::Circle => '\u{02DA}',
849            AccentKind::ArrowRight => '\u{2192}',
850            AccentKind::ArrowLeft => '\u{2190}',
851            AccentKind::Bar | AccentKind::Vector | AccentKind::Line => return None,
852            AccentKind::Strike => return None,
853            AccentKind::OverBrace => '\u{23DE}',
854            AccentKind::UnderBrace => '\u{23DF}',
855            AccentKind::OverBracket => '\u{23B4}',
856            AccentKind::UnderBracket => '\u{23B5}',
857            AccentKind::OverParen => '\u{23DC}',
858            AccentKind::UnderParen => '\u{23DD}',
859        })
860    }
861}
862
863/// Large operator with optional limits.
864#[derive(Clone, Debug, PartialEq, Eq)]
865pub struct BigOp {
866    pub base: Node,
867    pub sub: Option<Node>,
868    pub sup: Option<Node>,
869    /// Draws the limits above and below instead of beside the operator.
870    pub limits: bool,
871}
872
873/// Style, font or class override applied to a subtree.
874#[derive(Clone, Debug, PartialEq, Eq)]
875pub struct Styled {
876    pub body: Node,
877    pub style: Option<MathStyle>,
878    pub font: Option<Font>,
879    pub class: Option<Class>,
880}
881
882/// Position in the tree: the sequence of slot indices from the root.
883#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
884pub struct Path(Vec<usize>);
885
886impl Path {
887    /// The path naming the root.
888    pub fn root() -> Self {
889        Self(Vec::new())
890    }
891
892    /// Path with `index` appended.
893    pub fn child(&self, index: usize) -> Self {
894        let mut path = self.clone();
895        path.0.push(index);
896        path
897    }
898
899    /// Path with the last index removed, or `None` at the root.
900    pub fn parent(&self) -> Option<Self> {
901        let mut path = self.clone();
902        path.0.pop().map(|_| path)
903    }
904
905    /// Last index, i.e. the slot of the parent that holds this node.
906    pub fn last(&self) -> Option<usize> {
907        self.0.last().copied()
908    }
909
910    /// Split into the parent path and the final index.
911    pub fn split_last(&self) -> Option<(Self, usize)> {
912        let (index, rest) = self.0.split_last()?;
913        Some((Self(rest.to_vec()), *index))
914    }
915
916    pub fn push(&mut self, index: usize) {
917        self.0.push(index);
918    }
919
920    pub fn pop(&mut self) -> Option<usize> {
921        self.0.pop()
922    }
923
924    pub fn len(&self) -> usize {
925        self.0.len()
926    }
927
928    pub fn is_empty(&self) -> bool {
929        self.0.is_empty()
930    }
931
932    pub fn as_slice(&self) -> &[usize] {
933        &self.0
934    }
935}
936
937impl FromIterator<usize> for Path {
938    fn from_iter<T: IntoIterator<Item = usize>>(iter: T) -> Self {
939        Self(iter.into_iter().collect())
940    }
941}
942
943impl std::fmt::Display for Path {
944    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
945        if self.0.is_empty() {
946            return f.write_str(".");
947        }
948        for (position, index) in self.0.iter().enumerate() {
949            if position > 0 {
950                f.write_str(".")?;
951            }
952            write!(f, "{index}")?;
953        }
954        Ok(())
955    }
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961
962    fn scripts(base: Node, sub: Node, sup: Node) -> Node {
963        Node::Scripts(Box::new(Scripts {
964            base,
965            sub: Some(sub),
966            sup: Some(sup),
967        }))
968    }
969
970    #[test]
971    fn fraction_slots_are_numerator_then_denominator() {
972        let frac = Node::Frac(Box::new(Frac::new(
973            Node::variable('a'),
974            Node::variable('b'),
975        )));
976        assert_eq!(frac.slot_count(), 2);
977        assert_eq!(frac.slot(0), Some(&Node::variable('a')));
978        assert_eq!(frac.slot(1), Some(&Node::variable('b')));
979        assert_eq!(frac.slot(2), None);
980    }
981
982    #[test]
983    fn square_root_has_a_single_slot() {
984        let root = Node::Sqrt(Box::new(Sqrt::square(Node::variable('x'))));
985        assert_eq!(root.slot_count(), 1);
986        assert_eq!(root.slot(0), Some(&Node::variable('x')));
987
988        let nth = Node::Sqrt(Box::new(Sqrt::nth(
989            Node::variable('n'),
990            Node::variable('x'),
991        )));
992        assert_eq!(nth.slot_count(), 2);
993        assert_eq!(nth.slot(0), Some(&Node::variable('n')));
994        assert_eq!(nth.slot(1), Some(&Node::variable('x')));
995    }
996
997    #[test]
998    fn path_navigation_reaches_nested_slots() {
999        let math = Math::new(Node::row([
1000            Node::variable('x'),
1001            scripts(
1002                Node::variable('a'),
1003                Node::variable('i'),
1004                Node::variable('2'),
1005            ),
1006        ]));
1007        let sup = Path::root().child(1).child(2);
1008        assert_eq!(math.node_at(&sup), Some(&Node::variable('2')));
1009        assert_eq!(sup.to_string(), "1.2");
1010        assert_eq!(
1011            sup.parent().map(|path| path.to_string()),
1012            Some("1".to_owned())
1013        );
1014        assert_eq!(math.node_at(&Path::root()), Some(&math.body));
1015    }
1016
1017    #[test]
1018    fn replace_and_insert_operate_on_nested_slots() {
1019        let mut math = Math::new(Node::row([
1020            Node::variable('a'),
1021            Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
1022        ]));
1023        let radicand = Path::root().child(1).child(0);
1024        let replaced = math
1025            .node_at_mut(&radicand)
1026            .map(|node| std::mem::replace(node, Node::variable('y')));
1027        assert_eq!(replaced, Some(Node::variable('x')));
1028        assert_eq!(math.node_at(&radicand), Some(&Node::variable('y')));
1029
1030        let row = Path::root();
1031        assert!(math.body.insert_at(&row, Node::variable('z')));
1032        assert_eq!(math.body.slot_count(), 3);
1033        assert_eq!(
1034            math.node_at(&Path::root().child(2)),
1035            Some(&Node::variable('z'))
1036        );
1037        assert_eq!(
1038            math.body.remove_at(&Path::root().child(2)),
1039            Some(Node::variable('z'))
1040        );
1041        assert_eq!(math.body.slot_count(), 2);
1042    }
1043
1044    #[test]
1045    fn matrix_cells_are_addressed_row_major() {
1046        let mut matrix = Matrix::empty(2, 3);
1047        if let Some(cell) = matrix.cell_at_mut(4) {
1048            *cell = Node::variable('q');
1049        }
1050        let node = Node::Matrix(Box::new(matrix));
1051        assert_eq!(node.slot_count(), 6);
1052        assert_eq!(node.slot(4), Some(&Node::variable('q')));
1053        assert_eq!(node.slot(1), Some(&Node::empty()));
1054    }
1055
1056    #[test]
1057    fn walk_visits_every_reachable_node() {
1058        let math = Math::new(Node::row([
1059            scripts(Node::variable('a'), Node::variable('i'), Node::empty()),
1060            Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
1061        ]));
1062        let mut names = Vec::new();
1063        math.body.walk(&mut |node| {
1064            if let Node::Char(Char { ch, .. }) = node {
1065                names.push(*ch);
1066            }
1067        });
1068        assert_eq!(names, vec!['a', 'i', 'x']);
1069    }
1070
1071    #[test]
1072    fn normalisation_flattens_nested_rows_only() {
1073        let mut node = Node::row([
1074            Node::variable('a'),
1075            Node::row([Node::variable('b'), Node::variable('c')]),
1076        ]);
1077        node.normalize();
1078        assert_eq!(
1079            node,
1080            Node::row([
1081                Node::variable('a'),
1082                Node::variable('b'),
1083                Node::variable('c')
1084            ])
1085        );
1086
1087        let mut node = Node::row([Node::row([Node::variable('a')])]);
1088        node.normalize();
1089        assert_eq!(node, Node::row([Node::variable('a')]));
1090
1091        let mut fraction = Node::Frac(Box::new(Frac::new(
1092            Node::row([Node::row([Node::variable('1')])]),
1093            Node::variable('2'),
1094        )));
1095        fraction.normalize();
1096        assert_eq!(fraction.slot(0), Some(&Node::row([Node::variable('1')])));
1097    }
1098
1099    #[test]
1100    fn space_widths_follow_the_em_grid() {
1101        assert_eq!(Space::Thin.em(), 3.0 / 18.0);
1102        assert_eq!(Space::Quad.em(), 1.0);
1103        assert_eq!(Space::NegativeThick.em(), -5.0 / 18.0);
1104    }
1105
1106    #[test]
1107    fn delimiters_expose_matching_pairs() {
1108        assert_eq!(Delim::Paren.open(), Some('('));
1109        assert_eq!(Delim::Paren.close(), Some(')'));
1110        assert_eq!(Delim::None.open(), None);
1111        assert_eq!(Delim::Brace.close(), Some('}'));
1112    }
1113
1114    #[test]
1115    fn style_nesting_saturates() {
1116        assert_eq!(MathStyle::Full.smaller(), MathStyle::Script);
1117        assert_eq!(MathStyle::Script.smaller(), MathStyle::ScriptScript);
1118        assert_eq!(MathStyle::ScriptScript.smaller(), MathStyle::ScriptScript);
1119    }
1120
1121    #[test]
1122    fn the_euclid_faces_answer_for_their_own_weight_and_slant() {
1123        assert!(!Font::Euclid.is_bold() && !Font::Euclid.is_italic());
1124        assert!(Font::EuclidItalic.is_italic() && !Font::EuclidItalic.is_bold());
1125        assert!(Font::EuclidBold.is_bold() && !Font::EuclidBold.is_italic());
1126        assert!(Font::EuclidBoldItalic.is_bold() && Font::EuclidBoldItalic.is_italic());
1127        assert!(Font::EuclidSymbolItalic.is_italic() && !Font::EuclidSymbolItalic.is_bold());
1128        assert!(Font::EuclidSymbolBoldItalic.is_bold() && Font::EuclidSymbolBoldItalic.is_italic());
1129        assert!(Font::EuclidExtraBold.is_bold() && !Font::EuclidExtraBold.is_italic());
1130        assert!(!Font::EuclidExtra.is_bold() && !Font::EuclidExtra.is_italic());
1131        assert!(!Font::Fences.is_bold() && !Font::Fences.is_italic());
1132    }
1133}