latex-rust 3.0.1

Pure-Rust LaTeX math renderer. Parse to AST, TeX-faithful layout on exact rationals, emit SVG, PNG, or egui shapes. No JavaScript, no webview, no runtime.
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
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
//! Typed math AST produced by the parser.

use crate::color::Color;
use crate::dim::Dim;
use crate::parser::group_rules;
use crate::parser::parse::lexicon::is_superscript_char;
use crate::parser::parse::{option_ends_early, paren_script_match, ParseOptions, Stop};
use crate::parser::token::{tokenize, Token};

/// TeX math atom class (Appendix G).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AtomKind {
    /// Ordinary (`x`, `1`, `\alpha` as a letter-like glyph).
    Ord,
    /// Large operator class.
    Op,
    /// Binary operator (`+`, `\times`).
    Bin,
    /// Relation (`=`, `\leq`).
    Rel,
    /// Opening delimiter.
    Open,
    /// Closing delimiter.
    Close,
    /// Punctuation (`,`).
    Punct,
    /// Inner (fraction-like).
    Inner,
}

impl AtomKind {
    fn gold(self) -> &'static str {
        match self {
            Self::Ord => "Ord",
            Self::Op => "Op",
            Self::Bin => "Bin",
            Self::Rel => "Rel",
            Self::Open => "Open",
            Self::Close => "Close",
            Self::Punct => "Punct",
            Self::Inner => "Inner",
        }
    }
}

/// Accent or decoration applied to a nucleus.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccentKind {
    /// `\hat`
    Hat,
    /// `\check`
    Check,
    /// `\breve`
    Breve,
    /// `\acute`
    Acute,
    /// `\grave`
    Grave,
    /// `\tilde`
    Tilde,
    /// `\bar`
    Bar,
    /// `\vec`
    Vec,
    /// `\dot`
    Dot,
    /// `\ddot`
    Ddot,
    /// `\dddot`
    Dddot,
    /// `\ddddot`
    Ddddot,
    /// `\widehat`
    WideHat,
    /// `\widetilde`
    WideTilde,
    /// `\overline`
    Overline,
    /// `\underline`
    Underline,
    /// `\overbrace`
    Overbrace,
    /// `\underbrace`
    Underbrace,
    /// `\overleftarrow`
    Overleftarrow,
    /// `\overrightarrow`
    Overrightarrow,
    /// `\overleftrightarrow`
    Overleftrightarrow,
    /// `\underleftarrow`
    Underleftarrow,
    /// `\underrightarrow`
    Underrightarrow,
    /// `\underleftrightarrow`
    Underleftrightarrow,
    /// `\cancel`
    Cancel,
    /// `\bcancel`
    BCancel,
    /// `\xcancel`
    XCancel,
    /// `\boxed`
    Boxed,
    /// `\mathring`
    Ring,
    /// `\not`
    Not,
}

impl AccentKind {
    pub(crate) fn gold(self) -> &'static str {
        match self {
            Self::Hat => "hat",
            Self::Check => "check",
            Self::Breve => "breve",
            Self::Acute => "acute",
            Self::Grave => "grave",
            Self::Tilde => "tilde",
            Self::Bar => "bar",
            Self::Vec => "vec",
            Self::Dot => "dot",
            Self::Ddot => "ddot",
            Self::Dddot => "dddot",
            Self::Ddddot => "ddddot",
            Self::WideHat => "widehat",
            Self::WideTilde => "widetilde",
            Self::Overline => "overline",
            Self::Underline => "underline",
            Self::Overbrace => "overbrace",
            Self::Underbrace => "underbrace",
            Self::Overleftarrow => "overleftarrow",
            Self::Overrightarrow => "overrightarrow",
            Self::Overleftrightarrow => "overleftrightarrow",
            Self::Underleftarrow => "underleftarrow",
            Self::Underrightarrow => "underrightarrow",
            Self::Underleftrightarrow => "underleftrightarrow",
            Self::Cancel => "cancel",
            Self::BCancel => "bcancel",
            Self::XCancel => "xcancel",
            Self::Boxed => "boxed",
            Self::Ring => "mathring",
            Self::Not => "not",
        }
    }
}

/// Font / text style for a run of characters.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextStyle {
    /// `\mathrm`
    Rm,
    /// `\mathbf`
    Bf,
    /// `\mathit`
    It,
    /// `\mathsf`
    Sf,
    /// `\mathtt`
    Tt,
    /// `\mathbb`
    Bb,
    /// `\mathcal`
    Cal,
    /// `\mathfrak`
    Frak,
    /// `\mathscr`
    Scr,
    /// `\boldsymbol`
    Boldsymbol,
    /// `\pmb`
    Pmb,
    /// `\text`
    Text,
}

impl TextStyle {
    fn gold(self) -> &'static str {
        match self {
            Self::Rm => "rm",
            Self::Bf => "bf",
            Self::It => "it",
            Self::Sf => "sf",
            Self::Tt => "tt",
            Self::Bb => "bb",
            Self::Cal => "cal",
            Self::Frak => "frak",
            Self::Scr => "scr",
            Self::Boldsymbol => "boldsymbol",
            Self::Pmb => "pmb",
            Self::Text => "text",
        }
    }
}

/// One item of a text-mode run (`\text{…}` body).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TextItem {
    /// A maximal run of plain characters (no whitespace).
    Str(String),
    /// Collapsed inter-word space.
    Space,
    /// A `\ ` control space.
    ControlSpace,
    /// A `~` no-break space.
    NoBreakSpace,
    /// A text symbol such as `\ldots`, `\quad`, `\qquad`.
    Symbol(&'static str),
    /// A nested text command with its own style.
    Nested(TextStyle, TextRun),
    /// Math embedded in text with `\(…\)` or `$…$`.
    Math(Box<MathNode>),
}

/// Body of a text-mode command. Adjacent `Str` items are merged, no `Str` is
/// empty, and no `Space` follows a `Space`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TextRun(Vec<TextItem>);

impl TextRun {
    /// Creates a new `TextRun` from a vector of items, enforcing invariants.
    #[must_use]
    pub fn new(items: Vec<TextItem>) -> Self {
        let mut run = Self::default();
        for item in items {
            run.push(item);
        }
        run
    }

    /// Creates a `TextRun` from a plain string, converting spaces to `Space` items.
    #[must_use]
    pub fn plain(s: &str) -> Self {
        let mut run = Self::default();
        for c in s.chars() {
            if c == ' ' {
                run.push(TextItem::Space);
            } else {
                run.push_char(c);
            }
        }
        run
    }

    /// Appends an item to the run, maintaining invariants.
    pub fn push(&mut self, item: TextItem) {
        match (self.0.last_mut(), item) {
            (_, TextItem::Str(s)) if s.is_empty() => {}
            (Some(TextItem::Str(prev)), TextItem::Str(s)) => prev.push_str(&s),
            (Some(TextItem::Space), TextItem::Space) => {}
            (_, item) => self.0.push(item),
        }
    }

    /// Appends a character to the last `Str` item or creates a new one.
    pub fn push_char(&mut self, c: char) {
        if let Some(TextItem::Str(s)) = self.0.last_mut() {
            s.push(c);
        } else {
            self.0.push(TextItem::Str(c.to_string()));
        }
    }

    /// Appends all items from another `TextRun`.
    pub fn append(&mut self, other: TextRun) {
        for item in other.0 {
            self.push(item);
        }
    }

    /// Returns a slice of the items in this run.
    #[must_use]
    pub fn items(&self) -> &[TextItem] {
        &self.0
    }

    /// Checks if the run is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns `Some` only when the run contains exactly one `Str` item.
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self.0.as_slice() {
            [TextItem::Str(s)] => Some(s),
            _ => None,
        }
    }

    /// Converts the run to a plain string representation.
    #[must_use]
    pub fn to_plain_string(&self) -> String {
        let mut result = String::new();
        for item in &self.0 {
            match item {
                TextItem::Str(s) => result.push_str(s),
                TextItem::Space | TextItem::ControlSpace | TextItem::NoBreakSpace => {
                    result.push(' ');
                }
                TextItem::Symbol(name) => {
                    if *name == "ldots" {
                        result.push('\u{2026}');
                    } else {
                        result.push(' ');
                    }
                }
                TextItem::Nested(_, run) => result.push_str(&run.to_plain_string()),
                TextItem::Math(_) => {}
            }
        }
        result
    }
}

/// Horizontal skip.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpaceKind {
    /// `\,`
    Thin,
    /// `\:` or `\>`
    Medium,
    /// `\;`
    Thick,
    /// `\!`
    NegThin,
    /// `\quad`
    Quad,
    /// `\qquad`
    Qquad,
    /// `\ ` (control space)
    ControlSpace,
    /// `\hspace{...}` in em.
    Hspace(Dim),
}

/// Matrix / alignment environment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatrixStyle {
    /// `{matrix}`
    Matrix,
    /// `{pmatrix}`
    Pmatrix,
    /// `{bmatrix}`
    Bmatrix,
    /// `{vmatrix}`
    Vmatrix,
    /// `{Vmatrix}`
    VVmatrix,
    /// `{Bmatrix}`
    BBmatrix,
    /// `{cases}`
    Cases,
    /// `{array}`
    Array,
    /// `{aligned}`
    Aligned,
    /// `{align}`
    Align,
    /// `{gather}`
    Gather,
    /// `{multline}`
    Multline,
    /// `{equation}`
    Equation,
    /// `{split}`
    Split,
}

impl MatrixStyle {
    fn gold(self) -> &'static str {
        match self {
            Self::Matrix => "matrix",
            Self::Pmatrix => "pmatrix",
            Self::Bmatrix => "bmatrix",
            Self::Vmatrix => "vmatrix",
            Self::VVmatrix => "Vmatrix",
            Self::BBmatrix => "Bmatrix",
            Self::Cases => "cases",
            Self::Array => "array",
            Self::Aligned => "aligned",
            Self::Align => "align",
            Self::Gather => "gather",
            Self::Multline => "multline",
            Self::Equation => "equation",
            Self::Split => "split",
        }
    }

    /// `align` / `gather` / `multline` / `equation` take display style and numbers.
    #[must_use]
    pub fn is_display_env(self) -> bool {
        matches!(
            self,
            Self::Align | Self::Gather | Self::Multline | Self::Equation
        )
    }

    /// Rows are numbered unless `\nonumber` / `\notag` / `\tag` says otherwise.
    #[must_use]
    pub fn numbers_rows(self) -> bool {
        matches!(self, Self::Align | Self::Gather)
    }

    /// One equation number for the whole environment (last line for `multline`).
    #[must_use]
    pub fn numbers_once(self) -> bool {
        matches!(self, Self::Equation | Self::Multline)
    }
}

/// One column of an `{array}` preamble (`l`, `c`, `r`, `|`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColSpec {
    /// `l`
    Left,
    /// `c`
    Center,
    /// `r`
    Right,
    /// `|`
    VRule,
}

impl ColSpec {
    fn gold(self) -> char {
        match self {
            Self::Left => 'l',
            Self::Center => 'c',
            Self::Right => 'r',
            Self::VRule => '|',
        }
    }

