mt-core 0.6.0

Equation model: rows, characters and templates in the shape the editor and renderers share.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
//! The equation tree shared by the parsers, the editor and the renderers.
//!
//! The model follows the shape of an equation as an author sees it rather than a TeX token
//! stream: an equation is a [`Row`] of items, templates such as fractions or radicals own their
//! argument slots, and every node exposes a fixed, ordered list of slots. Editing code can
//! therefore walk and mutate any construct without knowing what the construct is, and layout can
//! recurse over the same slot list.

/// A complete equation together with the size preset it is laid out at.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Math {
    pub body: Node,
    pub style: MathStyle,
    /// Whether the equation is placed inline in the host document rather than on a line of its
    /// own. A new equation is a display equation.
    pub inline: bool,
}

impl Math {
    /// An equation wrapping `body` at full size.
    pub fn new(body: impl Into<Node>) -> Self {
        Self {
            body: body.into(),
            style: MathStyle::Full,
            inline: false,
        }
    }

    pub fn node_at(&self, path: &Path) -> Option<&Node> {
        self.body.node_at(path)
    }

    pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
        self.body.node_at_mut(path)
    }
}

/// Size preset an equation is laid out at, matching the size classes an author picks from.
///
/// The seven MathType typesizes plus this crate's own text size: the typesizes are full,
/// subscript, sub-subscript, symbol, sub-symbol, user 1 and user 2 (manual 11.45). A character
/// records the class it is set in, not the points that class currently resolves to, so a change
/// to the preset moves every character set in it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MathStyle {
    /// Inline text size.
    Text,
    /// Smaller than text, one step down in the nesting hierarchy.
    Script,
    /// Smallest supported size, two steps down in the nesting hierarchy.
    ScriptScript,
    /// Full size.
    #[default]
    Full,
    /// The size a large operator's own glyph is drawn at.
    Symbol,
    /// The size a large operator takes when it sits inside a script.
    SubSymbol,
    /// The first user-defined size.
    User1,
    /// The second user-defined size.
    User2,
}

impl MathStyle {
    /// The next smaller preset, saturating at [`MathStyle::ScriptScript`].
    ///
    /// Material inside a script slot steps down the positional ladder: full size, the symbol
    /// class and the user classes step to the subscript, and the subscript, the sub-symbol and
    /// the sub-subscript step to the sub-subscript. The sub-symbol class is where a symbol lands
    /// when it sits inside a script.
    pub fn smaller(self) -> Self {
        match self {
            MathStyle::Full
            | MathStyle::Text
            | MathStyle::Symbol
            | MathStyle::User1
            | MathStyle::User2 => MathStyle::Script,
            MathStyle::Script | MathStyle::SubSymbol | MathStyle::ScriptScript => {
                MathStyle::ScriptScript
            }
        }
    }
}

/// Horizontal sequence of items.
pub type Row = Vec<Node>;

/// One item of an equation.
///
/// Template variants are boxed so that a `Node` stays pointer sized.
#[derive(Clone, Debug, PartialEq)]
pub enum Node {
    /// Horizontal sequence of items; an empty row is an empty argument slot.
    Row(Row),
    /// A single character with its atom class and font.
    Char(Char),
    /// Literal text set upright (`\text{...}` and friends).
    Text(Box<TextRun>),
    /// Explicit horizontal spacing.
    Space(Space),
    /// Fraction, with or without a rule.
    Frac(Box<Frac>),
    /// Radical with an optional index.
    Sqrt(Box<Sqrt>),
    /// Subscript and/or superscript attached to a base.
    Scripts(Box<Scripts>),
    /// Over/under material that is not an accent (`\overset`, `\stackrel`, limits).
    Limits(Box<Limits>),
    /// Delimiters around a body.
    Fence(Box<Fence>),
    /// Table of cells with optional delimiters and alignment.
    Matrix(Box<Matrix>),
    /// Accent over or under a base.
    Accent(Box<Accent>),
    /// Arrow carrying text above, below or on both sides.
    LabeledArrow(Box<LabeledArrow>),
    /// Large operator with optional limits.
    Big(Box<BigOp>),
    /// Style, font or class applied to a subtree.
    Styled(Box<Styled>),
    /// Alignment point (`&` inside aligned environments).
    Align,
    /// Construct kept verbatim because it could not be represented.
    Error(String),
}

impl Node {
    /// An empty row, i.e. an empty slot.
    pub fn empty() -> Self {
        Node::Row(Row::new())
    }

    pub fn row(items: impl IntoIterator<Item = Node>) -> Self {
        Node::Row(items.into_iter().collect())
    }

    /// A character carrying `class` and `font`.
    pub fn char_with(ch: char, class: Class, font: Font) -> Self {
        Node::Char(Char {
            ch,
            class,
            font,
            style_ref: None,
        })
    }

    /// A default-class italic variable.
    pub fn variable(ch: char) -> Self {
        Node::Char(Char {
            style_ref: None,
            ch,
            class: Class::Ord,
            font: Font::Italic,
        })
    }

    /// A default-class upright operator or symbol.
    pub fn symbol(ch: char, class: Class) -> Self {
        Node::Char(Char {
            style_ref: None,
            ch,
            class,
            font: Font::Upright,
        })
    }

    pub fn text(text: impl Into<String>) -> Self {
        Node::Text(Box::new(TextRun {
            text: text.into(),
            font: Font::Upright,
        }))
    }

    /// True when the node is an empty row, which renderers draw as an empty slot.
    pub fn is_empty_slot(&self) -> bool {
        matches!(self, Node::Row(row) if row.is_empty())
    }

