retex-engine 1.0.0-rc.2

The TeX typesetting engine for retex
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
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
//! Building math lists (*TeX: The Program* ยง1136โ€“ยง1206, with e-TeX's
//! `\middle` and LuaTeX's extensions).
//!
//! A formula is read into an mlist of noads (see [`crate::nodes`]), which
//! [`crate::mlist`] converts into an hlist when the formula ends. LuaTeX
//! differences implemented here (established with black-box tests):
//!
//! * there is no "insufficient symbol fonts" check;
//! * `\mathchar`, `\Umathchar` and math characters given by `\mathchardef`
//!   are accepted in horizontal mode, where they typeset the character
//!   from the text font of the family (vertical mode starts a paragraph);
//! * the `Missing delimiter` help text has no full stop after "proceed";
//! * the `\Umathโ€ฆ` variants (`\Uradical`, `\Uroot`, `\Umathaccent`,
//!   `\Uleft`, `\Uskewed`, `\Ustack`, `\Usuperscript`, โ€ฆ) are supported with
//!   their keywords.

use std::rc::Rc;

use crate::Engine;
use crate::build::PackSpec;
use crate::cmd::Cmd;
use crate::eqtb::{Loc, Val};
use crate::input::TokKind;
use crate::maincontrol::{IGNORE_DEPTH, Mode};
use crate::nodes::{
    DEFAULT_CODE, FenceData, FractionData, NodeData, NodeRef, accent_sub, fence_sub, id, noad_opt,
    noad_sub, radical_sub,
};
use crate::primitives_gen::{assign_dimen as dp, assign_int as ip, assign_toks as tp};
use crate::save::GroupCode;
use crate::token::Token;

/// A noad field that `scan_math` fills.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Field {
    /// The nucleus.
    Nucleus = 0,
    /// The superscript.
    Sup = 1,
    /// The subscript.
    Sub = 2,
    /// The degree of a `\Uroot`.
    Degree = 3,
}

impl Field {
    fn from_i64(v: i64) -> Field {
        match v & 3 {
            0 => Field::Nucleus,
            1 => Field::Sup,
            2 => Field::Sub,
            _ => Field::Degree,
        }
    }
}

fn field_ref(noad: NodeRef, f: Field) -> i64 {
    (i64::from(noad.0) << 2) | f as i64
}

fn field_from_ref(v: i64) -> (NodeRef, Field) {
    (NodeRef((v >> 2) as u32), Field::from_i64(v))
}

/// A math character: class (0โ€“7, 8 for "math active"), family, character.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathChar {
    /// The class.
    pub class: u32,
    /// The family.
    pub fam: u32,
    /// The character.
    pub chr: u32,
}

impl MathChar {
    /// A `math_given` value (see [`Engine::scan_math_given`]).
    pub fn from_given(g: u32) -> MathChar {
        if g & crate::codes::MATH_GIVEN_PACKED != 0 {
            MathChar::from_packed(i64::from(g & !crate::codes::MATH_GIVEN_PACKED))
        } else {
            MathChar::from_classic(g as i32)
        }
    }

    /// Decodes TeX's 15-bit form (`"8000` is math active).
    pub fn from_classic(c: i32) -> MathChar {
        if c >= 0x8000 {
            return MathChar {
                class: 8,
                fam: 0,
                chr: 0,
            };
        }
        let c = c.max(0) as u32;
        MathChar {
            class: c >> 12,
            fam: (c >> 8) & 0xF,
            chr: c & 0xFF,
        }
    }

    /// Decodes LuaTeX's packed form (`\Umathcharnum`, `\mathcode`).
    pub fn from_packed(v: i64) -> MathChar {
        if v == crate::codes::MATH_ACTIVE {
            return MathChar {
                class: 8,
                fam: 0,
                chr: 0,
            };
        }
        MathChar {
            class: crate::codes::math_class(v),
            fam: crate::codes::math_fam(v),
            chr: crate::codes::math_char(v),
        }
    }
}

/// The parts (small family, small character, large family, large
/// character) of an internal delimiter code, or `None` for โˆ’1.
pub fn delcode_parts(v: i64) -> Option<(u32, u32, u32, u32)> {
    if v < 0 {
        return None;
    }
    if v & (1 << 62) != 0 {
        Some((
            ((v >> 53) & 0xF) as u32,
            ((v >> 32) & 0xFF) as u32,
            ((v >> 21) & 0xF) as u32,
            (v & 0xFF) as u32,
        ))
    } else {
        Some((((v >> 21) & 0xFF) as u32, (v & 0x1F_FFFF) as u32, 0, 0))
    }
}

/// The noad subtype for a math class.
fn class_subtype(class: u32) -> u16 {
    match class {
        1 => noad_sub::OP_DISPLAY_LIMITS,
        2 => noad_sub::BIN,
        3 => noad_sub::REL,
        4 => noad_sub::OPEN,
        5 => noad_sub::CLOSE,
        6 => noad_sub::PUNCT,
        _ => noad_sub::ORD,
    }
}

/// `cramped_style`.
pub const fn cramped_style(s: i32) -> i32 {
    2 * (s / 2) + 1
}

/// `sub_style`.
pub const fn sub_style(s: i32) -> i32 {
    2 * (s / 4) + 4 + 1
}

/// `sup_style`.
pub const fn sup_style(s: i32) -> i32 {
    2 * (s / 4) + 4 + (s % 2)
}

/// `num_style`.
pub const fn num_style(s: i32) -> i32 {
    s + 2 - 2 * (s / 6)
}

/// `denom_style`.
pub const fn denom_style(s: i32) -> i32 {
    2 * (s / 2) + 1 + 2 - 2 * (s / 6)
}

impl Engine {
    // ----- node constructors ------------------------------------------

    /// A new noad of the given subtype with empty fields (`new_noad`).
    pub fn new_noad(&mut self, sub: u16) -> NodeRef {
        self.new_node(id::NOAD, sub, NodeData::Noad(Box::default()))
    }

    /// A new `math_char` kernel.
    pub fn new_math_char(&mut self, fam: u32, chr: u32) -> NodeRef {
        self.new_node(id::MATH_CHAR, 0, NodeData::MathChar { fam, chr })
    }

    /// A new `sub_box` or `sub_mlist` kernel.
    pub fn new_sub_list(&mut self, mlist: bool, head: NodeRef) -> NodeRef {
        self.new_node(
            if mlist { id::SUB_MLIST } else { id::SUB_BOX },
            0,
            NodeData::SubList { head },
        )
    }

    /// A new delimiter node.
    pub fn new_delim(&mut self, parts: (u32, u32, u32, u32)) -> NodeRef {
        self.new_node(
            id::DELIM,
            0,
            NodeData::Delim {
                small_fam: parts.0,
                small_char: parts.1,
                large_fam: parts.2,
                large_char: parts.3,
            },
        )
    }

    /// A new style node.
    pub fn new_style(&mut self, s: u8) -> NodeRef {
        self.new_node(id::STYLE, u16::from(s), NodeData::Style { style: s })
    }

    /// The kernel in field `f` of noad `p`.
    pub fn noad_field(&self, p: NodeRef, f: Field) -> NodeRef {
        match self.nodes.noad(p) {
            Some(n) => match f {
                Field::Nucleus => n.nucleus,
                Field::Sup => n.sup,
                Field::Sub => n.sub,
                Field::Degree => n.degree,
            },
            None => NodeRef::NULL,
        }
    }

    /// Replaces the kernel in field `f` of noad `p` (the old one is not
    /// freed).
    pub fn set_noad_field(&mut self, p: NodeRef, f: Field, k: NodeRef) {
        if let Some(n) = self.nodes.noad_mut(p) {
            match f {
                Field::Nucleus => n.nucleus = k,
                Field::Sup => n.sup = k,
                Field::Sub => n.sub = k,
                Field::Degree => n.degree = k,
            }
        }
    }

    // ----- entering math mode -----------------------------------------