    /// True for `|`.
    #[must_use]
    pub fn is_rule(self) -> bool {
        matches!(self, Self::VRule)
    }
}

/// Per-row equation number in numbered environments.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EqNumber {
    /// Auto number when the environment numbers rows; none otherwise.
    Default,
    /// `\nonumber` / `\notag`
    Suppress,
    /// `\tag{...}` or `\tag*{...}`
    Tag {
        /// `\tag*` — no parentheses around the tag.
        star: bool,
        /// Tag body (text style at layout).
        body: Box<MathNode>,
    },
}

/// One row of a matrix / alignment environment.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EnvRow {
    /// Alignment cells (`&`-separated).
    Cells {
        /// Column entries.
        cells: Vec<MathNode>,
        /// Number / tag for this row.
        number: EqNumber,
        /// `\label{...}` keys bound to this row's number.
        labels: Vec<String>,
    },
    /// `\hline`
    Hline,
    /// `\intertext{...}`
    Intertext(Box<MathNode>),
}

impl EnvRow {
    /// A data row with default numbering and no labels.
    #[must_use]
    pub fn cells(cells: Vec<MathNode>) -> Self {
        Self::Cells {
            cells,
            number: EqNumber::Default,
            labels: Vec::new(),
        }
    }
}

/// Which integral glyph.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IntegralKind {
    /// `\int`
    Int,
    /// `\iint`
    Iint,
    /// `\iiint`
    Iiint,
    /// `\oint`
    Oint,
    /// `\oiint`
    Oiint,
}

impl IntegralKind {
    fn gold(self) -> &'static str {
        match self {
            Self::Int => "int",
            Self::Iint => "iint",
            Self::Iiint => "iiint",
            Self::Oint => "oint",
            Self::Oiint => "oiint",
        }
    }
}

/// `\phantom` / `\vphantom` / `\hphantom`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PhantomKind {
    /// `\phantom`
    Full,
    /// `\vphantom`
    Vertical,
    /// `\hphantom`
    Horizontal,
}

impl PhantomKind {
    fn gold(self) -> &'static str {
        match self {
            Self::Full => "phantom",
            Self::Vertical => "vphantom",
            Self::Horizontal => "hphantom",
        }
    }
}

/// A `\left` / `\right` delimiter (or `.` for empty).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Delimiter {
    /// `\left.` / `\right.`
    Empty,
    /// Literal character (`(`, `[`, `|`).
    Char(char),
    /// Named delimiter (`langle`, `{` from `\{`).
    Named(String),
}

impl Delimiter {
    fn gold(&self) -> String {
        match self {
            Self::Empty => ".".into(),
            Self::Char(c) => c.to_string(),
            Self::Named(n) => {
                if n == "{" || n == "}" || n == "|" {
                    format!("\\{n}")
                } else {
                    n.clone()
                }
            }
        }
    }
}

/// `\big` / `\Big` / `\bigg` / `\Bigg` (and `l`/`r`/`m` siblings).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DelimSize {
    /// `\big` — about 1.2 em.
    Big,
    /// `\Big` — about 1.8 em.
    Big2,
    /// `\bigg` — about 2.4 em.
    Bigg,
    /// `\Bigg` — about 3.0 em.
    Bigg2,
}

impl DelimSize {
    fn gold(self) -> &'static str {
        match self {
            Self::Big => "big",
            Self::Big2 => "Big",
            Self::Bigg => "bigg",
            Self::Bigg2 => "Bigg",
        }
    }

    /// Map a control sequence to a size. `None` if it is not a `\big` family command.
    #[must_use]
    pub fn from_command(name: &str) -> Option<Self> {
        match name {
            "big" | "bigl" | "bigr" | "bigm" => Some(Self::Big),
            "Big" | "Bigl" | "Bigr" | "Bigm" => Some(Self::Big2),
            "bigg" | "biggl" | "biggr" | "biggm" => Some(Self::Bigg),
            "Bigg" | "Biggl" | "Biggr" | "Biggm" => Some(Self::Bigg2),
            _ => None,
        }
    }

    /// Open / Close / Rel from the `l` / `r` / `m` suffix; `None` for unsuffixed `\big`.
    #[must_use]
    pub fn class_from_command(name: &str) -> Option<AtomKind> {
        if name.ends_with('l') {
            Some(AtomKind::Open)
        } else if name.ends_with('r') {
            Some(AtomKind::Close)
        } else if name.ends_with('m') {
            Some(AtomKind::Rel)
        } else {
            None
        }
    }
}

/// Which command built a [`MathNode::Fraction`].
///
/// `\frac` and `{a \over b}` are [`FracStyle::Frac`]. `\dfrac`, `\tfrac`, and
/// `\cfrac` keep their own style, which layout uses and which [`MathNode::gold`]
/// and [`MathNode::to_latex`] print back.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FracStyle {
    /// `\frac` and infix `\over`.
    Frac,
    /// `\dfrac`. Layout uses display style.
    Dfrac,
    /// `\tfrac`. Layout uses text style.
    Tfrac,
    /// `\cfrac`. Layout uses display style.
    Cfrac,
}

impl FracStyle {
    pub(crate) fn gold(self) -> &'static str {
        match self {
            Self::Frac => "frac",
            Self::Dfrac => "dfrac",
            Self::Tfrac => "tfrac",
            Self::Cfrac => "cfrac",
        }
    }
}

/// Typed math-mode syntax tree.
///
/// Produced by [`crate::parse()`]. [`MathNode::gold`] is the gold-stable debug form.
/// The enum is non-exhaustive so a later release can add a variant. A
/// downstream match needs a wildcard.
///
/// # Examples
///
/// ```
/// use latex_rust::parse;
///
/// let n = parse("x^2").unwrap();
/// assert!(n.gold().contains("sup"));
/// ```
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MathNode {
    /// Single character with a TeX atom class.
    Atom(char, AtomKind),
    /// `\frac` / `\dfrac` / `\tfrac` / `\cfrac` / `{a \over b}`.
    ///
    /// The style is the command. `\over` is [`FracStyle::Frac`].
    Fraction(FracStyle, Box<MathNode>, Box<MathNode>),
    /// `\sqrt` / `\sqrt[n]`. Index `None` is a square root.
    Radical(Option<Box<MathNode>>, Box<MathNode>),
    /// `x^{}`
    Superscript(Box<MathNode>, Box<MathNode>),
    /// `x_{}`
    Subscript(Box<MathNode>, Box<MathNode>),
    /// `x_{}^{}`
    SubSup(Box<MathNode>, Box<MathNode>, Box<MathNode>),
    /// `\left ... \right`
    Delimited(Delimiter, Box<MathNode>, Delimiter),
    /// `\big` / `\Big` / `\bigg` / `\Bigg` (and `l`/`r`/`m` forms).
    SizedDelim(Delimiter, DelimSize, AtomKind),
    /// Horizontal list of nodes.
    Row(Vec<MathNode>),
    /// Matrix or multiline environment. `colspec` is the `{array}` preamble (empty otherwise).
    Matrix(MatrixStyle, Vec<ColSpec>, Vec<EnvRow>),
    /// `\substack{...}` — stacked script-style lines.
    Substack(Vec<MathNode>),
    /// `\ref{key}`
    Ref(String),
    /// `\tag{...}` / `\tag*{...}` (peeled into [`EnvRow`] when inside an environment).
    Tag {
        /// `\tag*`
        star: bool,
        /// Tag body.
        body: Box<MathNode>,
    },
    /// `\label{key}`
    Label(String),
    /// `\nonumber` / `\notag`
    NoNumber,
    /// `\hline` (peeled into [`EnvRow::Hline`] in environments).
    Hline,
    /// `\intertext{...}`
    Intertext(Box<MathNode>),
    /// `\sum` with optional lower / upper limits.
    Sum(Option<Box<MathNode>>, Option<Box<MathNode>>),
    /// `\int` family with optional limits.
    Integral(IntegralKind, Option<Box<MathNode>>, Option<Box<MathNode>>),
    /// `\prod` with optional limits.
    Product(Option<Box<MathNode>>, Option<Box<MathNode>>),
    /// `\lim` with optional subscript.
    Limit(Option<Box<MathNode>>),
    /// `\overset` / `\underset` / `\stackrel` (base, over, under).
    OverUnder(Box<MathNode>, Option<Box<MathNode>>, Option<Box<MathNode>>),
    /// Accent or decoration on a nucleus.
    Accent(Box<MathNode>, AccentKind),
    /// `\cancelto{value}{expr}`
    CancelTo(Box<MathNode>, Box<MathNode>),
    /// Styled character run (`\mathrm`, `\text`, …).
    Text(TextRun, TextStyle),
    /// Explicit math skip.
    Space(SpaceKind),
    /// Named operator (`\sin`). The flag is `\limits` vs `\nolimits`.
    Operator(String, bool),
    /// Named glyph (`\alpha`, `\times`). The string is the control-sequence name.
    Symbol(String),
    /// `\color` applied to a following math list.
    Color(Color, Box<MathNode>),
    /// `\textcolor{...}{...}`
    TextColor(Color, Box<MathNode>),
    /// `\colorbox{...}{...}`
    ColorBox(Color, Box<MathNode>),
    /// `\fcolorbox{border}{fill}{body}`
    FColorBox(Color, Color, Box<MathNode>),
    /// Vertical strut (height, depth) in em.
    Strut(Dim, Dim),
    /// `\phantom` family.
    Phantom(PhantomKind, Box<MathNode>),
}

impl Clone for MathNode {
    fn clone(&self) -> Self {
        clone_node(self)
    }
}

impl Drop for MathNode {
    fn drop(&mut self) {
        // Box drop walks children on the native stack. A 10,000-deep `\left`
        // or `\frac` is a valid tree under a raised `max_depth` and must drop
        // on a 256 KiB thread, so the children move to a heap stack first.
        let mut stack = Vec::new();
        self.drain_children(&mut stack);
        while let Some(mut child) = stack.pop() {
            child.drain_children(&mut stack);
        }
    }
}

fn push_box(out: &mut Vec<MathNode>, slot: &mut Box<MathNode>) {
    out.push(std::mem::replace(slot.as_mut(), MathNode::Hline));
}

fn push_opt(out: &mut Vec<MathNode>, slot: &mut Option<Box<MathNode>>) {
    if let Some(child) = slot.take() {
        out.push(*child);
    }
}

