mathtex-editor-core 0.1.0

Headless core of the mathtex structural math editor: model, operations, navigation, selection, IR matching
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
//! Edit operations preserve slotmap integrity and keep semantic edits built from primitive tree changes.

use std::ops::Range;

use crate::command::Side;
use crate::model::{
    Cursor, Deco, FracStyle, Kind, Mark, MatrixEnv, Node, NodeId, ScriptSlot, Selection, Seq,
    SeqId, Symbol, Tree, UnderOverSpec, Variant,
};
use crate::nav;

/// Describes a node to create before `insert_new` allocates slot seqs and parent links.
pub(crate) enum NewNode {
    Atom(Symbol),
    Frac(FracStyle),
    Script(ScriptSlot),
    BigOp(Symbol),
    Sqrt,
    Delim { open: char, close: char },
    Accent(Mark),
    UnderOver(UnderOverSpec),
    Styled(Variant),
    Matrix { env: MatrixEnv, rows: usize, cols: usize },
}

impl Tree {
    pub(crate) fn alloc_seq(&mut self, parent: Option<NodeId>) -> SeqId {
        self.seqs.insert(Seq {
            parent,
            items: Vec::new(),
        })
    }

    /// Builds a node kind with empty slot seqs whose parent is set by [`Tree::insert_new`].
    fn build_kind(&mut self, spec: NewNode) -> Kind {
        match spec {
            NewNode::Atom(sym) => Kind::Atom(sym),
            NewNode::Frac(style) => Kind::Frac {
                num: self.alloc_seq(None),
                den: self.alloc_seq(None),
                style,
            },
            NewNode::Script(slot) => {
                let base = self.alloc_seq(None);
                let (sub, sup) = match slot {
                    ScriptSlot::Sub => (Some(self.alloc_seq(None)), None),
                    ScriptSlot::Sup => (None, Some(self.alloc_seq(None))),
                };
                Kind::Script { base, sub, sup }
            }
            NewNode::BigOp(op) => Kind::BigOp {
                op,
                lower: self.alloc_seq(None),
                upper: self.alloc_seq(None),
            },
            NewNode::Sqrt => Kind::Sqrt {
                // Both slots always exist, an empty degree is just a placeholder.
                index: self.alloc_seq(None),
                radicand: self.alloc_seq(None),
            },
            NewNode::Delim { open, close } => Kind::Delim {
                open,
                close,
                body: self.alloc_seq(None),
            },
            NewNode::Accent(mark) => Kind::Accent {
                mark,
                base: self.alloc_seq(None),
            },
            NewNode::UnderOver(spec) => Kind::UnderOver {
                base: self.alloc_seq(None),
                over: spec.over.then(|| self.alloc_seq(None)),
                under: spec.under.then(|| self.alloc_seq(None)),
                over_deco: spec.over_deco,
                under_deco: spec.under_deco,
            },
            NewNode::Styled(variant) => Kind::Styled {
                variant,
                content: self.alloc_seq(None),
            },
            NewNode::Matrix { env, rows, cols } => {
                let grid = (0..rows)
                    .map(|_| (0..cols).map(|_| self.alloc_seq(None)).collect())
                    .collect();
                Kind::Matrix { env, rows: grid }
            }
        }
    }

    /// Creates a node with empty slot seqs, splices it into `seq`, and wires parent links.
    pub(crate) fn insert_new(&mut self, seq: SeqId, index: usize, spec: NewNode) -> NodeId {
        let kind = self.build_kind(spec);
        let node_id = self.nodes.insert(Node { parent: seq, kind });
        for s in self.child_seqs(node_id) {
            if let Some(sq) = self.seqs.get_mut(s) {
                sq.parent = Some(node_id);
            }
        }
        if let Some(sq) = self.seqs.get_mut(seq) {
            let i = index.min(sq.items.len());
            sq.items.insert(i, node_id);
        }
        node_id
    }

    /// Unlinks a node from its parent seq while keeping its subtree alive.
    pub(crate) fn detach(&mut self, node: NodeId) -> NodeId {
        if let Some((parent, idx)) = self.index_in_parent(node) {
            if let Some(sq) = self.seqs.get_mut(parent) {
                sq.items.remove(idx);
            }
        }
        node
    }

    /// Recursively free a node, its slot seqs, and their contents.
    pub(crate) fn drop_node(&mut self, node: NodeId) {
        self.detach(node);
        self.free_node(node);
    }

    fn free_node(&mut self, node: NodeId) {
        for s in self.child_seqs(node) {
            self.free_seq(s);
        }
        self.nodes.remove(node);
    }

    fn free_seq(&mut self, seq: SeqId) {
        let items: Vec<NodeId> = self
            .seqs
            .get(seq)
            .map(|s| s.items.clone())
            .unwrap_or_default();
        for n in items {
            self.free_node(n);
        }
        self.seqs.remove(seq);
    }

    /// Moves nodes from `src[range]` into `dst` at `at`, the caller ensures the seqs differ.
    pub(crate) fn move_range(&mut self, src: SeqId, range: Range<usize>, dst: SeqId, at: usize) {
        let moved: Vec<NodeId> = self
            .seqs
            .get_mut(src)
            .map(|s| s.items.drain(range).collect())
            .unwrap_or_default();
        for &n in &moved {
            if let Some(nd) = self.nodes.get_mut(n) {
                nd.parent = dst;
            }
        }
        if let Some(d) = self.seqs.get_mut(dst) {
            let at = at.min(d.items.len());
            d.items.splice(at..at, moved);
        }
    }
}

impl Tree {
    /// Evicts a nonempty Script base so the next insertion replaces it.
    fn make_room_in_script_base(&mut self, at: Cursor) -> Cursor {
        if !self.is_empty(at.seq) {
            if let Some(script) = self.script_base_node(at.seq) {
                if let Some((pseq, pidx)) = self.index_in_parent(script) {
                    let n = self.len(at.seq);
                    self.move_range(at.seq, 0..n, pseq, pidx);
                    return Cursor {
                        seq: at.seq,
                        index: 0,
                    };
                }
            }
        }
        at
    }

    /// Inserts an atom and returns the cursor after it.
    pub fn insert_atom(&mut self, at: Cursor, sym: Symbol) -> Cursor {
        let at = self.make_room_in_script_base(at);
        self.insert_new(at.seq, at.index, NewNode::Atom(sym));
        Cursor {
            seq: at.seq,
            index: at.index + 1,
        }
    }

