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}
457
458impl Font {
459 pub fn is_italic(self) -> bool {
461 matches!(
462 self,
463 Font::Italic | Font::BoldItalic | Font::SansSerifItalic | Font::SansSerifBoldItalic
464 )
465 }
466
467 pub fn is_bold(self) -> bool {
469 matches!(
470 self,
471 Font::Bold
472 | Font::BoldItalic
473 | Font::SansSerifBold
474 | Font::SansSerifBoldItalic
475 | Font::BoldScript
476 | Font::BoldFraktur
477 )
478 }
479}
480
481#[derive(Clone, Debug, PartialEq, Eq)]
483pub struct TextRun {
484 pub text: String,
485 pub font: Font,
486}
487
488#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
490pub enum Space {
491 Thin,
493 Medium,
495 Thick,
497 Sixteenth,
499 Quad,
501 DoubleQuad,
503 NegativeThin,
505 NegativeMedium,
507 NegativeThick,
509}
510
511impl Space {
512 pub fn em(self) -> f64 {
514 match self {
515 Space::Thin => 3.0 / 18.0,
516 Space::Medium => 4.0 / 18.0,
517 Space::Thick => 5.0 / 18.0,
518 Space::Sixteenth => 6.0 / 18.0,
519 Space::Quad => 1.0,
520 Space::DoubleQuad => 2.0,
521 Space::NegativeThin => -3.0 / 18.0,
522 Space::NegativeMedium => -4.0 / 18.0,
523 Space::NegativeThick => -5.0 / 18.0,
524 }
525 }
526}
527
528#[derive(Clone, Debug, PartialEq, Eq)]
530pub struct Frac {
531 pub num: Node,
532 pub den: Node,
533 pub kind: FracKind,
534}
535
536impl Frac {
537 pub fn new(num: Node, den: Node) -> Self {
538 Self {
539 num,
540 den,
541 kind: FracKind::Bar,
542 }
543 }
544}
545
546#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
548pub enum FracKind {
549 #[default]
551 Bar,
552 Slash,
554 NoBar,
556 Linear,
558}
559
560#[derive(Clone, Debug, PartialEq, Eq)]
562pub struct Sqrt {
563 pub index: Option<Node>,
565 pub radicand: Node,
566}
567
568impl Sqrt {
569 pub fn square(radicand: Node) -> Self {
570 Self {
571 index: None,
572 radicand,
573 }
574 }
575
576 pub fn nth(index: Node, radicand: Node) -> Self {
577 Self {
578 index: Some(index),
579 radicand,
580 }
581 }
582}
583
584#[derive(Clone, Debug, PartialEq, Eq)]
586pub struct Scripts {
587 pub base: Node,
588 pub sub: Option<Node>,
589 pub sup: Option<Node>,
590}
591
592impl Scripts {
593 pub fn attach(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
598 Self { base, sub, sup }
599 }
600}
601
602#[derive(Clone, Debug, PartialEq, Eq)]
604pub struct Limits {
605 pub base: Node,
606 pub under: Option<Node>,
607 pub over: Option<Node>,
608 pub align: Side,
609}
610
611#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
613pub enum Side {
614 #[default]
615 Center,
616 Left,
617 Right,
618}
619
620#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
622pub enum Delim {
623 Paren,
624 Bracket,
625 Brace,
626 Abs,
627 Norm,
628 Angle,
629 Floor,
630 Ceil,
631 None,
633 Custom(char),
635 Arrow,
637 DoubleBar,
639}
640
641impl Delim {
642 pub fn open(self) -> Option<char> {
644 Some(match self {
645 Delim::Paren => '(',
646 Delim::Bracket => '[',
647 Delim::Brace => '{',
648 Delim::Abs => '|',
649 Delim::Norm => '\u{2016}',
650 Delim::Angle => '\u{27E8}',
651 Delim::Floor => '\u{230A}',
652 Delim::Ceil => '\u{2308}',
653 Delim::None => return None,
654 Delim::Custom(ch) => ch,
655 Delim::Arrow => '\u{27E8}',
656 Delim::DoubleBar => '\u{2016}',
657 })
658 }
659
660 pub fn close(self) -> Option<char> {
662 Some(match self {
663 Delim::Paren => ')',
664 Delim::Bracket => ']',
665 Delim::Brace => '}',
666 Delim::Abs => '|',
667 Delim::Norm => '\u{2016}',
668 Delim::Angle => '\u{27E9}',
669 Delim::Floor => '\u{230B}',
670 Delim::Ceil => '\u{2309}',
671 Delim::None => return None,
672 Delim::Custom(ch) => ch,
673 Delim::Arrow => '\u{27E9}',
674 Delim::DoubleBar => '\u{2016}',
675 })
676 }
677}
678
679#[derive(Clone, Debug, PartialEq, Eq)]
681pub struct Fence {
682 pub open: Delim,
683 pub close: Delim,
684 pub body: Node,
685}
686
687#[derive(Clone, Debug, PartialEq, Eq)]
689pub struct Matrix {
690 pub rows: Vec<Row>,
691 pub delims: Option<(Delim, Delim)>,
692 pub kind: MatrixKind,
693 pub align: Side,
695 pub columns: Vec<Side>,
697 pub rules: bool,
699}
700
701impl Matrix {
702 pub fn empty(rows: usize, cols: usize) -> Self {
704 Self {
705 rows: vec![vec![Node::empty(); cols]; rows],
706 delims: None,
707 kind: MatrixKind::Matrix,
708 align: Side::Center,
709 columns: Vec::new(),
710 rules: false,
711 }
712 }
713
714 pub fn row_count(&self) -> usize {
716 self.rows.len()
717 }
718
719 pub fn col_count(&self) -> usize {
721 self.rows.iter().map(Row::len).max().unwrap_or(0)
722 }
723
724 fn cell_position(&self, index: usize) -> Option<(usize, usize)> {
725 let mut remaining = index;
726 for (row, cells) in self.rows.iter().enumerate() {
727 if remaining < cells.len() {
728 return Some((row, remaining));
729 }
730 remaining -= cells.len();
731 }
732 None
733 }
734
735 pub fn cell_at(&self, index: usize) -> Option<&Node> {
737 let (row, col) = self.cell_position(index)?;
738 self.rows[row].get(col)
739 }
740
741 pub fn cell_at_mut(&mut self, index: usize) -> Option<&mut Node> {
743 let (row, col) = self.cell_position(index)?;
744 self.rows[row].get_mut(col)
745 }
746}
747
748#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
750pub enum MatrixKind {
751 #[default]
752 Matrix,
753 Cases,
755 Aligned,
757 Array,
759 Pile,
761 LongDivision,
763}
764
765#[derive(Clone, Debug, PartialEq, Eq)]
767pub struct Accent {
768 pub kind: AccentKind,
769 pub base: Node,
770 pub under: bool,
772}
773
774#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
776pub enum AccentKind {
777 Hat,
778 WideHat,
779 Tilde,
780 WideTilde,
781 Bar,
782 Vector,
783 Dot,
784 DoubleDot,
785 TripleDot,
786 Breve,
787 Check,
788 Acute,
789 Grave,
790 Circle,
791 OverBrace,
792 UnderBrace,
793 OverBracket,
794 UnderBracket,
795 OverParen,
796 UnderParen,
797 ArrowRight,
798 ArrowLeft,
799 Line,
800 Strike,
801}
802
803impl AccentKind {
804 pub fn glyph(self) -> Option<char> {
806 Some(match self {
807 AccentKind::Hat => '\u{02C6}',
808 AccentKind::WideHat => '\u{0302}',
809 AccentKind::Tilde => '~',
810 AccentKind::WideTilde => '\u{0303}',
811 AccentKind::Dot => '\u{02D9}',
812 AccentKind::DoubleDot => '\u{00A8}',
813 AccentKind::TripleDot => '\u{20DB}',
814 AccentKind::Breve => '\u{02D8}',
815 AccentKind::Check => '\u{02C7}',
816 AccentKind::Acute => '\u{00B4}',
817 AccentKind::Grave => '`',
818 AccentKind::Circle => '\u{02DA}',
819 AccentKind::ArrowRight => '\u{2192}',
820 AccentKind::ArrowLeft => '\u{2190}',
821 AccentKind::Bar | AccentKind::Vector | AccentKind::Line => return None,
822 AccentKind::Strike => return None,
823 AccentKind::OverBrace => '\u{23DE}',
824 AccentKind::UnderBrace => '\u{23DF}',
825 AccentKind::OverBracket => '\u{23B4}',
826 AccentKind::UnderBracket => '\u{23B5}',
827 AccentKind::OverParen => '\u{23DC}',
828 AccentKind::UnderParen => '\u{23DD}',
829 })
830 }
831}
832
833#[derive(Clone, Debug, PartialEq, Eq)]
835pub struct BigOp {
836 pub base: Node,
837 pub sub: Option<Node>,
838 pub sup: Option<Node>,
839 pub limits: bool,
841}
842
843#[derive(Clone, Debug, PartialEq, Eq)]
845pub struct Styled {
846 pub body: Node,
847 pub style: Option<MathStyle>,
848 pub font: Option<Font>,
849 pub class: Option<Class>,
850}
851
852#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
854pub struct Path(Vec<usize>);
855
856impl Path {
857 pub fn root() -> Self {
859 Self(Vec::new())
860 }
861
862 pub fn child(&self, index: usize) -> Self {
864 let mut path = self.clone();
865 path.0.push(index);
866 path
867 }
868
869 pub fn parent(&self) -> Option<Self> {
871 let mut path = self.clone();
872 path.0.pop().map(|_| path)
873 }
874
875 pub fn last(&self) -> Option<usize> {
877 self.0.last().copied()
878 }
879
880 pub fn split_last(&self) -> Option<(Self, usize)> {
882 let (index, rest) = self.0.split_last()?;
883 Some((Self(rest.to_vec()), *index))
884 }
885
886 pub fn push(&mut self, index: usize) {
887 self.0.push(index);
888 }
889
890 pub fn pop(&mut self) -> Option<usize> {
891 self.0.pop()
892 }
893
894 pub fn len(&self) -> usize {
895 self.0.len()
896 }
897
898 pub fn is_empty(&self) -> bool {
899 self.0.is_empty()
900 }
901
902 pub fn as_slice(&self) -> &[usize] {
903 &self.0
904 }
905}
906
907impl FromIterator<usize> for Path {
908 fn from_iter<T: IntoIterator<Item = usize>>(iter: T) -> Self {
909 Self(iter.into_iter().collect())
910 }
911}
912
913impl std::fmt::Display for Path {
914 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
915 if self.0.is_empty() {
916 return f.write_str(".");
917 }
918 for (position, index) in self.0.iter().enumerate() {
919 if position > 0 {
920 f.write_str(".")?;
921 }
922 write!(f, "{index}")?;
923 }
924 Ok(())
925 }
926}
927
928#[cfg(test)]
929mod tests {
930 use super::*;
931
932 fn scripts(base: Node, sub: Node, sup: Node) -> Node {
933 Node::Scripts(Box::new(Scripts {
934 base,
935 sub: Some(sub),
936 sup: Some(sup),
937 }))
938 }
939
940 #[test]
941 fn fraction_slots_are_numerator_then_denominator() {
942 let frac = Node::Frac(Box::new(Frac::new(
943 Node::variable('a'),
944 Node::variable('b'),
945 )));
946 assert_eq!(frac.slot_count(), 2);
947 assert_eq!(frac.slot(0), Some(&Node::variable('a')));
948 assert_eq!(frac.slot(1), Some(&Node::variable('b')));
949 assert_eq!(frac.slot(2), None);
950 }
951
952 #[test]
953 fn square_root_has_a_single_slot() {
954 let root = Node::Sqrt(Box::new(Sqrt::square(Node::variable('x'))));
955 assert_eq!(root.slot_count(), 1);
956 assert_eq!(root.slot(0), Some(&Node::variable('x')));
957
958 let nth = Node::Sqrt(Box::new(Sqrt::nth(
959 Node::variable('n'),
960 Node::variable('x'),
961 )));
962 assert_eq!(nth.slot_count(), 2);
963 assert_eq!(nth.slot(0), Some(&Node::variable('n')));
964 assert_eq!(nth.slot(1), Some(&Node::variable('x')));
965 }
966
967 #[test]
968 fn path_navigation_reaches_nested_slots() {
969 let math = Math::new(Node::row([
970 Node::variable('x'),
971 scripts(
972 Node::variable('a'),
973 Node::variable('i'),
974 Node::variable('2'),
975 ),
976 ]));
977 let sup = Path::root().child(1).child(2);
978 assert_eq!(math.node_at(&sup), Some(&Node::variable('2')));
979 assert_eq!(sup.to_string(), "1.2");
980 assert_eq!(
981 sup.parent().map(|path| path.to_string()),
982 Some("1".to_owned())
983 );
984 assert_eq!(math.node_at(&Path::root()), Some(&math.body));
985 }
986
987 #[test]
988 fn replace_and_insert_operate_on_nested_slots() {
989 let mut math = Math::new(Node::row([
990 Node::variable('a'),
991 Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
992 ]));
993 let radicand = Path::root().child(1).child(0);
994 let replaced = math
995 .node_at_mut(&radicand)
996 .map(|node| std::mem::replace(node, Node::variable('y')));
997 assert_eq!(replaced, Some(Node::variable('x')));
998 assert_eq!(math.node_at(&radicand), Some(&Node::variable('y')));
999
1000 let row = Path::root();
1001 assert!(math.body.insert_at(&row, Node::variable('z')));
1002 assert_eq!(math.body.slot_count(), 3);
1003 assert_eq!(
1004 math.node_at(&Path::root().child(2)),
1005 Some(&Node::variable('z'))
1006 );
1007 assert_eq!(
1008 math.body.remove_at(&Path::root().child(2)),
1009 Some(Node::variable('z'))
1010 );
1011 assert_eq!(math.body.slot_count(), 2);
1012 }
1013
1014 #[test]
1015 fn matrix_cells_are_addressed_row_major() {
1016 let mut matrix = Matrix::empty(2, 3);
1017 if let Some(cell) = matrix.cell_at_mut(4) {
1018 *cell = Node::variable('q');
1019 }
1020 let node = Node::Matrix(Box::new(matrix));
1021 assert_eq!(node.slot_count(), 6);
1022 assert_eq!(node.slot(4), Some(&Node::variable('q')));
1023 assert_eq!(node.slot(1), Some(&Node::empty()));
1024 }
1025
1026 #[test]
1027 fn walk_visits_every_reachable_node() {
1028 let math = Math::new(Node::row([
1029 scripts(Node::variable('a'), Node::variable('i'), Node::empty()),
1030 Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
1031 ]));
1032 let mut names = Vec::new();
1033 math.body.walk(&mut |node| {
1034 if let Node::Char(Char { ch, .. }) = node {
1035 names.push(*ch);
1036 }
1037 });
1038 assert_eq!(names, vec!['a', 'i', 'x']);
1039 }
1040
1041 #[test]
1042 fn normalisation_flattens_nested_rows_only() {
1043 let mut node = Node::row([
1044 Node::variable('a'),
1045 Node::row([Node::variable('b'), Node::variable('c')]),
1046 ]);
1047 node.normalize();
1048 assert_eq!(
1049 node,
1050 Node::row([
1051 Node::variable('a'),
1052 Node::variable('b'),
1053 Node::variable('c')
1054 ])
1055 );
1056
1057 let mut node = Node::row([Node::row([Node::variable('a')])]);
1058 node.normalize();
1059 assert_eq!(node, Node::row([Node::variable('a')]));
1060
1061 let mut fraction = Node::Frac(Box::new(Frac::new(
1062 Node::row([Node::row([Node::variable('1')])]),
1063 Node::variable('2'),
1064 )));
1065 fraction.normalize();
1066 assert_eq!(fraction.slot(0), Some(&Node::row([Node::variable('1')])));
1067 }
1068
1069 #[test]
1070 fn space_widths_follow_the_em_grid() {
1071 assert_eq!(Space::Thin.em(), 3.0 / 18.0);
1072 assert_eq!(Space::Quad.em(), 1.0);
1073 assert_eq!(Space::NegativeThick.em(), -5.0 / 18.0);
1074 }
1075
1076 #[test]
1077 fn delimiters_expose_matching_pairs() {
1078 assert_eq!(Delim::Paren.open(), Some('('));
1079 assert_eq!(Delim::Paren.close(), Some(')'));
1080 assert_eq!(Delim::None.open(), None);
1081 assert_eq!(Delim::Brace.close(), Some('}'));
1082 }
1083
1084 #[test]
1085 fn style_nesting_saturates() {
1086 assert_eq!(MathStyle::Full.smaller(), MathStyle::Script);
1087 assert_eq!(MathStyle::Script.smaller(), MathStyle::ScriptScript);
1088 assert_eq!(MathStyle::ScriptScript.smaller(), MathStyle::ScriptScript);
1089 }
1090}