impl MathNode {
    fn drain_children(&mut self, out: &mut Vec<MathNode>) {
        match self {
            Self::Fraction(_, a, b) | Self::Superscript(a, b) | Self::Subscript(a, b) => {
                push_box(out, a);
                push_box(out, b);
            }
            Self::CancelTo(a, b) => {
                push_box(out, a);
                push_box(out, b);
            }
            Self::SubSup(a, b, c) => {
                push_box(out, a);
                push_box(out, b);
                push_box(out, c);
            }
            Self::Radical(index, body) => {
                push_opt(out, index);
                push_box(out, body);
            }
            Self::Delimited(_, body, _) | Self::Intertext(body) => push_box(out, body),
            Self::Row(items) | Self::Substack(items) => out.append(items),
            Self::Matrix(_, _, rows) => {
                for row in rows {
                    row.drain_nodes(out);
                }
            }
            Self::Tag { body, .. } => push_box(out, body),
            Self::Sum(lower, upper) | Self::Product(lower, upper) => {
                push_opt(out, lower);
                push_opt(out, upper);
            }
            Self::Integral(_, lower, upper) => {
                push_opt(out, lower);
                push_opt(out, upper);
            }
            Self::Limit(lower) => push_opt(out, lower),
            Self::OverUnder(base, over, under) => {
                push_box(out, base);
                push_opt(out, over);
                push_opt(out, under);
            }
            Self::Accent(body, _)
            | Self::Color(_, body)
            | Self::TextColor(_, body)
            | Self::ColorBox(_, body)
            | Self::Phantom(_, body) => push_box(out, body),
            Self::FColorBox(_, _, body) => push_box(out, body),
            Self::Atom(_, _)
            | Self::SizedDelim(_, _, _)
            | Self::Ref(_)
            | Self::Label(_)
            | Self::NoNumber
            | Self::Hline
            | Self::Text(_, _)
            | Self::Space(_)
            | Self::Operator(_, _)
            | Self::Symbol(_)
            | Self::Strut(_, _) => {}
        }
    }
}

impl EnvRow {
    fn drain_nodes(&mut self, out: &mut Vec<MathNode>) {
        match self {
            Self::Cells { cells, number, .. } => {
                out.append(cells);
                number.drain_node(out);
            }
            Self::Hline => {}
            Self::Intertext(body) => push_box(out, body),
        }
    }
}

impl EqNumber {
    fn drain_node(&mut self, out: &mut Vec<MathNode>) {
        if let Self::Tag { body, .. } = self {
            push_box(out, body);
        }
    }
}

enum CloneTask<'a> {
    Node(&'a MathNode),
    Finish(Finish),
}

enum Finish {
    Pair(PairKind),
    Radical {
        has_index: bool,
    },
    SubSup,
    Delimited(Delimiter, Delimiter),
    List(ListKind, usize),
    Matrix {
        style: MatrixStyle,
        cols: Vec<ColSpec>,
        rows: Vec<RowPlan>,
    },
    Tag {
        star: bool,
    },
    Limits {
        kind: LimitKind,
        has_lo: bool,
        has_hi: bool,
    },
    Limit {
        has_lo: bool,
    },
    OverUnder {
        has_over: bool,
        has_under: bool,
    },
    Accent(AccentKind),
    Wrap(WrapKind),
    Intertext,
}

enum PairKind {
    Fraction(FracStyle),
    Superscript,
    Subscript,
    CancelTo,
}

enum ListKind {
    Row,
    Substack,
}

enum LimitKind {
    Sum,
    Product,
    Integral(IntegralKind),
}

enum WrapKind {
    Color(Color),
    TextColor(Color),
    ColorBox(Color),
    FColorBox(Color, Color),
    Phantom(PhantomKind),
}

enum RowPlan {
    Hline,
    Intertext,
    Cells {
        n: usize,
        number: NumPlan,
        labels: Vec<String>,
    },
}

enum NumPlan {
    Default,
    Suppress,
    Tag { star: bool },
}

fn clone_node(root: &MathNode) -> MathNode {
    let mut tasks = vec![CloneTask::Node(root)];
    let mut done = Vec::new();
    while let Some(task) = tasks.pop() {
        match task {
            CloneTask::Node(node) => schedule_clone(node, &mut tasks, &mut done),
            CloneTask::Finish(finish) => finish_clone(finish, &mut done),
        }
    }
    done.pop().unwrap_or(MathNode::Hline)
}

fn pop_node(done: &mut Vec<MathNode>) -> MathNode {
    done.pop().unwrap_or(MathNode::Hline)
}

fn schedule_clone<'a>(
    node: &'a MathNode,
    tasks: &mut Vec<CloneTask<'a>>,
    done: &mut Vec<MathNode>,
) {
    match node {
        MathNode::Atom(ch, kind) => done.push(MathNode::Atom(*ch, *kind)),
        MathNode::SizedDelim(delim, size, kind) => {
            done.push(MathNode::SizedDelim(delim.clone(), *size, *kind));
        }
        MathNode::Ref(key) => done.push(MathNode::Ref(key.clone())),
        MathNode::Label(key) => done.push(MathNode::Label(key.clone())),
        MathNode::NoNumber => done.push(MathNode::NoNumber),
        MathNode::Hline => done.push(MathNode::Hline),
        MathNode::Text(text, style) => done.push(MathNode::Text(text.clone(), *style)),
        MathNode::Space(kind) => done.push(MathNode::Space(kind.clone())),
        MathNode::Operator(name, limits) => {
            done.push(MathNode::Operator(name.clone(), *limits));
        }
        MathNode::Symbol(name) => done.push(MathNode::Symbol(name.clone())),
        MathNode::Strut(height, depth) => {
            done.push(MathNode::Strut(height.clone(), depth.clone()));
        }
        MathNode::Fraction(style, a, b) => {
            tasks.push(CloneTask::Finish(Finish::Pair(PairKind::Fraction(*style))));
            tasks.push(CloneTask::Node(b));
            tasks.push(CloneTask::Node(a));
        }
        MathNode::Superscript(a, b) => {
            tasks.push(CloneTask::Finish(Finish::Pair(PairKind::Superscript)));
            tasks.push(CloneTask::Node(b));
            tasks.push(CloneTask::Node(a));
        }
        MathNode::Subscript(a, b) => {
            tasks.push(CloneTask::Finish(Finish::Pair(PairKind::Subscript)));
            tasks.push(CloneTask::Node(b));
            tasks.push(CloneTask::Node(a));
        }
        MathNode::CancelTo(a, b) => {
            tasks.push(CloneTask::Finish(Finish::Pair(PairKind::CancelTo)));
            tasks.push(CloneTask::Node(b));
            tasks.push(CloneTask::Node(a));
        }
        MathNode::SubSup(a, b, c) => {
            tasks.push(CloneTask::Finish(Finish::SubSup));
            tasks.push(CloneTask::Node(c));
            tasks.push(CloneTask::Node(b));
            tasks.push(CloneTask::Node(a));
        }
        MathNode::Radical(index, body) => {
            tasks.push(CloneTask::Finish(Finish::Radical {
                has_index: index.is_some(),
            }));
            tasks.push(CloneTask::Node(body));
            if let Some(index) = index {
                tasks.push(CloneTask::Node(index));
            }
        }
        MathNode::Delimited(left, body, right) => {
            tasks.push(CloneTask::Finish(Finish::Delimited(
                left.clone(),
                right.clone(),
            )));
            tasks.push(CloneTask::Node(body));
        }
        MathNode::Row(items) => {
            tasks.push(CloneTask::Finish(Finish::List(ListKind::Row, items.len())));
            for item in items.iter().rev() {
                tasks.push(CloneTask::Node(item));
            }
        }
        MathNode::Substack(items) => {
            tasks.push(CloneTask::Finish(Finish::List(
                ListKind::Substack,
                items.len(),
            )));
            for item in items.iter().rev() {
                tasks.push(CloneTask::Node(item));
            }
        }
        MathNode::Matrix(style, cols, rows) => schedule_matrix(*style, cols, rows, tasks),
        MathNode::Tag { star, body } => {
            tasks.push(CloneTask::Finish(Finish::Tag { star: *star }));
            tasks.push(CloneTask::Node(body));
        }
        MathNode::Sum(lower, upper) => {
            schedule_limits(LimitKind::Sum, lower, upper, tasks);
        }
        MathNode::Product(lower, upper) => {
            schedule_limits(LimitKind::Product, lower, upper, tasks);
        }
        MathNode::Integral(kind, lower, upper) => {
            schedule_limits(LimitKind::Integral(*kind), lower, upper, tasks);
        }
        MathNode::Limit(lower) => {
            tasks.push(CloneTask::Finish(Finish::Limit {
                has_lo: lower.is_some(),
            }));
            if let Some(lower) = lower {
                tasks.push(CloneTask::Node(lower));
            }
        }
        MathNode::OverUnder(base, over, under) => {
            tasks.push(CloneTask::Finish(Finish::OverUnder {
                has_over: over.is_some(),
                has_under: under.is_some(),
            }));
            if let Some(under) = under {
                tasks.push(CloneTask::Node(under));
            }
            if let Some(over) = over {
                tasks.push(CloneTask::Node(over));
            }
            tasks.push(CloneTask::Node(base));
        }
        MathNode::Accent(body, kind) => {
            tasks.push(CloneTask::Finish(Finish::Accent(*kind)));
            tasks.push(CloneTask::Node(body));
        }
        MathNode::Color(color, body) => {
            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::Color(*color))));
            tasks.push(CloneTask::Node(body));
        }
        MathNode::TextColor(color, body) => {
            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::TextColor(*color))));
            tasks.push(CloneTask::Node(body));
        }
        MathNode::ColorBox(color, body) => {
            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::ColorBox(*color))));
            tasks.push(CloneTask::Node(body));
        }
        MathNode::FColorBox(border, fill, body) => {
            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::FColorBox(
                *border, *fill,
            ))));
            tasks.push(CloneTask::Node(body));
        }
        MathNode::Phantom(kind, body) => {
            tasks.push(CloneTask::Finish(Finish::Wrap(WrapKind::Phantom(*kind))));
            tasks.push(CloneTask::Node(body));
        }
        MathNode::Intertext(body) => {
            tasks.push(CloneTask::Finish(Finish::Intertext));
            tasks.push(CloneTask::Node(body));
        }
    }
}

fn schedule_limits<'a>(
    kind: LimitKind,
    lower: &'a Option<Box<MathNode>>,
    upper: &'a Option<Box<MathNode>>,
    tasks: &mut Vec<CloneTask<'a>>,
) {
    tasks.push(CloneTask::Finish(Finish::Limits {
        kind,
        has_lo: lower.is_some(),
        has_hi: upper.is_some(),
    }));
    if let Some(upper) = upper {
        tasks.push(CloneTask::Node(upper));
    }
    if let Some(lower) = lower {
        tasks.push(CloneTask::Node(lower));
    }
}

fn schedule_matrix<'a>(
    style: MatrixStyle,
    cols: &[ColSpec],
    rows: &'a [EnvRow],
    tasks: &mut Vec<CloneTask<'a>>,
) {
    let mut plan = Vec::with_capacity(rows.len());
    let mut kids = Vec::new();
    for row in rows {
        match row {
            EnvRow::Hline => plan.push(RowPlan::Hline),
            EnvRow::Intertext(body) => {
                plan.push(RowPlan::Intertext);
                kids.push(body.as_ref());
            }
            EnvRow::Cells {
                cells,
                number,
                labels,
            } => {
                let num = match number {
                    EqNumber::Default => NumPlan::Default,
                    EqNumber::Suppress => NumPlan::Suppress,
                    EqNumber::Tag { star, .. } => NumPlan::Tag { star: *star },
                };
                plan.push(RowPlan::Cells {
                    n: cells.len(),
                    number: num,
                    labels: labels.clone(),
                });
                for cell in cells {
                    kids.push(cell);
                }
                if let EqNumber::Tag { body, .. } = number {
                    kids.push(body);
                }
            }
        }
    }
    tasks.push(CloneTask::Finish(Finish::Matrix {
        style,
        cols: cols.to_vec(),
        rows: plan,
    }));
    for kid in kids.into_iter().rev() {
        tasks.push(CloneTask::Node(kid));
    }
}