    /// Inserts a structure and optionally wraps `sel` into the chosen slot.
    fn insert_struct(
        &mut self,
        at: Cursor,
        sel: Option<Selection>,
        spec: NewNode,
        wrap_slot: usize,
    ) -> (NodeId, bool) {
        match sel {
            None => {
                let at = self.make_room_in_script_base(at);
                (self.insert_new(at.seq, at.index, spec), false)
            }
            Some(s) => {
                let lo = s.anchor.min(s.focus);
                let hi = s.anchor.max(s.focus);
                let node = self.insert_new(s.seq, lo, spec);
                let slot = self.child_seqs(node)[wrap_slot];
                self.move_range(s.seq, lo + 1..hi + 1, slot, 0);
                (node, true)
            }
        }
    }

    /// Inserts a fraction and returns a cursor in the numerator or denominator.
    pub fn insert_fraction(&mut self, at: Cursor, style: FracStyle, sel: Option<Selection>) -> Cursor {
        let (node, wrapped) = self.insert_struct(at, sel, NewNode::Frac(style), 0);
        let slots = self.child_seqs(node);
        let (num, den) = (slots[0], slots[1]);
        if wrapped {
            Cursor { seq: den, index: 0 }
        } else {
            Cursor { seq: num, index: 0 }
        }
    }

    /// Inserts a radical and returns a cursor in the radicand.
    pub fn insert_sqrt(&mut self, at: Cursor, sel: Option<Selection>) -> Cursor {
        // child_seqs is [index, radicand], wrapped content goes into the radicand.
        let (node, _wrapped) = self.insert_struct(at, sel, NewNode::Sqrt, 1);
        let radicand = self.child_seqs(node)[1];
        Cursor {
            seq: radicand,
            index: 0,
        }
    }

    /// Inserts delimiters and returns a cursor in their body.
    pub fn insert_delimiters(
        &mut self,
        at: Cursor,
        open: char,
        close: char,
        sel: Option<Selection>,
    ) -> Cursor {
        let (node, wrapped) = self.insert_struct(at, sel, NewNode::Delim { open, close }, 0);
        let body = self.child_seqs(node)[0];
        Cursor {
            seq: body,
            index: if wrapped { self.len(body) } else { 0 },
        }
    }

    /// Inserts an accent and returns a cursor in its base.
    pub fn insert_accent(&mut self, at: Cursor, mark: Mark, sel: Option<Selection>) -> Cursor {
        let (node, wrapped) = self.insert_struct(at, sel, NewNode::Accent(mark), 0);
        let base = self.child_seqs(node)[0];
        Cursor {
            seq: base,
            index: if wrapped { self.len(base) } else { 0 },
        }
    }

    /// Inserts a styled wrapper and returns a cursor in its content.
    pub fn insert_styled(&mut self, at: Cursor, variant: Variant, sel: Option<Selection>) -> Cursor {
        let (node, wrapped) = self.insert_struct(at, sel, NewNode::Styled(variant), 0);
        let content = self.child_seqs(node)[0];
        Cursor {
            seq: content,
            index: if wrapped { self.len(content) } else { 0 },
        }
    }

    /// Inserts an under or over structure and returns a cursor in its base.
    pub fn insert_under_over(&mut self, at: Cursor, spec: UnderOverSpec, sel: Option<Selection>) -> Cursor {
        // base is the first slot when there's no `over`, else index 1.
        let wrap_slot = if spec.over { 1 } else { 0 };
        let (node, _wrapped) = self.insert_struct(at, sel, NewNode::UnderOver(spec), wrap_slot);
        let base = self.child_seqs(node)[wrap_slot];
        Cursor { seq: base, index: 0 }
    }

    /// Inserts a matrix and returns a cursor in the first cell.
    pub fn insert_matrix(&mut self, at: Cursor, env: MatrixEnv, rows: usize, cols: usize) -> Cursor {
        let rows = rows.max(1);
        let cols = cols.max(1);
        let node = self.insert_new(at.seq, at.index, NewNode::Matrix { env, rows, cols });
        let first = self.child_seqs(node)[0];
        Cursor {
            seq: first,
            index: 0,
        }
    }

    /// Inserts a big operator with empty limits and returns a cursor after it.
    pub fn insert_big_op(&mut self, at: Cursor, op: Symbol) -> Cursor {
        self.insert_new(at.seq, at.index, NewNode::BigOp(op));
        Cursor {
            seq: at.seq,
            index: at.index + 1,
        }
    }

    /// Returns the `BigOp` limit targeted by `_` or `^` when the cursor is after the operator.
    pub fn bigop_limit_target(&self, at: Cursor, which: ScriptSlot) -> Option<Cursor> {
        if at.index == 0 {
            return None;
        }
        let prev = self.items(at.seq)[at.index - 1];
        if let Some(Kind::BigOp { lower, upper, .. }) = self.kind(prev) {
            let target = match which {
                ScriptSlot::Sub => *lower,
                ScriptSlot::Sup => *upper,
            };
            return Some(Cursor {
                seq: target,
                index: self.len(target),
            });
        }
        None
    }

    /// Attaches or moves into a subscript or superscript on the node before the cursor.
    pub fn attach_script(&mut self, at: Cursor, which: ScriptSlot) -> Cursor {
        if at.index > 0 {
            let prev = self.items(at.seq)[at.index - 1];
            if matches!(self.kind(prev), Some(Kind::Script { .. })) {
                let slot = self.script_slot(prev, which);
                return Cursor {
                    seq: slot,
                    index: self.len(slot),
                };
            }
            // Wrap the preceding node as the base of a new Script.
            let script = self.insert_new(at.seq, at.index, NewNode::Script(which));
            let base = match self.kind(script) {
                Some(Kind::Script { base, .. }) => *base,
                _ => unreachable!(),
            };
            self.move_range(at.seq, at.index - 1..at.index, base, 0);
            let slot = self.script_slot(script, which);
            return Cursor { seq: slot, index: 0 };
        }
        // No base to the left means an empty base Script with the cursor in the script slot.
        let script = self.insert_new(at.seq, at.index, NewNode::Script(which));
        let slot = self.script_slot(script, which);
        Cursor { seq: slot, index: 0 }
    }

    /// Returns the existing or newly created subscript or superscript seq of a Script node.
    fn script_slot(&mut self, node: NodeId, which: ScriptSlot) -> SeqId {
        let existing = match self.kind(node) {
            Some(Kind::Script { sub, sup, .. }) => match which {
                ScriptSlot::Sub => *sub,
                ScriptSlot::Sup => *sup,
            },
            _ => None,
        };
        if let Some(s) = existing {
            return s;
        }
        let s = self.alloc_seq(Some(node));
        if let Some(Node {
            kind: Kind::Script { sub, sup, .. },
            ..
        }) = self.nodes.get_mut(node)
        {
            match which {
                ScriptSlot::Sub => *sub = Some(s),
                ScriptSlot::Sup => *sup = Some(s),
            }
        }
        s
    }

