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)]
11pub struct Math {
12    pub body: Node,
13    pub style: MathStyle,
14    /// Whether the equation is placed inline in the host document rather than on a line of its
15    /// own. A new equation is a display equation.
16    pub inline: bool,
17}
18
19impl Math {
20    /// An equation wrapping `body` at full size.
21    pub fn new(body: impl Into<Node>) -> Self {
22        Self {
23            body: body.into(),
24            style: MathStyle::Full,
25            inline: false,
26        }
27    }
28
29    pub fn node_at(&self, path: &Path) -> Option<&Node> {
30        self.body.node_at(path)
31    }
32
33    pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
34        self.body.node_at_mut(path)
35    }
36}
37
38/// Size preset an equation is laid out at, matching the size classes an author picks from.
39///
40/// The seven MathType typesizes plus this crate's own text size: the typesizes are full,
41/// subscript, sub-subscript, symbol, sub-symbol, user 1 and user 2 (manual 11.45). A character
42/// records the class it is set in, not the points that class currently resolves to, so a change
43/// to the preset moves every character set in it.
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45pub enum MathStyle {
46    /// Inline text size.
47    Text,
48    /// Smaller than text, one step down in the nesting hierarchy.
49    Script,
50    /// Smallest supported size, two steps down in the nesting hierarchy.
51    ScriptScript,
52    /// Full size.
53    #[default]
54    Full,
55    /// The size a large operator's own glyph is drawn at.
56    Symbol,
57    /// The size a large operator takes when it sits inside a script.
58    SubSymbol,
59    /// The first user-defined size.
60    User1,
61    /// The second user-defined size.
62    User2,
63}
64
65impl MathStyle {
66    /// The next smaller preset, saturating at [`MathStyle::ScriptScript`].
67    ///
68    /// Material inside a script slot steps down the positional ladder: full size, the symbol
69    /// class and the user classes step to the subscript, and the subscript, the sub-symbol and
70    /// the sub-subscript step to the sub-subscript. The sub-symbol class is where a symbol lands
71    /// when it sits inside a script.
72    pub fn smaller(self) -> Self {
73        match self {
74            MathStyle::Full
75            | MathStyle::Text
76            | MathStyle::Symbol
77            | MathStyle::User1
78            | MathStyle::User2 => MathStyle::Script,
79            MathStyle::Script | MathStyle::SubSymbol | MathStyle::ScriptScript => {
80                MathStyle::ScriptScript
81            }
82        }
83    }
84}
85
86/// Horizontal sequence of items.
87pub type Row = Vec<Node>;
88
89/// One item of an equation.
90///
91/// Template variants are boxed so that a `Node` stays pointer sized.
92#[derive(Clone, Debug, PartialEq)]
93pub enum Node {
94    /// Horizontal sequence of items; an empty row is an empty argument slot.
95    Row(Row),
96    /// A single character with its atom class and font.
97    Char(Char),
98    /// Literal text set upright (`\text{...}` and friends).
99    Text(Box<TextRun>),
100    /// Explicit horizontal spacing.
101    Space(Space),
102    /// Fraction, with or without a rule.
103    Frac(Box<Frac>),
104    /// Radical with an optional index.
105    Sqrt(Box<Sqrt>),
106    /// Subscript and/or superscript attached to a base.
107    Scripts(Box<Scripts>),
108    /// Over/under material that is not an accent (`\overset`, `\stackrel`, limits).
109    Limits(Box<Limits>),
110    /// Delimiters around a body.
111    Fence(Box<Fence>),
112    /// Table of cells with optional delimiters and alignment.
113    Matrix(Box<Matrix>),
114    /// Accent over or under a base.
115    Accent(Box<Accent>),
116    /// Arrow carrying text above, below or on both sides.
117    LabeledArrow(Box<LabeledArrow>),
118    /// Large operator with optional limits.
119    Big(Box<BigOp>),
120    /// Style, font or class applied to a subtree.
121    Styled(Box<Styled>),
122    /// Alignment point (`&` inside aligned environments).
123    Align,
124    /// Construct kept verbatim because it could not be represented.
125    Error(String),
126}
127
128impl Node {
129    /// An empty row, i.e. an empty slot.
130    pub fn empty() -> Self {
131        Node::Row(Row::new())
132    }
133
134    pub fn row(items: impl IntoIterator<Item = Node>) -> Self {
135        Node::Row(items.into_iter().collect())
136    }
137
138    /// A character carrying `class` and `font`.
139    pub fn char_with(ch: char, class: Class, font: Font) -> Self {
140        Node::Char(Char {
141            ch,
142            class,
143            font,
144            style_ref: None,
145        })
146    }
147
148    /// A default-class italic variable.
149    pub fn variable(ch: char) -> Self {
150        Node::Char(Char {
151            style_ref: None,
152            ch,
153            class: Class::Ord,
154            font: Font::Italic,
155        })
156    }
157
158    /// A default-class upright operator or symbol.
159    pub fn symbol(ch: char, class: Class) -> Self {
160        Node::Char(Char {
161            style_ref: None,
162            ch,
163            class,
164            font: Font::Upright,
165        })
166    }
167
168    pub fn text(text: impl Into<String>) -> Self {
169        Node::Text(Box::new(TextRun {
170            text: text.into(),
171            font: Font::Upright,
172        }))
173    }
174
175    /// True when the node is an empty row, which renderers draw as an empty slot.
176    pub fn is_empty_slot(&self) -> bool {
177        matches!(self, Node::Row(row) if row.is_empty())
178    }
179
180    /// Whether the node is a row and can therefore accept siblings.
181    pub fn is_row(&self) -> bool {
182        matches!(self, Node::Row(_))
183    }
184
185    /// Number of child slots the node exposes, in visual order.
186    pub fn slot_count(&self) -> usize {
187        match self {
188            Node::Row(row) => row.len(),
189            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => 0,
190            Node::Frac(_) => 2,
191            Node::Sqrt(sqrt) => 1 + usize::from(sqrt.index.is_some()),
192            Node::Scripts(_) => 3,
193            Node::Limits(_) => 3,
194            Node::Fence(_) => 1,
195            Node::Matrix(matrix) => matrix.rows.iter().map(Row::len).sum(),
196            Node::Accent(_) => 1,
197            Node::LabeledArrow(arrow) => arrow.slot_count(),
198            Node::Big(_) => 3,
199            Node::Styled(_) => 1,
200        }
201    }
202
203    /// Read-only access to slot `index`, in the order defined by [`Node::slot_count`].
204    pub fn slot(&self, index: usize) -> Option<&Node> {
205        match self {
206            Node::Row(row) => row.get(index),
207            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
208            Node::Frac(frac) => match index {
209                0 => Some(&frac.num),
210                1 => Some(&frac.den),
211                _ => None,
212            },
213            Node::Sqrt(sqrt) => match (index, &sqrt.index) {
214                (0, Some(radicand)) => Some(radicand),
215                (0, None) => Some(&sqrt.radicand),
216                (1, Some(_)) => Some(&sqrt.radicand),
217                _ => None,
218            },
219            Node::Scripts(scripts) => match index {
220                0 => Some(&scripts.base),
221                1 => scripts.sub.as_ref(),
222                2 => scripts.sup.as_ref(),
223                _ => None,
224            },
225            Node::Limits(limits) => match index {
226                0 => Some(&limits.base),
227                1 => limits.under.as_ref(),
228                2 => limits.over.as_ref(),
229                _ => None,
230            },
231            Node::Fence(fence) => (index == 0).then_some(&fence.body),
232            Node::Matrix(matrix) => matrix.cell_at(index),
233            Node::Accent(accent) => (index == 0).then_some(&accent.base),
234            Node::LabeledArrow(arrow) => arrow.slot(index),
235            Node::Big(big) => match index {
236                0 => Some(&big.base),
237                1 => big.sub.as_ref(),
238                2 => big.sup.as_ref(),
239                _ => None,
240            },
241            Node::Styled(styled) => (index == 0).then_some(&styled.body),
242        }
243    }
244
245    /// Mutable access to slot `index`, in the order defined by [`Node::slot_count`].
246    pub fn slot_mut(&mut self, index: usize) -> Option<&mut Node> {
247        match self {
248            Node::Row(row) => row.get_mut(index),
249            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
250            Node::Frac(frac) => match index {
251                0 => Some(&mut frac.num),
252                1 => Some(&mut frac.den),
253                _ => None,
254            },
255            Node::Sqrt(sqrt) => match (index, &mut sqrt.index) {
256                (0, Some(radicand)) => Some(radicand),
257                (0, None) => Some(&mut sqrt.radicand),
258                (1, Some(_)) => Some(&mut sqrt.radicand),
259                _ => None,
260            },
261            Node::Scripts(scripts) => match index {
262                0 => Some(&mut scripts.base),
263                1 => scripts.sub.as_mut(),
264                2 => scripts.sup.as_mut(),
265                _ => None,
266            },
267            Node::Limits(limits) => match index {
268                0 => Some(&mut limits.base),
269                1 => limits.under.as_mut(),
270                2 => limits.over.as_mut(),
271                _ => None,
272            },
273            Node::Fence(fence) => (index == 0).then_some(&mut fence.body),
274            Node::Matrix(matrix) => matrix.cell_at_mut(index),
275            Node::Accent(accent) => (index == 0).then_some(&mut accent.base),
276            Node::LabeledArrow(arrow) => arrow.slot_mut(index),
277            Node::Big(big) => match index {
278                0 => Some(&mut big.base),
279                1 => big.sub.as_mut(),
280                2 => big.sup.as_mut(),
281                _ => None,
282            },
283            Node::Styled(styled) => (index == 0).then_some(&mut styled.body),
284        }
285    }
286
287    /// Slots in visual order. Allocates; use [`Node::slot_count`] plus [`Node::slot`] in hot paths.
288    pub fn slots(&self) -> Vec<&Node> {
289        (0..self.slot_count())
290            .filter_map(|i| self.slot(i))
291            .collect()
292    }
293
294    /// Depth-first walk over the node and every node reachable through its slots.
295    pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Node)) {
296        visit(self);
297        for index in 0..self.slot_count() {
298            if let Some(slot) = self.slot(index) {
299                slot.walk(visit);
300            }
301        }
302    }
303
304    /// Node reached by following `path` from here.
305    pub fn node_at(&self, path: &Path) -> Option<&Node> {
306        let mut current = self;
307        for &index in path.as_slice() {
308            current = current.slot(index)?;
309        }
310        Some(current)
311    }
312
313    /// Mutable node reached by following `path` from here.
314    pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
315        let mut current = self;
316        for &index in path.as_slice() {
317            current = current.slot_mut(index)?;
318        }
319        Some(current)
320    }
321
322    /// Replace the node at `path`, returning the replaced node.
323    ///
324    /// The root cannot be replaced: pass a non-empty path.
325    pub fn replace_at(&mut self, path: &Path, node: Node) -> Option<Node> {
326        let (parent_path, index) = path.split_last()?;
327        let parent = self.node_at_mut(&parent_path)?;
328        match parent {
329            Node::Row(row) => {
330                let target = row.get_mut(index)?;
331                Some(std::mem::replace(target, node))
332            }
333            other => {
334                let target = other.slot_mut(index)?;
335                Some(std::mem::replace(target, node))
336            }
337        }
338    }
339
340    /// Insert `node` into the row at `path`, directly before the item at `path` or appended when
341    /// the path names a row itself.
342    pub fn insert_at(&mut self, path: &Path, node: Node) -> bool {
343        match self.node_at_mut(path) {
344            Some(Node::Row(row)) => {
345                row.push(node);
346                true
347            }
348            Some(_) => match path.split_last() {
349                Some((parent_path, index)) => match self.node_at_mut(&parent_path) {
350                    Some(parent) => parent.insert_sibling(index, node),
351                    None => false,
352                },
353                None => false,
354            },
355            None => false,
356        }
357    }
358
359    /// Insert `node` before slot `index` of a row-like parent.
360    fn insert_sibling(&mut self, index: usize, node: Node) -> bool {
361        match self {
362            Node::Row(row) => {
363                let index = index.min(row.len());
364                row.insert(index, node);
365                true
366            }
367            _ => false,
368        }
369    }
370
371    /// Remove the node at `path`, returning it. The root cannot be removed.
372    pub fn remove_at(&mut self, path: &Path) -> Option<Node> {
373        let (parent_path, index) = path.split_last()?;
374        match self.node_at_mut(&parent_path)? {
375            Node::Row(row) => (index < row.len()).then(|| row.remove(index)),
376            _ => None,
377        }
378    }
379
380    /// Flatten rows nested directly inside a row and drop empty nested rows.
381    ///
382    /// Template slots are untouched, so this only removes row nesting that carries no meaning and
383    /// keeps parse-then-serialise round trips stable.
384    pub fn normalize(&mut self) {
385        for index in 0..self.slot_count() {
386            if let Some(slot) = self.slot_mut(index) {
387                slot.normalize();
388            }
389        }
390        if let Node::Row(row) = self {
391            let mut flat = Row::with_capacity(row.len());
392            for node in row.drain(..) {
393                match node {
394                    Node::Row(inner) => flat.extend(inner),
395                    other => flat.push(other),
396                }
397            }
398            *row = flat;
399        }
400    }
401}
402
403impl From<char> for Node {
404    fn from(ch: char) -> Self {
405        Node::variable(ch)
406    }
407}
408
409impl From<&str> for Node {
410    fn from(text: &str) -> Self {
411        Node::Text(Box::new(TextRun {
412            text: text.to_owned(),
413            font: Font::Upright,
414        }))
415    }
416}
417
418impl From<String> for Node {
419    fn from(text: String) -> Self {
420        Node::Text(Box::new(TextRun {
421            text,
422            font: Font::Upright,
423        }))
424    }
425}
426
427impl From<Vec<Node>> for Node {
428    fn from(items: Vec<Node>) -> Self {
429        Node::Row(items)
430    }
431}
432
433impl Default for Node {
434    /// An empty slot.
435    fn default() -> Self {
436        Node::empty()
437    }
438}
439
440/// A character together with the atom class that drives spacing and the font it is set in.
441#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
442pub struct Char {
443    pub ch: char,
444    pub class: Class,
445    pub font: Font,
446    /// The user style the character was set in, when it was. The other functional styles need
447    /// no marker of their own: the structural faces and the operator class carry them, and
448    /// layout resolves those through the preset's style slots.
449    pub style_ref: Option<StyleRef>,
450}
451
452/// A functional style with no structural face of its own, recorded on the character.
453///
454/// The user styles name whatever face the preset's slot holds for them, so a character set in
455/// one must keep the style rather than the face: redefining the slot moves it, and a MathType
456/// stream names it with the typeface of that slot (9 and 10) rather than an explicit font.
457#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
458pub enum StyleRef {
459    User1,
460    User2,
461}
462
463/// Atom class, used for operator spacing between neighbouring atoms.
464#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
465pub enum Class {
466    /// Ordinary atom: variables, numbers, most symbols.
467    #[default]
468    Ord,
469    /// Large operator or function name taking limits.
470    Op,
471    /// Binary operator.
472    Bin,
473    /// Relation.
474    Rel,
475    /// Opening delimiter.
476    Open,
477    /// Closing delimiter.
478    Close,
479    /// Punctuation.
480    Punct,
481    /// Inner atom, e.g. a fraction or matrix.
482    Inner,
483}
484
485/// Typeface a run is set in.
486#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
487pub enum Font {
488    /// Italic math variable, the default for letters.
489    #[default]
490    Italic,
491    /// Upright roman.
492    Upright,
493    Bold,
494    BoldItalic,
495    SansSerif,
496    SansSerifBold,
497    SansSerifItalic,
498    SansSerifBoldItalic,
499    Monospace,
500    Script,
501    BoldScript,
502    Fraktur,
503    BoldFraktur,
504    DoubleStruck,
505    /// Symbols drawn from the symbol font rather than the text face.
506    Symbol,
507    /// Glyphs from the extra symbol face.
508    Extra,
509    /// Fences, the face MathType draws the characters decorating a template with.
510    Fences,
511    /// Euclid, the text face MathType names in an explicit font definition.
512    Euclid,
513    EuclidItalic,
514    EuclidBold,
515    EuclidBoldItalic,
516    /// Euclid Symbol, a symbol-encoded face MathType names in an explicit font definition.
517    EuclidSymbol,
518    EuclidSymbolItalic,
519    EuclidSymbolBold,
520    EuclidSymbolBoldItalic,
521    /// Euclid Extra, the extra face MathType names in an explicit font definition.
522    EuclidExtra,
523    EuclidExtraBold,
524}
525
526impl Font {
527    /// Whether the face is set in italics, which layout needs for metric selection.
528    pub fn is_italic(self) -> bool {
529        matches!(
530            self,
531            Font::Italic
532                | Font::BoldItalic
533                | Font::SansSerifItalic
534                | Font::SansSerifBoldItalic
535                | Font::EuclidItalic
536                | Font::EuclidBoldItalic
537                | Font::EuclidSymbolItalic
538                | Font::EuclidSymbolBoldItalic
539        )
540    }
541
542    /// Whether the face is bold.
543    pub fn is_bold(self) -> bool {
544        matches!(
545            self,
546            Font::Bold
547                | Font::BoldItalic
548                | Font::SansSerifBold
549                | Font::SansSerifBoldItalic
550                | Font::BoldScript
551                | Font::BoldFraktur
552                | Font::EuclidBold
553                | Font::EuclidBoldItalic
554                | Font::EuclidSymbolBold
555                | Font::EuclidSymbolBoldItalic
556                | Font::EuclidExtraBold
557        )
558    }
559}
560
561/// Literal text set upright, optionally in a specific face.
562#[derive(Clone, Debug, PartialEq, Eq)]
563pub struct TextRun {
564    pub text: String,
565    pub font: Font,
566}
567
568/// Explicit horizontal space.
569#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
570pub enum Space {
571    /// 3/18 em.
572    Thin,
573    /// 4/18 em.
574    Medium,
575    /// 5/18 em.
576    Thick,
577    /// 6/18 em.
578    Sixteenth,
579    /// 1 em.
580    Quad,
581    /// 2 em.
582    DoubleQuad,
583    /// No width at all, the zero-width space.
584    ZeroWidth,
585    /// One point, a width that depends on the size the equation is set in.
586    OnePoint,
587    /// -3/18 em.
588    NegativeThin,
589    /// -4/18 em.
590    NegativeMedium,
591    /// -5/18 em.
592    NegativeThick,
593}
594
595impl Space {
596    /// Width in em units, negative for backspacing.
597    ///
598    /// `size` is the size of the equation's full-size text in points. Only the point-sized space
599    /// needs it, the rest are fractions of an em whatever the size.
600    pub fn em(self, size: f64) -> f64 {
601        match self {
602            Space::Thin => 3.0 / 18.0,
603            Space::Medium => 4.0 / 18.0,
604            Space::Thick => 5.0 / 18.0,
605            Space::Sixteenth => 6.0 / 18.0,
606            Space::Quad => 1.0,
607            Space::DoubleQuad => 2.0,
608            Space::ZeroWidth => 0.0,
609            Space::OnePoint => 1.0 / size,
610            Space::NegativeThin => -3.0 / 18.0,
611            Space::NegativeMedium => -4.0 / 18.0,
612            Space::NegativeThick => -5.0 / 18.0,
613        }
614    }
615}
616
617/// Fraction, with or without a rule, drawn stacked or inline.
618#[derive(Clone, Debug, PartialEq)]
619pub struct Frac {
620    pub num: Node,
621    pub den: Node,
622    pub kind: FracKind,
623    /// Sets the slots one size preset below the material around them.
624    pub small: bool,
625}
626
627impl Frac {
628    pub fn new(num: Node, den: Node) -> Self {
629        Self {
630            num,
631            den,
632            kind: FracKind::Bar,
633            small: false,
634        }
635    }
636}
637
638/// How a fraction is drawn.
639#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
640pub enum FracKind {
641    /// Stacked with a horizontal rule.
642    #[default]
643    Bar,
644    /// Stacked with a slash instead of a rule.
645    Slash,
646    /// Stacked without a rule, e.g. binomial coefficients.
647    NoBar,
648    /// Written inline as `a/b`.
649    Linear,
650}
651
652/// Radical, with an optional index for higher roots.
653#[derive(Clone, Debug, PartialEq)]
654pub struct Sqrt {
655    /// Root index; `None` is a square root.
656    pub index: Option<Node>,
657    pub radicand: Node,
658}
659
660impl Sqrt {
661    pub fn square(radicand: Node) -> Self {
662        Self {
663            index: None,
664            radicand,
665        }
666    }
667
668    pub fn nth(index: Node, radicand: Node) -> Self {
669        Self {
670            index: Some(index),
671            radicand,
672        }
673    }
674}
675
676/// Subscript and superscript attached to a base.
677#[derive(Clone, Debug, PartialEq)]
678pub struct Scripts {
679    pub base: Node,
680    pub sub: Option<Node>,
681    pub sup: Option<Node>,
682    /// Draws the scripts to the left of the base instead of to its right.
683    ///
684    /// The slots keep the order base, subscript, superscript on both sides, so editing code
685    /// addresses a pre-script the way it addresses a post-script.
686    pub precedes: bool,
687}
688
689impl Scripts {
690    /// Attach `sub`/`sup` to `base` on the right.
691    ///
692    /// Merging into an existing [`Node::Scripts`] node is up to the caller, which knows whether
693    /// the new scripts belong inside or outside the existing ones.
694    pub fn attach(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
695        Self {
696            base,
697            sub,
698            sup,
699            precedes: false,
700        }
701    }
702
703    /// Attach `sub`/`sup` to the left of `base`.
704    pub fn attach_preceding(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
705        Self {
706            base,
707            sub,
708            sup,
709            precedes: true,
710        }
711    }
712}
713
714/// Over/under material that is not an accent.
715#[derive(Clone, Debug, PartialEq)]
716pub struct Limits {
717    pub base: Node,
718    pub under: Option<Node>,
719    pub over: Option<Node>,
720    pub align: Side,
721}
722
723/// Horizontal alignment of over/under material and table columns.
724///
725/// The five values are the horizontal alignment values of the equation format. Over/under
726/// material and single columns use the first three; relation and decimal alignment apply to a
727/// whole table, where lines are split at their first relation or at the decimal point.
728#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
729pub enum Side {
730    #[default]
731    Center,
732    Left,
733    Right,
734    /// Aligns lines at their first relational operator.
735    AtRelation,
736    /// Aligns lines at the decimal point of their first number.
737    AtDecimal,
738}
739
740/// Vertical alignment of a table with its line, or of a cell within its row.
741///
742/// The five values are the vertical alignment values of the equation format. The interface only
743/// offers the first three; the other two are kept from a stream and written back unchanged.
744#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
745pub enum VerticalAlign {
746    /// Top line's baseline.
747    Top,
748    /// Middle line's baseline.
749    #[default]
750    Center,
751    /// Bottom line's baseline.
752    Bottom,
753    /// The material centred as a whole.
754    Centered,
755    /// Centred on the math axis.
756    Axis,
757}
758
759/// Style of a partition line between or around the cells of a table.
760#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
761pub enum LineStyle {
762    /// No line is drawn.
763    #[default]
764    None,
765    Solid,
766    Dashed,
767    Dotted,
768}
769
770/// Delimiter shape.
771#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
772pub enum Delim {
773    Paren,
774    Bracket,
775    Brace,
776    Abs,
777    Norm,
778    Angle,
779    Floor,
780    Ceil,
781    /// No delimiter drawn.
782    None,
783    /// A specific character, drawn from a font that provides it.
784    Custom(char),
785    /// An arrow delimiter.
786    Arrow,
787    /// A double bar delimiter.
788    DoubleBar,
789}
790
791impl Delim {
792    /// The opening character, or `None` when nothing is drawn.
793    pub fn open(self) -> Option<char> {
794        Some(match self {
795            Delim::Paren => '(',
796            Delim::Bracket => '[',
797            Delim::Brace => '{',
798            Delim::Abs => '|',
799            Delim::Norm => '\u{2016}',
800            Delim::Angle => '\u{27E8}',
801            Delim::Floor => '\u{230A}',
802            Delim::Ceil => '\u{2308}',
803            Delim::None => return None,
804            Delim::Custom(ch) => ch,
805            Delim::Arrow => '\u{27E8}',
806            Delim::DoubleBar => '\u{2016}',
807        })
808    }
809
810    /// The closing character, or `None` when nothing is drawn.
811    pub fn close(self) -> Option<char> {
812        Some(match self {
813            Delim::Paren => ')',
814            Delim::Bracket => ']',
815            Delim::Brace => '}',
816            Delim::Abs => '|',
817            Delim::Norm => '\u{2016}',
818            Delim::Angle => '\u{27E9}',
819            Delim::Floor => '\u{230B}',
820            Delim::Ceil => '\u{2309}',
821            Delim::None => return None,
822            Delim::Custom(ch) => ch,
823            Delim::Arrow => '\u{27E9}',
824            Delim::DoubleBar => '\u{2016}',
825        })
826    }
827}
828
829/// How a fence's delimiters sit vertically against the line that holds them.
830#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
831pub enum FenceAlign {
832    /// The fence is centred on the line's math axis, the contents' math axis on the same axis,
833    /// and the fence grows symmetrically until it covers the contents.
834    #[default]
835    Axis,
836    /// The fence is centred on the contents, whose math axis stays on the line's math axis.
837    Contents,
838    /// The fence is centred on the contents, and the two are centred on the line's math axis.
839    Centered,
840}
841
842/// Delimiters around a body.
843#[derive(Clone, Debug, PartialEq)]
844pub struct Fence {
845    pub open: Delim,
846    pub close: Delim,
847    pub body: Node,
848    /// How the delimiters sit vertically against the surrounding line.
849    pub align: FenceAlign,
850}
851
852/// Table of cells with optional delimiters.
853#[derive(Clone, Debug, PartialEq)]
854pub struct Matrix {
855    pub rows: Vec<Row>,
856    pub delims: Option<(Delim, Delim)>,
857    pub kind: MatrixKind,
858    /// Baseline-to-baseline distance from each row to the one below it, in points. `None` uses
859    /// the style's line or matrix-row spacing. The vector has one entry per row.
860    pub line_spacings: Vec<Option<f64>>,
861    /// Alignment applied to every column; per-column rules come from [`Matrix::columns`].
862    pub align: Side,
863    /// Optional per-column alignment overriding [`Matrix::align`].
864    pub columns: Vec<Side>,
865    /// How the table sits on the line that contains it.
866    pub stack_align: VerticalAlign,
867    /// How a cell's material sits within its row: top, baseline or bottom.
868    pub cell_align: VerticalAlign,
869    /// Style of the line above each row, from the top edge to the bottom edge; `row_count + 1`
870    /// entries.
871    pub row_lines: Vec<LineStyle>,
872    /// Style of the line left of each column, from the left edge to the right edge;
873    /// `col_count + 1` entries.
874    pub col_lines: Vec<LineStyle>,
875}
876
877impl Matrix {
878    /// A matrix of `rows` rows and `cols` columns, each cell an empty slot.
879    pub fn empty(rows: usize, cols: usize) -> Self {
880        Self {
881            rows: vec![vec![Node::empty(); cols]; rows],
882            delims: None,
883            kind: MatrixKind::Matrix,
884            line_spacings: vec![None; rows],
885            align: Side::Center,
886            columns: Vec::new(),
887            stack_align: VerticalAlign::Center,
888            cell_align: VerticalAlign::Center,
889            row_lines: vec![LineStyle::None; rows + 1],
890            col_lines: vec![LineStyle::None; cols + 1],
891        }
892    }
893
894    /// Whether any partition line is drawn.
895    pub fn has_lines(&self) -> bool {
896        self.row_lines
897            .iter()
898            .chain(&self.col_lines)
899            .any(|style| *style != LineStyle::None)
900    }
901
902    /// Number of rows.
903    pub fn row_count(&self) -> usize {
904        self.rows.len()
905    }
906
907    /// Number of columns, taken from the widest row.
908    pub fn col_count(&self) -> usize {
909        self.rows.iter().map(Row::len).max().unwrap_or(0)
910    }
911
912    /// Row and column of the cell addressed by a flat slot index, row-major.
913    pub fn cell_position(&self, index: usize) -> Option<(usize, usize)> {
914        let mut remaining = index;
915        for (row, cells) in self.rows.iter().enumerate() {
916            if remaining < cells.len() {
917                return Some((row, remaining));
918            }
919            remaining -= cells.len();
920        }
921        None
922    }
923
924    /// Cell addressed by a flat slot index, row-major.
925    pub fn cell_at(&self, index: usize) -> Option<&Node> {
926        let (row, col) = self.cell_position(index)?;
927        self.rows[row].get(col)
928    }
929
930    /// Mutable cell addressed by a flat slot index, row-major.
931    pub fn cell_at_mut(&mut self, index: usize) -> Option<&mut Node> {
932        let (row, col) = self.cell_position(index)?;
933        self.rows[row].get_mut(col)
934    }
935}
936
937/// Kind of table, which decides delimiter defaults and column alignment.
938#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
939pub enum MatrixKind {
940    #[default]
941    Matrix,
942    /// Piecewise definitions: left brace, left aligned columns.
943    Cases,
944    /// Aligned equations on the alignment points.
945    Aligned,
946    /// Plain array.
947    Array,
948    /// Vertically stacked material.
949    Pile,
950    /// Long division layout.
951    LongDivision,
952}
953
954/// Accent drawn over or under a base.
955#[derive(Clone, Debug, PartialEq)]
956pub struct Accent {
957    pub kind: AccentKind,
958    pub base: Node,
959    /// Draws the accent under the base instead of over it.
960    pub under: bool,
961}
962
963/// Accent shapes.
964#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
965pub enum AccentKind {
966    Hat,
967    WideHat,
968    Tilde,
969    WideTilde,
970    /// A single horizontal rule over the base, or under it when the accent says so.
971    Bar,
972    Vector,
973    Dot,
974    DoubleDot,
975    TripleDot,
976    QuadDot,
977    Breve,
978    Check,
979    Acute,
980    Grave,
981    Circle,
982    OverBrace,
983    UnderBrace,
984    OverBracket,
985    UnderBracket,
986    OverParen,
987    UnderParen,
988    ArrowRight,
989    ArrowLeft,
990    /// A rightward harpoon over the base.
991    HarpoonRight,
992    /// A leftward harpoon over the base.
993    HarpoonLeft,
994    /// A double-headed arrow over the base.
995    DoubleArrow,
996    /// A doubled horizontal rule, as MathType's doubled bar template draws it. Only a doubled
997    /// overline character in markup, or that template in MTEF, produces it.
998    Line,
999    /// A horizontal rule through the middle of the base.
1000    Strike,
1001    /// A slash from the lower left to the upper right.
1002    StrikeUp,
1003    /// A slash from the upper left to the lower right.
1004    StrikeDown,
1005    /// Both slashes, as an X through the base.
1006    CrossStrike,
1007    /// A half circle over the base.
1008    Arc,
1009    /// MathType's joint status construct: a rule with a short tick at its left end.
1010    JointStatus,
1011}
1012
1013impl AccentKind {
1014    /// The character used when the accent is drawn from a font rather than as a rule or path.
1015    pub fn glyph(self) -> Option<char> {
1016        Some(match self {
1017            AccentKind::Hat => '\u{02C6}',
1018            AccentKind::WideHat => '\u{0302}',
1019            AccentKind::Tilde => '~',
1020            AccentKind::WideTilde => '\u{0303}',
1021            AccentKind::Dot => '\u{02D9}',
1022            AccentKind::DoubleDot => '\u{00A8}',
1023            AccentKind::TripleDot => '\u{20DB}',
1024            AccentKind::QuadDot => '\u{20DC}',
1025            AccentKind::Breve => '\u{02D8}',
1026            AccentKind::Check => '\u{02C7}',
1027            AccentKind::Acute => '\u{00B4}',
1028            AccentKind::Grave => '`',
1029            AccentKind::Circle => '\u{02DA}',
1030            AccentKind::ArrowRight => '\u{2192}',
1031            AccentKind::ArrowLeft => '\u{2190}',
1032            AccentKind::HarpoonRight => '\u{21C0}',
1033            AccentKind::HarpoonLeft => '\u{21BC}',
1034            AccentKind::DoubleArrow => '\u{2194}',
1035            AccentKind::Arc => '\u{0311}',
1036            AccentKind::Bar
1037            | AccentKind::Vector
1038            | AccentKind::Line
1039            | AccentKind::Strike
1040            | AccentKind::StrikeUp
1041            | AccentKind::StrikeDown
1042            | AccentKind::CrossStrike
1043            | AccentKind::JointStatus => return None,
1044            AccentKind::OverBrace => '\u{23DE}',
1045            AccentKind::UnderBrace => '\u{23DF}',
1046            AccentKind::OverBracket => '\u{23B4}',
1047            AccentKind::UnderBracket => '\u{23B5}',
1048            AccentKind::OverParen => '\u{23DC}',
1049            AccentKind::UnderParen => '\u{23DD}',
1050        })
1051    }
1052}
1053
1054/// An arrow carrying text above, below or on both sides.
1055///
1056/// The arrow is the construct itself, so its text slots are the only slots. The shapes MathType
1057/// draws as a pair of arrows of different sizes, the large-over-small and small-over-large
1058/// arrows and harpoons, keep their two strokes in the layout rather than in the tree.
1059#[derive(Clone, Debug, PartialEq)]
1060pub struct LabeledArrow {
1061    pub arrow: ArrowKind,
1062    /// Text above the arrow.
1063    pub over: Option<Node>,
1064    /// Text below the arrow.
1065    pub under: Option<Node>,
1066}
1067
1068impl LabeledArrow {
1069    /// Slots in visual order: the upper text, then the lower text.
1070    pub fn slot_count(&self) -> usize {
1071        usize::from(self.over.is_some()) + usize::from(self.under.is_some())
1072    }
1073
1074    pub fn slot(&self, index: usize) -> Option<&Node> {
1075        match (index, &self.over) {
1076            (0, Some(over)) => Some(over),
1077            (0, None) => self.under.as_ref(),
1078            (1, Some(_)) => self.under.as_ref(),
1079            _ => None,
1080        }
1081    }
1082
1083    pub fn slot_mut(&mut self, index: usize) -> Option<&mut Node> {
1084        match (index, &mut self.over) {
1085            (0, Some(over)) => Some(over),
1086            (0, None) => self.under.as_mut(),
1087            (1, Some(_)) => self.under.as_mut(),
1088            _ => None,
1089        }
1090    }
1091}
1092
1093/// The arrow shape of a [`LabeledArrow`].
1094///
1095/// The names follow MathType's labeled arrow palette (manual 6.9, 8.5.8.8). The size pairs are
1096/// the shapes drawn as one arrow over a smaller one, which no single character spells.
1097#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1098pub enum ArrowKind {
1099    /// A rightward arrow.
1100    Right,
1101    /// A leftward arrow.
1102    Left,
1103    /// An arrow with heads at both ends.
1104    DoubleHeaded,
1105    /// A rightward arrow over a leftward one.
1106    Double,
1107    /// A large rightward arrow over a small leftward one.
1108    LargeOverSmall,
1109    /// A small rightward arrow over a large leftward one.
1110    SmallOverLarge,
1111    /// A rightward harpoon over a leftward one.
1112    Harpoons,
1113    /// A large rightward harpoon over a small leftward one.
1114    LargeOverSmallHarpoons,
1115    /// A small rightward harpoon over a large leftward one.
1116    SmallOverLargeHarpoons,
1117}
1118
1119impl ArrowKind {
1120    /// The one character that draws the shape, when a face spells it as one character.
1121    pub fn glyph(self) -> Option<char> {
1122        Some(match self {
1123            ArrowKind::Right => '\u{2192}',
1124            ArrowKind::Left => '\u{2190}',
1125            ArrowKind::DoubleHeaded => '\u{2194}',
1126            ArrowKind::Double => '\u{21C4}',
1127            ArrowKind::LargeOverSmall | ArrowKind::SmallOverLarge => '\u{21C4}',
1128            ArrowKind::Harpoons => '\u{21CC}',
1129            ArrowKind::LargeOverSmallHarpoons | ArrowKind::SmallOverLargeHarpoons => '\u{21CC}',
1130        })
1131    }
1132}
1133
1134/// Large operator with optional limits.
1135#[derive(Clone, Debug, PartialEq)]
1136pub struct BigOp {
1137    pub base: Node,
1138    pub sub: Option<Node>,
1139    pub sup: Option<Node>,
1140    /// Draws the limits above and below instead of beside the operator.
1141    pub limits: bool,
1142}
1143
1144/// A positional offset applied to a subtree, in 32nds of a point.
1145///
1146/// MathType records nudging on the record the selected item was written as. The vertical
1147/// component points up, the direction of the equation's own coordinate system.
1148#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1149pub struct Nudge {
1150    pub dx: i32,
1151    pub dy: i32,
1152}
1153
1154impl Nudge {
1155    /// Whether the offset leaves the item where it sits.
1156    pub fn is_zero(&self) -> bool {
1157        self.dx == 0 && self.dy == 0
1158    }
1159}
1160
1161/// Style, font, class, size or position override applied to a subtree.
1162#[derive(Clone, Debug, PartialEq)]
1163pub struct Styled {
1164    pub body: Node,
1165    pub style: Option<MathStyle>,
1166    pub font: Option<Font>,
1167    pub class: Option<Class>,
1168    /// Size adjustment on top of, or instead of, the size class.
1169    pub size: Option<Size>,
1170    /// Offset applied to the laid-out subtree.
1171    pub nudge: Option<Nudge>,
1172}
1173
1174/// A size recorded on a subtree, in 32nds of a point, MathType's own resolution.
1175///
1176/// A delta is measured from the size the class resolves to, which is how Smaller and Larger
1177/// work: the offset follows the class when the preset changes. A delta needs the class it is
1178/// measured from, so a node carrying one records [`Styled::style`] too.
1179#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1180pub enum Size {
1181    /// Offset from the class's size. Negative values shrink.
1182    Delta(i32),
1183    /// An explicit size, which replaces the class, as Other Size assigns.
1184    Points(i32),
1185}
1186
1187impl Size {
1188    /// A delta of `points` points.
1189    pub fn delta(points: f64) -> Self {
1190        Size::Delta(thirty_seconds(points))
1191    }
1192
1193    /// An explicit size of `points` points.
1194    pub fn points(points: f64) -> Self {
1195        Size::Points(thirty_seconds(points))
1196    }
1197}
1198
1199/// `points` in 32nds of a point.
1200fn thirty_seconds(points: f64) -> i32 {
1201    (points * 32.0).round() as i32
1202}
1203
1204/// Position in the tree: the sequence of slot indices from the root.
1205#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
1206pub struct Path(Vec<usize>);
1207
1208impl Path {
1209    /// The path naming the root.
1210    pub fn root() -> Self {
1211        Self(Vec::new())
1212    }
1213
1214    /// Path with `index` appended.
1215    pub fn child(&self, index: usize) -> Self {
1216        let mut path = self.clone();
1217        path.0.push(index);
1218        path
1219    }
1220
1221    /// Path with the last index removed, or `None` at the root.
1222    pub fn parent(&self) -> Option<Self> {
1223        let mut path = self.clone();
1224        path.0.pop().map(|_| path)
1225    }
1226
1227    /// Last index, i.e. the slot of the parent that holds this node.
1228    pub fn last(&self) -> Option<usize> {
1229        self.0.last().copied()
1230    }
1231
1232    /// Split into the parent path and the final index.
1233    pub fn split_last(&self) -> Option<(Self, usize)> {
1234        let (index, rest) = self.0.split_last()?;
1235        Some((Self(rest.to_vec()), *index))
1236    }
1237
1238    pub fn push(&mut self, index: usize) {
1239        self.0.push(index);
1240    }
1241
1242    pub fn pop(&mut self) -> Option<usize> {
1243        self.0.pop()
1244    }
1245
1246    pub fn len(&self) -> usize {
1247        self.0.len()
1248    }
1249
1250    pub fn is_empty(&self) -> bool {
1251        self.0.is_empty()
1252    }
1253
1254    pub fn as_slice(&self) -> &[usize] {
1255        &self.0
1256    }
1257}
1258
1259impl FromIterator<usize> for Path {
1260    fn from_iter<T: IntoIterator<Item = usize>>(iter: T) -> Self {
1261        Self(iter.into_iter().collect())
1262    }
1263}
1264
1265impl std::fmt::Display for Path {
1266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1267        if self.0.is_empty() {
1268            return f.write_str(".");
1269        }
1270        for (position, index) in self.0.iter().enumerate() {
1271            if position > 0 {
1272                f.write_str(".")?;
1273            }
1274            write!(f, "{index}")?;
1275        }
1276        Ok(())
1277    }
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282    use super::*;
1283
1284    fn scripts(base: Node, sub: Node, sup: Node) -> Node {
1285        Node::Scripts(Box::new(Scripts {
1286            base,
1287            sub: Some(sub),
1288            sup: Some(sup),
1289            precedes: false,
1290        }))
1291    }
1292
1293    #[test]
1294    fn a_new_equation_is_a_display_equation() {
1295        assert!(!Math::new(Node::variable('x')).inline);
1296    }
1297
1298    #[test]
1299    fn fraction_slots_are_numerator_then_denominator() {
1300        let frac = Node::Frac(Box::new(Frac::new(
1301            Node::variable('a'),
1302            Node::variable('b'),
1303        )));
1304        assert_eq!(frac.slot_count(), 2);
1305        assert_eq!(frac.slot(0), Some(&Node::variable('a')));
1306        assert_eq!(frac.slot(1), Some(&Node::variable('b')));
1307        assert_eq!(frac.slot(2), None);
1308    }
1309
1310    #[test]
1311    fn square_root_has_a_single_slot() {
1312        let root = Node::Sqrt(Box::new(Sqrt::square(Node::variable('x'))));
1313        assert_eq!(root.slot_count(), 1);
1314        assert_eq!(root.slot(0), Some(&Node::variable('x')));
1315
1316        let nth = Node::Sqrt(Box::new(Sqrt::nth(
1317            Node::variable('n'),
1318            Node::variable('x'),
1319        )));
1320        assert_eq!(nth.slot_count(), 2);
1321        assert_eq!(nth.slot(0), Some(&Node::variable('n')));
1322        assert_eq!(nth.slot(1), Some(&Node::variable('x')));
1323    }
1324
1325    #[test]
1326    fn path_navigation_reaches_nested_slots() {
1327        let math = Math::new(Node::row([
1328            Node::variable('x'),
1329            scripts(
1330                Node::variable('a'),
1331                Node::variable('i'),
1332                Node::variable('2'),
1333            ),
1334        ]));
1335        let sup = Path::root().child(1).child(2);
1336        assert_eq!(math.node_at(&sup), Some(&Node::variable('2')));
1337        assert_eq!(sup.to_string(), "1.2");
1338        assert_eq!(
1339            sup.parent().map(|path| path.to_string()),
1340            Some("1".to_owned())
1341        );
1342        assert_eq!(math.node_at(&Path::root()), Some(&math.body));
1343    }
1344
1345    #[test]
1346    fn replace_and_insert_operate_on_nested_slots() {
1347        let mut math = Math::new(Node::row([
1348            Node::variable('a'),
1349            Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
1350        ]));
1351        let radicand = Path::root().child(1).child(0);
1352        let replaced = math
1353            .node_at_mut(&radicand)
1354            .map(|node| std::mem::replace(node, Node::variable('y')));
1355        assert_eq!(replaced, Some(Node::variable('x')));
1356        assert_eq!(math.node_at(&radicand), Some(&Node::variable('y')));
1357
1358        let row = Path::root();
1359        assert!(math.body.insert_at(&row, Node::variable('z')));
1360        assert_eq!(math.body.slot_count(), 3);
1361        assert_eq!(
1362            math.node_at(&Path::root().child(2)),
1363            Some(&Node::variable('z'))
1364        );
1365        assert_eq!(
1366            math.body.remove_at(&Path::root().child(2)),
1367            Some(Node::variable('z'))
1368        );
1369        assert_eq!(math.body.slot_count(), 2);
1370    }
1371
1372    #[test]
1373    fn matrix_cells_are_addressed_row_major() {
1374        let mut matrix = Matrix::empty(2, 3);
1375        if let Some(cell) = matrix.cell_at_mut(4) {
1376            *cell = Node::variable('q');
1377        }
1378        let node = Node::Matrix(Box::new(matrix));
1379        assert_eq!(node.slot_count(), 6);
1380        assert_eq!(node.slot(4), Some(&Node::variable('q')));
1381        assert_eq!(node.slot(1), Some(&Node::empty()));
1382    }
1383
1384    #[test]
1385    fn walk_visits_every_reachable_node() {
1386        let math = Math::new(Node::row([
1387            scripts(Node::variable('a'), Node::variable('i'), Node::empty()),
1388            Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
1389        ]));
1390        let mut names = Vec::new();
1391        math.body.walk(&mut |node| {
1392            if let Node::Char(Char { ch, .. }) = node {
1393                names.push(*ch);
1394            }
1395        });
1396        assert_eq!(names, vec!['a', 'i', 'x']);
1397    }
1398
1399    #[test]
1400    fn normalisation_flattens_nested_rows_only() {
1401        let mut node = Node::row([
1402            Node::variable('a'),
1403            Node::row([Node::variable('b'), Node::variable('c')]),
1404        ]);
1405        node.normalize();
1406        assert_eq!(
1407            node,
1408            Node::row([
1409                Node::variable('a'),
1410                Node::variable('b'),
1411                Node::variable('c')
1412            ])
1413        );
1414
1415        let mut node = Node::row([Node::row([Node::variable('a')])]);
1416        node.normalize();
1417        assert_eq!(node, Node::row([Node::variable('a')]));
1418
1419        let mut fraction = Node::Frac(Box::new(Frac::new(
1420            Node::row([Node::row([Node::variable('1')])]),
1421            Node::variable('2'),
1422        )));
1423        fraction.normalize();
1424        assert_eq!(fraction.slot(0), Some(&Node::row([Node::variable('1')])));
1425    }
1426
1427    #[test]
1428    fn space_widths_follow_the_em_grid() {
1429        assert_eq!(Space::Thin.em(12.0), 3.0 / 18.0);
1430        assert_eq!(Space::Quad.em(12.0), 1.0);
1431        assert_eq!(Space::NegativeThick.em(12.0), -5.0 / 18.0);
1432    }
1433
1434    #[test]
1435    fn the_zero_width_space_takes_no_room_at_any_size() {
1436        assert_eq!(Space::ZeroWidth.em(12.0), 0.0);
1437        assert_eq!(Space::ZeroWidth.em(24.0), 0.0);
1438    }
1439
1440    #[test]
1441    fn the_point_space_is_one_point_whatever_the_size() {
1442        // An em is the size itself, so one point is 1/size of an em.
1443        assert_eq!(Space::OnePoint.em(12.0), 1.0 / 12.0);
1444        assert_eq!(Space::OnePoint.em(24.0), 1.0 / 24.0);
1445    }
1446
1447    #[test]
1448    fn delimiters_expose_matching_pairs() {
1449        assert_eq!(Delim::Paren.open(), Some('('));
1450        assert_eq!(Delim::Paren.close(), Some(')'));
1451        assert_eq!(Delim::None.open(), None);
1452        assert_eq!(Delim::Brace.close(), Some('}'));
1453    }
1454
1455    #[test]
1456    fn style_nesting_saturates() {
1457        assert_eq!(MathStyle::Full.smaller(), MathStyle::Script);
1458        assert_eq!(MathStyle::Script.smaller(), MathStyle::ScriptScript);
1459        assert_eq!(MathStyle::ScriptScript.smaller(), MathStyle::ScriptScript);
1460    }
1461
1462    #[test]
1463    fn the_euclid_faces_answer_for_their_own_weight_and_slant() {
1464        assert!(!Font::Euclid.is_bold() && !Font::Euclid.is_italic());
1465        assert!(Font::EuclidItalic.is_italic() && !Font::EuclidItalic.is_bold());
1466        assert!(Font::EuclidBold.is_bold() && !Font::EuclidBold.is_italic());
1467        assert!(Font::EuclidBoldItalic.is_bold() && Font::EuclidBoldItalic.is_italic());
1468        assert!(Font::EuclidSymbolItalic.is_italic() && !Font::EuclidSymbolItalic.is_bold());
1469        assert!(Font::EuclidSymbolBoldItalic.is_bold() && Font::EuclidSymbolBoldItalic.is_italic());
1470        assert!(Font::EuclidExtraBold.is_bold() && !Font::EuclidExtraBold.is_italic());
1471        assert!(!Font::EuclidExtra.is_bold() && !Font::EuclidExtra.is_italic());
1472        assert!(!Font::Fences.is_bold() && !Font::Fences.is_italic());
1473    }
1474}