    /// Enters a math level (`push_math`).
    fn push_math(&mut self, c: GroupCode, style: i32) {
        self.push_nest(Mode::Math);
        self.cur_list_mut().incompleat_noad = NodeRef::NULL;
        self.cur_list_mut().math_style = style;
        self.new_save_level(c);
        if c == GroupCode::MathShift {
            self.begin_math_dirs();
        }
    }

    /// `$` in horizontal mode (`init_math`).
    pub fn init_math(&mut self) {
        let shift_cs = self.cur_cmd == Cmd::MathShiftCs;
        let display = if shift_cs {
            // \Ustartmath (2) or \Ustartdisplaymath (0).
            self.cur_chr == 0 && self.mode == Mode::Horizontal
        } else {
            self.get_token();
            if self.cur_cmd == Cmd::MathShift && self.mode == Mode::Horizontal {
                true
            } else {
                self.back_input();
                false
            }
        };
        if display {
            self.go_into_display_math();
        } else {
            self.go_into_ordinary_math();
        }
    }

    fn go_into_ordinary_math(&mut self) {
        self.push_math(GroupCode::MathShift, 2);
        self.eq_define(Loc::IntPar(ip::FAM), Val::Int(-1));
        let t = self.eqtb.toks_param(tp::EVERYMATH).clone();
        if !t.is_empty() {
            self.begin_token_list(t, TokKind::EveryMathText);
        }
    }

    /// Starts a display: breaks the paragraph so far into lines and
    /// computes `\predisplaysize`, `\displaywidth` and `\displayindent`.
    fn go_into_display_math(&mut self) {
        let max_dimen = 0o7777777777;
        let mut w = -max_dimen;
        let (head, tail) = (self.cur_list().head, self.cur_list().tail);
        let only_local_par = self.nodes.next(head) == tail
            && matches!(self.nodes.data(tail), NodeData::LocalPar { .. });
        if head == tail || only_local_par {
            // `\noindent$$` or `$${ }$$`.
            if only_local_par {
                self.nodes.flush_list(tail);
                self.nodes.set_next(head, NodeRef::NULL);
            }
            self.pop_nest();
        } else {
            let wp = self.eqtb.int(ip::DISPLAYWIDOWPENALTY);
            self.line_break(wp);
            w = self.pre_display_width();
        }
        // Now in vertical mode: the length and shift of the display lines.
        let prev_graf = self.cur_list().prev_graf;
        let (l, s) = self.display_line_size(prev_graf);
        self.push_math(GroupCode::MathShift, 0);
        self.mode = Mode::DisplayMath;
        self.cur_list_mut().mode = Mode::DisplayMath;
        self.eq_define(Loc::IntPar(ip::FAM), Val::Int(-1));
        self.eq_define(Loc::DimenPar(dp::PREDISPLAYSIZE), Val::Int(i64::from(w)));
        self.eq_define(Loc::DimenPar(dp::DISPLAYWIDTH), Val::Int(i64::from(l)));
        self.eq_define(Loc::DimenPar(dp::DISPLAYINDENT), Val::Int(i64::from(s)));
        let t = self.eqtb.toks_param(tp::EVERYDISPLAY).clone();
        if !t.is_empty() {
            self.begin_token_list(t, TokKind::EveryDisplayText);
        }
        if self.nest.len() == 2 {
            self.build_page_from("before_display");
        }
    }

    /// The natural width by which the last line of the paragraph before a
    /// display extends to the right, plus two quads (`\predisplaygapfactor`
    /// thousandths of a quad); `max_dimen` if it depends on glue setting.
    fn pre_display_width(&mut self) -> i32 {
        let max_dimen = 0o7777777777;
        let jb = self.ts.just_box;
        if jb.is_null() {
            return -max_dimen;
        }
        let Some(b) = self.nodes.box_data(jb).cloned() else {
            return -max_dimen;
        };
        let f = self.eqtb.cur_font.val;
        let gap = self.eqtb.int(ip::PREDISPLAYGAPFACTOR);
        let q = self.quad(f);
        // Observed: (quad div 1000) * \predisplaygapfactor.
        let extra = (q / 1000).wrapping_mul(gap);
        let mut v = b.shift + extra;
        let mut w = -max_dimen;
        let mut p = b.head;
        while !p.is_null() {
            let (d, visible) = match self.nodes.data(p) {
                NodeData::Glyph(_) => (self.glyph_dimensions(p).0, true),
                NodeData::Box(bx) => (bx.width, true),
                NodeData::Rule { width, .. } => (*width, true),
                NodeData::Kern { kern, .. } => (*kern, false),
                NodeData::MarginKern { width, .. } => (*width, false),
                NodeData::Math { .. } => (self.nodes.width(p), false),
                NodeData::Glue { spec, .. } => {
                    let spec = *spec;
                    if b.glue_sign == 1 {
                        if b.glue_order == spec.stretch_order && spec.stretch != 0 {
                            v = max_dimen;
                        }
                    } else if b.glue_sign == 2
                        && b.glue_order == spec.shrink_order
                        && spec.shrink != 0
                    {
                        v = max_dimen;
                    }
                    (
                        spec.width,
                        self.nodes.subtype(p) >= crate::nodes::glue_sub::A_LEADERS,
                    )
                }
                _ => (0, false),
            };
            if visible {
                if v < max_dimen {
                    v += d;
                    w = v;
                } else {
                    w = max_dimen;
                    break;
                }
            } else if v < max_dimen {
                v += d;
            }
            p = self.nodes.next(p);
        }
        w
    }

    /// The length and shift of line `prev_graf + 2` (ยง1149).
    fn display_line_size(&self, prev_graf: i32) -> (i32, i32) {
        let hsize = self.eqtb.dimen(dp::HSIZE);
        match &self.eqtb.par_shape.val {
            None => {
                let hi = self.eqtb.dimen(dp::HANGINDENT);
                let ha = self.eqtb.int(ip::HANGAFTER);
                if hi != 0 && ((ha >= 0 && prev_graf + 2 > ha) || (prev_graf + 1 < -ha)) {
                    (hsize - hi.abs(), if hi > 0 { hi } else { 0 })
                } else {
                    (hsize, 0)
                }
            }
            Some(shape) => {
                let n = (shape.len() / 2) as i32;
                let i = if prev_graf + 2 >= n { n } else { prev_graf + 2 };
                let k = 2 * (i.max(1) as usize - 1);
                let indent = shape.get(k).copied().unwrap_or(0);
                let len = shape.get(k + 1).copied().unwrap_or(hsize);
                (len, indent)
            }
        }
    }

    // ----- the main switch --------------------------------------------