    /// Deletes backward, escalating empty placeholders and otherwise moving left when no leaf is removed.
    pub fn delete_backward(&mut self, at: Cursor) -> Cursor {
        if at.index > 0 {
            let prev = self.items(at.seq)[at.index - 1];
            if self.child_seqs(prev).is_empty() {
                self.drop_node(prev);
                return Cursor {
                    seq: at.seq,
                    index: at.index - 1,
                };
            }
            return nav::move_left(self, at).unwrap_or(at);
        }
        if self.is_empty(at.seq) {
            if let Some(parent) = self.seq_parent(at.seq) {
                return self.escalate_delete(parent, at.seq, at);
            }
            return at;
        }
        nav::move_left(self, at).unwrap_or(at)
    }

    /// Deletes forward as the mirror of [`Tree::delete_backward`].
    pub fn delete_forward(&mut self, at: Cursor) -> Cursor {
        if at.index < self.len(at.seq) {
            let next = self.items(at.seq)[at.index];
            if self.child_seqs(next).is_empty() {
                self.drop_node(next);
                return Cursor {
                    seq: at.seq,
                    index: at.index,
                };
            }
            return nav::move_right(self, at).unwrap_or(at);
        }
        if self.is_empty(at.seq) {
            if let Some(parent) = self.seq_parent(at.seq) {
                return self.escalate_delete(parent, at.seq, at);
            }
            return at;
        }
        nav::move_right(self, at).unwrap_or(at)
    }

    /// Deletes a contiguous selection run within one seq.
    pub fn delete_selection(&mut self, sel: Selection) -> Cursor {
        let lo = sel.anchor.min(sel.focus);
        let hi = sel.anchor.max(sel.focus);
        let victims: Vec<NodeId> = self.items(sel.seq)[lo..hi.min(self.len(sel.seq))].to_vec();
        for n in victims {
            self.drop_node(n);
        }
        Cursor {
            seq: sel.seq,
            index: lo,
        }
    }

    /// Drops `parent` and leaves the cursor in the grandparent seq.
    fn drop_and_step_out(&mut self, parent: NodeId, at_parent: Cursor) -> Cursor {
        self.drop_node(parent);
        at_parent
    }

    /// Promotes `from` into `into`, drops `parent`, and returns a cursor after the promoted run.
    fn promote_and_drop(&mut self, parent: NodeId, from: SeqId, into: SeqId, at: usize) -> Cursor {
        let n = self.len(from);
        self.move_range(from, 0..n, into, at);
        self.drop_node(parent);
        Cursor { seq: into, index: at + n }
    }

    /// Handles deletion from an empty Script base by reattaching or dissolving the script.
    fn delete_empty_script_base(
        &mut self,
        parent: NodeId,
        base: SeqId,
        sub: Option<SeqId>,
        sup: Option<SeqId>,
        pseq: SeqId,
        pidx: usize,
        at_parent: Cursor,
    ) -> Cursor {
        if pidx > 0 {
            // The preceding sibling becomes the base.
            self.move_range(pseq, pidx - 1..pidx, base, 0);
            return Cursor { seq: base, index: self.len(base) };
        }
        let mut offset = 0;
        for s in [Some(base), sub, sup].into_iter().flatten() {
            let n = self.len(s);
            if n > 0 {
                self.move_range(s, 0..n, pseq, pidx + offset);
                offset += n;
            }
        }
        self.drop_and_step_out(parent, at_parent)
    }

    /// Promotes the base when no optional slots remain, or keeps the cursor at the base end.
    fn collapse_to_base_or_stay(
        &mut self,
        parent: NodeId,
        base: SeqId,
        opt_a: Option<SeqId>,
        opt_b: Option<SeqId>,
        pseq: SeqId,
        pidx: usize,
    ) -> Cursor {
        if opt_a.is_none() && opt_b.is_none() {
            self.promote_and_drop(parent, base, pseq, pidx)
        } else {
            Cursor { seq: base, index: self.len(base) }
        }
    }

    /// Handles structure deletion when the cursor is at the start of an empty slot.
    fn escalate_delete(&mut self, parent: NodeId, slot: SeqId, fallback: Cursor) -> Cursor {
        let Some((pseq, pidx)) = self.index_in_parent(parent) else {
            return fallback;
        };
        let Some(kind) = self.nodes.get(parent).map(|n| n.kind.clone()) else {
            return fallback;
        };
        let at_parent = Cursor {
            seq: pseq,
            index: pidx,
        };
        match kind {
            // Empty Frac slots drop the frac or promote the sibling content.
            Kind::Frac { num, den, .. } => {
                let other = if slot == num { den } else { num };
                if self.is_empty(other) {
                    self.drop_and_step_out(parent, at_parent)
                } else {
                    self.promote_and_drop(parent, other, pseq, pidx)
                }
            }

            // An empty radicand drops the radical, while the permanent empty degree steps out left.
            Kind::Sqrt { radicand, .. } => {
                if slot == radicand {
                    self.drop_and_step_out(parent, at_parent)
                } else {
                    at_parent
                }
            }

            // Empty single body wrappers are removed.
            Kind::Delim { .. } | Kind::Accent { .. } | Kind::Styled { .. } => {
                self.drop_and_step_out(parent, at_parent)
            }

            Kind::Script { base, sub, sup } => {
                if slot == base {
                    self.delete_empty_script_base(parent, base, sub, sup, pseq, pidx, at_parent)
                } else {
                    // Empty subscript or superscript slots are dropped before collapse checks.
                    if let Some(Node {
                        kind: Kind::Script { sub, sup, .. },
                        ..
                    }) = self.nodes.get_mut(parent)
                    {
                        if *sub == Some(slot) {
                            *sub = None;
                        } else if *sup == Some(slot) {
                            *sup = None;
                        }
                    }
                    self.free_seq(slot);
                    let (rsub, rsup) = match self.kind(parent) {
                        Some(Kind::Script { sub, sup, .. }) => (*sub, *sup),
                        _ => (None, None),
                    };
                    self.collapse_to_base_or_stay(parent, base, rsub, rsup, pseq, pidx)
                }
            }

            // Empty BigOp limits drop the operator or step into the nonempty other limit.
            Kind::BigOp { lower, upper, .. } => {
                let other = if slot == lower { upper } else { lower };
                if self.is_empty(other) {
                    self.drop_and_step_out(parent, at_parent)
                } else {
                    Cursor {
                        seq: other,
                        index: self.len(other),
                    }
                }
            }

            Kind::UnderOver {
                base, over, under, ..
            } => {
                if slot == base {
                    self.drop_and_step_out(parent, at_parent)
                } else {
                    // Empty over or under slots are dropped before collapse checks.
                    if let Some(Node {
                        kind: Kind::UnderOver { over, under, .. },
                        ..
                    }) = self.nodes.get_mut(parent)
                    {
                        if *over == Some(slot) {
                            *over = None;
                        } else if *under == Some(slot) {
                            *under = None;
                        }
                    }
                    self.free_seq(slot);
                    let (rover, runder) = match self.kind(parent) {
                        Some(Kind::UnderOver { over, under, .. }) => (*over, *under),
                        _ => (None, None),
                    };
                    self.collapse_to_base_or_stay(parent, base, rover, runder, pseq, pidx)
                }
            }

            // Empty matrix cells are valid, so the matrix is removed only when every cell is empty.
            Kind::Matrix { rows, .. } => {
                let all_empty = rows.iter().flatten().all(|&c| self.is_empty(c));
                if all_empty {
                    self.drop_and_step_out(parent, at_parent)
                } else {
                    nav::move_left(self, Cursor { seq: slot, index: 0 }).unwrap_or(fallback)
                }
            }

            Kind::Atom(_) => fallback,
        }
    }