    /// Whether the node is a row and can therefore accept siblings.
    pub fn is_row(&self) -> bool {
        matches!(self, Node::Row(_))
    }

    /// Number of child slots the node exposes, in visual order.
    pub fn slot_count(&self) -> usize {
        match self {
            Node::Row(row) => row.len(),
            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => 0,
            Node::Frac(_) => 2,
            Node::Sqrt(sqrt) => 1 + usize::from(sqrt.index.is_some()),
            Node::Scripts(_) => 3,
            Node::Limits(_) => 3,
            Node::Fence(_) => 1,
            Node::Matrix(matrix) => matrix.rows.iter().map(Row::len).sum(),
            Node::Accent(_) => 1,
            Node::LabeledArrow(arrow) => arrow.slot_count(),
            Node::Big(_) => 3,
            Node::Styled(_) => 1,
        }
    }

    /// Read-only access to slot `index`, in the order defined by [`Node::slot_count`].
    pub fn slot(&self, index: usize) -> Option<&Node> {
        match self {
            Node::Row(row) => row.get(index),
            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
            Node::Frac(frac) => match index {
                0 => Some(&frac.num),
                1 => Some(&frac.den),
                _ => None,
            },
            Node::Sqrt(sqrt) => match (index, &sqrt.index) {
                (0, Some(radicand)) => Some(radicand),
                (0, None) => Some(&sqrt.radicand),
                (1, Some(_)) => Some(&sqrt.radicand),
                _ => None,
            },
            Node::Scripts(scripts) => match index {
                0 => Some(&scripts.base),
                1 => scripts.sub.as_ref(),
                2 => scripts.sup.as_ref(),
                _ => None,
            },
            Node::Limits(limits) => match index {
                0 => Some(&limits.base),
                1 => limits.under.as_ref(),
                2 => limits.over.as_ref(),
                _ => None,
            },
            Node::Fence(fence) => (index == 0).then_some(&fence.body),
            Node::Matrix(matrix) => matrix.cell_at(index),
            Node::Accent(accent) => (index == 0).then_some(&accent.base),
            Node::LabeledArrow(arrow) => arrow.slot(index),
            Node::Big(big) => match index {
                0 => Some(&big.base),
                1 => big.sub.as_ref(),
                2 => big.sup.as_ref(),
                _ => None,
            },
            Node::Styled(styled) => (index == 0).then_some(&styled.body),
        }
    }

    /// Mutable access to slot `index`, in the order defined by [`Node::slot_count`].
    pub fn slot_mut(&mut self, index: usize) -> Option<&mut Node> {
        match self {
            Node::Row(row) => row.get_mut(index),
            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
            Node::Frac(frac) => match index {
                0 => Some(&mut frac.num),
                1 => Some(&mut frac.den),
                _ => None,
            },
            Node::Sqrt(sqrt) => match (index, &mut sqrt.index) {
                (0, Some(radicand)) => Some(radicand),
                (0, None) => Some(&mut sqrt.radicand),
                (1, Some(_)) => Some(&mut sqrt.radicand),
                _ => None,
            },
            Node::Scripts(scripts) => match index {
                0 => Some(&mut scripts.base),
                1 => scripts.sub.as_mut(),
                2 => scripts.sup.as_mut(),
                _ => None,
            },
            Node::Limits(limits) => match index {
                0 => Some(&mut limits.base),
                1 => limits.under.as_mut(),
                2 => limits.over.as_mut(),
                _ => None,
            },
            Node::Fence(fence) => (index == 0).then_some(&mut fence.body),
            Node::Matrix(matrix) => matrix.cell_at_mut(index),
            Node::Accent(accent) => (index == 0).then_some(&mut accent.base),
            Node::LabeledArrow(arrow) => arrow.slot_mut(index),
            Node::Big(big) => match index {
                0 => Some(&mut big.base),
                1 => big.sub.as_mut(),
                2 => big.sup.as_mut(),
                _ => None,
            },
            Node::Styled(styled) => (index == 0).then_some(&mut styled.body),
        }
    }

    /// Slots in visual order. Allocates; use [`Node::slot_count`] plus [`Node::slot`] in hot paths.
    pub fn slots(&self) -> Vec<&Node> {
        (0..self.slot_count())
            .filter_map(|i| self.slot(i))
            .collect()
    }

