1#[derive(Clone, Debug, Default, PartialEq)]
11pub struct Math {
12 pub body: Node,
13 pub style: MathStyle,
14 pub inline: bool,
17}
18
19impl Math {
20 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45pub enum MathStyle {
46 Text,
48 Script,
50 ScriptScript,
52 #[default]
54 Full,
55 Symbol,
57 SubSymbol,
59 User1,
61 User2,
63}
64
65impl MathStyle {
66 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
86pub type Row = Vec<Node>;
88
89#[derive(Clone, Debug, PartialEq)]
93pub enum Node {
94 Row(Row),
96 Char(Char),
98 Text(Box<TextRun>),
100 Space(Space),
102 Frac(Box<Frac>),
104 Sqrt(Box<Sqrt>),
106 Scripts(Box<Scripts>),
108 Limits(Box<Limits>),
110 Fence(Box<Fence>),
112 Matrix(Box<Matrix>),
114 Accent(Box<Accent>),
116 LabeledArrow(Box<LabeledArrow>),
118 Big(Box<BigOp>),
120 Styled(Box<Styled>),
122 Align,
124 Error(String),
126}
127
128impl Node {
129 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 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 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 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 pub fn is_empty_slot(&self) -> bool {
177 matches!(self, Node::Row(row) if row.is_empty())
178 }
179
180 pub fn is_row(&self) -> bool {
182 matches!(self, Node::Row(_))
183 }
184
185 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 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 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 pub fn slots(&self) -> Vec<&Node> {
289 (0..self.slot_count())
290 .filter_map(|i| self.slot(i))
291 .collect()
292 }
293
294 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 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 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 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 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 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 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 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 fn default() -> Self {
436 Node::empty()
437 }
438}
439
440#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
442pub struct Char {
443 pub ch: char,
444 pub class: Class,
445 pub font: Font,
446 pub style_ref: Option<StyleRef>,
450}
451
452#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
458pub enum StyleRef {
459 User1,
460 User2,
461}
462
463#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
465pub enum Class {
466 #[default]
468 Ord,
469 Op,
471 Bin,
473 Rel,
475 Open,
477 Close,
479 Punct,
481 Inner,
483}
484
485#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
487pub enum Font {
488 #[default]
490 Italic,
491 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 Symbol,
507 Extra,
509 Fences,
511 Euclid,
513 EuclidItalic,
514 EuclidBold,
515 EuclidBoldItalic,
516 EuclidSymbol,
518 EuclidSymbolItalic,
519 EuclidSymbolBold,
520 EuclidSymbolBoldItalic,
521 EuclidExtra,
523 EuclidExtraBold,
524}
525
526impl Font {
527 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 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#[derive(Clone, Debug, PartialEq, Eq)]
563pub struct TextRun {
564 pub text: String,
565 pub font: Font,
566}
567
568#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
570pub enum Space {
571 Thin,
573 Medium,
575 Thick,
577 Sixteenth,
579 Quad,
581 DoubleQuad,
583 ZeroWidth,
585 OnePoint,
587 NegativeThin,
589 NegativeMedium,
591 NegativeThick,
593}
594
595impl Space {
596 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#[derive(Clone, Debug, PartialEq)]
619pub struct Frac {
620 pub num: Node,
621 pub den: Node,
622 pub kind: FracKind,
623 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
640pub enum FracKind {
641 #[default]
643 Bar,
644 Slash,
646 NoBar,
648 Linear,
650}
651
652#[derive(Clone, Debug, PartialEq)]
654pub struct Sqrt {
655 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#[derive(Clone, Debug, PartialEq)]
678pub struct Scripts {
679 pub base: Node,
680 pub sub: Option<Node>,
681 pub sup: Option<Node>,
682 pub precedes: bool,
687}
688
689impl Scripts {
690 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 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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
729pub enum Side {
730 #[default]
731 Center,
732 Left,
733 Right,
734 AtRelation,
736 AtDecimal,
738}
739
740#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
745pub enum VerticalAlign {
746 Top,
748 #[default]
750 Center,
751 Bottom,
753 Centered,
755 Axis,
757}
758
759#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
761pub enum LineStyle {
762 #[default]
764 None,
765 Solid,
766 Dashed,
767 Dotted,
768}
769
770#[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 None,
783 Custom(char),
785 Arrow,
787 DoubleBar,
789}
790
791impl Delim {
792 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
831pub enum FenceAlign {
832 #[default]
835 Axis,
836 Contents,
838 Centered,
840}
841
842#[derive(Clone, Debug, PartialEq)]
844pub struct Fence {
845 pub open: Delim,
846 pub close: Delim,
847 pub body: Node,
848 pub align: FenceAlign,
850}
851
852#[derive(Clone, Debug, PartialEq)]
854pub struct Matrix {
855 pub rows: Vec<Row>,
856 pub delims: Option<(Delim, Delim)>,
857 pub kind: MatrixKind,
858 pub line_spacings: Vec<Option<f64>>,
861 pub align: Side,
863 pub columns: Vec<Side>,
865 pub stack_align: VerticalAlign,
867 pub cell_align: VerticalAlign,
869 pub row_lines: Vec<LineStyle>,
872 pub col_lines: Vec<LineStyle>,
875}
876
877impl Matrix {
878 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 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 pub fn row_count(&self) -> usize {
904 self.rows.len()
905 }
906
907 pub fn col_count(&self) -> usize {
909 self.rows.iter().map(Row::len).max().unwrap_or(0)
910 }
911
912 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 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
939pub enum MatrixKind {
940 #[default]
941 Matrix,
942 Cases,
944 Aligned,
946 Array,
948 Pile,
950 LongDivision,
952}
953
954#[derive(Clone, Debug, PartialEq)]
956pub struct Accent {
957 pub kind: AccentKind,
958 pub base: Node,
959 pub under: bool,
961}
962
963#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
965pub enum AccentKind {
966 Hat,
967 WideHat,
968 Tilde,
969 WideTilde,
970 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 HarpoonRight,
992 HarpoonLeft,
994 DoubleArrow,
996 Line,
999 Strike,
1001 StrikeUp,
1003 StrikeDown,
1005 CrossStrike,
1007 Arc,
1009 JointStatus,
1011}
1012
1013impl AccentKind {
1014 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#[derive(Clone, Debug, PartialEq)]
1060pub struct LabeledArrow {
1061 pub arrow: ArrowKind,
1062 pub over: Option<Node>,
1064 pub under: Option<Node>,
1066}
1067
1068impl LabeledArrow {
1069 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1098pub enum ArrowKind {
1099 Right,
1101 Left,
1103 DoubleHeaded,
1105 Double,
1107 LargeOverSmall,
1109 SmallOverLarge,
1111 Harpoons,
1113 LargeOverSmallHarpoons,
1115 SmallOverLargeHarpoons,
1117}
1118
1119impl ArrowKind {
1120 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#[derive(Clone, Debug, PartialEq)]
1136pub struct BigOp {
1137 pub base: Node,
1138 pub sub: Option<Node>,
1139 pub sup: Option<Node>,
1140 pub limits: bool,
1142}
1143
1144#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1149pub struct Nudge {
1150 pub dx: i32,
1151 pub dy: i32,
1152}
1153
1154impl Nudge {
1155 pub fn is_zero(&self) -> bool {
1157 self.dx == 0 && self.dy == 0
1158 }
1159}
1160
1161#[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 pub size: Option<Size>,
1170 pub nudge: Option<Nudge>,
1172}
1173
1174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1180pub enum Size {
1181 Delta(i32),
1183 Points(i32),
1185}
1186
1187impl Size {
1188 pub fn delta(points: f64) -> Self {
1190 Size::Delta(thirty_seconds(points))
1191 }
1192
1193 pub fn points(points: f64) -> Self {
1195 Size::Points(thirty_seconds(points))
1196 }
1197}
1198
1199fn thirty_seconds(points: f64) -> i32 {
1201 (points * 32.0).round() as i32
1202}
1203
1204#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
1206pub struct Path(Vec<usize>);
1207
1208impl Path {
1209 pub fn root() -> Self {
1211 Self(Vec::new())
1212 }
1213
1214 pub fn child(&self, index: usize) -> Self {
1216 let mut path = self.clone();
1217 path.0.push(index);
1218 path
1219 }
1220
1221 pub fn parent(&self) -> Option<Self> {
1223 let mut path = self.clone();
1224 path.0.pop().map(|_| path)
1225 }
1226
1227 pub fn last(&self) -> Option<usize> {
1229 self.0.last().copied()
1230 }
1231
1232 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 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}