    /// Returns the matrix node, row, and column for the cursor's cell when it is in a matrix.
    fn matrix_of(&self, at: Cursor) -> Option<(NodeId, usize, usize)> {
        let m = self.seq_parent(at.seq)?;
        if let Some(Kind::Matrix { rows, .. }) = self.kind(m) {
            for (r, row) in rows.iter().enumerate() {
                if let Some(c) = row.iter().position(|&s| s == at.seq) {
                    return Some((m, r, c));
                }
            }
        }
        None
    }

    fn matrix_cols(&self, m: NodeId) -> usize {
        match self.kind(m) {
            Some(Kind::Matrix { rows, .. }) => rows.first().map_or(0, |r| r.len()),
            _ => 0,
        }
    }

    /// Returns the shape of the matrix containing the cursor.
    pub fn matrix_shape_at(&self, at: Cursor) -> Option<(usize, usize)> {
        let (m, _, _) = self.matrix_of(at)?;
        let Some(Kind::Matrix { rows, .. }) = self.kind(m) else {
            return None;
        };
        Some((rows.len(), self.matrix_cols(m)))
    }

    /// Inserts a matrix row before or after the current row.
    pub fn matrix_insert_row(&mut self, at: Cursor, side: Side) -> Cursor {
        let Some((m, r, _c)) = self.matrix_of(at) else {
            return at;
        };
        let cols = self.matrix_cols(m);
        let new_row: Vec<SeqId> = (0..cols).map(|_| self.alloc_seq(Some(m))).collect();
        let first = new_row.first().copied();
        let idx = match side {
            Side::Before => r,
            Side::After => r + 1,
        };
        if let Some(Node {
            kind: Kind::Matrix { rows, .. },
            ..
        }) = self.nodes.get_mut(m)
        {
            let idx = idx.min(rows.len());
            rows.insert(idx, new_row);
        }
        first.map_or(at, |s| Cursor { seq: s, index: 0 })
    }

    /// Deletes the current matrix row when more than one row remains.
    pub fn matrix_delete_row(&mut self, at: Cursor) -> Cursor {
        let Some((m, r, _c)) = self.matrix_of(at) else {
            return at;
        };
        let row_cells: Vec<SeqId> = match self.kind(m) {
            Some(Kind::Matrix { rows, .. }) if rows.len() > 1 => rows[r].clone(),
            _ => return at,
        };
        if let Some(Node {
            kind: Kind::Matrix { rows, .. },
            ..
        }) = self.nodes.get_mut(m)
        {
            rows.remove(r);
        }
        for c in row_cells {
            self.free_seq(c);
        }
        let target = match self.kind(m) {
            Some(Kind::Matrix { rows, .. }) => rows.get(r.min(rows.len().saturating_sub(1))).and_then(|row| row.first().copied()),
            _ => None,
        };
        target.map_or(at, |s| Cursor { seq: s, index: 0 })
    }

    /// Inserts a matrix column before or after the current column.
    pub fn matrix_insert_col(&mut self, at: Cursor, side: Side) -> Cursor {
        let Some((m, _r, c)) = self.matrix_of(at) else {
            return at;
        };
        let nrows = match self.kind(m) {
            Some(Kind::Matrix { rows, .. }) => rows.len(),
            _ => 0,
        };
        let new_cells: Vec<SeqId> = (0..nrows).map(|_| self.alloc_seq(Some(m))).collect();
        let idx = match side {
            Side::Before => c,
            Side::After => c + 1,
        };
        let first = new_cells.first().copied();
        if let Some(Node {
            kind: Kind::Matrix { rows, .. },
            ..
        }) = self.nodes.get_mut(m)
        {
            for (row, cell) in rows.iter_mut().zip(new_cells) {
                let i = idx.min(row.len());
                row.insert(i, cell);
            }
        }
        first.map_or(at, |s| Cursor { seq: s, index: 0 })
    }

    /// Deletes the current matrix column when more than one column remains.
    pub fn matrix_delete_col(&mut self, at: Cursor) -> Cursor {
        let Some((m, _r, c)) = self.matrix_of(at) else {
            return at;
        };
        if self.matrix_cols(m) <= 1 {
            return at;
        }
        let mut removed = Vec::new();
        if let Some(Node {
            kind: Kind::Matrix { rows, .. },
            ..
        }) = self.nodes.get_mut(m)
        {
            for row in rows.iter_mut() {
                if c < row.len() {
                    removed.push(row.remove(c));
                }
            }
        }
        for cell in removed {
            self.free_seq(cell);
        }
        let target = match self.kind(m) {
            Some(Kind::Matrix { rows, .. }) => rows.first().and_then(|row| {
                row.get(c.min(row.len().saturating_sub(1))).copied()
            }),
            _ => None,
        };
        target.map_or(at, |s| Cursor { seq: s, index: 0 })
    }