    /// Depth-first walk over the node and every node reachable through its slots.
    pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Node)) {
        visit(self);
        for index in 0..self.slot_count() {
            if let Some(slot) = self.slot(index) {
                slot.walk(visit);
            }
        }
    }

    /// Node reached by following `path` from here.
    pub fn node_at(&self, path: &Path) -> Option<&Node> {
        let mut current = self;
        for &index in path.as_slice() {
            current = current.slot(index)?;
        }
        Some(current)
    }

    /// Mutable node reached by following `path` from here.
    pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
        let mut current = self;
        for &index in path.as_slice() {
            current = current.slot_mut(index)?;
        }
        Some(current)
    }

    /// Replace the node at `path`, returning the replaced node.
    ///
    /// The root cannot be replaced: pass a non-empty path.
    pub fn replace_at(&mut self, path: &Path, node: Node) -> Option<Node> {
        let (parent_path, index) = path.split_last()?;
        let parent = self.node_at_mut(&parent_path)?;
        match parent {
            Node::Row(row) => {
                let target = row.get_mut(index)?;
                Some(std::mem::replace(target, node))
            }
            other => {
                let target = other.slot_mut(index)?;
                Some(std::mem::replace(target, node))
            }
        }
    }

    /// Insert `node` into the row at `path`, directly before the item at `path` or appended when
    /// the path names a row itself.
    pub fn insert_at(&mut self, path: &Path, node: Node) -> bool {
        match self.node_at_mut(path) {
            Some(Node::Row(row)) => {
                row.push(node);
                true
            }
            Some(_) => match path.split_last() {
                Some((parent_path, index)) => match self.node_at_mut(&parent_path) {
                    Some(parent) => parent.insert_sibling(index, node),
                    None => false,
                },
                None => false,
            },
            None => false,
        }
    }

    /// Insert `node` before slot `index` of a row-like parent.
    fn insert_sibling(&mut self, index: usize, node: Node) -> bool {
        match self {
            Node::Row(row) => {
                let index = index.min(row.len());
                row.insert(index, node);
                true
            }
            _ => false,
        }
    }

    /// Remove the node at `path`, returning it. The root cannot be removed.
    pub fn remove_at(&mut self, path: &Path) -> Option<Node> {
        let (parent_path, index) = path.split_last()?;
        match self.node_at_mut(&parent_path)? {
            Node::Row(row) => (index < row.len()).then(|| row.remove(index)),
            _ => None,
        }
    }

    /// Flatten rows nested directly inside a row and drop empty nested rows.
    ///
    /// Template slots are untouched, so this only removes row nesting that carries no meaning and
    /// keeps parse-then-serialise round trips stable.
    pub fn normalize(&mut self) {
        for index in 0..self.slot_count() {
            if let Some(slot) = self.slot_mut(index) {
                slot.normalize();
            }
        }
        if let Node::Row(row) = self {
            let mut flat = Row::with_capacity(row.len());
            for node in row.drain(..) {
                match node {
                    Node::Row(inner) => flat.extend(inner),
                    other => flat.push(other),
                }
            }
            *row = flat;
        }
    }
}

impl From<char> for Node {
    fn from(ch: char) -> Self {
        Node::variable(ch)
    }
}

impl From<&str> for Node {
    fn from(text: &str) -> Self {
        Node::Text(Box::new(TextRun {
            text: text.to_owned(),
            font: Font::Upright,
        }))
    }
}

impl From<String> for Node {
    fn from(text: String) -> Self {
        Node::Text(Box::new(TextRun {
            text,
            font: Font::Upright,
        }))
    }
}

impl From<Vec<Node>> for Node {
    fn from(items: Vec<Node>) -> Self {
        Node::Row(items)
    }
}

impl Default for Node {
    /// An empty slot.
    fn default() -> Self {
        Node::empty()
    }
}

/// A character together with the atom class that drives spacing and the font it is set in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Char {
    pub ch: char,
    pub class: Class,
    pub font: Font,
    /// The user style the character was set in, when it was. The other functional styles need
    /// no marker of their own: the structural faces and the operator class carry them, and
    /// layout resolves those through the preset's style slots.
    pub style_ref: Option<StyleRef>,
}

/// A functional style with no structural face of its own, recorded on the character.
///
/// The user styles name whatever face the preset's slot holds for them, so a character set in
/// one must keep the style rather than the face: redefining the slot moves it, and a MathType
/// stream names it with the typeface of that slot (9 and 10) rather than an explicit font.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StyleRef {
    User1,
    User2,
}

/// Atom class, used for operator spacing between neighbouring atoms.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Class {
    /// Ordinary atom: variables, numbers, most symbols.
    #[default]
    Ord,
    /// Large operator or function name taking limits.
    Op,
    /// Binary operator.
    Bin,
    /// Relation.
    Rel,
    /// Opening delimiter.
    Open,
    /// Closing delimiter.
    Close,
    /// Punctuation.
    Punct,
    /// Inner atom, e.g. a fraction or matrix.
    Inner,
}

/// Typeface a run is set in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Font {
    /// Italic math variable, the default for letters.
    #[default]
    Italic,
    /// Upright roman.
    Upright,
    Bold,
    BoldItalic,
    SansSerif,
    SansSerifBold,
    SansSerifItalic,
    SansSerifBoldItalic,
    Monospace,
    Script,
    BoldScript,
    Fraktur,
    BoldFraktur,
    DoubleStruck,
    /// Symbols drawn from the symbol font rather than the text face.
    Symbol,
    /// Glyphs from the extra symbol face.
    Extra,
    /// Fences, the face MathType draws the characters decorating a template with.
    Fences,
    /// Euclid, the text face MathType names in an explicit font definition.
    Euclid,
    EuclidItalic,
    EuclidBold,
    EuclidBoldItalic,
    /// Euclid Symbol, a symbol-encoded face MathType names in an explicit font definition.
    EuclidSymbol,
    EuclidSymbolItalic,
    EuclidSymbolBold,
    EuclidSymbolBoldItalic,
    /// Euclid Extra, the extra face MathType names in an explicit font definition.
    EuclidExtra,
    EuclidExtraBold,
}

impl Font {
    /// Whether the face is set in italics, which layout needs for metric selection.
    pub fn is_italic(self) -> bool {
        matches!(
            self,
            Font::Italic
                | Font::BoldItalic
                | Font::SansSerifItalic
                | Font::SansSerifBoldItalic
                | Font::EuclidItalic
                | Font::EuclidBoldItalic
                | Font::EuclidSymbolItalic
                | Font::EuclidSymbolBoldItalic
        )
    }

    /// Whether the face is bold.
    pub fn is_bold(self) -> bool {
        matches!(
            self,
            Font::Bold
                | Font::BoldItalic
                | Font::SansSerifBold
                | Font::SansSerifBoldItalic
                | Font::BoldScript
                | Font::BoldFraktur
                | Font::EuclidBold
                | Font::EuclidBoldItalic
                | Font::EuclidSymbolBold
                | Font::EuclidSymbolBoldItalic
                | Font::EuclidExtraBold
        )
    }
}