fn finish_clone(finish: Finish, done: &mut Vec<MathNode>) {
    match finish {
        Finish::Pair(kind) => {
            let b = Box::new(pop_node(done));
            let a = Box::new(pop_node(done));
            done.push(match kind {
                PairKind::Fraction(style) => MathNode::Fraction(style, a, b),
                PairKind::Superscript => MathNode::Superscript(a, b),
                PairKind::Subscript => MathNode::Subscript(a, b),
                PairKind::CancelTo => MathNode::CancelTo(a, b),
            });
        }
        Finish::SubSup => {
            let c = Box::new(pop_node(done));
            let b = Box::new(pop_node(done));
            let a = Box::new(pop_node(done));
            done.push(MathNode::SubSup(a, b, c));
        }
        Finish::Radical { has_index } => {
            let body = Box::new(pop_node(done));
            let index = if has_index {
                Some(Box::new(pop_node(done)))
            } else {
                None
            };
            done.push(MathNode::Radical(index, body));
        }
        Finish::Delimited(left, right) => {
            let body = Box::new(pop_node(done));
            done.push(MathNode::Delimited(left, body, right));
        }
        Finish::List(kind, n) => {
            let start = done.len().saturating_sub(n);
            let items = done.split_off(start);
            done.push(match kind {
                ListKind::Row => MathNode::Row(items),
                ListKind::Substack => MathNode::Substack(items),
            });
        }
        Finish::Tag { star } => {
            let body = Box::new(pop_node(done));
            done.push(MathNode::Tag { star, body });
        }
        Finish::Limits {
            kind,
            has_lo,
            has_hi,
        } => {
            let upper = if has_hi {
                Some(Box::new(pop_node(done)))
            } else {
                None
            };
            let lower = if has_lo {
                Some(Box::new(pop_node(done)))
            } else {
                None
            };
            done.push(match kind {
                LimitKind::Sum => MathNode::Sum(lower, upper),
                LimitKind::Product => MathNode::Product(lower, upper),
                LimitKind::Integral(integral) => MathNode::Integral(integral, lower, upper),
            });
        }
        Finish::Limit { has_lo } => {
            let lower = if has_lo {
                Some(Box::new(pop_node(done)))
            } else {
                None
            };
            done.push(MathNode::Limit(lower));
        }
        Finish::OverUnder {
            has_over,
            has_under,
        } => {
            let under = if has_under {
                Some(Box::new(pop_node(done)))
            } else {
                None
            };
            let over = if has_over {
                Some(Box::new(pop_node(done)))
            } else {
                None
            };
            let base = Box::new(pop_node(done));
            done.push(MathNode::OverUnder(base, over, under));
        }
        Finish::Accent(kind) => {
            let body = Box::new(pop_node(done));
            done.push(MathNode::Accent(body, kind));
        }
        Finish::Wrap(kind) => {
            let body = Box::new(pop_node(done));
            done.push(match kind {
                WrapKind::Color(color) => MathNode::Color(color, body),
                WrapKind::TextColor(color) => MathNode::TextColor(color, body),
                WrapKind::ColorBox(color) => MathNode::ColorBox(color, body),
                WrapKind::FColorBox(border, fill) => MathNode::FColorBox(border, fill, body),
                WrapKind::Phantom(phantom) => MathNode::Phantom(phantom, body),
            });
        }
        Finish::Intertext => {
            let body = Box::new(pop_node(done));
            done.push(MathNode::Intertext(body));
        }
        Finish::Matrix { style, cols, rows } => {
            let n = matrix_child_count(&rows);
            let start = done.len().saturating_sub(n);
            let kids = done.split_off(start);
            let mut kids = kids.into_iter();
            let mut built = Vec::with_capacity(rows.len());
            for row in rows {
                built.push(match row {
                    RowPlan::Hline => EnvRow::Hline,
                    RowPlan::Intertext => {
                        EnvRow::Intertext(Box::new(kids.next().unwrap_or(MathNode::Hline)))
                    }
                    RowPlan::Cells { n, number, labels } => {
                        let mut cells = Vec::with_capacity(n);
                        for _ in 0..n {
                            cells.push(kids.next().unwrap_or(MathNode::Hline));
                        }
                        let number = match number {
                            NumPlan::Default => EqNumber::Default,
                            NumPlan::Suppress => EqNumber::Suppress,
                            NumPlan::Tag { star } => EqNumber::Tag {
                                star,
                                body: Box::new(kids.next().unwrap_or(MathNode::Hline)),
                            },
                        };
                        EnvRow::Cells {
                            cells,
                            number,
                            labels,
                        }
                    }
                });
            }
            done.push(MathNode::Matrix(style, cols, built));
        }
    }
}

fn matrix_child_count(rows: &[RowPlan]) -> usize {
    let mut n = 0usize;
    for row in rows {
        match row {
            RowPlan::Hline => {}
            RowPlan::Intertext => n = n.saturating_add(1),
            RowPlan::Cells {
                n: cells, number, ..
            } => {
                n = n.saturating_add(*cells);
                if matches!(number, NumPlan::Tag { .. }) {
                    n = n.saturating_add(1);
                }
            }
        }
    }
    n
}

impl MathNode {
    /// Gold-stable S-expression. One space between items; no trailing space.
    ///
    /// The walk is an explicit heap stack, so a tree `parse` accepted cannot
    /// overflow the caller's stack here.
    #[must_use]
    pub fn gold(&self) -> String {
        let mut stack = vec![GoldOp::Node(self)];
        let mut out = String::new();
        while let Some(op) = stack.pop() {
            match op {
                GoldOp::Text(text) => out.push_str(&text),
                GoldOp::Node(node) => {
                    let mut forward = Vec::new();
                    gold_expand(node, &mut forward);
                    for op in forward.into_iter().rev() {
                        stack.push(op);
                    }
                }
            }
        }
        out
    }

    /// LaTeX reprint of this tree.
    ///
    /// The method is total: every node prints, and it does not return
    /// [`Err`](crate::Error) or panic. Braces and spaces may differ from the
    /// source that built the tree, so compare trees, then compare a reprint
    /// to a reprint. It is not a byte-preserving formatter.
    ///
    /// Braces follow one rule based on the parser's grouping rules
    /// (documents/TEXT_MODE_SPEC.md section 5), and a reprint never nests
    /// deeper than any source of the same tree. Command arguments always
    /// print braced (`\frac {1}{2}`). A script argument that is a single
    /// nucleus prints bare (`x_a`), a row is one group, and an empty
    /// argument is `{}`. Row items print bare unless one would change
    /// meaning: a nested row, a superscript character, or a `)` that the
    /// parser's paren lookahead would pair with an earlier `(`. Superscript
    /// primes print as `'` marks. An alphabetic control word is followed by
    /// a space, so `\sin x` does not become `\sinx`, and two bare letters
    /// are split by a space. `\overline` is that full command.
    ///
    /// A [`MathNode::Fraction`] prints as the command in its [`FracStyle`].
    /// `\over` is stored as [`FracStyle::Frac`], so it prints as `\frac`;
    /// `\choose` and `\binom` print as `\binom`.
    ///
    /// A [`MathNode::Color`] is its own group. A color nested in a row
    /// therefore does not swallow the nodes that follow it.
    #[must_use]
    pub fn to_latex(&self) -> String {
        self.to_latex_with(&ParseOptions::new())
    }

    /// [`to_latex`](Self::to_latex) for a tree that will be read back with
    /// `options`. Only [`ParseOptions::prime_symbol`] changes the output:
    /// with it on, `'` reads back as `\prime`, so a `′` superscript prints
    /// as `^{′}` instead of a `'` mark.
    #[must_use]
    pub fn to_latex_with(&self, options: &ParseOptions) -> String {
        let mut out = self.print_raw(options.prime_symbol);
        // The parser strips `\(…\)` and `\[…\]` fences around the whole
        // input and rejects an unclosed one, so a print that only starts
        // with `\(` or `\[` is one group. A print that starts or ends with a
        // whitespace atom the tokenizer does not skip (U+00A0, U+2007, `\x0b`;
        // a comment hid it from the `preprocess` trim) is one group too, so
        // the braces are its ends. A space, tab or newline is not an atom:
        // `<`, `>` and `!` print with a trailing space the tokenizer skips.
        let fenced = ["\\(", "\\["]
            .iter()
            .any(|open| out.starts_with(open) && out.len() > open.len());
        let trimmed = |c: Option<char>| {
            c.is_some_and(|c| c.is_whitespace() && !matches!(c, ' ' | '\t' | '\n' | '\r'))
        };
        if fenced || trimmed(out.chars().next()) || trimmed(out.chars().next_back()) {
            out.insert(0, '{');
            out.push('}');
        }
        out
    }

    /// The print of `self` as it is written inside a larger print: no group
    /// is added around a leading `\(` or `\[`.
    fn print_raw(&self, literal_primes: bool) -> String {
        let mut buf = LatexBuf::new(literal_primes);
        let mut stack = vec![LatexOp::Node(self)];
        while let Some(op) = stack.pop() {
            match op {
                LatexOp::Text(text) => buf.out.push_str(&text),
                LatexOp::Node(node) => {
                    let mut forward = LatexBuf::new(buf.literal_primes);
                    write_node(&mut forward, node);
                    for op in forward.ops.into_iter().rev() {
                        stack.push(op);
                    }
                }
            }
        }
        buf.out
    }
}

enum LatexOp<'a> {
    Node(&'a MathNode),
    Text(String),
}

struct LatexBuf<'a> {
    ops: Vec<LatexOp<'a>>,
    out: String,
    /// A `′` superscript prints as `^{′}`, not as `'` marks.
    literal_primes: bool,
}

impl<'a> LatexBuf<'a> {
    fn new(literal_primes: bool) -> Self {
        Self {
            ops: Vec::new(),
            out: String::new(),
            literal_primes,
        }
    }

    fn push_str(&mut self, text: &str) {
        if let Some(LatexOp::Text(prev)) = self.ops.last_mut() {
            prev.push_str(text);
            return;
        }
        self.ops.push(LatexOp::Text(text.to_string()));
    }

    fn push(&mut self, c: char) {
        if let Some(LatexOp::Text(prev)) = self.ops.last_mut() {
            prev.push(c);
            return;
        }
        self.ops.push(LatexOp::Text(c.to_string()));
    }

    fn node(&mut self, node: &'a MathNode) {
        self.ops.push(LatexOp::Node(node));
    }
}

enum GoldOp<'a> {
    Node(&'a MathNode),
    Text(String),
}

fn gold_text(buf: &mut Vec<GoldOp<'_>>, text: impl Into<String>) {
    buf.push(GoldOp::Text(text.into()));
}