    /// Returns swap menu alternatives for `node`, excluding its current value.
    pub fn swap_variants(&self, node: NodeId) -> Option<Vec<SwapVariant>> {
        match self.kind(node)? {
            Kind::Atom(_) | Kind::Frac { .. } | Kind::Script { .. } | Kind::Sqrt { .. } => None,
            Kind::Delim { open, close, .. } => {
                let (open, close) = (*open, *close);
                Some(
                    DELIM_PAIRS
                        .iter()
                        .filter(|&&(o, c, _)| o != open || c != close)
                        .map(|&(open, close, label)| SwapVariant::Delim { open, close, label })
                        .collect(),
                )
            }
            Kind::BigOp { op, .. } => {
                let current = op.latex.as_str();
                Some(
                    BIGOP_ALTS
                        .iter()
                        .filter(|&&(latex, _)| latex != current)
                        .map(|&(latex, label)| SwapVariant::BigOp { latex, label })
                        .collect(),
                )
            }
            Kind::Accent { mark, .. } => {
                let mark = *mark;
                Some(
                    ACCENT_ALTS
                        .iter()
                        .filter(|&&(m, _)| m != mark)
                        .map(|&(mark, label)| SwapVariant::Accent { mark, label })
                        .collect(),
                )
            }
            // Only decoration for slots that are present varies.
            Kind::UnderOver { over, under, over_deco, under_deco, .. } => {
                let mut alts = Vec::new();
                if over.is_some() {
                    alts.extend(
                        DECO_ALTS
                            .iter()
                            .filter(|&&(d, _)| d != *over_deco)
                            .map(|&(deco, label)| SwapVariant::UnderOverDeco {
                                over: deco,
                                under: *under_deco,
                                label,
                            }),
                    );
                }
                if under.is_some() {
                    alts.extend(
                        DECO_ALTS
                            .iter()
                            .filter(|&&(d, _)| d != *under_deco)
                            .map(|&(deco, label)| SwapVariant::UnderOverDeco {
                                over: *over_deco,
                                under: deco,
                                label,
                            }),
                    );
                }
                Some(alts)
            }
            // `\text{}` is a carve out where the caret enters instead of swapping.
            Kind::Styled { variant, .. } if *variant == Variant::Text => None,
            Kind::Styled { variant, .. } => {
                let current = *variant;
                Some(
                    STYLED_ALTS
                        .iter()
                        .filter(|&&(v, _)| v != current)
                        .map(|&(variant, label)| SwapVariant::Styled { variant, label })
                        .collect(),
                )
            }
            Kind::Matrix { env, .. } => {
                let current = *env;
                Some(
                    MATRIX_ENV_ALTS
                        .iter()
                        .filter(|&&(e, _)| e != current)
                        .map(|&(env, label)| SwapVariant::Matrix { env, label })
                        .collect(),
                )
            }
        }
    }

    /// Applies a chosen alternative by changing only the named tag fields.
    pub fn apply_swap(&mut self, node: NodeId, variant: &SwapVariant) {
        let Some(n) = self.nodes.get_mut(node) else {
            return;
        };
        match (&mut n.kind, variant) {
            (Kind::Delim { open, close, .. }, SwapVariant::Delim { open: o, close: c, .. }) => {
                *open = *o;
                *close = *c;
            }
            (Kind::BigOp { op, .. }, SwapVariant::BigOp { latex, .. }) => {
                op.latex = (*latex).to_string();
            }
            (Kind::Accent { mark, .. }, SwapVariant::Accent { mark: m, .. }) => {
                *mark = *m;
            }
            (
                Kind::UnderOver { over_deco, under_deco, .. },
                SwapVariant::UnderOverDeco { over, under, .. },
            ) => {
                *over_deco = *over;
                *under_deco = *under;
            }
            (Kind::Styled { variant: v, .. }, SwapVariant::Styled { variant: nv, .. }) => {
                *v = *nv;
            }
            (Kind::Matrix { env, .. }, SwapVariant::Matrix { env: e, .. }) => {
                *env = *e;
            }
            _ => {}
        }
    }
}

/// Describes one swap menu alternative for a swappable structure.
#[derive(Debug, Clone, PartialEq)]
pub enum SwapVariant {
    /// Delimiter pair replacement.
    Delim {
        /// Opening delimiter.
        open: char,
        /// Closing delimiter.
        close: char,
        /// Menu label.
        label: &'static str,
    },
    /// Big operator replacement.
    BigOp {
        /// TeX command for the operator.
        latex: &'static str,
        /// Menu label.
        label: &'static str,
    },
    /// Accent mark replacement.
    Accent {
        /// Accent mark.
        mark: Mark,
        /// Menu label.
        label: &'static str,
    },
    /// Under or over decoration replacement.
    UnderOverDeco {
        /// Over slot decoration.
        over: Deco,
        /// Under slot decoration.
        under: Deco,
        /// Menu label.
        label: &'static str,
    },
    /// Styled variant replacement.
    Styled {
        /// Math variant.
        variant: Variant,
        /// Menu label.
        label: &'static str,
    },
    /// Matrix environment replacement.
    Matrix {
        /// Matrix environment.
        env: MatrixEnv,
        /// Menu label.
        label: &'static str,
    },
}

impl SwapVariant {
    /// Returns the menu label for this swap alternative.
    pub fn label(&self) -> &'static str {
        match self {
            SwapVariant::Delim { label, .. }
            | SwapVariant::BigOp { label, .. }
            | SwapVariant::Accent { label, .. }
            | SwapVariant::UnderOverDeco { label, .. }
            | SwapVariant::Styled { label, .. }
            | SwapVariant::Matrix { label, .. } => label,
        }
    }
}

const DELIM_PAIRS: &[(char, char, &str)] = &[
    ('(', ')', "( ) parentheses"),
    ('[', ']', "[ ] brackets"),
    ('{', '}', "{ } braces"),
    ('|', '|', "| | bars"),
    ('\u{2308}', '\u{2309}', "⌈ ⌉ ceiling"),
    ('\u{230A}', '\u{230B}', "⌊ ⌋ floor"),
    ('\u{27E8}', '\u{27E9}', "⟨ ⟩ angle"),
];

const BIGOP_ALTS: &[(&str, &str)] = &[
    ("\\sum", "∑ sum"),
    ("\\prod", "∏ product"),
    ("\\coprod", "∐ coproduct"),
    ("\\int", "∫ integral"),
    ("\\iint", "∬ double integral"),
    ("\\iiint", "∭ triple integral"),
    ("\\oint", "∮ contour integral"),
    ("\\bigcup", "⋃ union"),
    ("\\bigcap", "⋂ intersection"),
    ("\\bigsqcup", "⊔ disjoint union"),
    ("\\biguplus", "⊎ uplus"),
    ("\\bigoplus", "⊕ oplus"),
    ("\\bigotimes", "⊗ otimes"),
    ("\\bigodot", "⊙ odot"),
    ("\\bigvee", "⋁ vee"),
    ("\\bigwedge", "⋀ wedge"),
];