    /// Commands in math mode (the `mmode+โ€ฆ` cases of `main_control`).
    pub fn math_command(&mut self) {
        let cmd = self.cur_cmd;
        match cmd {
            Cmd::Letter | Cmd::OtherChar | Cmd::CharGiven => {
                let code = self.eqtb.math.get(self.cur_chr);
                self.set_math_char(MathChar::from_packed(code));
            }
            Cmd::CharNum => {
                self.scan_char_num();
                self.cur_chr = self.cur_val as u32;
                let code = self.eqtb.math.get(self.cur_chr);
                self.set_math_char(MathChar::from_packed(code));
            }
            Cmd::MathCharNum => {
                let mc = self.scan_math_char_num();
                self.set_math_char(mc);
            }
            Cmd::MathGiven => {
                let mc = MathChar::from_given(self.cur_chr);
                self.set_math_char(mc);
            }
            Cmd::XmathGiven => {
                let mc = MathChar::from_packed(i64::from(self.cur_chr));
                self.set_math_char(mc);
            }
            Cmd::DelimNum => {
                let mc = self.scan_delim_num_char();
                self.set_math_char(mc);
            }
            Cmd::LeftBrace => {
                let n = self.new_noad(noad_sub::ORD);
                self.tail_append(n);
                self.back_input();
                let st = self.cur_list().math_style;
                self.scan_math(n, Field::Nucleus, st);
            }
            Cmd::MathComp => {
                let sub = self.cur_chr as u16;
                let n = self.new_noad(sub);
                self.tail_append(n);
                let st = self.cur_list().math_style;
                let st = if sub == noad_sub::OVER || sub == noad_sub::UNDER {
                    if sub == noad_sub::OVER {
                        cramped_style(st)
                    } else {
                        st
                    }
                } else {
                    st
                };
                self.scan_math(n, Field::Nucleus, st);
            }
            Cmd::LimitSwitch => self.math_limit_switch(),
            Cmd::SupMark | Cmd::SubMark => {
                let sup = cmd == Cmd::SupMark;
                self.sub_sup(sup, false);
            }
            Cmd::SuperSubScript => {
                let sup = self.cur_chr == Cmd::SupMark as u32;
                self.sub_sup(sup, false);
            }
            Cmd::NoSuperSubScript => {
                let sup = self.cur_chr == Cmd::SupMark as u32;
                self.sub_sup(sup, true);
            }
            Cmd::Radical => self.math_radical(),
            Cmd::Accent | Cmd::MathAccent => self.math_ac(),
            Cmd::Vcenter => {
                self.scan_spec(GroupCode::Vcenter, None);
                self.normal_paragraph();
                self.push_nest(Mode::InternalVertical);
                self.cur_list_mut().prev_depth = IGNORE_DEPTH;
                let t = self.eqtb.toks_param(tp::EVERYVBOX).clone();
                if !t.is_empty() {
                    self.begin_token_list(t, TokKind::EveryVboxText);
                }
            }
            Cmd::MathStyle => {
                let s = self.cur_chr.min(7) as u8;
                let n = self.new_style(s);
                self.tail_append(n);
                self.cur_list_mut().math_style = i32::from(s);
            }
            Cmd::NonScript => {
                let g = self.new_glue_node(
                    crate::glue::Glue::ZERO,
                    crate::nodes::glue_sub::COND_MATH_GLUE,
                );
                self.tail_append(g);
            }
            Cmd::MathChoice => {
                if self.cur_chr == 0 {
                    self.append_choices();
                } else {
                    // \Ustack: a subformula in numerator style.
                    let n = self.new_noad(noad_sub::ORD);
                    self.tail_append(n);
                    let st = num_style(self.cur_list().math_style);
                    self.scan_left_brace();
                    let sub = self.new_sub_list(true, NodeRef::NULL);
                    self.set_noad_field(n, Field::Nucleus, sub);
                    self.push_saved(field_ref(n, Field::Nucleus));
                    self.push_math(GroupCode::Math, st);
                }
            }
            Cmd::Above => self.math_fraction(),
            Cmd::MathShift => {
                if self.save.cur_group == GroupCode::MathShift {
                    self.after_math();
                } else {
                    self.off_save();
                }
            }
            Cmd::MathShiftCs => {
                // \Ustopmath (3) and \Ustopdisplaymath (1) end the
                // formula; the start commands are not allowed here.
                let c = self.cur_chr;
                let ok = (c == 3 && self.mode == Mode::Math)
                    || (c == 1 && self.mode == Mode::DisplayMath);
                if (c == 1 || c == 3) && self.save.cur_group == GroupCode::MathShift && ok {
                    self.after_math();
                } else if c == 1 || c == 3 {
                    if self.save.cur_group == GroupCode::MathShift {
                        self.print_err("Invalid math code");
                        self.help(&["I'm going to ignore this math shift command."]);
                        self.error();
                    } else {
                        self.off_save();
                    }
                } else {
                    self.report_illegal_case();
                }
            }
            Cmd::EqNo => {
                if self.privileged() {
                    if self.save.cur_group == GroupCode::MathShift {
                        self.start_eq_no();
                    } else {
                        self.off_save();
                    }
                }
            }
            Cmd::LeftRight => self.math_left_right(),
            Cmd::Endv
            | Cmd::ParEnd
            | Cmd::Stop
            | Cmd::Vskip
            | Cmd::UnVbox
            | Cmd::Valign
            | Cmd::Hrule => self.insert_dollar_sign(),
            Cmd::Halign => {
                if self.privileged() {
                    if self.save.cur_group == GroupCode::MathShift {
                        self.init_align();
                    } else {
                        self.off_save();
                    }
                }
            }
            _ => {
                let (c, r) = (self.cur_cmd, self.cur_chr);
                let s = self.print_to_string(|e| e.print_cmd_chr(c, r));
                self.not_implemented(&String::from_utf8_lossy(&s));
            }
        }
    }

    /// `\mathchar`, `\Umathchar` and `\Umathcharnum`.
    fn scan_math_char_num(&mut self) -> MathChar {
        match self.cur_chr {
            0 => {
                let g = self.scan_math_given();
                MathChar::from_given(g)
            }
            1 => {
                let v = self.scan_umath_triple();
                MathChar::from_packed(v)
            }
            _ => {
                self.scan_int();
                MathChar::from_packed(i64::from(self.cur_val))
            }
        }
    }

    /// `\delimiter` (its 15-bit part) and `\Udelimiter` as a math character.
    fn scan_delim_num_char(&mut self) -> MathChar {
        if self.cur_chr == 0 {
            self.scan_twenty_seven_bit_int();
            MathChar::from_classic(self.cur_val / 0o10000)
        } else {
            let v = self.scan_umath_triple();
            MathChar::from_packed(v)
        }
    }

    /// Whether `\fam` is a valid family (`fam_in_range`).
    fn fam_in_range(&self) -> Option<u32> {
        let f = self.eqtb.int(ip::FAM);
        if (0..crate::eqtb::NUM_FAMILIES as i32).contains(&f) {
            Some(f as u32)
        } else {
            None
        }
    }

    /// The family of a math character, taking class 7 and `\fam` into
    /// account.
    fn effective_fam(&self, mc: MathChar) -> u32 {
        if mc.class == 7
            && let Some(f) = self.fam_in_range()
        {
            return f;
        }
        let vf = self.eqtb.int(ip::VARIABLEFAM);
        if vf >= 0
            && mc.fam == vf as u32
            && let Some(f) = self.fam_in_range()
        {
            return f;
        }
        mc.fam
    }

    /// Treats `cur_chr` as an active character (ยง1152).
    fn treat_as_active(&mut self) {
        let cs = self.hash.active(self.cur_chr);
        self.cur_cs = cs;
        let m = self.eqtb.meaning(cs).clone();
        self.cur_cmd = m.cmd;
        self.cur_chr = m.chr;
        self.x_token();
        self.back_input();
    }

    /// Appends a noad for a math character (`set_math_char`).
    fn set_math_char(&mut self, mc: MathChar) {
        if mc.class >= 8 {
            self.treat_as_active();
            return;
        }
        let fam = self.effective_fam(mc);
        let k = self.new_math_char(fam, mc.chr);
        let sub = class_subtype(mc.class);
        let p = self.new_noad(sub);
        self.set_noad_field(p, Field::Nucleus, k);
        self.tail_append(p);
    }

    /// Fills field `f` of noad `p` with the next math character or
    /// subformula (`scan_math`); `style` is the style of a subformula.
    /// Returns true if a subformula group was opened.
    fn scan_math(&mut self, p: NodeRef, f: Field, style: i32) -> bool {
        self.scan_math_flag(p, f, style, 0)
    }