/// Literal text set upright, optionally in a specific face.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextRun {
    pub text: String,
    pub font: Font,
}

/// Explicit horizontal space.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Space {
    /// 3/18 em.
    Thin,
    /// 4/18 em.
    Medium,
    /// 5/18 em.
    Thick,
    /// 6/18 em.
    Sixteenth,
    /// 1 em.
    Quad,
    /// 2 em.
    DoubleQuad,
    /// No width at all, the zero-width space.
    ZeroWidth,
    /// One point, a width that depends on the size the equation is set in.
    OnePoint,
    /// -3/18 em.
    NegativeThin,
    /// -4/18 em.
    NegativeMedium,
    /// -5/18 em.
    NegativeThick,
}

impl Space {
    /// Width in em units, negative for backspacing.
    ///
    /// `size` is the size of the equation's full-size text in points. Only the point-sized space
    /// needs it, the rest are fractions of an em whatever the size.
    pub fn em(self, size: f64) -> f64 {
        match self {
            Space::Thin => 3.0 / 18.0,
            Space::Medium => 4.0 / 18.0,
            Space::Thick => 5.0 / 18.0,
            Space::Sixteenth => 6.0 / 18.0,
            Space::Quad => 1.0,
            Space::DoubleQuad => 2.0,
            Space::ZeroWidth => 0.0,
            Space::OnePoint => 1.0 / size,
            Space::NegativeThin => -3.0 / 18.0,
            Space::NegativeMedium => -4.0 / 18.0,
            Space::NegativeThick => -5.0 / 18.0,
        }
    }
}

/// Fraction, with or without a rule, drawn stacked or inline.
#[derive(Clone, Debug, PartialEq)]
pub struct Frac {
    pub num: Node,
    pub den: Node,
    pub kind: FracKind,
    /// Sets the slots one size preset below the material around them.
    pub small: bool,
}

impl Frac {
    pub fn new(num: Node, den: Node) -> Self {
        Self {
            num,
            den,
            kind: FracKind::Bar,
            small: false,
        }
    }
}

/// How a fraction is drawn.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FracKind {
    /// Stacked with a horizontal rule.
    #[default]
    Bar,
    /// Stacked with a slash instead of a rule.
    Slash,
    /// Stacked without a rule, e.g. binomial coefficients.
    NoBar,
    /// Written inline as `a/b`.
    Linear,
}

/// Radical, with an optional index for higher roots.
#[derive(Clone, Debug, PartialEq)]
pub struct Sqrt {
    /// Root index; `None` is a square root.
    pub index: Option<Node>,
    pub radicand: Node,
}

impl Sqrt {
    pub fn square(radicand: Node) -> Self {
        Self {
            index: None,
            radicand,
        }
    }

    pub fn nth(index: Node, radicand: Node) -> Self {
        Self {
            index: Some(index),
            radicand,
        }
    }
}

/// Subscript and superscript attached to a base.
#[derive(Clone, Debug, PartialEq)]
pub struct Scripts {
    pub base: Node,
    pub sub: Option<Node>,
    pub sup: Option<Node>,
    /// Draws the scripts to the left of the base instead of to its right.
    ///
    /// The slots keep the order base, subscript, superscript on both sides, so editing code
    /// addresses a pre-script the way it addresses a post-script.
    pub precedes: bool,
}

impl Scripts {
    /// Attach `sub`/`sup` to `base` on the right.
    ///
    /// Merging into an existing [`Node::Scripts`] node is up to the caller, which knows whether
    /// the new scripts belong inside or outside the existing ones.
    pub fn attach(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
        Self {
            base,
            sub,
            sup,
            precedes: false,
        }
    }

    /// Attach `sub`/`sup` to the left of `base`.
    pub fn attach_preceding(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
        Self {
            base,
            sub,
            sup,
            precedes: true,
        }
    }
}

/// Over/under material that is not an accent.
#[derive(Clone, Debug, PartialEq)]
pub struct Limits {
    pub base: Node,
    pub under: Option<Node>,
    pub over: Option<Node>,
    pub align: Side,
}

/// Horizontal alignment of over/under material and table columns.
///
/// The five values are the horizontal alignment values of the equation format. Over/under
/// material and single columns use the first three; relation and decimal alignment apply to a
/// whole table, where lines are split at their first relation or at the decimal point.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Side {
    #[default]
    Center,
    Left,
    Right,
    /// Aligns lines at their first relational operator.
    AtRelation,
    /// Aligns lines at the decimal point of their first number.
    AtDecimal,
}

/// Vertical alignment of a table with its line, or of a cell within its row.
///
/// The five values are the vertical alignment values of the equation format. The interface only
/// offers the first three; the other two are kept from a stream and written back unchanged.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum VerticalAlign {
    /// Top line's baseline.
    Top,
    /// Middle line's baseline.
    #[default]
    Center,
    /// Bottom line's baseline.
    Bottom,
    /// The material centred as a whole.
    Centered,
    /// Centred on the math axis.
    Axis,
}

/// Style of a partition line between or around the cells of a table.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LineStyle {
    /// No line is drawn.
    #[default]
    None,
    Solid,
    Dashed,
    Dotted,
}

/// Delimiter shape.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Delim {
    Paren,
    Bracket,
    Brace,
    Abs,
    Norm,
    Angle,
    Floor,
    Ceil,
    /// No delimiter drawn.
    None,
    /// A specific character, drawn from a font that provides it.
    Custom(char),
    /// An arrow delimiter.
    Arrow,
    /// A double bar delimiter.
    DoubleBar,
}