fn gold_node<'a>(buf: &mut Vec<GoldOp<'a>>, node: &'a MathNode) {
    buf.push(GoldOp::Node(node));
}

fn gold_opt<'a>(buf: &mut Vec<GoldOp<'a>>, node: &'a Option<Box<MathNode>>) {
    match node {
        None => gold_text(buf, "_"),
        Some(node) => gold_node(buf, node),
    }
}

fn gold_expand<'a>(node: &'a MathNode, buf: &mut Vec<GoldOp<'a>>) {
    match node {
        MathNode::Atom(c, k) => gold_text(buf, format!("(atom {} {})", k.gold(), quote_atom(*c))),
        MathNode::Fraction(style, n, d) => {
            gold_text(buf, format!("({} ", style.gold()));
            gold_node(buf, n);
            gold_text(buf, " ");
            gold_node(buf, d);
            gold_text(buf, ")");
        }
        MathNode::Radical(None, r) => {
            gold_text(buf, "(sqrt ");
            gold_node(buf, r);
            gold_text(buf, ")");
        }
        MathNode::Radical(Some(i), r) => {
            gold_text(buf, "(sqrtn ");
            gold_node(buf, i);
            gold_text(buf, " ");
            gold_node(buf, r);
            gold_text(buf, ")");
        }
        MathNode::Superscript(b, e) => {
            gold_text(buf, "(sup ");
            gold_node(buf, b);
            gold_text(buf, " ");
            gold_node(buf, e);
            gold_text(buf, ")");
        }
        MathNode::Subscript(b, s) => {
            gold_text(buf, "(sub ");
            gold_node(buf, b);
            gold_text(buf, " ");
            gold_node(buf, s);
            gold_text(buf, ")");
        }
        MathNode::SubSup(b, s, e) => {
            gold_text(buf, "(subsup ");
            gold_node(buf, b);
            gold_text(buf, " ");
            gold_node(buf, s);
            gold_text(buf, " ");
            gold_node(buf, e);
            gold_text(buf, ")");
        }
        MathNode::Delimited(l, b, r) => {
            gold_text(buf, format!("(delim {} ", l.gold()));
            gold_node(buf, b);
            gold_text(buf, format!(" {})", r.gold()));
        }
        MathNode::SizedDelim(d, sz, k) => {
            gold_text(
                buf,
                format!("(big {} {} {})", sz.gold(), k.gold(), quote_delim(d)),
            );
        }
        MathNode::Row(items) => {
            if items.is_empty() {
                gold_text(buf, "(row)");
            } else {
                gold_text(buf, "(row");
                for it in items {
                    gold_text(buf, " ");
                    gold_node(buf, it);
                }
                gold_text(buf, ")");
            }
        }
        MathNode::Matrix(style, spec, rows) => {
            let mut head = format!("(matrix {}", style.gold());
            if !spec.is_empty() {
                head.push(' ');
                for c in spec {
                    head.push(c.gold());
                }
            }
            gold_text(buf, head);
            for row in rows {
                gold_text(buf, " ");
                gold_row(buf, row);
            }
            gold_text(buf, ")");
        }
        MathNode::Substack(lines) => {
            gold_text(buf, "(substack");
            for ln in lines {
                gold_text(buf, " ");
                gold_node(buf, ln);
            }
            gold_text(buf, ")");
        }
        MathNode::Ref(k) => gold_text(buf, format!("(ref {k})")),
        MathNode::Tag { star: false, body } => {
            gold_text(buf, "(tag ");
            gold_node(buf, body);
            gold_text(buf, ")");
        }
        MathNode::Tag { star: true, body } => {
            gold_text(buf, "(tagstar ");
            gold_node(buf, body);
            gold_text(buf, ")");
        }
        MathNode::Label(k) => gold_text(buf, format!("(label {k})")),
        MathNode::NoNumber => gold_text(buf, "(nonumber)"),
        MathNode::Hline => gold_text(buf, "(hline)"),
        MathNode::Intertext(n) => {
            gold_text(buf, "(intertext ");
            gold_node(buf, n);
            gold_text(buf, ")");
        }
        MathNode::Sum(lo, hi) => {
            gold_text(buf, "(sum ");
            gold_opt(buf, lo);
            gold_text(buf, " ");
            gold_opt(buf, hi);
            gold_text(buf, ")");
        }
        MathNode::Integral(k, lo, hi) => {
            gold_text(buf, format!("({} ", k.gold()));
            gold_opt(buf, lo);
            gold_text(buf, " ");
            gold_opt(buf, hi);
            gold_text(buf, ")");
        }
        MathNode::Product(lo, hi) => {
            gold_text(buf, "(prod ");
            gold_opt(buf, lo);
            gold_text(buf, " ");
            gold_opt(buf, hi);
            gold_text(buf, ")");
        }
        MathNode::Limit(lo) => {
            gold_text(buf, "(lim ");
            gold_opt(buf, lo);
            gold_text(buf, ")");
        }
        MathNode::OverUnder(b, over, under) => {
            gold_text(buf, "(overunder ");
            gold_node(buf, b);
            gold_text(buf, " ");
            gold_opt(buf, over);
            gold_text(buf, " ");
            gold_opt(buf, under);
            gold_text(buf, ")");
        }
        MathNode::Accent(b, a) => {
            gold_text(buf, format!("(accent {} ", a.gold()));
            gold_node(buf, b);
            gold_text(buf, ")");
        }
        MathNode::CancelTo(v, e) => {
            gold_text(buf, "(cancelto ");
            gold_node(buf, v);
            gold_text(buf, " ");
            gold_node(buf, e);
            gold_text(buf, ")");
        }
        MathNode::Text(t, st) => {
            let plain = t
                .items()
                .iter()
                .all(|item| matches!(item, TextItem::Str(_) | TextItem::Space));
            if plain {
                gold_text(
                    buf,
                    format!("(text {} {})", st.gold(), quote_text(&t.to_plain_string())),
                );
            } else {
                gold_text(buf, format!("(text {} ", st.gold()));
                gold_run(buf, t);
                gold_text(buf, ")");
            }
        }
        MathNode::Space(SpaceKind::Thin) => gold_text(buf, "(space thin)"),
        MathNode::Space(SpaceKind::Medium) => gold_text(buf, "(space medium)"),
        MathNode::Space(SpaceKind::Thick) => gold_text(buf, "(space thick)"),
        MathNode::Space(SpaceKind::NegThin) => gold_text(buf, "(space negthin)"),
        MathNode::Space(SpaceKind::Quad) => gold_text(buf, "(space quad)"),
        MathNode::Space(SpaceKind::Qquad) => gold_text(buf, "(space qquad)"),
        MathNode::Space(SpaceKind::ControlSpace) => gold_text(buf, "(space control)"),
        MathNode::Space(SpaceKind::Hspace(d)) => {
            gold_text(buf, format!("(space hspace {})", dim_gold(d)));
        }
        MathNode::Operator(name, false) => gold_text(buf, format!("(op {name})")),
        MathNode::Operator(name, true) => gold_text(buf, format!("(op {name} limits)")),
        MathNode::Symbol(name) => gold_text(buf, format!("(symbol {name})")),
        MathNode::Color(c, b) => {
            gold_text(buf, format!("(color {} ", c.css_hex()));
            gold_node(buf, b);
            gold_text(buf, ")");
        }
        MathNode::TextColor(c, b) => {
            gold_text(buf, format!("(textcolor {} ", c.css_hex()));
            gold_node(buf, b);
            gold_text(buf, ")");
        }
        MathNode::ColorBox(c, b) => {
            gold_text(buf, format!("(colorbox {} ", c.css_hex()));
            gold_node(buf, b);
            gold_text(buf, ")");
        }
        MathNode::FColorBox(border, fill, b) => {
            gold_text(
                buf,
                format!("(fcolorbox {} {} ", border.css_hex(), fill.css_hex()),
            );
            gold_node(buf, b);
            gold_text(buf, ")");
        }
        MathNode::Strut(h, d) => {
            gold_text(buf, format!("(strut {} {})", dim_gold(h), dim_gold(d)));
        }
        MathNode::Phantom(k, b) => {
            gold_text(buf, format!("({} ", k.gold()));
            gold_node(buf, b);
            gold_text(buf, ")");
        }
    }
}

fn gold_row<'a>(buf: &mut Vec<GoldOp<'a>>, row: &'a EnvRow) {
    match row {
        EnvRow::Hline => gold_text(buf, "(hline)"),
        EnvRow::Intertext(n) => {
            gold_text(buf, "(intertext ");
            gold_node(buf, n);
            gold_text(buf, ")");
        }
        EnvRow::Cells {
            cells,
            number,
            labels,
        } => {
            gold_text(buf, "(");
            for (i, cell) in cells.iter().enumerate() {
                if i > 0 {
                    gold_text(buf, " ");
                }
                gold_node(buf, cell);
            }
            match number {
                EqNumber::Default => {}
                EqNumber::Suppress => gold_text(buf, " (nonumber)"),
                EqNumber::Tag { star: false, body } => {
                    gold_text(buf, " (tag ");
                    gold_node(buf, body);
                    gold_text(buf, ")");
                }
                EqNumber::Tag { star: true, body } => {
                    gold_text(buf, " (tagstar ");
                    gold_node(buf, body);
                    gold_text(buf, ")");
                }
            }
            for lab in labels {
                gold_text(buf, format!(" (label {lab})"));
            }
            gold_text(buf, ")");
        }
    }
}

fn quote_delim(d: &Delimiter) -> String {
    match d {
        Delimiter::Empty => ".".into(),
        Delimiter::Char(c) => quote_atom(*c),
        Delimiter::Named(n) => n.clone(),
    }
}

fn quote_atom(c: char) -> String {
    match c {
        '"' => "'\"'".into(),
        '\'' => "\"'\"".into(),
        _ => format!("\"{c}\""),
    }
}

/// `(run item…)` for a text run that is not plain characters and spaces.
fn gold_run<'a>(buf: &mut Vec<GoldOp<'a>>, run: &'a TextRun) {
    gold_text(buf, "(run");
    for item in run.items() {
        match item {
            TextItem::Str(s) => gold_text(buf, format!(" {}", quote_text(s))),
            TextItem::Space => gold_text(buf, " space"),
            TextItem::ControlSpace => gold_text(buf, " ctrlspace"),
            TextItem::NoBreakSpace => gold_text(buf, " nbsp"),
            TextItem::Symbol(n) => gold_text(buf, format!(" (symbol {n})")),
            TextItem::Nested(st, r) => {
                gold_text(buf, format!(" (nested {} ", st.gold()));
                gold_run(buf, r);
                gold_text(buf, ")");
            }
            TextItem::Math(m) => {
                gold_text(buf, " (math ");
                gold_node(buf, m);
                gold_text(buf, ")");
            }
        }
    }
    gold_text(buf, ")");
}

fn quote_text(t: &str) -> String {
    format!("\"{}\"", t.replace('\\', "\\\\").replace('"', "\\\""))
}