    /// [`scan_math`](Self::scan_math) with extra bits in the saved field
    /// reference (bit 62: scan the nucleus when the group ends).
    fn scan_math_flag(&mut self, p: NodeRef, f: Field, style: i32, flag: i64) -> bool {
        self.get_nonblank_nonrelax_noncall();
        let mc = loop {
            match self.cur_cmd {
                Cmd::Letter | Cmd::OtherChar | Cmd::CharGiven => {
                    let code = self.eqtb.math.get(self.cur_chr);
                    let mc = MathChar::from_packed(code);
                    if mc.class == 8 {
                        self.treat_as_active();
                        self.get_nonblank_nonrelax_noncall();
                        continue;
                    }
                    break mc;
                }
                Cmd::CharNum => {
                    self.scan_char_num();
                    self.cur_chr = self.cur_val as u32;
                    self.cur_cmd = Cmd::CharGiven;
                }
                Cmd::MathCharNum => break self.scan_math_char_num(),
                Cmd::MathGiven => break MathChar::from_given(self.cur_chr),
                Cmd::XmathGiven => break MathChar::from_packed(i64::from(self.cur_chr)),
                Cmd::DelimNum => break self.scan_delim_num_char(),
                _ => {
                    // A subformula enclosed in braces.
                    self.back_input();
                    self.scan_left_brace();
                    let sub = self.new_sub_list(true, NodeRef::NULL);
                    let old = self.noad_field(p, f);
                    self.nodes.flush_list(old);
                    self.set_noad_field(p, f, sub);
                    self.push_saved(field_ref(p, f) | flag);
                    self.push_math(GroupCode::Math, style);
                    return true;
                }
            }
        };
        self.finish_scan_math(p, f, mc);
        false
    }

    fn finish_scan_math(&mut self, p: NodeRef, f: Field, mc: MathChar) {
        let fam = if mc.class == 8 {
            0
        } else {
            self.effective_fam(mc)
        };
        let k = self.new_math_char(fam, mc.chr);
        let old = self.noad_field(p, f);
        self.nodes.flush_list(old);
        self.set_noad_field(p, f, k);
    }

    /// `\limits`, `\nolimits`, `\displaylimits` (`math_limit_switch`).
    fn math_limit_switch(&mut self) {
        let (head, tail) = (self.cur_list().head, self.cur_list().tail);
        if head != tail
            && self.nodes.id(tail) == id::NOAD
            && matches!(
                self.nodes.subtype(tail),
                noad_sub::OP_DISPLAY_LIMITS | noad_sub::OP_LIMITS | noad_sub::OP_NO_LIMITS
            )
        {
            self.nodes.set_subtype(tail, self.cur_chr as u16);
            return;
        }
        self.print_err("Limit controls must follow a math operator");
        self.help(&["I'm ignoring this misplaced \\limits or \\nolimits command."]);
        self.error();
    }

    /// Scans a delimiter (`scan_delimiter`); `radical` selects TeX's
    /// 27-bit form, `fam_char` LuaTeX's `<fam> <char>` form. Returns a new
    /// delimiter node.
    fn scan_delimiter(&mut self, radical: bool, fam_char: bool) -> NodeRef {
        let parts: Option<(u32, u32, u32, u32)> = if fam_char {
            self.scan_math_family();
            let fam = self.cur_val as u32;
            self.scan_char_num();
            Some((fam, self.cur_val as u32, 0, 0))
        } else if radical {
            self.scan_twenty_seven_bit_int();
            classic_delimiter(self.cur_val)
        } else {
            self.get_nonblank_nonrelax_noncall();
            match self.cur_cmd {
                Cmd::Letter | Cmd::OtherChar => delcode_parts(self.eqtb.del.get(self.cur_chr)),
                Cmd::DelimNum => {
                    if self.cur_chr == 0 {
                        self.scan_twenty_seven_bit_int();
                        classic_delimiter(self.cur_val)
                    } else {
                        let v = self.scan_umath_triple();
                        let mc = MathChar::from_packed(v);
                        Some((mc.fam, mc.chr, 0, 0))
                    }
                }
                _ => None,
            }
        };
        let parts = match parts {
            Some(p) => p,
            None => {
                self.print_err("Missing delimiter (. inserted)");
                self.help(&[
                    "I was expecting to see something like `(' or `\\{' or",
                    "`\\}' here. If you typed, e.g., `{' instead of `\\{', you",
                    "should probably delete the `{' by typing `1' now, so that",
                    "braces don't get unbalanced. Otherwise just proceed",
                    "Acceptable delimiters are characters whose \\delcode is",
                    "nonnegative, or you can use `\\delimiter <delimiter code>'.",
                ]);
                self.back_error();
                (0, 0, 0, 0)
            }
        };
        self.new_delim(parts)
    }

    /// `\radical` and LuaTeX's radical-like commands (`math_radical`).
    fn math_radical(&mut self) {
        let c = self.cur_chr as u16;
        let p = self.new_node(id::RADICAL, c, NodeData::Noad(Box::default()));
        self.tail_append(p);
        let mut opts = 0u32;
        let mut width = 0i32;
        if c == radical_sub::UHEXTENSIBLE || c >= radical_sub::UUNDERDELIMITER {
            loop {
                if self.scan_keyword("width") {
                    self.scan_normal_dimen();
                    width = self.cur_val;
                } else if self.scan_keyword("left") {
                    opts |= noad_opt::LEFT;
                } else if self.scan_keyword("middle") {
                    opts |= noad_opt::MIDDLE;
                } else if self.scan_keyword("right") {
                    opts |= noad_opt::RIGHT;
                } else {
                    break;
                }
            }
        }
        let d = self.scan_delimiter(c == radical_sub::RADICAL, c != radical_sub::RADICAL);
        if let Some(n) = self.nodes.noad_mut(p) {
            n.left = d;
            n.options = opts;
            n.width = width;
        }
        let st = self.cur_list().math_style;
        match c {
            radical_sub::UHEXTENSIBLE => {}
            radical_sub::UROOT => {
                // The degree first, then the radicand. The degree is a
                // subformula in scriptscript style.
                // The radicand follows when the degree group ends.
                if !self.scan_math_flag(p, Field::Degree, 6, 1 << 62) {
                    self.scan_math(p, Field::Nucleus, cramped_style(st));
                }
            }
            radical_sub::UUNDERDELIMITER => {
                self.scan_math(p, Field::Nucleus, sub_style(st));
            }
            radical_sub::UOVERDELIMITER => {
                self.scan_math(p, Field::Nucleus, sup_style(st));
            }
            radical_sub::UDELIMITERUNDER => {
                self.scan_math(p, Field::Nucleus, st);
            }
            _ => {
                self.scan_math(p, Field::Nucleus, cramped_style(st));
            }
        }
    }

    /// Scans `[fixed] <class> <fam> <char>` for `\Umathaccent`.
    fn scan_accent_char(&mut self, umath: bool) -> (NodeRef, bool) {
        let fixed = umath && self.scan_keyword("fixed");
        let mc = if umath {
            let v = self.scan_umath_triple();
            MathChar::from_packed(v)
        } else {
            let g = self.scan_math_given();
            MathChar::from_given(g)
        };
        let fam = if mc.class == 8 {
            0
        } else {
            self.effective_fam(mc)
        };
        (self.new_math_char(fam, mc.chr), fixed)
    }

    /// `\mathaccent` and `\Umathaccent` (`math_ac`).
    fn math_ac(&mut self) {
        if self.cur_cmd == Cmd::Accent {
            self.print_err("Please use ");
            self.print_esc_str("mathaccent");
            self.printer.print_str(" for accents in math mode");
            self.help(&[
                "I'm changing \\accent to \\mathaccent here; wish me luck.",
                "(Accents are not the same in formulas as they are in text.)",
            ]);
            self.error();
        }
        let umath = self.cur_cmd == Cmd::MathAccent && self.cur_chr == 1;
        let p = self.new_node(
            id::ACCENT,
            accent_sub::BOTH_FLEXIBLE,
            NodeData::Noad(Box::default()),
        );
        self.tail_append(p);
        let mut sub = accent_sub::BOTH_FLEXIBLE;
        let (mut top, mut bot) = (NodeRef::NULL, NodeRef::NULL);
        let fraction = 0;
        let mut overlay = false;
        if umath {
            let (want_top, want_bot) = if self.scan_keyword("bottom") {
                (false, true)
            } else if self.scan_keyword("both") {
                (true, true)
            } else if self.scan_keyword("overlay") {
                overlay = true;
                (true, false)
            } else {
                let _ = self.scan_keyword("top");
                (true, false)
            };
            if want_top {
                let (k, fixed) = self.scan_accent_char(true);
                top = k;
                if fixed {
                    sub |= accent_sub::FIXED_TOP;
                }
            }
            if want_bot {
                let (k, fixed) = self.scan_accent_char(true);
                bot = k;
                if fixed {
                    sub |= accent_sub::FIXED_BOTTOM;
                }
            }
        } else {
            top = self.scan_accent_char(false).0;
        }
        self.nodes.set_subtype(p, sub);
        if let Some(n) = self.nodes.noad_mut(p) {
            n.accent = top;
            n.bot_accent = bot;
            n.fraction = fraction;
            if overlay {
                n.options |= noad_opt::OVERLAY;
            }
        }
        let st = cramped_style(self.cur_list().math_style);
        self.scan_math(p, Field::Nucleus, st);
    }