const ACCENT_ALTS: &[(Mark, &str)] = &[
    (Mark::Hat, "hat"),
    (Mark::Vec, "vec"),
    (Mark::Bar, "bar"),
    (Mark::Tilde, "tilde"),
    (Mark::Dot, "dot"),
    (Mark::Ddot, "double dot"),
    (Mark::Widehat, "wide hat"),
    (Mark::Widetilde, "wide tilde"),
    (Mark::Overline, "overline"),
    (Mark::Underline, "underline"),
    (Mark::Check, "check"),
    (Mark::Breve, "breve"),
];

const DECO_ALTS: &[(Deco, &str)] = &[
    (Deco::None, "plain"),
    (Deco::Brace, "brace"),
    (Deco::Arrow, "arrow"),
    (Deco::Line, "line"),
];

const STYLED_ALTS: &[(Variant, &str)] = &[
    (Variant::Normal, "normal"),
    (Variant::Bold, "bold"),
    (Variant::Blackboard, "blackboard"),
    (Variant::Calligraphic, "calligraphic"),
    (Variant::Fraktur, "fraktur"),
    (Variant::Roman, "roman"),
    (Variant::SansSerif, "sans serif"),
    (Variant::Typewriter, "typewriter"),
    (Variant::OperatorName, "operator name"),
];