fn dim_gold(d: &Dim) -> String {
    const RATIOS: [(i64, i64); 10] = [
        (0, 1),
        (1, 1),
        (2, 1),
        (1, 2),
        (1, 18),
        (2, 18),
        (3, 18),
        (7, 10),
        (3, 10),
        (1, 10),
    ];
    for (n, den) in RATIOS {
        if d.eq_dim(&Dim::ratio(n, den)) {
            if den == 1 {
                return n.to_string();
            }
            return format!("{n}/{den}");
        }
    }
    for i in -64i64..65 {
        if d.eq_dim(&Dim::from_i64(i)) {
            return i.to_string();
        }
    }
    d.to_dec_string()
}

fn write_node<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
    match node {
        MathNode::Atom(c, _) => write_atom(out, *c),
        MathNode::Fraction(style, num, den) => {
            write_cmd(out, style.gold());
            write_arg(out, num);
            write_arg(out, den);
        }
        MathNode::Radical(index, body) => {
            write_cmd(out, "sqrt");
            if let Some(index) = index {
                write_option(out, index);
            }
            write_arg_after_option(out, body);
        }
        MathNode::Superscript(base, sup) => write_scripts(out, base, None, Some(sup)),
        MathNode::Subscript(base, sub) => write_scripts(out, base, Some(sub), None),
        MathNode::SubSup(base, sub, sup) => write_scripts(out, base, Some(sub), Some(sup)),
        MathNode::Delimited(open, body, close) => {
            // `\binom` parses to this tree and costs one level less.
            if let (
                Delimiter::Char('('),
                Delimiter::Char(')'),
                MathNode::Fraction(FracStyle::Frac, n, d),
            ) = (open, close, body.as_ref())
            {
                write_cmd(out, "binom");
                write_arg(out, n);
                write_arg(out, d);
            } else {
                write_cmd(out, "left");
                write_delim(out, open);
                out.node(body);
                write_cmd(out, "right");
                write_delim(out, close);
            }
        }
        MathNode::SizedDelim(delim, size, kind) => {
            out.push('\\');
            out.push_str(size.gold());
            out.push_str(sized_suffix(*kind, delim));
            out.push(' ');
            write_delim(out, delim);
        }
        MathNode::Row(items) => write_row(out, items),
        MathNode::Matrix(style, spec, rows) => write_matrix(out, *style, spec, rows),
        MathNode::Substack(lines) => {
            write_cmd(out, "substack");
            out.push('{');
            match lines.as_slice() {
                // The `{` is required, and `{]}` unwraps to a bare `]` (G3),
                // so a lone bracket keeps two groups.
                [line @ MathNode::Atom('[' | ']', _)] => write_group(out, line),
                _ => {
                    for (i, line) in lines.iter().enumerate() {
                        if i > 0 {
                            out.push_str("\\\\");
                        }
                        out.node(line);
                    }
                }
            }
            out.push('}');
        }
        MathNode::Ref(key) => write_braced_text(out, "ref", key),
        MathNode::Tag { star, body } => {
            write_cmd(out, "tag");
            if *star {
                out.push('*');
            }
            write_group(out, body);
        }
        MathNode::Label(key) => write_braced_text(out, "label", key),
        MathNode::NoNumber => write_cmd(out, "nonumber"),
        MathNode::Hline => write_cmd(out, "hline"),
        MathNode::Intertext(body) => write_intertext(out, body),
        MathNode::Sum(lower, upper) => {
            write_op_scripts(out, "sum", lower.as_deref(), upper.as_deref())
        }
        MathNode::Product(lower, upper) => {
            write_op_scripts(out, "prod", lower.as_deref(), upper.as_deref())
        }
        MathNode::Integral(kind, lower, upper) => {
            write_op_scripts(out, kind.gold(), lower.as_deref(), upper.as_deref())
        }
        MathNode::Limit(lower) => write_op_scripts(out, "lim", lower.as_deref(), None),
        MathNode::OverUnder(base, over, under) => {
            write_over_under(out, base, over.as_deref(), under.as_deref())
        }
        MathNode::Accent(body, kind) => {
            write_cmd(out, kind.gold());
            write_arg(out, body);
        }
        MathNode::CancelTo(value, expr) => {
            write_cmd(out, "cancelto");
            write_arg(out, value);
            write_arg(out, expr);
        }
        MathNode::Text(text, style) => {
            if *style == TextStyle::Text
                || text
                    .as_str()
                    .is_some_and(|t| t.chars().all(|c| c.is_ascii_alphabetic()))
            {
                write_cmd(out, style_cmd(*style));
                out.push('{');
                print_run(out, text);
                out.push('}');
            } else {
                write_cmd(out, style_cmd(*style));
                out.push('{');
                write_cmd(out, "text");
                out.push('{');
                print_run(out, text);
                out.push('}');
                out.push('}');
            }
        }
        MathNode::Space(kind) => write_space(out, kind),
        MathNode::Operator(name, limits) => write_operator(out, name, *limits),
        MathNode::Symbol(name) => write_cmd(out, name),
        MathNode::Color(color, body) => {
            out.push('{');
            write_cmd(out, "color");
            push_html(out, *color);
            out.node(body);
            out.push('}');
        }
        MathNode::TextColor(color, body) => write_paint(out, "textcolor", *color, None, body),
        MathNode::ColorBox(color, body) => write_paint(out, "colorbox", *color, None, body),
        MathNode::FColorBox(border, fill, body) => {
            write_paint(out, "fcolorbox", *border, Some(*fill), body)
        }
        MathNode::Strut(height, depth) => write_strut(out, height, depth),
        MathNode::Phantom(kind, body) => {
            write_cmd(out, kind.gold());
            write_arg(out, body);
        }
    }
}

/// The items of a row of two or more primes of one spelling (all U+2032
/// atoms, or all `\prime` symbols). Such a run prints unbraced inside one
/// `^{…}` group, so its reprint costs one brace level for any run length.
fn prime_run(node: &MathNode) -> Option<&[MathNode]> {
    match node {
        MathNode::Row(items)
            if items.len() >= 2
                && (items
                    .iter()
                    .all(|item| matches!(item, MathNode::Atom('′', AtomKind::Ord)))
                    || items
                        .iter()
                        .all(|item| matches!(item, MathNode::Symbol(name) if name == "prime"))) =>
        {
            Some(items)
        }
        _ => None,
    }
}

/// True for a superscript that prints as `'` marks: one `′` atom or a run.
fn is_primes(sup: &MathNode) -> bool {
    matches!(sup, MathNode::Atom('′', AtomKind::Ord))
        || prime_run(sup).is_some_and(|items| {
            items
                .iter()
                .all(|item| matches!(item, MathNode::Atom('′', AtomKind::Ord)))
        })
}

fn write_scripts<'a>(
    out: &mut LatexBuf<'a>,
    base: &'a MathNode,
    sub: Option<&'a MathNode>,
    sup: Option<&'a MathNode>,
) {
    match base {
        MathNode::Row(items) if items.is_empty() => out.push_str("{}"),
        // `x'^a` parses as `(x')^a` and `x_b'^a` as `(x_b')^a`, so a primed
        // base needs no braces when a `^` superscript follows. More marks
        // would join the base's primes instead.
        MathNode::Superscript(_, prime) | MathNode::SubSup(_, _, prime)
            if sub.is_none()
                && !out.literal_primes
                && is_primes(prime)
                && !sup.is_some_and(is_primes) =>
        {
            out.node(base)
        }
        // A lone bracket is a nucleus here, though not as an argument.
        MathNode::Atom('(' | ')' | '[', _) => out.node(base),
        _ if bare_arg(base) => out.node(base),
        _ => write_group(out, base),
    }
    if let Some(sub) = sub {
        out.push('_');
        write_script_arg(out, sub);
    }
    let Some(sup) = sup else {
        return;
    };
    if !out.literal_primes && matches!(sup, MathNode::Atom('′', AtomKind::Ord)) {
        out.push('\'');
        return;
    }
    match prime_run(sup) {
        Some(items)
            if !out.literal_primes
                && items
                    .iter()
                    .all(|item| matches!(item, MathNode::Atom('′', AtomKind::Ord))) =>
        {
            for _ in items {
                out.push('\'');
            }
        }
        Some(items) => {
            out.push_str("^{");
            for item in items {
                out.node(item);
            }
            out.push('}');
        }
        None => {
            // Primes after a superscript join it: `x^a''` is the row of the
            // old superscript and the primes. Print them as marks after the
            // argument.
            let (core, marks) = match sup {
                MathNode::Row(items) if !out.literal_primes => match items.split_first() {
                    Some((rest, tail))
                        if !tail.is_empty()
                            && tail
                                .iter()
                                .all(|item| matches!(item, MathNode::Atom('′', AtomKind::Ord))) =>
                    {
                        (rest, tail.len())
                    }
                    _ => (sup, 0),
                },
                _ => (sup, 0),
            };
            out.push('^');
            write_script_arg(out, core);
            for _ in 0..marks {
                out.push('\'');
            }
        }
    }
}

fn write_op_scripts<'a>(
    out: &mut LatexBuf<'a>,
    name: &str,
    sub: Option<&'a MathNode>,
    sup: Option<&'a MathNode>,
) {
    write_cmd(out, name);
    if let Some(sub) = sub {
        out.push('_');
        write_script_arg(out, sub);
    }
    if let Some(sup) = sup {
        out.push('^');
        write_script_arg(out, sup);
    }
}

fn write_group<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
    out.push('{');
    out.node(node);
    out.push('}');
}

fn write_row<'a>(out: &mut LatexBuf<'a>, items: &'a [MathNode]) {
    if items.is_empty() {
        out.push_str("{}");
        return;
    }
    write_row_items(out, items);
}

/// Row items print bare unless the parser would read them back differently
/// (spec 5.3, row item): a nested row stays a group, and a prime or
/// superscript character would attach to its neighbour. Two bare letters are
/// split by a space so they do not form an operator word. Then the row paren
/// pass (spec 5.4) groups any item that would close a scripted paren group.
fn write_row_items_at<'a>(out: &mut LatexBuf<'a>, items: &'a [MathNode], row_start: bool) {
    let mut braced: Vec<bool> = items
        .iter()
        .enumerate()
        .map(|(i, item)| {
            if row_start && i == 0 && matches!(item, MathNode::Hline | MathNode::Intertext(_)) {
                true
            } else {
                match item {
                    MathNode::Row(_) => true,
                    MathNode::Atom(c, _) => *c == '\'' || is_superscript_char(*c),
                    _ => false,
                }
            }
        })
        .collect();
    // The pass prints every item once; those strings are reused below, so a
    // nested row is printed once per level, not twice (that was 2^k).
    let prints = paren_groups(items, &mut braced, out.literal_primes);
    let mut prev_letter = false;
    for (i, (item, braced)) in items.iter().zip(braced).enumerate() {
        let letter = !braced && matches!(item, MathNode::Atom(c, _) if c.is_ascii_alphabetic());
        if letter && prev_letter {
            out.push(' ');
        }
        prev_letter = letter;
        match (item, prints.as_ref().and_then(|p| p.get(i))) {
            (MathNode::Row(inner), _) if braced && inner.is_empty() => out.push_str("{}"),
            (_, Some(print)) if braced => {
                out.push('{');
                out.push_str(print);
                out.push('}');
            }
            (_, Some(print)) => out.push_str(print),
            _ if braced => write_group(out, item),
            _ => out.node(item),
        }
    }
}