    /// `^` and `_` (`sub_sup`); `no_style` is set for `\Unosuperscript`
    /// and `\Unosubscript`.
    fn sub_sup(&mut self, sup: bool, no_style: bool) {
        let field = if sup { Field::Sup } else { Field::Sub };
        let (head, tail) = (self.cur_list().head, self.cur_list().tail);
        let mut target = NodeRef::NULL;
        let mut t_nonempty = false;
        if tail != head && self.nodes.scripts_allowed(tail) {
            target = tail;
            t_nonempty = !self.noad_field(tail, field).is_null();
        }
        if target.is_null() || t_nonempty {
            // Observed: the new noad's nucleus is an empty sub-list.
            let n = self.new_noad(noad_sub::ORD);
            let k = self.new_sub_list(true, NodeRef::NULL);
            self.set_noad_field(n, Field::Nucleus, k);
            self.tail_append(n);
            target = n;
            if t_nonempty {
                if sup {
                    self.print_err("Double superscript");
                    self.help(&["I treat `x^1^2' essentially like `x^1{}^2'."]);
                } else {
                    self.print_err("Double subscript");
                    self.help(&["I treat `x_1_2' essentially like `x_1{}_2'."]);
                }
                self.error();
            }
        }
        let st = self.cur_list().math_style;
        let style = if no_style {
            if let Some(n) = self.nodes.noad_mut(target) {
                n.options |= if sup {
                    noad_opt::NO_SUPER_SCRIPT
                } else {
                    noad_opt::NO_SUB_SCRIPT
                };
            }
            st
        } else if sup {
            sup_style(st)
        } else {
            sub_style(st)
        };
        self.scan_math(target, field, style);
    }

    /// `\over`, `\atop`, `\above` and their variants (`math_fraction`).
    fn math_fraction(&mut self) {
        let c = self.cur_chr;
        // LuaTeX codes: above 0, over 1, atop 2, skewed 3; +4 with delims.
        let delimited = c >= 4;
        let kind = c % 4;
        if !self.cur_list().incompleat_noad.is_null() {
            if delimited {
                let a = self.scan_delimiter(false, false);
                let b = self.scan_delimiter(false, false);
                self.nodes.flush_list(a);
                self.nodes.flush_list(b);
            }
            if kind == 3 {
                let m = self.scan_delimiter(false, false);
                self.nodes.flush_list(m);
                self.scan_fraction_options();
            } else if kind == 0 {
                let _ = self.scan_keyword("exact");
                self.scan_normal_dimen();
            }
            self.print_err("Ambiguous; you need another { and }");
            self.help(&[
                "I'm ignoring this fraction specification, since I don't",
                "know whether a construction like `x \\over y \\over z'",
                "means `{x \\over y} \\over z' or `x \\over {y \\over z}'.",
            ]);
            self.error();
            return;
        }
        let head = self.cur_list().head;
        let first = self.nodes.next(head);
        let num = self.new_sub_list(true, first);
        let mut fr = FractionData {
            thickness: DEFAULT_CODE,
            num,
            denom: NodeRef::NULL,
            left: NodeRef::NULL,
            right: NodeRef::NULL,
            middle: NodeRef::NULL,
            options: 0,
            new_hlist: NodeRef::NULL,
        };
        self.nodes.set_next(head, NodeRef::NULL);
        self.cur_list_mut().tail = head;
        if delimited {
            fr.left = self.scan_delimiter(false, false);
            fr.right = self.scan_delimiter(false, false);
        }
        match kind {
            0 => {
                if self.scan_keyword("exact") {
                    fr.options |= noad_opt::EXACT;
                }
                self.scan_normal_dimen();
                fr.thickness = self.cur_val;
            }
            1 => fr.thickness = DEFAULT_CODE,
            2 => fr.thickness = 0,
            _ => {
                fr.middle = self.scan_delimiter(false, false);
                fr.options |= self.scan_fraction_options();
                fr.thickness = 0;
            }
        }
        let n = self.new_node(id::FRACTION, 0, NodeData::Fraction(Box::new(fr)));
        self.cur_list_mut().incompleat_noad = n;
        // The denominator is read in the cramped style (observed with
        // \mathstyle; in \Ustack this gives the denominator style).
        let st = cramped_style(self.cur_list().math_style);
        self.cur_list_mut().math_style = st;
    }

    /// The `noaxis`/`exact` options of `\Uskewed`.
    fn scan_fraction_options(&mut self) -> u32 {
        let mut o = 0;
        loop {
            if self.scan_keyword("noaxis") {
                o |= noad_opt::NO_AXIS;
            } else if self.scan_keyword("exact") {
                o |= noad_opt::EXACT;
            } else {
                return o;
            }
        }
    }

    /// Finishes the current mlist and pops the nest (`fin_mlist`); `p`, if
    /// not null, is a right (or middle) fence ending the list.
    fn fin_mlist(&mut self, p: NodeRef) -> NodeRef {
        let inc = self.cur_list().incompleat_noad;
        let head = self.cur_list().head;
        let q;
        if !inc.is_null() {
            let first = self.nodes.next(head);
            let denom = self.new_sub_list(true, first);
            if let NodeData::Fraction(f) = self.nodes.data_mut(inc) {
                f.denom = denom;
            }
            if p.is_null() {
                q = inc;
            } else {
                // A \leftโ€ฆ\overโ€ฆ\right: the left fence (and any middle
                // fences up to delim_ptr) stays outside the fraction.
                let num = match self.nodes.data(inc) {
                    NodeData::Fraction(f) => f.num,
                    _ => NodeRef::NULL,
                };
                let num_list = self.nodes.list_ptr_kernel(num);
                q = num_list;
                let dp = self.cur_list().delim_ptr;
                if num_list.is_null() || self.nodes.id(num_list) != id::FENCE || dp.is_null() {
                    self.confusion("right");
                }
                let after = self.nodes.next(dp);
                self.nodes.set_kernel_list(num, after);
                if !after.is_null() {
                    self.nodes.set_prev(after, NodeRef::NULL);
                }
                self.nodes.link(dp, inc);
                self.nodes.link(inc, p);
            }
        } else {
            let tail = self.cur_list().tail;
            self.nodes.link(tail, p);
            q = self.nodes.next(head);
        }
        self.nodes.set_next(head, NodeRef::NULL);
        if !q.is_null() {
            self.nodes.set_prev(q, NodeRef::NULL);
        }
        self.pop_nest();
        q
    }