impl Delim {
    /// The opening character, or `None` when nothing is drawn.
    pub fn open(self) -> Option<char> {
        Some(match self {
            Delim::Paren => '(',
            Delim::Bracket => '[',
            Delim::Brace => '{',
            Delim::Abs => '|',
            Delim::Norm => '\u{2016}',
            Delim::Angle => '\u{27E8}',
            Delim::Floor => '\u{230A}',
            Delim::Ceil => '\u{2308}',
            Delim::None => return None,
            Delim::Custom(ch) => ch,
            Delim::Arrow => '\u{27E8}',
            Delim::DoubleBar => '\u{2016}',
        })
    }

    /// The closing character, or `None` when nothing is drawn.
    pub fn close(self) -> Option<char> {
        Some(match self {
            Delim::Paren => ')',
            Delim::Bracket => ']',
            Delim::Brace => '}',
            Delim::Abs => '|',
            Delim::Norm => '\u{2016}',
            Delim::Angle => '\u{27E9}',
            Delim::Floor => '\u{230B}',
            Delim::Ceil => '\u{2309}',
            Delim::None => return None,
            Delim::Custom(ch) => ch,
            Delim::Arrow => '\u{27E9}',
            Delim::DoubleBar => '\u{2016}',
        })
    }
}

/// How a fence's delimiters sit vertically against the line that holds them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FenceAlign {
    /// The fence is centred on the line's math axis, the contents' math axis on the same axis,
    /// and the fence grows symmetrically until it covers the contents.
    #[default]
    Axis,
    /// The fence is centred on the contents, whose math axis stays on the line's math axis.
    Contents,
    /// The fence is centred on the contents, and the two are centred on the line's math axis.
    Centered,
}

/// Delimiters around a body.
#[derive(Clone, Debug, PartialEq)]
pub struct Fence {
    pub open: Delim,
    pub close: Delim,
    pub body: Node,
    /// How the delimiters sit vertically against the surrounding line.
    pub align: FenceAlign,
}

/// Table of cells with optional delimiters.
#[derive(Clone, Debug, PartialEq)]
pub struct Matrix {
    pub rows: Vec<Row>,
    pub delims: Option<(Delim, Delim)>,
    pub kind: MatrixKind,
    /// Baseline-to-baseline distance from each row to the one below it, in points. `None` uses
    /// the style's line or matrix-row spacing. The vector has one entry per row.
    pub line_spacings: Vec<Option<f64>>,
    /// Alignment applied to every column; per-column rules come from [`Matrix::columns`].
    pub align: Side,
    /// Optional per-column alignment overriding [`Matrix::align`].
    pub columns: Vec<Side>,
    /// How the table sits on the line that contains it.
    pub stack_align: VerticalAlign,
    /// How a cell's material sits within its row: top, baseline or bottom.
    pub cell_align: VerticalAlign,
    /// Style of the line above each row, from the top edge to the bottom edge; `row_count + 1`
    /// entries.
    pub row_lines: Vec<LineStyle>,
    /// Style of the line left of each column, from the left edge to the right edge;
    /// `col_count + 1` entries.
    pub col_lines: Vec<LineStyle>,
}

impl Matrix {
    /// A matrix of `rows` rows and `cols` columns, each cell an empty slot.
    pub fn empty(rows: usize, cols: usize) -> Self {
        Self {
            rows: vec![vec![Node::empty(); cols]; rows],
            delims: None,
            kind: MatrixKind::Matrix,
            line_spacings: vec![None; rows],
            align: Side::Center,
            columns: Vec::new(),
            stack_align: VerticalAlign::Center,
            cell_align: VerticalAlign::Center,
            row_lines: vec![LineStyle::None; rows + 1],
            col_lines: vec![LineStyle::None; cols + 1],
        }
    }

    /// Whether any partition line is drawn.
    pub fn has_lines(&self) -> bool {
        self.row_lines
            .iter()
            .chain(&self.col_lines)
            .any(|style| *style != LineStyle::None)
    }

    /// Number of rows.
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Number of columns, taken from the widest row.
    pub fn col_count(&self) -> usize {
        self.rows.iter().map(Row::len).max().unwrap_or(0)
    }

    /// Row and column of the cell addressed by a flat slot index, row-major.
    pub fn cell_position(&self, index: usize) -> Option<(usize, usize)> {
        let mut remaining = index;
        for (row, cells) in self.rows.iter().enumerate() {
            if remaining < cells.len() {
                return Some((row, remaining));
            }
            remaining -= cells.len();
        }
        None
    }

    /// Cell addressed by a flat slot index, row-major.
    pub fn cell_at(&self, index: usize) -> Option<&Node> {
        let (row, col) = self.cell_position(index)?;
        self.rows[row].get(col)
    }

    /// Mutable cell addressed by a flat slot index, row-major.
    pub fn cell_at_mut(&mut self, index: usize) -> Option<&mut Node> {
        let (row, col) = self.cell_position(index)?;
        self.rows[row].get_mut(col)
    }
}

/// Kind of table, which decides delimiter defaults and column alignment.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MatrixKind {
    #[default]
    Matrix,
    /// Piecewise definitions: left brace, left aligned columns.
    Cases,
    /// Aligned equations on the alignment points.
    Aligned,
    /// Plain array.
    Array,
    /// Vertically stacked material.
    Pile,
    /// Long division layout.
    LongDivision,
}

/// Accent drawn over or under a base.
#[derive(Clone, Debug, PartialEq)]
pub struct Accent {
    pub kind: AccentKind,
    pub base: Node,
    /// Draws the accent under the base instead of over it.
    pub under: bool,
}