const MATRIX_ENV_ALTS: &[(MatrixEnv, &str)] = &[
    (MatrixEnv::Matrix, "matrix"),
    (MatrixEnv::Pmatrix, "( matrix )"),
    (MatrixEnv::Bmatrix, "[ matrix ]"),
    (MatrixEnv::Vmatrix, "| matrix |"),
    (MatrixEnv::Cases, "cases"),
    (MatrixEnv::Aligned, "aligned"),
    (MatrixEnv::Array, "array"),
];

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Deco, MathClass};

    fn atom(c: &str) -> Symbol {
        Symbol {
            latex: c.into(),
            class: MathClass::Ord,
        }
    }

    fn fill(t: &mut Tree, seq: SeqId, s: &str) {
        let mut c = Cursor { seq, index: t.len(seq) };
        for ch in s.chars() {
            c = t.insert_atom(c, atom(&ch.to_string()));
        }
    }

    #[test]
    fn insert_wires_parents_and_splices() {
        let mut t = Tree::new();
        let root = t.root();
        t.insert_new(root, 0, NewNode::Atom(atom("a")));
        let frac = t.insert_new(root, 1, NewNode::Frac(FracStyle::Bar));
        assert_eq!(t.child_seqs(frac).len(), 2);
        assert_eq!(t.seq_parent(t.child_seqs(frac)[0]), Some(frac));
        assert_eq!(t.index_in_parent(frac), Some((root, 1)));
    }

    #[test]
    fn move_right_walks_source_order_through_a_fraction() {
        let mut t = Tree::new();
        let root = t.root();
        let frac = t.insert_new(root, 0, NewNode::Frac(FracStyle::Bar));
        let slots = t.child_seqs(frac);
        let (num, den) = (slots[0], slots[1]);
        let c = nav::move_right(&t, Cursor { seq: root, index: 0 }).unwrap();
        assert_eq!((c.seq, c.index), (num, 0));
        let c = nav::move_right(&t, c).unwrap();
        assert_eq!((c.seq, c.index), (den, 0));
        let c = nav::move_right(&t, c).unwrap();
        assert_eq!((c.seq, c.index), (root, 1));
        assert_eq!(nav::move_right(&t, c), None);
    }

    #[test]
    fn drop_node_frees_the_whole_subtree() {
        let mut t = Tree::new();
        let root = t.root();
        let frac = t.insert_new(root, 0, NewNode::Frac(FracStyle::Bar));
        assert!(t.seqs.len() >= 3);
        t.drop_node(frac);
        assert_eq!(t.len(root), 0);
        assert_eq!(t.seqs.len(), 1);
    }

    #[test]
    fn backspace_deletes_an_atom() {
        let mut t = Tree::new();
        let root = t.root();
        fill(&mut t, root, "ab");
        let c = t.delete_backward(Cursor { seq: root, index: 2 });
        assert_eq!((c.seq, c.index), (root, 1));
        assert_eq!(t.len(root), 1);
    }

    #[test]
    fn backspace_in_empty_fraction_removes_it() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_fraction(Cursor { seq: root, index: 0 }, FracStyle::Bar, None);
        // The empty numerator escalates to removing the frac.
        let c = t.delete_backward(c);
        assert_eq!((c.seq, c.index), (root, 0));
        assert_eq!(t.len(root), 0);
        assert_eq!(t.seqs.len(), 1);
    }

    #[test]
    fn backspace_in_partial_fraction_unwraps_and_promotes() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_fraction(Cursor { seq: root, index: 0 }, FracStyle::Bar, None);
        let num = c.seq;
        fill(&mut t, num, "xy");
        // Backspace from the empty denominator start.
        let frac = t.items(root)[0];
        let den = t.child_seqs(frac)[1];
        let c = t.delete_backward(Cursor { seq: den, index: 0 });
        // The numerator content is promoted to root.
        assert_eq!(t.len(root), 2);
        assert_eq!(c.seq, root);
    }

    #[test]
    fn backspace_at_nonempty_slot_start_exits_without_deleting() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_fraction(Cursor { seq: root, index: 0 }, FracStyle::Bar, None);
        let num = c.seq;
        fill(&mut t, num, "x");
        let before = t.len(num);
        let c = t.delete_backward(Cursor { seq: num, index: 0 });
        assert_eq!(t.len(num), before);
        assert_eq!(c.seq, root);
    }

    #[test]
    fn fraction_wraps_a_selection() {
        let mut t = Tree::new();
        let root = t.root();
        fill(&mut t, root, "ab");
        let sel = Selection {
            seq: root,
            anchor: 0,
            focus: 2,
        };
        let c = t.insert_fraction(Cursor { seq: root, index: 0 }, FracStyle::Bar, Some(sel));
        let frac = t.items(root)[0];
        let num = t.child_seqs(frac)[0];
        assert_eq!(t.len(num), 2);
        assert_eq!(t.len(root), 1);
        assert_eq!(c.seq, t.child_seqs(frac)[1]);
    }

    #[test]
    fn script_attaches_to_preceding_atom() {
        let mut t = Tree::new();
        let root = t.root();
        fill(&mut t, root, "x");
        let c = t.attach_script(Cursor { seq: root, index: 1 }, ScriptSlot::Sup);
        let script = t.items(root)[0];
        assert!(matches!(t.kind(script), Some(Kind::Script { .. })));
        // The base holds "x" and the cursor is in the empty sup.
        if let Some(Kind::Script { base, sup, .. }) = t.kind(script) {
            assert_eq!(t.len(*base), 1);
            assert_eq!(Some(c.seq), *sup);
        } else {
            panic!();
        }
    }

    #[test]
    fn deleting_empty_script_unwraps_with_cursor_after_base() {
        let mut t = Tree::new();
        let root = t.root();
        t.insert_atom(Cursor { seq: root, index: 0 }, atom("x"));
        let c = t.attach_script(Cursor { seq: root, index: 1 }, ScriptSlot::Sup);
        let c = t.insert_atom(c, atom("2"));
        let c = t.delete_backward(c);
        let c = t.delete_backward(c);
        assert_eq!(t.len(root), 1);
        assert!(matches!(t.kind(t.items(root)[0]), Some(Kind::Atom(_))));
        assert_eq!((c.seq, c.index), (root, 1));
    }

    #[test]
    fn typing_into_script_base_evicts_old_base_left() {
        let mut t = Tree::new();
        let root = t.root();
        t.insert_atom(Cursor { seq: root, index: 0 }, atom("x"));
        let c = t.attach_script(Cursor { seq: root, index: 1 }, ScriptSlot::Sup);
        t.insert_atom(c, atom("2"));
        let script = t.items(root)[0];
        let base = match t.kind(script) {
            Some(Kind::Script { base, .. }) => *base,
            _ => panic!(),
        };
        // Typing y at the base end evicts x to the left.
        let c = t.insert_atom(Cursor { seq: base, index: 1 }, atom("y"));
        assert_eq!(t.len(base), 1);
        assert_eq!((c.seq, c.index), (base, 1));
        assert_eq!(t.len(root), 2);
        assert!(matches!(t.kind(t.items(root)[0]), Some(Kind::Atom(_))));
        assert_eq!(t.items(root)[1], script);
    }

    #[test]
    fn deleting_lone_script_base_dissolves_into_sequence() {
        let mut t = Tree::new();
        let root = t.root();
        t.insert_atom(Cursor { seq: root, index: 0 }, atom("x"));
        let c = t.attach_script(Cursor { seq: root, index: 1 }, ScriptSlot::Sup);
        t.insert_atom(c, atom("2"));
        let script = t.items(root)[0];
        let base = match t.kind(script) {
            Some(Kind::Script { base, .. }) => *base,
            _ => panic!(),
        };
        // Backspace at the base end deletes the base atom.
        let c = t.delete_backward(Cursor { seq: base, index: 1 });
        assert_eq!((c.seq, c.index), (base, 0));
        assert!(t.is_empty(base));
        // Backspace again with nothing to the left dissolves into a plain seq.
        let c = t.delete_backward(c);
        assert_eq!(t.len(root), 1);
        assert!(matches!(t.kind(t.items(root)[0]), Some(Kind::Atom(_))));
        assert_eq!((c.seq, c.index), (root, 0));
    }

    #[test]
    fn deleting_empty_base_pulls_left_sibling_in() {
        let mut t = Tree::new();
        let root = t.root();
        // Backspace in the empty base pulls the left sibling in.
        t.insert_atom(Cursor { seq: root, index: 0 }, atom("a"));
        let c = t.attach_script(Cursor { seq: root, index: 1 }, ScriptSlot::Sup);
        // Pop the wrapped base back out to recreate `a` plus an empty base.
        let script = t.items(root)[0];
        let base = match t.kind(script) {
            Some(Kind::Script { base, .. }) => *base,
            _ => panic!(),
        };
        t.insert_atom(c, atom("2"));
        t.move_range(base, 0..1, root, 0);
        let c = t.delete_backward(Cursor { seq: base, index: 0 });
        assert_eq!(t.len(root), 1);
        assert_eq!(t.len(base), 1);
        assert_eq!((c.seq, c.index), (base, 1));
    }

    #[test]
    fn backspace_in_empty_sqrt_radicand_drops_radical() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_sqrt(Cursor { seq: root, index: 0 }, None);
        let c = t.delete_backward(c);
        assert_eq!(t.len(root), 0);
        assert_eq!((c.seq, c.index), (root, 0));
    }

    #[test]
    fn backspace_in_empty_delim_drops_it() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_delimiters(Cursor { seq: root, index: 0 }, '(', ')', None);
        let c = t.delete_backward(c);
        assert_eq!(t.len(root), 0);
        assert_eq!((c.seq, c.index), (root, 0));
    }

    #[test]
    fn backspace_in_empty_bigop_limit_steps_into_nonempty_other() {
        let mut t = Tree::new();
        let root = t.root();
        let op = Symbol { latex: "\\sum".into(), class: MathClass::Op };
        t.insert_big_op(Cursor { seq: root, index: 0 }, op);
        let bigop = t.items(root)[0];
        let cs = t.child_seqs(bigop);
        let (upper, lower) = (cs[0], cs[1]);
        fill(&mut t, lower, "2");
        // Backspace from the empty upper limit steps into the nonempty lower.
        let c = t.delete_backward(Cursor { seq: upper, index: 0 });
        assert_eq!(t.len(root), 1);
        assert_eq!((c.seq, c.index), (lower, 1));
    }

    #[test]
    fn backspace_in_empty_bigop_both_limits_empty_drops_op() {
        let mut t = Tree::new();
        let root = t.root();
        let op = Symbol { latex: "\\sum".into(), class: MathClass::Op };
        t.insert_big_op(Cursor { seq: root, index: 0 }, op);
        let bigop = t.items(root)[0];
        let lower = t.child_seqs(bigop)[1];
        let c = t.delete_backward(Cursor { seq: lower, index: 0 });
        assert_eq!(t.len(root), 0);
        assert_eq!((c.seq, c.index), (root, 0));
    }

    #[test]
    fn backspace_in_underover_over_collapses_to_base() {
        let mut t = Tree::new();
        let root = t.root();
        let spec = UnderOverSpec { over: true, under: false, over_deco: Deco::None, under_deco: Deco::None };
        let c = t.insert_under_over(Cursor { seq: root, index: 0 }, spec, None);
        let node = t.items(root)[0];
        let over = match t.kind(node) {
            Some(Kind::UnderOver { over, .. }) => over.unwrap(),
            _ => panic!(),
        };
        fill(&mut t, c.seq, "x");
        // Backspace from the empty over slot drops over and promotes the base.
        let c = t.delete_backward(Cursor { seq: over, index: 0 });
        assert_eq!(t.len(root), 1);
        assert!(matches!(t.kind(t.items(root)[0]), Some(Kind::Atom(_))));
        assert_eq!((c.seq, c.index), (root, 1));
    }

    #[test]
    fn backspace_in_all_empty_matrix_drops_it() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_matrix(Cursor { seq: root, index: 0 }, MatrixEnv::Pmatrix, 2, 2);
        let c = t.delete_backward(c);
        assert_eq!(t.len(root), 0);
        assert_eq!((c.seq, c.index), (root, 0));
    }

    #[test]
    fn vertical_nav_switches_fraction_slots() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_fraction(Cursor { seq: root, index: 0 }, FracStyle::Bar, None);
        let num = c.seq;
        let frac = t.items(root)[0];
        let den = t.child_seqs(frac)[1];
        let down = nav::vertical(&t, Cursor { seq: num, index: 0 }, false).unwrap();
        assert_eq!(down.seq, den);
        let up = nav::vertical(&t, Cursor { seq: den, index: 0 }, true).unwrap();
        assert_eq!(up.seq, num);
    }

    #[test]
    fn matrix_row_col_ops() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_matrix(Cursor { seq: root, index: 0 }, MatrixEnv::Pmatrix, 2, 2);
        let m = t.items(root)[0];
        let count = |t: &Tree| match t.kind(m) {
            Some(Kind::Matrix { rows, .. }) => (rows.len(), rows[0].len()),
            _ => (0, 0),
        };
        assert_eq!(count(&t), (2, 2));
        let c = t.matrix_insert_row(c, Side::After);
        assert_eq!(count(&t), (3, 2));
        let c = t.matrix_insert_col(c, Side::Before);
        assert_eq!(count(&t), (3, 3));
        let c = t.matrix_delete_row(c);
        assert_eq!(count(&t), (2, 3));
        let _c = t.matrix_delete_col(c);
        assert_eq!(count(&t), (2, 2));
    }

    #[test]
    fn matrix_shape_at_reports_current_grid_size_and_none_outside_a_matrix() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_matrix(Cursor { seq: root, index: 0 }, MatrixEnv::Pmatrix, 2, 2);
        assert_eq!(t.matrix_shape_at(c), Some((2, 2)));
        let c = t.matrix_insert_row(c, Side::After);
        assert_eq!(t.matrix_shape_at(c), Some((3, 2)));

        // The document root is outside any matrix.
        assert_eq!(t.matrix_shape_at(Cursor { seq: root, index: 0 }), None);
    }

    #[test]
    fn swap_variants_for_delim_excludes_the_current_pair() {
        let mut t = Tree::new();
        let root = t.root();
        t.insert_delimiters(Cursor { seq: root, index: 0 }, '(', ')', None);
        let delim = t.items(root)[0];
        let variants = t.swap_variants(delim).expect("Delim should be swappable");
        assert!(variants.iter().all(|v| !matches!(
            v,
            SwapVariant::Delim { open: '(', close: ')', .. }
        )));
        assert!(variants
            .iter()
            .any(|v| matches!(v, SwapVariant::Delim { open: '[', close: ']', .. })));
    }

    #[test]
    fn apply_swap_changes_only_the_tag_field() {
        let mut t = Tree::new();
        let root = t.root();
        let c = t.insert_delimiters(Cursor { seq: root, index: 0 }, '(', ')', None);
        fill(&mut t, c.seq, "x");
        let delim = t.items(root)[0];
        let body_before = t.child_seqs(delim)[0];

        t.apply_swap(delim, &SwapVariant::Delim { open: '[', close: ']', label: "[ ]" });
        match t.kind(delim) {
            Some(Kind::Delim { open, close, body }) => {
                assert_eq!((*open, *close), ('[', ']'));
                assert_eq!(*body, body_before);
                assert_eq!(t.len(*body), 1);
            }
            _ => panic!("expected Delim"),
        }
    }

    #[test]
    fn swap_variants_none_for_non_swappable_kinds() {
        let mut t = Tree::new();
        let root = t.root();

        t.insert_atom(Cursor { seq: root, index: 0 }, atom("x"));
        let atom_node = t.items(root)[0];
        assert!(t.swap_variants(atom_node).is_none());

        let c = t.insert_fraction(Cursor { seq: root, index: 1 }, FracStyle::Bar, None);
        let _ = c;
        let frac = t.items(root)[1];
        assert!(t.swap_variants(frac).is_none());

        let c = t.insert_sqrt(Cursor { seq: root, index: 2 }, None);
        let _ = c;
        let sqrt = t.items(root)[2];
        assert!(t.swap_variants(sqrt).is_none());
    }

    #[test]
    fn swap_variants_none_for_text_carve_out() {
        let mut t = Tree::new();
        let root = t.root();
        t.insert_styled(Cursor { seq: root, index: 0 }, Variant::Text, None);
        let text = t.items(root)[0];
        assert!(t.swap_variants(text).is_none());
    }

    #[test]
    fn swap_variants_for_styled_font_excludes_current_and_text() {
        let mut t = Tree::new();
        let root = t.root();
        t.insert_styled(Cursor { seq: root, index: 0 }, Variant::Bold, None);
        let styled = t.items(root)[0];
        let variants = t.swap_variants(styled).expect("Styled(Bold) should be swappable");
        assert!(variants
            .iter()
            .all(|v| !matches!(v, SwapVariant::Styled { variant: Variant::Bold, .. })));
        assert!(variants
            .iter()
            .all(|v| !matches!(v, SwapVariant::Styled { variant: Variant::Text, .. })));
    }

    #[test]
    fn swap_variants_for_underover_only_varies_present_slots() {
        let mut t = Tree::new();
        let root = t.root();
        // With over only, every alternative leaves `under` at its absent equivalent default.
        let spec = UnderOverSpec {
            over: true,
            under: false,
            over_deco: Deco::Brace,
            under_deco: Deco::None,
        };
        t.insert_under_over(Cursor { seq: root, index: 0 }, spec, None);
        let node = t.items(root)[0];
        let variants = t.swap_variants(node).expect("UnderOver should be swappable");
        assert!(!variants.is_empty());
        for v in &variants {
            match v {
                SwapVariant::UnderOverDeco { over, under, .. } => {
                    assert_ne!(*over, Deco::Brace);
                    assert_eq!(*under, Deco::None);
                }
                _ => panic!("expected UnderOverDeco"),
            }
        }
    }
}