    /// Right braces ending math groups, `\mathchoice` groups and
    /// `\vcenter` (cases of `handle_right_brace`).
    pub fn math_right_brace(&mut self) {
        match self.save.cur_group {
            GroupCode::Math => {
                self.unsave();
                let r = self.pop_saved();
                let root_follows = r & (1 << 62) != 0;
                let (noad, f) = field_from_ref(r & !(1 << 62));
                let p = self.fin_mlist(NodeRef::NULL);
                let k = self.noad_field(noad, f);
                self.nodes.set_kernel_list(k, p);
                if !p.is_null() && self.nodes.next(p).is_null() {
                    let pid = self.nodes.id(p);
                    // Observed: \mathflattenmode says which single noads
                    // are flattened (1 ord, 2 bin, 4 rel, 8 punct,
                    // 16 inner).
                    let flatten = self.eqtb.int(ip::MATHFLATTENMODE);
                    let bit = match self.nodes.subtype(p) {
                        noad_sub::ORD => 1,
                        noad_sub::BIN => 2,
                        noad_sub::REL => 4,
                        noad_sub::PUNCT => 8,
                        noad_sub::INNER => 16,
                        _ => 0,
                    };
                    if pid == id::NOAD && flatten & bit != 0 {
                        let (sub, sup) = (
                            self.noad_field(p, Field::Sub),
                            self.noad_field(p, Field::Sup),
                        );
                        if sub.is_null() && sup.is_null() {
                            // {x}: the field becomes x's nucleus.
                            let nuc = self.noad_field(p, Field::Nucleus);
                            self.set_noad_field(p, Field::Nucleus, NodeRef::NULL);
                            self.nodes.flush_list(p);
                            self.nodes.set_kernel_list(k, NodeRef::NULL);
                            self.nodes.flush_list(k);
                            self.set_noad_field(noad, f, nuc);
                        }
                    } else if pid == id::ACCENT
                        && f == Field::Nucleus
                        && noad == self.cur_list().tail
                        && self.nodes.id(noad) == id::NOAD
                        && self.nodes.subtype(noad) == noad_sub::ORD
                    {
                        // Replace the tail of the list by the accent noad.
                        let head = self.cur_list().head;
                        let mut q = head;
                        while self.nodes.next(q) != noad {
                            q = self.nodes.next(q);
                        }
                        self.nodes.set_kernel_list(k, NodeRef::NULL);
                        self.nodes.link(q, p);
                        self.nodes.set_next(noad, NodeRef::NULL);
                        self.nodes.flush_list(noad);
                        self.cur_list_mut().tail = p;
                    }
                }
                if root_follows {
                    let st = cramped_style(self.cur_list().math_style);
                    self.scan_math(noad, Field::Nucleus, st);
                }
            }
            GroupCode::MathChoice => self.build_choices(),
            GroupCode::Vcenter => {
                if self.par_token_before_group_end(1) {
                    return;
                }
                self.end_graf();
                self.unsave();
                let (spec, _dir) = self.pop_spec_pub();
                let head = self.cur_list().head;
                let first = self.nodes.next(head);
                self.nodes.set_next(head, NodeRef::NULL);
                let first = self.filter_list("vpack_filter", first, "vcenter");
                let d = self.eqtb.dimen(dp::BOXMAXDEPTH);
                let b = self.vpackage(first, spec, d);
                self.pop_nest();
                let n = self.new_noad(noad_sub::VCENTER);
                let k = self.new_sub_list(false, b);
                self.set_noad_field(n, Field::Nucleus, k);
                self.tail_append(n);
            }
            _ => self.confusion("rightbrace"),
        }
    }

    /// `\mathchoice` (`append_choices`).
    fn append_choices(&mut self) {
        let c = self.new_node(
            id::CHOICE,
            0,
            NodeData::Choice(Box::new([NodeRef::NULL; 4])),
        );
        self.tail_append(c);
        self.push_saved(0);
        self.push_math(GroupCode::MathChoice, 0);
        self.scan_left_brace();
    }

    /// The end of one of the four `\mathchoice` lists (`build_choices`).
    fn build_choices(&mut self) {
        self.unsave();
        let p = self.fin_mlist(NodeRef::NULL);
        let k = self.pop_saved();
        let tail = self.cur_list().tail;
        if let NodeData::Choice(c) = self.nodes.data_mut(tail) {
            c[(k as usize).min(3)] = p;
        }
        if k >= 3 {
            return;
        }
        self.push_saved(k + 1);
        self.push_math(GroupCode::MathChoice, 2 * (k as i32 + 1));
        self.scan_left_brace();
    }

    /// `\left`, `\middle`, `\right` and their `\Uโ€ฆ` forms
    /// (`math_left_right`).
    fn math_left_right(&mut self) {
        let c = self.cur_chr;
        // LuaTeX codes: left 1, middle 2, right 3; \Uleft 11, \Umiddle 12,
        // \Uright 13, \Uvextensible 14.
        if c == 14 {
            self.math_vextensible();
            return;
        }
        let t = match c % 10 {
            1 => fence_sub::LEFT,
            2 => fence_sub::MIDDLE,
            _ => fence_sub::RIGHT,
        };
        if t != fence_sub::LEFT && self.save.cur_group != GroupCode::MathLeft {
            if self.save.cur_group == GroupCode::MathShift {
                // LuaTeX reads the delimiter without checking it.
                self.get_nonblank_nonrelax_noncall();
                if self.cur_cmd == Cmd::DelimNum {
                    if self.cur_chr == 0 {
                        self.scan_twenty_seven_bit_int();
                    } else {
                        self.scan_umath_triple();
                    }
                }
                self.print_err("Extra ");
                if t == fence_sub::MIDDLE {
                    self.print_esc_str("middle");
                    self.help(&["I'm ignoring a \\middle that had no matching \\left."]);
                } else {
                    self.print_esc_str("right");
                    self.help(&["I'm ignoring a \\right that had no matching \\left."]);
                }
                self.error();
            } else {
                self.off_save();
            }
            return;
        }
        let mut fe = FenceData {
            class: -1,
            ..FenceData::default()
        };
        if c >= 10 {
            loop {
                if self.scan_keyword("height") {
                    self.scan_normal_dimen();
                    fe.height = self.cur_val;
                } else if self.scan_keyword("depth") {
                    self.scan_normal_dimen();
                    fe.depth = self.cur_val;
                } else if self.scan_keyword("axis") {
                    fe.options |= noad_opt::AXIS;
                } else if self.scan_keyword("noaxis") {
                    fe.options |= noad_opt::NO_AXIS;
                } else if self.scan_keyword("exact") {
                    fe.options |= noad_opt::EXACT;
                } else if self.scan_keyword("class") {
                    self.scan_int();
                    fe.class = self.cur_val;
                } else {
                    break;
                }
            }
        }
        fe.delim = self.scan_delimiter(false, false);
        let p = self.new_node(id::FENCE, t, NodeData::Fence(Box::new(fe)));
        let q = if t == fence_sub::LEFT {
            p
        } else {
            let q = self.fin_mlist(p);
            self.unsave();
            q
        };
        if t != fence_sub::RIGHT {
            let st = self.cur_list().math_style;
            self.push_math(GroupCode::MathLeft, st);
            let head = self.cur_list().head;
            self.nodes.link(head, q);
            self.cur_list_mut().tail = p;
            self.cur_list_mut().delim_ptr = p;
        } else {
            let n = self.new_noad(noad_sub::INNER);
            let k = self.new_sub_list(true, q);
            self.set_noad_field(n, Field::Nucleus, k);
            self.tail_append(n);
        }
    }

    /// `\Uvextensible`: a stand-alone extensible delimiter.
    fn math_vextensible(&mut self) {
        let mut fe = FenceData {
            class: -1,
            ..FenceData::default()
        };
        loop {
            if self.scan_keyword("height") {
                self.scan_normal_dimen();
                fe.height = self.cur_val;
            } else if self.scan_keyword("depth") {
                self.scan_normal_dimen();
                fe.depth = self.cur_val;
            } else if self.scan_keyword("axis") {
                fe.options |= noad_opt::AXIS;
            } else if self.scan_keyword("noaxis") {
                fe.options |= noad_opt::NO_AXIS;
            } else if self.scan_keyword("exact") {
                fe.options |= noad_opt::EXACT;
            } else {
                break;
            }
        }
        fe.delim = self.scan_delimiter(false, false);
        // Observed: a fence of subtype "no".
        let p = self.new_node(id::FENCE, fence_sub::NO, NodeData::Fence(Box::new(fe)));
        let n = self.new_noad(noad_sub::INNER);
        let k = self.new_sub_list(true, p);
        self.set_noad_field(n, Field::Nucleus, k);
        self.tail_append(n);
    }