fn write_row_items<'a>(out: &mut LatexBuf<'a>, items: &'a [MathNode]) {
    write_row_items_at(out, items, false);
}

/// The first cell of an environment row: the parser reads a leading `\hline` or
/// `\intertext` as a row rule or a text row, so such an item prints braced.
fn write_cell<'a>(out: &mut LatexBuf<'a>, cell: &'a MathNode) {
    match cell {
        MathNode::Hline | MathNode::Intertext(_) => write_group(out, cell),
        MathNode::Row(items) if !items.is_empty() => write_row_items_at(out, items, true),
        _ => out.node(cell),
    }
}

/// True when the print of `node` starts with a bare `(` that begins an atom:
/// the `(` itself, or a scripted node whose innermost base is `(`.
fn starts_with_open_paren(node: &MathNode) -> bool {
    let mut current = node;
    loop {
        match current {
            MathNode::Superscript(base, _)
            | MathNode::Subscript(base, _)
            | MathNode::SubSup(base, _, _) => current = base,
            MathNode::Atom(c, _) => return *c == '(',
            _ => return false,
        }
    }
}

/// The parser's tokens for a print: tokenized and passed through the group
/// rules, as `parse_with_options` does.
fn item_tokens(printed: &str) -> Option<Vec<Token>> {
    tokenize(printed).ok().map(group_rules::apply)
}

/// The row paren pass (spec 5.4). The row is tokenized as printed, and the
/// parser's own lookahead ([`paren_script_match`]) runs from every bare `(`
/// that starts an item. Paren-script groups always print braced, so any match
/// it finds is a hazard: the item holding the matching `)` is grouped, which
/// hides it, and the scan repeats until no `(` matches. Returns the print of
/// each item when the pass ran, so the caller does not print them again.
fn paren_groups(
    items: &[MathNode],
    braced: &mut [bool],
    literal_primes: bool,
) -> Option<Vec<String>> {
    let starts = |braced: &[bool]| {
        items
            .iter()
            .zip(braced)
            .any(|(item, braced)| !braced && starts_with_open_paren(item))
    };
    if !starts(braced) {
        return None;
    }
    let prints: Vec<String> = items
        .iter()
        .map(|item| item.print_raw(literal_primes))
        .collect();
    let mut item_toks = Vec::with_capacity(items.len());
    for (print, flag) in prints.iter().zip(braced.iter_mut()) {
        match item_tokens(print) {
            Some(toks) => item_toks.push(toks),
            None => {
                // Not expected for printer output; grouping is always safe.
                *flag = true;
                item_toks.push(Vec::new());
            }
        }
    }
    loop {
        let mut tokens = Vec::new();
        let mut owner = Vec::new();
        let mut first = Vec::with_capacity(items.len());
        let mut prev_letter = false;
        let mut spans: Vec<(usize, usize)> = Vec::with_capacity(items.len());
        for (i, ((item, toks), flag)) in items
            .iter()
            .zip(item_toks.iter_mut())
            .zip(braced.iter())
            .enumerate()
        {
            let letter = !flag && matches!(item, MathNode::Atom(c, _) if c.is_ascii_alphabetic());
            if letter && prev_letter {
                tokens.push(Token::Space);
                owner.push(i);
            }
            prev_letter = letter;
            if *flag {
                tokens.push(Token::BeginGroup);
                owner.push(i);
            }
            let skip = toks
                .iter()
                .take_while(|t| matches!(t, Token::Space))
                .count();
            first.push(tokens.len() + skip);
            spans.push((tokens.len(), toks.len()));
            tokens.append(toks);
            owner.resize(tokens.len(), i);
            if *flag {
                tokens.push(Token::EndGroup);
                owner.push(i);
            }
        }
        let hit = items
            .iter()
            .zip(braced.iter())
            .zip(&first)
            .filter(|((item, flag), _)| !**flag && starts_with_open_paren(item))
            .find_map(|(_, pos)| paren_script_match(&tokens, *pos, Stop::eof()))
            .and_then(|m| owner.get(m).copied());
        let grouped = match hit.and_then(|j| braced.get_mut(j)) {
            Some(flag) if !*flag => {
                *flag = true;
                true
            }
            _ => false,
        };
        if !grouped {
            return Some(prints);
        }
        for ((start, len), toks) in spans.into_iter().rev().zip(item_toks.iter_mut().rev()) {
            let mut piece = tokens.split_off(start);
            piece.truncate(len);
            *toks = piece;
        }
    }
}

/// True when `node` prints as exactly one nucleus, so an argument needs no
/// braces around it.
fn bare_arg(node: &MathNode) -> bool {
    let mut node = node;
    loop {
        return match node {
            MathNode::Atom(c, _) => {
                !c.is_whitespace()
                    && !is_superscript_char(*c)
                    && !matches!(
                        *c,
                        '(' | ')' | '[' | '\'' | '^' | '_' | '&' | '#' | '~' | '$'
                    )
            }
            MathNode::Row(_)
            | MathNode::Superscript(..)
            | MathNode::Subscript(..)
            | MathNode::SubSup(..)
            | MathNode::Color(..)
            | MathNode::Ref(_)
            | MathNode::Tag { .. }
            | MathNode::Label(_)
            | MathNode::NoNumber
            | MathNode::Hline
            | MathNode::Intertext(_) => false,
            MathNode::Operator(name, limits) => match operator_limits(name) {
                Some(default) => default == *limits,
                None => !*limits,
            },
            MathNode::Sum(lo, hi) | MathNode::Product(lo, hi) | MathNode::Integral(_, lo, hi) => {
                lo.is_none() && hi.is_none()
            }
            MathNode::Limit(lo) => lo.is_none(),
            MathNode::OverUnder(base, None, None) => {
                node = base;
                continue;
            }
            MathNode::OverUnder(base, ..) => !matches!(
                base.as_ref(),
                MathNode::Accent(_, AccentKind::Overbrace | AccentKind::Underbrace)
            ),
            _ => true,
        };
    }
}

/// True when `printed` contains `pattern` outside every brace group, not
/// as the second character of a control symbol.
fn has_top_level(printed: &str, pattern: &[char]) -> bool {
    let chars: Vec<char> = printed.chars().collect();
    let mut braces = 0usize;
    let mut i = 0;
    while let Some(&c) = chars.get(i) {
        if braces == 0 && chars.get(i..i + pattern.len()) == Some(pattern) {
            return true;
        }
        match c {
            '\\' => i += 1,
            '{' => braces += 1,
            '}' => braces = braces.saturating_sub(1),
            _ => {}
        }
        i += 1;
    }
    false
}

/// `[…]` around an optional argument (spec 5.3). A `]` at brace level zero
/// would end the option early, so such content is grouped; a lone `]` keeps
/// two groups, since `{]}` is read as a bare `]` (G3). Parens need nothing:
/// the paren lookahead skips options (Q1).
fn write_option<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
    out.push('[');
    match node {
        // `[]` reads as an empty row; `[{}]` would cost one more level.
        MathNode::Row(items) if items.is_empty() => {}
        MathNode::Atom(']', _) => {
            out.push('{');
            write_group(out, node);
            out.push('}');
        }
        _ => {
            // Print the body once and reuse it: printing it again through
            // `out.node` made nested options cost 2^k.
            let body = node.print_raw(out.literal_primes);
            if item_tokens(&body).is_none_or(option_ends_early) {
                out.push('{');
                out.push_str(&body);
                out.push('}');
            } else {
                out.push_str(&body);
            }
        }
    }
    out.push(']');
}

/// An argument right after a command that takes `[…]`: a lone `[` keeps two
/// groups, since `{[}` is read as a bare `[` and would open the option (G3).
fn write_arg_after_option<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
    if matches!(node, MathNode::Atom('[', _)) {
        out.push('{');
        write_group(out, node);
        out.push('}');
    } else {
        write_arg(out, node);
    }
}

/// A command argument: always braced (spec 5, Q2). An empty row is `{}`, a
/// row is one group, and a color is already its own group. A braced argument
/// costs no more depth than a bare one, so this never nests deeper than the
/// source.
fn write_arg<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
    match node {
        MathNode::Row(items) if items.is_empty() => out.push_str("{}"),
        MathNode::Row(items) => {
            out.push('{');
            write_row_items(out, items);
            out.push('}');
        }
        MathNode::Color(..) => out.node(node),
        _ => write_group(out, node),
    }
}

/// A sub- or superscript argument, bare first (spec 5.3, script): bare when it
/// prints as exactly one nucleus (G1), otherwise one group.
fn write_script_arg<'a>(out: &mut LatexBuf<'a>, node: &'a MathNode) {
    match node {
        MathNode::Row(items) if items.is_empty() => out.push_str("{}"),
        MathNode::Row(items) => {
            out.push('{');
            write_row_items(out, items);
            out.push('}');
        }
        MathNode::Color(..) => out.node(node),
        _ if bare_arg(node) => out.node(node),
        _ => write_group(out, node),
    }
}

fn write_matrix<'a>(
    out: &mut LatexBuf<'a>,
    style: MatrixStyle,
    spec: &[ColSpec],
    rows: &'a [EnvRow],
) {
    write_cmd(out, "begin");
    out.push('{');
    out.push_str(style.gold());
    out.push('}');
    if matches!(style, MatrixStyle::Array) || !spec.is_empty() {
        out.push('{');
        for col in spec {
            out.push(col.gold());
        }
        out.push('}');
    }
    let mut prev_cells = false;
    for row in rows {
        let cells = matches!(row, EnvRow::Cells { .. });
        if prev_cells {
            out.push_str("\\\\");
        }
        prev_cells = cells;
        match row {
            EnvRow::Hline => write_cmd(out, "hline"),
            EnvRow::Intertext(body) => write_intertext(out, body),
            EnvRow::Cells {
                cells,
                number,
                labels,
            } => {
                for (i, cell) in cells.iter().enumerate() {
                    if i > 0 {
                        out.push('&');
                    }
                    if i == 0 {
                        write_cell(out, cell);
                    } else {
                        out.node(cell);
                    }
                    if i + 1 == cells.len() {
                        write_eq_meta(out, number, labels);
                    }
                }
                if cells.is_empty() {
                    write_eq_meta(out, number, labels);
                }
            }
        }
    }
    write_cmd(out, "end");
    out.push('{');
    out.push_str(style.gold());
    out.push('}');
}

fn write_eq_meta<'a>(out: &mut LatexBuf<'a>, number: &'a EqNumber, labels: &[String]) {
    for key in labels {
        write_braced_text(out, "label", key);
    }
    match number {
        EqNumber::Default => {}
        EqNumber::Suppress => write_cmd(out, "nonumber"),
        EqNumber::Tag { star, body } => {
            write_cmd(out, "tag");
            if *star {
                out.push('*');
            }
            write_group(out, body);
        }
    }
}