/// Accent shapes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AccentKind {
    Hat,
    WideHat,
    Tilde,
    WideTilde,
    /// A single horizontal rule over the base, or under it when the accent says so.
    Bar,
    Vector,
    Dot,
    DoubleDot,
    TripleDot,
    QuadDot,
    Breve,
    Check,
    Acute,
    Grave,
    Circle,
    OverBrace,
    UnderBrace,
    OverBracket,
    UnderBracket,
    OverParen,
    UnderParen,
    ArrowRight,
    ArrowLeft,
    /// A rightward harpoon over the base.
    HarpoonRight,
    /// A leftward harpoon over the base.
    HarpoonLeft,
    /// A double-headed arrow over the base.
    DoubleArrow,
    /// A doubled horizontal rule, as MathType's doubled bar template draws it. Only a doubled
    /// overline character in markup, or that template in MTEF, produces it.
    Line,
    /// A horizontal rule through the middle of the base.
    Strike,
    /// A slash from the lower left to the upper right.
    StrikeUp,
    /// A slash from the upper left to the lower right.
    StrikeDown,
    /// Both slashes, as an X through the base.
    CrossStrike,
    /// A half circle over the base.
    Arc,
    /// MathType's joint status construct: a rule with a short tick at its left end.
    JointStatus,
}

impl AccentKind {
    /// The character used when the accent is drawn from a font rather than as a rule or path.
    pub fn glyph(self) -> Option<char> {
        Some(match self {
            AccentKind::Hat => '\u{02C6}',
            AccentKind::WideHat => '\u{0302}',
            AccentKind::Tilde => '~',
            AccentKind::WideTilde => '\u{0303}',
            AccentKind::Dot => '\u{02D9}',
            AccentKind::DoubleDot => '\u{00A8}',
            AccentKind::TripleDot => '\u{20DB}',
            AccentKind::QuadDot => '\u{20DC}',
            AccentKind::Breve => '\u{02D8}',
            AccentKind::Check => '\u{02C7}',
            AccentKind::Acute => '\u{00B4}',
            AccentKind::Grave => '`',
            AccentKind::Circle => '\u{02DA}',
            AccentKind::ArrowRight => '\u{2192}',
            AccentKind::ArrowLeft => '\u{2190}',
            AccentKind::HarpoonRight => '\u{21C0}',
            AccentKind::HarpoonLeft => '\u{21BC}',
            AccentKind::DoubleArrow => '\u{2194}',
            AccentKind::Arc => '\u{0311}',
            AccentKind::Bar
            | AccentKind::Vector
            | AccentKind::Line
            | AccentKind::Strike
            | AccentKind::StrikeUp
            | AccentKind::StrikeDown
            | AccentKind::CrossStrike
            | AccentKind::JointStatus => return None,
            AccentKind::OverBrace => '\u{23DE}',
            AccentKind::UnderBrace => '\u{23DF}',
            AccentKind::OverBracket => '\u{23B4}',
            AccentKind::UnderBracket => '\u{23B5}',
            AccentKind::OverParen => '\u{23DC}',
            AccentKind::UnderParen => '\u{23DD}',
        })
    }
}

/// An arrow carrying text above, below or on both sides.
///
/// The arrow is the construct itself, so its text slots are the only slots. The shapes MathType
/// draws as a pair of arrows of different sizes, the large-over-small and small-over-large
/// arrows and harpoons, keep their two strokes in the layout rather than in the tree.
#[derive(Clone, Debug, PartialEq)]
pub struct LabeledArrow {
    pub arrow: ArrowKind,
    /// Text above the arrow.
    pub over: Option<Node>,
    /// Text below the arrow.
    pub under: Option<Node>,
}

impl LabeledArrow {
    /// Slots in visual order: the upper text, then the lower text.
    pub fn slot_count(&self) -> usize {
        usize::from(self.over.is_some()) + usize::from(self.under.is_some())
    }

    pub fn slot(&self, index: usize) -> Option<&Node> {
        match (index, &self.over) {
            (0, Some(over)) => Some(over),
            (0, None) => self.under.as_ref(),
            (1, Some(_)) => self.under.as_ref(),
            _ => None,
        }
    }

    pub fn slot_mut(&mut self, index: usize) -> Option<&mut Node> {
        match (index, &mut self.over) {
            (0, Some(over)) => Some(over),
            (0, None) => self.under.as_mut(),
            (1, Some(_)) => self.under.as_mut(),
            _ => None,
        }
    }
}

/// The arrow shape of a [`LabeledArrow`].
///
/// The names follow MathType's labeled arrow palette (manual 6.9, 8.5.8.8). The size pairs are
/// the shapes drawn as one arrow over a smaller one, which no single character spells.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ArrowKind {
    /// A rightward arrow.
    Right,
    /// A leftward arrow.
    Left,
    /// An arrow with heads at both ends.
    DoubleHeaded,
    /// A rightward arrow over a leftward one.
    Double,
    /// A large rightward arrow over a small leftward one.
    LargeOverSmall,
    /// A small rightward arrow over a large leftward one.
    SmallOverLarge,
    /// A rightward harpoon over a leftward one.
    Harpoons,
    /// A large rightward harpoon over a small leftward one.
    LargeOverSmallHarpoons,
    /// A small rightward harpoon over a large leftward one.
    SmallOverLargeHarpoons,
}