    /// `\eqno` and `\leqno` in display math (`start_eq_no`).
    fn start_eq_no(&mut self) {
        self.push_saved(i64::from(self.cur_chr));
        self.go_into_ordinary_math();
    }

    /// Appends a box in math mode as an ord noad with a `sub_box`
    /// nucleus (ยง1076).
    pub fn math_box_end(&mut self, b: NodeRef) {
        let n = self.new_noad(noad_sub::ORD);
        let k = self.new_sub_list(false, b);
        self.set_noad_field(n, Field::Nucleus, k);
        self.tail_append(n);
    }

    /// Mathchars in horizontal mode: LuaTeX typesets the character in the
    /// text font of its family.
    pub fn math_char_in_text(&mut self) {
        let mc = match self.cur_cmd {
            Cmd::MathCharNum => self.scan_math_char_num(),
            Cmd::MathGiven => MathChar::from_given(self.cur_chr),
            _ => MathChar::from_packed(i64::from(self.cur_chr)),
        };
        if mc.class >= 8 {
            self.treat_as_active();
            return;
        }
        let f = self.fam_fnt(mc.fam, 0);
        let g = self.new_char_node(f, mc.chr);
        self.tail_append(g);
        self.cur_list_mut().space_factor = 1000;
    }

    /// The font of family `fam` in size `size` (0 text, 1 script,
    /// 2 scriptscript): `fam_fnt`.
    pub fn fam_fnt(&self, fam: u32, size: u32) -> u32 {
        self.eqtb
            .math_font
            .get((size * crate::eqtb::NUM_FAMILIES as u32 + fam) as usize)
            .map_or(0, |s| s.val)
    }

    // ----- leaving math mode ------------------------------------------

    /// The end of a formula (`after_math`).
    fn after_math(&mut self) {
        let mut m = self.mode;
        let mut l = false;
        let mut p = self.fin_mlist(NodeRef::NULL);
        let a;
        if self.mode == Mode::DisplayMath && m == Mode::Math {
            // The end of an equation number.
            self.check_dollar_follows();
            let hl = self.formula_to_hlist(p, 2, false);
            a = self.hpack(hl, PackSpec::NATURAL);
            self.take_outer_math_dirs();
            self.unsave();
            if self.pop_saved() == 1 {
                l = true;
            }
            m = self.mode;
            p = self.fin_mlist(NodeRef::NULL);
        } else {
            a = NodeRef::NULL;
        }
        if m == Mode::Math {
            self.finish_math_in_text(p);
        } else {
            if a.is_null() {
                self.check_dollar_follows();
            }
            self.finish_displayed_math(p, a, l);
        }
    }

    /// The math and text directions outside the formula whose group is
    /// the current one.
    fn take_outer_math_dirs(&mut self) -> Option<(i32, i32)> {
        let level = self.save.cur_level;
        while let Some(&(l, m, t)) = self.outer_math_dirs.last() {
            if l < level {
                break;
            }
            self.outer_math_dirs.pop();
            if l == level {
                return Some((m, t));
            }
        }
        None
    }

    /// Checks that a second `$` ends a display.
    fn check_dollar_follows(&mut self) {
        self.get_x_token();
        if self.cur_cmd != Cmd::MathShift
            && !(self.cur_cmd == Cmd::MathShiftCs && self.cur_chr == 1)
        {
            self.print_err("Display math should end with $$");
            self.help(&[
                "The `$' that I just saw supposedly matches a previous `$$'.",
                "So I shall assume that you typed `$$' both times.",
            ]);
            self.back_error();
        }
    }

    fn finish_math_in_text(&mut self, p: NodeRef) {
        let ms = self.eqtb.dimen(dp::MATHSURROUND);
        let mg = self
            .eqtb
            .glue(crate::primitives_gen::assign_glue::MATHSURROUNDSKIP);
        let pen = self.mode == Mode::Horizontal;
        // As in TeX, the formula's group ends last: the opening math node
        // is the tail while the mlist_to_hlist callback runs (luamml reads
        // it), and the nodes take the attributes inside the formula.
        // A formula whose direction differs from the text's is wrapped in
        // direction nodes (see `dirs`).
        // The directions are those outside the formula.
        let (math_dir, text_dir) = self.take_outer_math_dirs().unwrap_or((
            self.dir_param(crate::primitives_gen::assign_dir::MATHDIR),
            self.dir_param(crate::primitives_gen::assign_dir::TEXTDIR),
        ));
        let wrap = (math_dir != text_dir).then(|| math_dir.rem_euclid(4) as i8);
        let b = self.new_math_node(ms, mg, 0);
        self.tail_append(b);
        if let Some(d) = wrap {
            let p = self.new_dir_node(d, false);
            self.tail_append(p);
        }
        let hl = self.formula_to_hlist(p, 2, pen);
        let tail = self.cur_list().tail;
        self.nodes.link(tail, hl);
        let mut t = tail;
        while !self.nodes.next(t).is_null() {
            t = self.nodes.next(t);
        }
        self.cur_list_mut().tail = t;
        if let Some(d) = wrap {
            let p = self.new_dir_node(d, true);
            self.tail_append(p);
        }
        let e = self.new_math_node(ms, mg, 1);
        self.tail_append(e);
        self.cur_list_mut().space_factor = 1000;
        self.unsave();
    }

    /// A math node with `\mathsurround` and `\mathsurroundskip`.
    fn new_math_node(&mut self, surround: i32, skip: crate::glue::Glue, sub: u16) -> NodeRef {
        let p = self.new_node(
            id::MATH,
            sub,
            NodeData::Math {
                surround,
                glue: crate::glue::Glue::ZERO,
            },
        );
        if (skip.width != 0 || skip.stretch != 0 || skip.shrink != 0)
            && let NodeData::Math { glue, .. } = self.nodes.data_mut(p)
        {
            *glue = skip;
        }
        p
    }