fn write_over_under<'a>(
    out: &mut LatexBuf<'a>,
    base: &'a MathNode,
    over: Option<&'a MathNode>,
    under: Option<&'a MathNode>,
) {
    if let MathNode::Accent(body, kind @ (AccentKind::Overbrace | AccentKind::Underbrace)) = base {
        write_cmd(out, kind.gold());
        write_arg(out, body);
        if let Some(under) = under {
            out.push('_');
            write_arg(out, under);
        }
        if let Some(over) = over {
            out.push('^');
            write_arg(out, over);
        }
        return;
    }
    if let MathNode::Symbol(name) = base {
        let cmd = match (name.as_str(), over) {
            ("longrightarrow", Some(_)) => Some("xrightarrow"),
            ("longleftarrow", Some(_)) => Some("xleftarrow"),
            _ => None,
        };
        if let Some(cmd) = cmd {
            write_cmd(out, cmd);
            if let Some(under) = under {
                write_option(out, under);
            }
            if let Some(over) = over {
                write_arg_after_option(out, over);
            }
            return;
        }
    }
    match (over, under) {
        (Some(over), Some(under)) => {
            write_cmd(out, "overset");
            write_arg(out, over);
            write_cmd(out, "underset");
            write_arg(out, under);
            write_arg(out, base);
        }
        (Some(over), None) => {
            write_cmd(out, "overset");
            write_arg(out, over);
            write_arg(out, base);
        }
        (None, Some(under)) => {
            write_cmd(out, "underset");
            write_arg(out, under);
            write_arg(out, base);
        }
        (None, None) => out.node(base),
    }
}

fn write_intertext<'a>(out: &mut LatexBuf<'a>, body: &'a MathNode) {
    write_cmd(out, "intertext");
    out.push('{');
    if let MathNode::Text(text, _) = body {
        print_run(out, text);
    } else {
        out.node(body);
    }
    out.push('}');
}

fn write_paint<'a>(
    out: &mut LatexBuf<'a>,
    cmd: &str,
    first: Color,
    second: Option<Color>,
    body: &'a MathNode,
) {
    write_cmd(out, cmd);
    push_html(out, first);
    if let Some(second) = second {
        push_html(out, second);
    }
    write_arg(out, body);
}

fn write_operator(out: &mut LatexBuf<'_>, name: &str, limits: bool) {
    match operator_limits(name) {
        Some(default) => {
            write_cmd(out, name);
            if limits != default {
                write_cmd(out, if limits { "limits" } else { "nolimits" });
            }
        }
        None => {
            write_cmd(out, "operatorname");
            out.push('{');
            push_escaped(out, name);
            out.push('}');
            if limits {
                write_cmd(out, "limits");
            }
        }
    }
}

fn operator_limits(name: &str) -> Option<bool> {
    Some(match name {
        "sin" | "cos" | "tan" | "cot" | "sec" | "csc" | "arcsin" | "arccos" | "arctan" | "sinh"
        | "cosh" | "tanh" | "coth" | "log" | "ln" | "lg" | "exp" | "limsup" | "liminf" | "sup"
        | "inf" | "max" | "min" | "det" | "dim" | "ker" | "deg" | "gcd" | "lcm" | "Pr" | "arg" => {
            false
        }
        "coprod" | "bigcup" | "bigcap" | "bigsqcup" | "bigvee" | "bigwedge" | "bigoplus"
        | "bigotimes" | "biguplus" => true,
        _ => return None,
    })
}

fn write_space(out: &mut LatexBuf<'_>, kind: &SpaceKind) {
    match kind {
        SpaceKind::Thin => out.push_str("\\,"),
        SpaceKind::Medium => out.push_str("\\:"),
        SpaceKind::Thick => out.push_str("\\;"),
        SpaceKind::NegThin => out.push_str("\\!"),
        SpaceKind::Quad => write_cmd(out, "quad"),
        SpaceKind::Qquad => write_cmd(out, "qquad"),
        // The space is the control symbol, not disposable padding. `preprocess`
        // keeps one trailing ASCII space after an odd run of backslashes, so
        // this reprint parses again. Do not drop the space or replace it with
        // a token that trimming would delete.
        SpaceKind::ControlSpace => out.push_str("\\ "),
        SpaceKind::Hspace(dim) => {
            write_cmd(out, "hspace");
            out.push('{');
            out.push_str(&dim.to_tex_string());
            out.push('}');
        }
    }
}

fn write_strut(out: &mut LatexBuf<'_>, height: &Dim, depth: &Dim) {
    if height.eq_dim(&Dim::ratio(7, 10)) && depth.eq_dim(&Dim::ratio(3, 10)) {
        write_cmd(out, "strut");
        return;
    }
    write_cmd(out, "rule");
    out.push_str("{0em}{");
    out.push_str(&height.to_tex_string());
    out.push('}');
}

fn write_atom(out: &mut LatexBuf<'_>, c: char) {
    match c {
        '{' | '}' | '%' | '\\' => {
            out.push('\\');
            out.push(c);
        }
        '<' | '>' | '!' => {
            out.push(c);
            out.push(' ');
        }
        _ => out.push(c),
    }
}

fn write_delim(out: &mut LatexBuf<'_>, delim: &Delimiter) {
    match delim {
        Delimiter::Empty => out.push('.'),
        Delimiter::Char(c) => write_atom(out, *c),
        Delimiter::Named(name) if name == "{" || name == "}" || name == "|" => {
            out.push('\\');
            out.push_str(name);
        }
        Delimiter::Named(name) => write_cmd(out, name),
    }
}

fn sized_suffix(kind: AtomKind, delim: &Delimiter) -> &'static str {
    if kind == delim_class(delim) {
        return "";
    }
    match kind {
        AtomKind::Open => "l",
        AtomKind::Close => "r",
        AtomKind::Rel => "m",
        AtomKind::Ord | AtomKind::Op | AtomKind::Bin | AtomKind::Punct | AtomKind::Inner => "",
    }
}

fn delim_class(delim: &Delimiter) -> AtomKind {
    match delim {
        Delimiter::Char(c) => atom_class(*c),
        Delimiter::Named(name) if name == "{" => AtomKind::Open,
        Delimiter::Named(name) if name == "}" => AtomKind::Close,
        Delimiter::Empty | Delimiter::Named(_) => AtomKind::Open,
    }
}

fn atom_class(c: char) -> AtomKind {
    match c {
        '+' | '-' | '*' | '±' | '∓' | '·' | '×' | '÷' => AtomKind::Bin,
        '=' | '<' | '>' | '≠' | '≤' | '≥' | '≈' | '≡' => AtomKind::Rel,
        '(' | '[' | '{' => AtomKind::Open,
        ')' | ']' | '}' => AtomKind::Close,
        ',' | ';' | '!' | '?' | ':' => AtomKind::Punct,
        _ => AtomKind::Ord,
    }
}

fn style_cmd(style: TextStyle) -> &'static str {
    match style {
        TextStyle::Rm => "mathrm",
        TextStyle::Bf => "mathbf",
        TextStyle::It => "mathit",
        TextStyle::Sf => "mathsf",
        TextStyle::Tt => "mathtt",
        TextStyle::Bb => "mathbb",
        TextStyle::Cal => "mathcal",
        TextStyle::Frak => "mathfrak",
        TextStyle::Scr => "mathscr",
        TextStyle::Boldsymbol => "boldsymbol",
        TextStyle::Pmb => "pmb",
        TextStyle::Text => "text",
    }
}

fn write_cmd(out: &mut LatexBuf<'_>, name: &str) {
    out.push('\\');
    out.push_str(name);
    if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphabetic()) {
        out.push(' ');
    }
}

fn write_braced_text(out: &mut LatexBuf<'_>, cmd: &str, text: &str) {
    write_cmd(out, cmd);
    out.push('{');
    push_escaped(out, text);
    out.push('}');
}

/// Escapes special LaTeX characters in text.
///
/// The first character is escaped if it is a space, '[', or ']'.
/// All characters are escaped if they are '\', '{', '}', '%', '$', '&', '_', or '^'.
/// Command for a nested text run of `style` inside text.
fn text_cmd(style: TextStyle) -> &'static str {
    match style {
        TextStyle::Text => "text",
        TextStyle::Rm => "textrm",
        TextStyle::Bf => "textbf",
        TextStyle::It => "textit",
        TextStyle::Sf => "textsf",
        TextStyle::Tt => "texttt",
        _ => "text",
    }
}

/// Canonical text-mode print of a run (spec 2.5). `parse` reads it back to
/// the same run, and math-level code never looks inside it.
fn print_run<'a>(out: &mut LatexBuf<'a>, run: &'a TextRun) {
    let mut stack = vec![run.items().iter()];

    while let Some(mut iter) = stack.pop() {
        if let Some(item) = iter.next() {
            stack.push(iter);

            match item {
                TextItem::Str(s) => {
                    for c in s.chars() {
                        match c {
                            '\\' => out.push_str(r"\textbackslash{}"),
                            '^' => out.push_str(r"\textasciicircum{}"),
                            '~' => out.push_str(r"\textasciitilde{}"),
                            '{' | '}' | '$' | '%' | '&' | '#' | '_' => {
                                out.push('\\');
                                out.push(c);
                            }
                            _ => out.push(c),
                        }
                    }
                }
                TextItem::Space => out.push(' '),
                TextItem::ControlSpace => out.push_str(r"\ "),
                TextItem::NoBreakSpace => out.push('~'),
                TextItem::Symbol(name) => {
                    out.push('\\');
                    out.push_str(name);
                    out.push_str("{}");
                }
                TextItem::Nested(style, nested_run) => {
                    write_cmd(out, text_cmd(*style));
                    out.push('{');
                    stack.push(nested_run.items().iter());
                }
                TextItem::Math(node) => {
                    // A `\)` in the body would close `\(` early. Such a body
                    // uses `$…$`, or one group when it also has a `$`.
                    let body = node.print_raw(out.literal_primes);
                    let close = has_top_level(&body, &['\\', ')']);
                    // The body is printed once (`out.node` again would cost
                    // 2^k for text nested in math nested in text).
                    if close && !has_top_level(&body, &['$']) {
                        out.push('$');
                        out.push_str(&body);
                        out.push('$');
                    } else if close {
                        out.push_str(r"\({");
                        out.push_str(&body);
                        out.push_str(r"}\)");
                    } else {
                        out.push_str(r"\(");
                        out.push_str(&body);
                        out.push_str(r"\)");
                    }
                }
            }
        } else if !stack.is_empty() {
            out.push('}');
        }
    }
}

fn push_escaped(out: &mut LatexBuf<'_>, text: &str) {
    for (i, c) in text.chars().enumerate() {
        match c {
            ' ' | '[' | ']' if i == 0 => {
                out.push('\\');
                out.push(c);
            }
            '\\' | '{' | '}' | '%' | '$' | '&' | '_' | '^' => {
                out.push('\\');
                out.push(c);
            }
            _ => out.push(c),
        }
    }
}

fn push_html(out: &mut LatexBuf<'_>, color: Color) {
    out.push_str("[HTML]{");
    let hex = color.css_hex();
    match hex.strip_prefix('#') {
        Some(body) => out.push_str(body),
        None => out.push_str(&hex),
    }
    out.push('}');
}