impl ArrowKind {
    /// The one character that draws the shape, when a face spells it as one character.
    pub fn glyph(self) -> Option<char> {
        Some(match self {
            ArrowKind::Right => '\u{2192}',
            ArrowKind::Left => '\u{2190}',
            ArrowKind::DoubleHeaded => '\u{2194}',
            ArrowKind::Double => '\u{21C4}',
            ArrowKind::LargeOverSmall | ArrowKind::SmallOverLarge => '\u{21C4}',
            ArrowKind::Harpoons => '\u{21CC}',
            ArrowKind::LargeOverSmallHarpoons | ArrowKind::SmallOverLargeHarpoons => '\u{21CC}',
        })
    }
}

/// Large operator with optional limits.
#[derive(Clone, Debug, PartialEq)]
pub struct BigOp {
    pub base: Node,
    pub sub: Option<Node>,
    pub sup: Option<Node>,
    /// Draws the limits above and below instead of beside the operator.
    pub limits: bool,
}

/// A positional offset applied to a subtree, in 32nds of a point.
///
/// MathType records nudging on the record the selected item was written as. The vertical
/// component points up, the direction of the equation's own coordinate system.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Nudge {
    pub dx: i32,
    pub dy: i32,
}

impl Nudge {
    /// Whether the offset leaves the item where it sits.
    pub fn is_zero(&self) -> bool {
        self.dx == 0 && self.dy == 0
    }
}

/// Style, font, class, size or position override applied to a subtree.
#[derive(Clone, Debug, PartialEq)]
pub struct Styled {
    pub body: Node,
    pub style: Option<MathStyle>,
    pub font: Option<Font>,
    pub class: Option<Class>,
    /// Size adjustment on top of, or instead of, the size class.
    pub size: Option<Size>,
    /// Offset applied to the laid-out subtree.
    pub nudge: Option<Nudge>,
}

/// A size recorded on a subtree, in 32nds of a point, MathType's own resolution.
///
/// A delta is measured from the size the class resolves to, which is how Smaller and Larger
/// work: the offset follows the class when the preset changes. A delta needs the class it is
/// measured from, so a node carrying one records [`Styled::style`] too.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Size {
    /// Offset from the class's size. Negative values shrink.
    Delta(i32),
    /// An explicit size, which replaces the class, as Other Size assigns.
    Points(i32),
}

impl Size {
    /// A delta of `points` points.
    pub fn delta(points: f64) -> Self {
        Size::Delta(thirty_seconds(points))
    }

    /// An explicit size of `points` points.
    pub fn points(points: f64) -> Self {
        Size::Points(thirty_seconds(points))
    }
}

/// `points` in 32nds of a point.
fn thirty_seconds(points: f64) -> i32 {
    (points * 32.0).round() as i32
}

/// Position in the tree: the sequence of slot indices from the root.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Path(Vec<usize>);

impl Path {
    /// The path naming the root.
    pub fn root() -> Self {
        Self(Vec::new())
    }

    /// Path with `index` appended.
    pub fn child(&self, index: usize) -> Self {
        let mut path = self.clone();
        path.0.push(index);
        path
    }

    /// Path with the last index removed, or `None` at the root.
    pub fn parent(&self) -> Option<Self> {
        let mut path = self.clone();
        path.0.pop().map(|_| path)
    }

    /// Last index, i.e. the slot of the parent that holds this node.
    pub fn last(&self) -> Option<usize> {
        self.0.last().copied()
    }

    /// Split into the parent path and the final index.
    pub fn split_last(&self) -> Option<(Self, usize)> {
        let (index, rest) = self.0.split_last()?;
        Some((Self(rest.to_vec()), *index))
    }

    pub fn push(&mut self, index: usize) {
        self.0.push(index);
    }

