1#[derive(Clone, Debug, Default, PartialEq, Eq)]
11pub struct Math {
12 pub body: Node,
13 pub style: MathStyle,
14}
15
16impl Math {
17 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
36pub enum MathStyle {
37 Text,
39 Script,
41 ScriptScript,
43 #[default]
45 Full,
46}
47
48impl MathStyle {
49 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
60pub type Row = Vec<Node>;
62
63#[derive(Clone, Debug, PartialEq, Eq)]
67pub enum Node {
68 Row(Row),
70 Char(Char),
72 Text(Box<TextRun>),
74 Space(Space),
76 Frac(Box<Frac>),
78 Sqrt(Box<Sqrt>),
80 Scripts(Box<Scripts>),
82 Limits(Box<Limits>),
84 Fence(Box<Fence>),
86 Matrix(Box<Matrix>),
88 Accent(Box<Accent>),
90 Big(Box<BigOp>),
92 Styled(Box<Styled>),
94 Align,
96 Error(String),
98}
99
100impl Node {
101 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 pub fn char_with(ch: char, class: Class, font: Font) -> Self {
112 Node::Char(Char { ch, class, font })
113 }
114
115 pub fn variable(ch: char) -> Self {
117 Node::Char(Char {
118 ch,
119 class: Class::Ord,
120 font: Font::Italic,
121 })
122 }
123
124 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 pub fn is_empty_slot(&self) -> bool {
142 matches!(self, Node::Row(row) if row.is_empty())
143 }
144
145 pub fn is_row(&self) -> bool {
147 matches!(self, Node::Row(_))
148 }
149
150 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 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 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 pub fn slots(&self) -> Vec<&Node> {
251 (0..self.slot_count())
252 .filter_map(|i| self.slot(i))
253 .collect()
254 }
255
256 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 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 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 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 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 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 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 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 fn default() -> Self {
398 Node::empty()
399 }
400}
401
402#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
412pub enum Class {
413 #[default]
415 Ord,
416 Op,
418 Bin,
420 Rel,
422 Open,
424 Close,
426 Punct,
428 Inner,
430}
431
432#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
434pub enum Font {
435 #[default]
437 Italic,
438 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 Symbol,
454 Extra,
456 Fences,
458 Euclid,
460 EuclidItalic,
461 EuclidBold,
462 EuclidBoldItalic,
463 EuclidSymbol,
465 EuclidSymbolItalic,
466 EuclidSymbolBold,
467 EuclidSymbolBoldItalic,
468 EuclidExtra,
470 EuclidExtraBold,
471}
472
473impl Font {
474 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 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#[derive(Clone, Debug, PartialEq, Eq)]
510pub struct TextRun {
511 pub text: String,
512 pub font: Font,
513}
514
515#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
517pub enum Space {
518 Thin,
520 Medium,
522 Thick,
524 Sixteenth,
526 Quad,
528 DoubleQuad,
530 NegativeThin,
532 NegativeMedium,
534 NegativeThick,
536}
537
538impl Space {
539 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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
575pub enum FracKind {
576 #[default]
578 Bar,
579 Slash,
581 NoBar,
583 Linear,
585}
586
587#[derive(Clone, Debug, PartialEq, Eq)]
589pub struct Sqrt {
590 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#[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 pub fn attach(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
625 Self { base, sub, sup }
626 }
627}
628
629#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
640pub enum Side {
641 #[default]
642 Center,
643 Left,
644 Right,
645}
646
647#[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 None,
660 Custom(char),
662 Arrow,
664 DoubleBar,
666}
667
668impl Delim {
669 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 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#[derive(Clone, Debug, PartialEq, Eq)]
708pub struct Fence {
709 pub open: Delim,
710 pub close: Delim,
711 pub body: Node,
712}
713
714#[derive(Clone, Debug, PartialEq, Eq)]
716pub struct Matrix {
717 pub rows: Vec<Row>,
718 pub delims: Option<(Delim, Delim)>,
719 pub kind: MatrixKind,
720 pub align: Side,
722 pub columns: Vec<Side>,
724 pub rules: bool,
726}
727
728impl Matrix {
729 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 pub fn row_count(&self) -> usize {
743 self.rows.len()
744 }
745
746 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 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
777pub enum MatrixKind {
778 #[default]
779 Matrix,
780 Cases,
782 Aligned,
784 Array,
786 Pile,
788 LongDivision,
790}
791
792#[derive(Clone, Debug, PartialEq, Eq)]
794pub struct Accent {
795 pub kind: AccentKind,
796 pub base: Node,
797 pub under: bool,
799}
800
801#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
803pub enum AccentKind {
804 Hat,
805 WideHat,
806 Tilde,
807 WideTilde,
808 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 Line,
830 Strike,
831}
832
833impl AccentKind {
834 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#[derive(Clone, Debug, PartialEq, Eq)]
865pub struct BigOp {
866 pub base: Node,
867 pub sub: Option<Node>,
868 pub sup: Option<Node>,
869 pub limits: bool,
871}
872
873#[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#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
884pub struct Path(Vec<usize>);
885
886impl Path {
887 pub fn root() -> Self {
889 Self(Vec::new())
890 }
891
892 pub fn child(&self, index: usize) -> Self {
894 let mut path = self.clone();
895 path.0.push(index);
896 path
897 }
898
899 pub fn parent(&self) -> Option<Self> {
901 let mut path = self.clone();
902 path.0.pop().map(|_| path)
903 }
904
905 pub fn last(&self) -> Option<usize> {
907 self.0.last().copied()
908 }
909
910 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}