    /// Places a finished display (ยง1199โ€“ยง1205).
    fn finish_displayed_math(&mut self, p: NodeRef, a: NodeRef, l: bool) {
        use crate::nodes::glue_sub as gs;
        self.take_outer_math_dirs();
        let hl = self.formula_to_hlist(p, 0, false);
        let adj_head = self.nodes.new_temp();
        self.ts.adjust_tail = Some(adj_head);
        let mut b = self.hpack(hl, PackSpec::NATURAL);
        let p = self.nodes.list_ptr(b);
        let t = self.ts.adjust_tail.unwrap_or(adj_head);
        self.ts.adjust_tail = None;
        let mut w = self.nodes.box_data(b).map_or(0, |x| x.width);
        let z = self.eqtb.dimen(dp::DISPLAYWIDTH);
        let s = self.eqtb.dimen(dp::DISPLAYINDENT);
        let (mut e, q) = if a.is_null() {
            (0, 0)
        } else {
            let e = self.nodes.box_data(a).map_or(0, |x| x.width);
            let f2 = self.fam_fnt(2, 0);
            let mq = self.math_quad_text(f2);
            let step = self.eqtb.int(ip::MATHEQNOGAPSTEP);
            let gap = if step == 1000 {
                mq
            } else {
                retex_arith::xn_over_d(mq, step, 1000).map_or(0, |r| r.quotient)
            };
            (e, e + gap)
        };
        if w + q > z {
            // Squeeze the equation as much as possible.
            let tot = self.ts.last_totals;
            if e != 0
                && (w - tot.1[0] + q <= z
                    || tot.1[1] != 0
                    || tot.1[2] != 0
                    || tot.1[3] != 0
                    || tot.1[4] != 0)
            {
                self.nodes.set_list_ptr(b, NodeRef::NULL);
                self.nodes.free(b);
                b = self.hpack(p, PackSpec::Exactly(z - q));
            } else {
                e = 0;
                if w > z {
                    self.nodes.set_list_ptr(b, NodeRef::NULL);
                    self.nodes.free(b);
                    b = self.hpack(p, PackSpec::Exactly(z));
                }
            }
            w = self.nodes.box_data(b).map_or(0, |x| x.width);
        }
        self.nodes.set_subtype(b, 6); // equation
        // The displacement of the left edge of the equation.
        let mut d = half(z - w);
        if e > 0 && d < 2 * e {
            d = half(z - w - e);
            let p = self.nodes.list_ptr(b);
            if !p.is_null() && self.nodes.id(p) == id::GLUE {
                d = 0;
            }
        }
        // The glue or equation number preceding the display.
        let pen = self.new_penalty_node(self.eqtb.int(ip::PREDISPLAYPENALTY));
        self.tail_append(pen);
        let pds = self.eqtb.dimen(dp::PREDISPLAYSIZE);
        let (g1, mut g2) = if d + s <= pds || l {
            (gs::ABOVE_DISPLAY, gs::BELOW_DISPLAY)
        } else {
            (gs::ABOVE_DISPLAY_SHORT, gs::BELOW_DISPLAY_SHORT)
        };
        let mode = self.eqtb.int(ip::MATHDISPLAYSKIPMODE);
        if l && e == 0 {
            if let Some(bd) = self.nodes.box_data_mut(a) {
                bd.shift = s;
            }
            self.nodes.set_subtype(a, 7);
            self.append_to_vlist(a);
            let pen = self.new_penalty_node(10000);
            self.tail_append(pen);
        } else {
            self.append_display_skip(g1, mode, true);
        }
        // The display and perhaps the equation number. LuaTeX packs an
        // equation with its number into a box of the display width:
        // kern d, equation, kern, number (or number, kern, equation,
        // kern d for \leqno), not shifted by d.
        if e != 0 {
            let r = self.new_kern_node(z - w - e - d, 0);
            self.nodes.set_subtype(a, 7);
            // Observed: the kern after a \leqno equation is z - w - d
            // (which makes the line wider than z when d was reduced).
            let k = self.new_kern_node(if l { z - w - d } else { d }, 0);
            if l {
                self.nodes.link(a, r);
                self.nodes.link(r, b);
                self.nodes.link(b, k);
                b = a;
            } else {
                self.nodes.link(k, b);
                self.nodes.link(b, r);
                self.nodes.link(r, a);
                b = k;
            }
            b = self.hpack(b, PackSpec::NATURAL);
            d = 0;
        }
        if let Some(bd) = self.nodes.box_data_mut(b) {
            bd.shift = s + d;
        }
        self.append_to_vlist(b);
        // The glue or equation number following the display.
        if !a.is_null() && e == 0 && !l {
            let pen = self.new_penalty_node(10000);
            self.tail_append(pen);
            let aw = self.nodes.box_data(a).map_or(0, |x| x.width);
            if let Some(bd) = self.nodes.box_data_mut(a) {
                bd.shift = s + z - aw;
            }
            self.nodes.set_subtype(a, 7);
            self.append_to_vlist(a);
            g2 = 0;
        }
        if t != adj_head {
            let first = self.nodes.next(adj_head);
            let tail = self.cur_list().tail;
            self.nodes.link(tail, first);
            self.cur_list_mut().tail = t;
        }
        self.nodes.free(adj_head);
        let pen = self.new_penalty_node(self.eqtb.int(ip::POSTDISPLAYPENALTY));
        self.tail_append(pen);
        if g2 > 0 {
            self.append_display_skip(g2, mode, false);
        }
        self.resume_after_display();
    }

    /// Appends `\abovedisplayskip` and friends, honouring
    /// `\mathdisplayskipmode` (0 and 1: TeX's rule, an above skip always
    /// and a below skip always; 2: only when not zero; 3: never).
    fn append_display_skip(&mut self, sub: u16, mode: i32, _above: bool) {
        let g = self.eqtb.glue(crate::build::glue_param_of_subtype(sub));
        let zero = g.width == 0 && g.stretch == 0 && g.shrink == 0;
        let skip = match mode {
            2 => zero,
            3 => true,
            _ => false,
        };
        if !skip {
            let n = self.new_param_glue(sub);
            self.tail_append(n);
        }
    }

    /// `math_quad(text_size)` from the font in family 2.
    fn math_quad_text(&self, f2: u32) -> i32 {
        let v = self.math_param_value(0, 2);
        if v != crate::codes::UNDEFINED_MATH_PARAM {
            v
        } else {
            self.quad(f2)
        }
    }

    /// The value of math parameter `p` in style `s`.
    pub fn math_param_value(&self, p: u32, s: u32) -> i32 {
        self.eqtb
            .math_param
            .get(&(p * 8 + s))
            .map_or(crate::codes::UNDEFINED_MATH_PARAM, |x| x.val)
    }

    /// Resumes the paragraph after a display (`resume_after_display`).
    fn resume_after_display(&mut self) {
        if self.save.cur_group != GroupCode::MathShift {
            self.confusion("display");
        }
        self.unsave();
        let pg = self.cur_list().prev_graf + 3;
        self.cur_list_mut().prev_graf = pg;
        self.push_nest(Mode::Horizontal);
        self.cur_list_mut().space_factor = 1000;
        let l = self.cur_lang() as i32;
        self.cur_list_mut().clang = l;
        let lp = self.new_local_par();
        self.tail_append(lp);
        // Scan an optional space.
        self.get_x_token();
        if self.cur_cmd != Cmd::Spacer {
            self.back_input();
        }
        if self.nest.len() == 2 {
            self.build_page_from("after_display");
        }
    }

    /// Finishes an alignment in a display (ยง1206).
    pub fn finish_display_alignment(&mut self, p: NodeRef, q: NodeRef, aux_save: i32) {
        self.do_assignments();
        if self.cur_cmd != Cmd::MathShift {
            self.print_err("Missing $$ inserted");
            self.help(&[
                "Displays can use special alignments (like \\eqalignno)",
                "only if nothing but the alignment itself is between $$'s.",
            ]);
            self.back_error();
        } else {
            self.check_dollar_follows();
        }
        self.pop_nest();
        let pen = self.new_penalty_node(self.eqtb.int(ip::PREDISPLAYPENALTY));
        self.tail_append(pen);
        let g = self.new_param_glue(crate::nodes::glue_sub::ABOVE_DISPLAY);
        self.tail_append(g);
        let tail = self.cur_list().tail;
        self.nodes.link(tail, p);
        if !p.is_null() {
            self.cur_list_mut().tail = q;
        }
        let pen = self.new_penalty_node(self.eqtb.int(ip::POSTDISPLAYPENALTY));
        self.tail_append(pen);
        let g = self.new_param_glue(crate::nodes::glue_sub::BELOW_DISPLAY);
        self.tail_append(g);
        self.cur_list_mut().prev_depth = aux_save;
        self.resume_after_display();
    }

    /// Empties the current math list (`flush_math`).
    pub fn flush_math(&mut self) {
        let head = self.cur_list().head;
        let first = self.nodes.next(head);
        self.nodes.flush_list(first);
        let inc = self.cur_list().incompleat_noad;
        self.nodes.flush_list(inc);
        self.nodes.set_next(head, NodeRef::NULL);
        self.cur_list_mut().tail = head;
        self.cur_list_mut().incompleat_noad = NodeRef::NULL;
    }

    /// Inserts the tokens of a list as if typed (used by error recovery).
    pub fn ins_tokens(&mut self, toks: Vec<Token>) {
        self.ins_list(Rc::from(toks));
    }
}

pub use retex_arith::half;

/// The parts of a TeX 27-bit delimiter code.
fn classic_delimiter(v: i32) -> Option<(u32, u32, u32, u32)> {
    if v < 0 {
        return None;
    }
    let v = v as u32;
    Some((
        (v / 0o4000000) % 16,
        (v / 0o10000) % 256,
        (v / 256) % 16,
        v % 256,
    ))
}