    pub fn pop(&mut self) -> Option<usize> {
        self.0.pop()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn as_slice(&self) -> &[usize] {
        &self.0
    }
}

impl FromIterator<usize> for Path {
    fn from_iter<T: IntoIterator<Item = usize>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

impl std::fmt::Display for Path {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.0.is_empty() {
            return f.write_str(".");
        }
        for (position, index) in self.0.iter().enumerate() {
            if position > 0 {
                f.write_str(".")?;
            }
            write!(f, "{index}")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn scripts(base: Node, sub: Node, sup: Node) -> Node {
        Node::Scripts(Box::new(Scripts {
            base,
            sub: Some(sub),
            sup: Some(sup),
            precedes: false,
        }))
    }

    #[test]
    fn a_new_equation_is_a_display_equation() {
        assert!(!Math::new(Node::variable('x')).inline);
    }

    #[test]
    fn fraction_slots_are_numerator_then_denominator() {
        let frac = Node::Frac(Box::new(Frac::new(
            Node::variable('a'),
            Node::variable('b'),
        )));
        assert_eq!(frac.slot_count(), 2);
        assert_eq!(frac.slot(0), Some(&Node::variable('a')));
        assert_eq!(frac.slot(1), Some(&Node::variable('b')));
        assert_eq!(frac.slot(2), None);
    }

    #[test]
    fn square_root_has_a_single_slot() {
        let root = Node::Sqrt(Box::new(Sqrt::square(Node::variable('x'))));
        assert_eq!(root.slot_count(), 1);
        assert_eq!(root.slot(0), Some(&Node::variable('x')));

        let nth = Node::Sqrt(Box::new(Sqrt::nth(
            Node::variable('n'),
            Node::variable('x'),
        )));
        assert_eq!(nth.slot_count(), 2);
        assert_eq!(nth.slot(0), Some(&Node::variable('n')));
        assert_eq!(nth.slot(1), Some(&Node::variable('x')));
    }

    #[test]
    fn path_navigation_reaches_nested_slots() {
        let math = Math::new(Node::row([
            Node::variable('x'),
            scripts(
                Node::variable('a'),
                Node::variable('i'),
                Node::variable('2'),
            ),
        ]));
        let sup = Path::root().child(1).child(2);
        assert_eq!(math.node_at(&sup), Some(&Node::variable('2')));
        assert_eq!(sup.to_string(), "1.2");
        assert_eq!(
            sup.parent().map(|path| path.to_string()),
            Some("1".to_owned())
        );
        assert_eq!(math.node_at(&Path::root()), Some(&math.body));
    }

    #[test]
    fn replace_and_insert_operate_on_nested_slots() {
        let mut math = Math::new(Node::row([
            Node::variable('a'),
            Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
        ]));
        let radicand = Path::root().child(1).child(0);
        let replaced = math
            .node_at_mut(&radicand)
            .map(|node| std::mem::replace(node, Node::variable('y')));
        assert_eq!(replaced, Some(Node::variable('x')));
        assert_eq!(math.node_at(&radicand), Some(&Node::variable('y')));

        let row = Path::root();
        assert!(math.body.insert_at(&row, Node::variable('z')));
        assert_eq!(math.body.slot_count(), 3);
        assert_eq!(
            math.node_at(&Path::root().child(2)),
            Some(&Node::variable('z'))
        );
        assert_eq!(
            math.body.remove_at(&Path::root().child(2)),
            Some(Node::variable('z'))
        );
        assert_eq!(math.body.slot_count(), 2);
    }

    #[test]
    fn matrix_cells_are_addressed_row_major() {
        let mut matrix = Matrix::empty(2, 3);
        if let Some(cell) = matrix.cell_at_mut(4) {
            *cell = Node::variable('q');
        }
        let node = Node::Matrix(Box::new(matrix));
        assert_eq!(node.slot_count(), 6);
        assert_eq!(node.slot(4), Some(&Node::variable('q')));
        assert_eq!(node.slot(1), Some(&Node::empty()));
    }

    #[test]
    fn walk_visits_every_reachable_node() {
        let math = Math::new(Node::row([
            scripts(Node::variable('a'), Node::variable('i'), Node::empty()),
            Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
        ]));
        let mut names = Vec::new();
        math.body.walk(&mut |node| {
            if let Node::Char(Char { ch, .. }) = node {
                names.push(*ch);
            }
        });
        assert_eq!(names, vec!['a', 'i', 'x']);
    }

    #[test]
    fn normalisation_flattens_nested_rows_only() {
        let mut node = Node::row([
            Node::variable('a'),
            Node::row([Node::variable('b'), Node::variable('c')]),
        ]);
        node.normalize();
        assert_eq!(
            node,
            Node::row([
                Node::variable('a'),
                Node::variable('b'),
                Node::variable('c')
            ])
        );

        let mut node = Node::row([Node::row([Node::variable('a')])]);
        node.normalize();
        assert_eq!(node, Node::row([Node::variable('a')]));

        let mut fraction = Node::Frac(Box::new(Frac::new(
            Node::row([Node::row([Node::variable('1')])]),
            Node::variable('2'),
        )));
        fraction.normalize();
        assert_eq!(fraction.slot(0), Some(&Node::row([Node::variable('1')])));
    }

    #[test]
    fn space_widths_follow_the_em_grid() {
        assert_eq!(Space::Thin.em(12.0), 3.0 / 18.0);
        assert_eq!(Space::Quad.em(12.0), 1.0);
        assert_eq!(Space::NegativeThick.em(12.0), -5.0 / 18.0);
    }

    #[test]
    fn the_zero_width_space_takes_no_room_at_any_size() {
        assert_eq!(Space::ZeroWidth.em(12.0), 0.0);
        assert_eq!(Space::ZeroWidth.em(24.0), 0.0);
    }

    #[test]
    fn the_point_space_is_one_point_whatever_the_size() {
        // An em is the size itself, so one point is 1/size of an em.
        assert_eq!(Space::OnePoint.em(12.0), 1.0 / 12.0);
        assert_eq!(Space::OnePoint.em(24.0), 1.0 / 24.0);
    }

    #[test]
    fn delimiters_expose_matching_pairs() {
        assert_eq!(Delim::Paren.open(), Some('('));
        assert_eq!(Delim::Paren.close(), Some(')'));
        assert_eq!(Delim::None.open(), None);
        assert_eq!(Delim::Brace.close(), Some('}'));
    }

    #[test]
    fn style_nesting_saturates() {
        assert_eq!(MathStyle::Full.smaller(), MathStyle::Script);
        assert_eq!(MathStyle::Script.smaller(), MathStyle::ScriptScript);
        assert_eq!(MathStyle::ScriptScript.smaller(), MathStyle::ScriptScript);
    }

    #[test]
    fn the_euclid_faces_answer_for_their_own_weight_and_slant() {
        assert!(!Font::Euclid.is_bold() && !Font::Euclid.is_italic());
        assert!(Font::EuclidItalic.is_italic() && !Font::EuclidItalic.is_bold());
        assert!(Font::EuclidBold.is_bold() && !Font::EuclidBold.is_italic());
        assert!(Font::EuclidBoldItalic.is_bold() && Font::EuclidBoldItalic.is_italic());
        assert!(Font::EuclidSymbolItalic.is_italic() && !Font::EuclidSymbolItalic.is_bold());
        assert!(Font::EuclidSymbolBoldItalic.is_bold() && Font::EuclidSymbolBoldItalic.is_italic());
        assert!(Font::EuclidExtraBold.is_bold() && !Font::EuclidExtraBold.is_italic());
        assert!(!Font::EuclidExtra.is_bold() && !Font::EuclidExtra.is_italic());
        assert!(!Font::Fences.is_bold() && !Font::Fences.is_italic());
    }
}