latex-rust 3.0.3

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
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
//! `MathNode` → `MathBox`. All sizes are [`Dim`](crate::Dim).

use core::cell::{Cell, RefCell};
use core::cmp::Ordering;

#[path = "engine_walk.rs"]
mod walk;

use crate::atoms::symbol_atom_kind;
use crate::color::Color;
use crate::dim::Dim;
use crate::error::Error;
use crate::font::MathFont;
use crate::layout::metrics::MathParams;
use crate::layout::numbering::NumberingState;
use crate::layout::space::{atom_space_mu, convert_bin, space_width};
use crate::layout::style::MathStyle;
use crate::layout::{BoxContent, MathBox};
use crate::parser::DEFAULT_MAX_NESTING_DEPTH;
use crate::parser::{
    AccentKind, AtomKind, ColSpec, DelimSize, Delimiter, EnvRow, FracStyle, IntegralKind, MathNode,
    MatrixStyle, PhantomKind, SpaceKind, TextItem, TextRun, TextStyle,
};
use crate::style_map::styled_char;
use crate::symbols::lookup;

const DEFAULT_LAYOUT_EM_SIZE_PT: i64 = 10;
const TEX_DELIMITER_FACTOR_NUM: i64 = 901;
const TEX_DELIMITER_FACTOR_DEN: i64 = 500;
const TEX_DELIMITER_SHORTFALL_PT: i64 = 5;
const TEX_ARRAY_COLSEP_PT: i64 = 5;
const TEX_MIN_ALIGN_SEP_PT: i64 = 10;
const TEX_BASELINE_SKIP_PT: i64 = 12;
const TEX_JOT_PT: i64 = 3;
const TEX_LINE_SKIP_PT: i64 = 1;

/// Lay out `node` in `style` using STIX Two Math metrics.
///
/// Every dimension on the returned [`MathBox`] is a [`Dim`](crate::Dim). Missing
/// glyphs and unsupported constructs are errors — never a substitute glyph.
///
/// # Arguments
///
/// * `node` — parsed math tree.
/// * `font` — face providing MATH constants and glyph metrics.
/// * `style` — TeX math style (`Display`, `Text`, scripts).
///
/// # Returns
///
/// A box tree ready for SVG, PNG, or egui emission.
///
/// # Errors
///
/// * [`Error::Font`] — glyph missing from the face.
/// * [`Error::Unsupported`] — construct or MATH table the engine will not fake.
/// * [`Error::Malformed`] — invalid structure discovered during layout.
///
/// # Examples
///
/// ```
/// use latex_rust::{layout, parse, MathFont, MathStyle};
///
/// let ast = parse(r"\frac{1}{2}").unwrap();
/// let font = MathFont::stix_two_math().unwrap();
/// let boxed = layout(&ast, &font, MathStyle::Text).unwrap();
/// assert!(!boxed.width.is_zero());
/// ```
pub fn layout(node: &MathNode, font: &MathFont, style: MathStyle) -> Result<MathBox, Error> {
    let mut state = NumberingState::default();
    layout_impl(
        node,
        font,
        style,
        &mut state,
        DEFAULT_MAX_NESTING_DEPTH,
        &Dim::from_i64(DEFAULT_LAYOUT_EM_SIZE_PT),
    )
}

/// Lay out `node` using an explicit physical root em size in TeX points.
///
/// Returned dimensions remain normalized em units. The physical root em is
/// used only to normalize absolute TeX dimensions such as
/// `\delimitershortfall` and AMSMath spacing constants.
///
/// # Errors
///
/// Same as [`layout`], plus [`Error::InvalidOption`] when `em_size_pt` is not
/// positive.
pub fn layout_with_em_size_pt(
    node: &MathNode,
    font: &MathFont,
    style: MathStyle,
    em_size_pt: &Dim,
) -> Result<MathBox, Error> {
    let mut state = NumberingState::default();
    layout_impl(
        node,
        font,
        style,
        &mut state,
        DEFAULT_MAX_NESTING_DEPTH,
        em_size_pt,
    )
}

/// Lay out with a caller-owned equation counter and `\label` / `\ref` table.
///
/// # Arguments
///
/// * `node` — parsed math tree.
/// * `font` — face providing MATH constants and glyph metrics.
/// * `style` — TeX math style.
/// * `state` — counter and label map; survives across calls.
///
/// # Returns
///
/// A box tree. Numbers assigned for this tree are recorded in `state`.
///
/// # Errors
///
/// Same as [`layout`].
///
/// # Examples
///
/// ```
/// use latex_rust::{layout_with_numbering, parse, MathFont, MathStyle, NumberingState};
///
/// let ast = parse(r"\begin{equation}x\end{equation}").unwrap();
/// let font = MathFont::stix_two_math().unwrap();
/// let mut state = NumberingState::default();
/// let boxed = layout_with_numbering(&ast, &font, MathStyle::Display, &mut state).unwrap();
/// assert!(!boxed.width.is_zero());
/// ```
pub fn layout_with_numbering(
    node: &MathNode,
    font: &MathFont,
    style: MathStyle,
    state: &mut NumberingState,
) -> Result<MathBox, Error> {
    layout_impl(
        node,
        font,
        style,
        state,
        DEFAULT_MAX_NESTING_DEPTH,
        &Dim::from_i64(DEFAULT_LAYOUT_EM_SIZE_PT),
    )
}

/// Lay out with caller-owned numbering and an explicit physical root em size
/// in TeX points.
///
/// Returned dimensions remain normalized em units. `em_size_pt` is used only
/// to normalize absolute TeX dimensions.
///
/// # Errors
///
/// Same as [`layout_with_em_size_pt`].
pub fn layout_with_numbering_and_em_size_pt(
    node: &MathNode,
    font: &MathFont,
    style: MathStyle,
    state: &mut NumberingState,
    em_size_pt: &Dim,
) -> Result<MathBox, Error> {
    layout_impl(
        node,
        font,
        style,
        state,
        DEFAULT_MAX_NESTING_DEPTH,
        em_size_pt,
    )
}

/// Lay out with an explicit nesting limit instead of
/// [`DEFAULT_MAX_NESTING_DEPTH`](crate::DEFAULT_MAX_NESTING_DEPTH).
///
/// Use the same limit given to [`ParseOptions::with_max_depth`](crate::ParseOptions::with_max_depth),
/// so that every tree the parser accepts can also be laid out.
///
/// # Errors
///
/// Same as [`layout`]. A tree nesting deeper than `max_depth` returns
/// [`Error::Unsupported`].
///
/// # Examples
///
/// ```
/// use latex_rust::{layout_with_max_depth, parse, MathFont, MathStyle};
///
/// let ast = parse(r"\frac{1}{2}").unwrap();
/// let font = MathFont::stix_two_math().unwrap();
/// assert!(layout_with_max_depth(&ast, &font, MathStyle::Text, 64).is_ok());
/// assert!(layout_with_max_depth(&ast, &font, MathStyle::Text, 1).is_err());
/// ```
pub fn layout_with_max_depth(
    node: &MathNode,
    font: &MathFont,
    style: MathStyle,
    max_depth: usize,
) -> Result<MathBox, Error> {
    let mut state = NumberingState::default();
    layout_impl(
        node,
        font,
        style,
        &mut state,
        max_depth,
        &Dim::from_i64(DEFAULT_LAYOUT_EM_SIZE_PT),
    )
}

fn layout_impl(
    node: &MathNode,
    font: &MathFont,
    style: MathStyle,
    state: &mut NumberingState,
    max_depth: usize,
    em_size_pt: &Dim,
) -> Result<MathBox, Error> {
    if em_size_pt.is_nan() || !matches!(em_size_pt.cmp(&Dim::zero()), Some(Ordering::Greater)) {
        return Err(Error::InvalidOption {
            what: "em_size_pt must be positive".into(),
        });
    }

    let params = MathParams::from_font(font)?;
    let script_placement = ScriptPlacementParams::from_params(&params);
    let substack = SubstackParams::from_params(&params);
    let delimiter_shortfall = &Dim::from_i64(TEX_DELIMITER_SHORTFALL_PT) / em_size_pt;
    let start = state.collect(node);
    Engine {
        font,
        params,
        script_placement,
        substack,
        delimiter_shortfall,
        root_em_size_pt: em_size_pt.clone(),
        numbers: state,
        idx: Cell::new(start),
        kids: RefCell::new(Vec::new()),
        kid_i: Cell::new(0),
        arena: RefCell::new(Vec::new()),
        max_depth,
    }
    .layout(node, style)
}

struct Engine<'a> {
    font: &'a MathFont,
    params: MathParams,
    script_placement: ScriptPlacementParams,
    substack: SubstackParams,
    delimiter_shortfall: Dim,
    root_em_size_pt: Dim,
    numbers: &'a NumberingState,
    idx: Cell<usize>,
    /// Precomputed children for the node currently being assembled.
    kids: RefCell<Vec<Item>>,
    kid_i: Cell<usize>,
    /// Synthetic nodes built while planning (`\begin{equation}` rows, aligned
    /// prefixes). Each node is boxed so its address stays valid when the
    /// arena vec grows.
    arena: RefCell<Vec<ArenaNode>>,
    /// Deepest nesting accepted.
    max_depth: usize,
}

struct ArenaNode(Box<MathNode>);

struct ScriptPlacementParams {
    subscript_top_max: Dim,
    subscript_baseline_drop_min: Dim,
    superscript_bottom_min: Dim,
    superscript_bottom_max_with_subscript: Dim,
    superscript_baseline_drop_max: Dim,
}

impl ScriptPlacementParams {
    fn from_params(params: &MathParams) -> Self {
        Self {
            subscript_top_max: params.subscript_top_max.clone(),
            subscript_baseline_drop_min: params.subscript_baseline_drop_min.clone(),
            superscript_bottom_min: params.superscript_bottom_min.clone(),
            superscript_bottom_max_with_subscript: params
                .superscript_bottom_max_with_subscript
                .clone(),
            superscript_baseline_drop_max: params.superscript_baseline_drop_max.clone(),
        }
    }
}

struct SubstackParams {
    baseline_skip: Dim,
    line_skip: Dim,
}

impl SubstackParams {
    fn from_params(params: &MathParams) -> Self {
        let script_scale = params.scale(MathStyle::Script);
        Self {
            baseline_skip: &(&params.stack_top_shift_up + &params.stack_bottom_shift_down)
                * &script_scale,
            line_skip: &params.stack_gap_min * &script_scale,
        }
    }
}
struct Item {
    bx: MathBox,
    class: Option<AtomKind>,
}

impl Engine<'_> {
    fn layout(&self, node: &MathNode, style: MathStyle) -> Result<MathBox, Error> {
        Ok(self.item(node, style)?.bx)
    }

    /// Lay out `node`, refusing to descend past `max_depth`.
    ///
    /// The walk is an explicit heap stack. A tree `parse` accepts — including
    /// one built at a raised `max_depth` — does not grow the caller's stack
    /// with the tree.
    fn item(&self, node: &MathNode, style: MathStyle) -> Result<Item, Error> {
        self.drive(node, style)
    }

    fn item_inner(&self, node: &MathNode, style: MathStyle) -> Result<Item, Error> {
        match node {
            MathNode::Atom(c, k) => {
                let bx = self.glyph(math_italic(math_char(*c)), style)?;
                Ok(Item {
                    bx,
                    class: Some(*k),
                })
            }
            MathNode::Symbol(name) => {
                let ch = math_italic(symbol_char(name)?);
                let bx = self.glyph(ch, style)?;
                Ok(Item {
                    bx,
                    class: Some(symbol_class(name)),
                })
            }
            MathNode::Row(items) => self.row(items, style),
            MathNode::Fraction(kind, num, den) => {
                self.fraction(num, den, frac_math_style(*kind, style))
            }
            MathNode::Radical(deg, rad) => self.radical(deg.as_deref(), rad, style),
            MathNode::Superscript(base, exp) => self.scripts(base, None, Some(exp), style),
            MathNode::Subscript(base, sub) => self.scripts(base, Some(sub), None, style),
            MathNode::SubSup(base, sub, exp) => self.scripts(base, Some(sub), Some(exp), style),
            MathNode::Delimited(open, body, close) => self.delimited(open, body, close, style),
            MathNode::SizedDelim(d, size, k) => {
                let needed = self.explicit_delim_span(*size, style);
                Ok(Item {
                    class: Some(*k),
                    bx: self.delim_box(d, &needed, style)?,
                })
            }
            MathNode::Space(kind) => Ok(Item {
                bx: MathBox::kern(self.space_dim(kind, style)),
                class: None,
            }),
            MathNode::Strut(h, d) => {
                let s = self.params.scale(style);
                Ok(Item {
                    bx: MathBox {
                        width: Dim::zero(),
                        height: h * &s,
                        depth: d * &s,
                        italic: Dim::zero(),
                        shift: Dim::zero(),
                        content: BoxContent::Empty,
                    },
                    class: Some(AtomKind::Ord),
                })
            }
            MathNode::Phantom(kind, inner) => {
                let mut bx = self.take_box()?;
                match kind {
                    PhantomKind::Full => bx.content = BoxContent::Empty,
                    PhantomKind::Vertical => {
                        bx.width = Dim::zero();
                        bx.content = BoxContent::Empty;
                    }
                    PhantomKind::Horizontal => {
                        bx.height = Dim::zero();
                        bx.depth = Dim::zero();
                        bx.content = BoxContent::Empty;
                    }
                }
                Ok(Item {
                    class: class_of(inner),
                    bx,
                })
            }
            MathNode::Text(run, ts) => self.text_items(run, *ts, style),
            MathNode::Operator(name, limits) => self.operator(name, *limits, style),
            MathNode::Sum(lo, hi) => self.large_op('∑', lo.as_deref(), hi.as_deref(), style, true),
            MathNode::Product(lo, hi) => {
                self.large_op('∏', lo.as_deref(), hi.as_deref(), style, true)
            }
            MathNode::Integral(k, lo, hi) => {
                self.integral_op(*k, lo.as_deref(), hi.as_deref(), style)
            }
            MathNode::Limit(sub) => {
                let op = self.text_run("lim", TextStyle::Rm, style)?;
                if let Some(s) = sub {
                    self.attach_limits(op.bx, None, Some(s), style, true)
                } else {
                    Ok(Item {
                        bx: op.bx,
                        class: Some(AtomKind::Op),
                    })
                }
            }
            MathNode::OverUnder(_base, over, under) => {
                let mut b = self.take_box()?;
                let mut needed = b.width.clone();
                if let Some(_o) = over {
                    needed = needed.max(&self.take_box()?.width);
                }
                if let Some(_u) = under {
                    needed = needed.max(&self.take_box()?.width);
                }
                b = self.stretch_h(b, &needed, style)?;
                self.attach_limits(b, over.as_deref(), under.as_deref(), style, true)
            }
            MathNode::Accent(base, kind) => self.accent(base, *kind, style),
            MathNode::CancelTo(value, expr) => self.cancelto(value, expr, style),
            MathNode::Matrix(ms, spec, rows) => self.matrix(*ms, spec, rows, style),
            MathNode::Substack(lines) => self.substack(lines, style),
            MathNode::Ref(key) => self.reference(key, style),
            MathNode::Tag { star, body } => self.tag_box(*star, body, style),
            MathNode::Label(_) | MathNode::NoNumber => Ok(Item {
                bx: MathBox::empty(),
                class: None,
            }),
            MathNode::Hline => Err(Error::Unsupported {
                what: "hline outside array".into(),
            }),
            MathNode::Intertext(_n) => Ok(Item {
                class: Some(AtomKind::Ord),
                bx: self.take_box()?,
            }),
            MathNode::Color(c, body) | MathNode::TextColor(c, body) => {
                let inner = self.take_box()?;
                Ok(Item {
                    class: class_of(body),
                    bx: color_wrap(*c, inner),
                })
            }
            MathNode::ColorBox(c, _body) => {
                let inner = self.take_box()?;
                let pad = self.params.mu(style) * Dim::from_i64(3);
                Ok(Item {
                    class: Some(AtomKind::Inner),
                    bx: back_color_wrap(*c, pad_box(inner, &pad)),
                })
            }
            MathNode::FColorBox(border, fill, _body) => {
                let inner = self.take_box()?;
                let pad = self.params.mu(style) * Dim::from_i64(3);
                let thick = self.params.fraction_rule_thickness.clone() * self.params.scale(style);
                Ok(Item {
                    class: Some(AtomKind::Inner),
                    bx: back_color_wrap(
                        *fill,
                        frame_wrap(thick, Some(*border), pad_box(inner, &pad)),
                    ),
                })
            }
        }
    }

    fn glyph(&self, ch: char, style: MathStyle) -> Result<MathBox, Error> {
        let base = self.font.glyph(ch)?;
        let glyph_id = self
            .font
            .script_alternate_glyph_id(base.glyph_id, style.script_level())
            .unwrap_or(base.glyph_id);

        let g = if glyph_id == base.glyph_id {
            base
        } else {
            self.font.glyph_id(ch, glyph_id)?
        };

        let s = self.params.scale(style);
        let italic = self.font.italic_correction(glyph_id);

        Ok(MathBox {
            width: &g.advance * &s,
            height: &g.height * &s,
            depth: &g.depth * &s,
            italic: &italic * &s,
            shift: Dim::zero(),
            content: BoxContent::glyph(ch, glyph_id, s),
        })
    }

    fn glyph_id(&self, ch: char, gid: u16, style: MathStyle) -> Result<MathBox, Error> {
        let glyph_id = self
            .font
            .script_alternate_glyph_id(gid, style.script_level())
            .unwrap_or(gid);
        let g = self.font.glyph_id(ch, glyph_id)?;
        let s = self.params.scale(style);
        let italic = self.font.italic_correction(glyph_id);

        Ok(MathBox {
            width: &g.advance * &s,
            height: &g.height * &s,
            depth: &g.depth * &s,
            italic: &italic * &s,
            shift: Dim::zero(),
            content: BoxContent::glyph(ch, glyph_id, s),
        })
    }

    fn space_dim(&self, kind: &SpaceKind, style: MathStyle) -> Dim {
        let mu = self.params.mu(style);
        match kind {
            SpaceKind::Thin => mu * Dim::from_i64(3),
            SpaceKind::Medium => mu * Dim::from_i64(4),
            SpaceKind::Thick => mu * Dim::from_i64(5),
            SpaceKind::NegThin => -(mu * Dim::from_i64(3)),
            SpaceKind::Quad => self.params.em(style),
            SpaceKind::Qquad => self.params.em(style) * Dim::from_i64(2),
            SpaceKind::ControlSpace => self.params.em(style) / Dim::from_i64(3),
            SpaceKind::Hspace(d) => d * &self.params.scale(style),
        }
    }

    fn text_run(&self, s: &str, ts: TextStyle, style: MathStyle) -> Result<Item, Error> {
        if ts == TextStyle::Pmb {
            return self.pmb(s, style);
        }
        let mut kids = Vec::new();
        for c in s.chars() {
            if c == ' ' {
                kids.push(MathBox::kern(self.params.mu(style) * Dim::from_i64(4)));
            } else {
                kids.push(self.glyph(styled_char(c, ts), style)?);
            }
        }
        Ok(Item {
            bx: MathBox::hpack(kids),
            class: Some(AtomKind::Ord),
        })
    }

    /// Lays out a text run. Inline math boxes come from the planned children,
    /// in document order (see `plan_text`).
    fn text_items(&self, run: &TextRun, ts: TextStyle, style: MathStyle) -> Result<Item, Error> {
        if ts == TextStyle::Pmb {
            return self.pmb(&run.to_plain_string(), style);
        }

        let mut kids = Vec::new();
        let mut stack = vec![(run.items().iter(), ts)];

        while let Some((mut iter, cur_style)) = stack.pop() {
            while let Some(item) = iter.next() {
                match item {
                    TextItem::Str(s) => {
                        for c in s.chars() {
                            kids.push(self.glyph(styled_char(c, cur_style), style)?);
                        }
                    }
                    TextItem::Space | TextItem::ControlSpace | TextItem::NoBreakSpace => {
                        kids.push(MathBox::kern(self.params.mu(style) * Dim::from_i64(4)));
                    }
                    TextItem::Symbol(s) => match *s {
                        "ldots" => {
                            kids.push(self.glyph(styled_char('\u{2026}', cur_style), style)?);
                        }
                        "quad" => {
                            kids.push(MathBox::kern(self.params.mu(style) * Dim::from_i64(18)));
                        }
                        "qquad" => {
                            kids.push(MathBox::kern(self.params.mu(style) * Dim::from_i64(36)));
                        }
                        _ => {
                            kids.push(MathBox::kern(self.params.mu(style) * Dim::from_i64(4)));
                        }
                    },
                    TextItem::Nested(st, r) => {
                        stack.push((iter, cur_style));
                        stack.push((r.items().iter(), *st));
                        break;
                    }
                    TextItem::Math(_) => {
                        kids.push(self.take_box()?);
                    }
                }
            }
        }

        Ok(Item {
            bx: MathBox::hpack(kids),
            class: Some(AtomKind::Ord),
        })
    }

    fn pmb(&self, s: &str, style: MathStyle) -> Result<Item, Error> {
        let base = self.text_run(s, TextStyle::Rm, style)?;
        let dx = self.params.em(style) / Dim::from_i64(25);
        let shifted = MathBox::hpack(vec![MathBox::kern(dx.clone()), base.bx.clone()]);
        Ok(Item {
            class: Some(AtomKind::Ord),
            bx: MathBox {
                width: &base.bx.width + &dx,
                height: base.bx.height.clone(),
                depth: base.bx.depth.clone(),
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: BoxContent::Overlap(vec![base.bx, shifted]),
            },
        })
    }

    fn operator(&self, name: &str, limits: bool, style: MathStyle) -> Result<Item, Error> {
        if let Some(ch) = single_glyph(name) {
            if !ch.is_ascii_alphabetic() {
                return self.large_op(ch, None, None, style, limits);
            }
        }
        self.text_run(name, TextStyle::Rm, style).map(|mut it| {
            it.class = Some(AtomKind::Op);
            it
        })
    }

    fn row(&self, items: &[MathNode], style: MathStyle) -> Result<Item, Error> {
        if items.is_empty() {
            return Ok(Item {
                bx: MathBox::empty(),
                class: Some(AtomKind::Ord),
            });
        }
        let mut laid = Vec::new();
        for _n in items {
            laid.push(self.take_item()?);
        }
        let n = laid.len();
        let mut classes: Vec<Option<AtomKind>> = Vec::with_capacity(n);
        for i in 0..n {
            let prev = if i == 0 { None } else { laid[i - 1].class };
            let next = if i + 1 < n { laid[i + 1].class } else { None };
            classes.push(laid[i].class.map(|c| convert_bin(prev, c, next)));
        }
        let mut out = Vec::new();
        for i in 0..n {
            if i > 0 {
                if let (Some(l), Some(r)) = (classes[i - 1], classes[i]) {
                    let mu = atom_space_mu(l, r, style);
                    let w = space_width(mu, &self.params, style);
                    if !w.is_zero() {
                        out.push(MathBox::kern(w));
                    }
                }
            }
            out.push(laid[i].bx.clone());

            if row_needs_math_italic_kern(&items[i]) && !laid[i].bx.italic.is_zero() {
                out.push(MathBox::kern(laid[i].bx.italic.clone()));
            }
        }
        let class = if n == 1 {
            classes[0]
        } else {
            Some(AtomKind::Ord)
        };
        Ok(Item {
            bx: MathBox::hpack(out),
            class,
        })
    }

    fn fraction(&self, _num: &MathNode, _den: &MathNode, style: MathStyle) -> Result<Item, Error> {
        let num_b = self.take_box()?;
        let den_b = self.take_box()?;
        let s = self.params.scale(style);
        let axis = &self.params.axis_height * &s;
        let thick = &self.params.fraction_rule_thickness * &s;
        let half = &thick / &Dim::from_i64(2);
        let (shift_up0, shift_dn0, gap_num, gap_den) = if style.is_display() {
            (
                &self.params.fraction_numerator_display_style_shift_up * &s,
                &self.params.fraction_denominator_display_style_shift_down * &s,
                &self.params.fraction_num_display_style_gap_min * &s,
                &self.params.fraction_denom_display_style_gap_min * &s,
            )
        } else {
            (
                &self.params.fraction_numerator_shift_up * &s,
                &self.params.fraction_denominator_shift_down * &s,
                &self.params.fraction_numerator_gap_min * &s,
                &self.params.fraction_denominator_gap_min * &s,
            )
        };
        let num_shift = shift_up0.max(&(&axis + &half + &gap_num + &num_b.depth));
        let den_shift = shift_dn0.max(&(&den_b.height + &gap_den + &half - &axis).clamp_nonneg());
        let content_width = num_b.width.max(&den_b.width);
        let num_c = center_in(num_b, &content_width);
        let den_c = center_in(den_b, &content_width);
        let num_h = num_c.height.clone();
        let den_d = den_c.depth.clone();
        let bar = MathBox::rule(content_width.clone(), thick.clone(), Dim::zero())
            .with_shift(&axis - &half);
        let inner = MathBox {
            width: content_width,
            height: &num_shift + &num_h,
            depth: &den_shift + &den_d,
            italic: Dim::zero(),
            shift: Dim::zero(),
            content: BoxContent::Overlap(vec![
                num_c.with_shift(num_shift),
                bar,
                den_c.with_shift(-den_shift),
            ]),
        };

        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: inner,
        })
    }

    fn radical(
        &self,
        deg: Option<&MathNode>,
        _rad: &MathNode,
        style: MathStyle,
    ) -> Result<Item, Error> {
        let rad_b = self.take_box()?;
        let s = self.params.scale(style);
        let thick = &self.params.radical_rule_thickness * &s;
        let extra = &self.params.radical_extra_ascender * &s;
        let gap = if style.is_display() {
            &self.params.radical_display_style_vertical_gap * &s
        } else {
            &self.params.radical_vertical_gap * &s
        };
        // RadicalExtraAscender reserves whitespace above the
        // finished radical; it is not part of the minimum span passed to MathVariants.
        let needed = &rad_b.height + &rad_b.depth + &gap + &thick;
        let mut surd = self.sized_glyph('√', &needed, style)?;
        let surd_span = &surd.height + &surd.depth;
        let radicand_span = &rad_b.height + &rad_b.depth;

        // A ready-made radical variant can be taller
        // than the minimum request. Redistribute that discrete slack into
        // the vertical gap instead of lowering the entire surd to the
        // original rule position.
        let distributed_gap =
            (&(&(&surd_span - &thick) - &radicand_span) + &gap) / &Dim::from_i64(2);
        let gap = gap.max(&distributed_gap);
        let inner_ascent = &rad_b.height + &gap + &thick;
        let surd_descent = (&surd_span - &inner_ascent).clamp_nonneg();
        surd.shift = &inner_ascent - &surd.height;

        let bar = MathBox::rule(rad_b.width.clone(), thick.clone(), Dim::zero())
            .with_shift(&rad_b.height + &gap);
        let rad_col = MathBox {
            width: rad_b.width.clone(),
            height: &inner_ascent + &extra,
            depth: rad_b.depth.clone(),
            italic: Dim::zero(),
            shift: Dim::zero(),
            content: BoxContent::Overlap(vec![bar, rad_b.clone()]),
        };
        let mut kids = vec![surd, rad_col];
        let mut width = {
            let packed = MathBox::hpack(vec![kids[0].clone(), kids[1].clone()]);
            packed.width.clone()
        };
        let mut height = &inner_ascent + &extra;
        let mut depth = rad_b.depth.max(&surd_descent);
        if let Some(_d) = deg {
            let db = self.take_box()?;
            let before = &self.params.radical_kern_before_degree * &s;
            let after = &self.params.radical_kern_after_degree * &s;
            let pct = Dim::from_i64(i64::from(self.params.radical_degree_bottom_raise_percent))
                / Dim::from_i64(100);

            // radicalDegreeBottomRaisePercent is the height of the
            // degree's ink bottom above the bottom of the radical sign.
            let raise = &(&(&surd_span * &pct) - &surd_descent) + &db.depth;
            height = height.max(&(&db.height + &raise));
            depth = depth.max(&(&db.depth - &raise).clamp_nonneg());
            let deg_box = db.with_shift(raise);
            kids = vec![
                MathBox::kern(before),
                deg_box,
                MathBox::kern(after),
                kids[0].clone(),
                kids[1].clone(),
            ];
            width = {
                let packed = MathBox::hpack(kids.clone());
                packed.width.clone()
            };
        }
        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: MathBox {
                width,
                height,
                depth,
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: BoxContent::HList(kids),
            },
        })
    }

    fn scripts(
        &self,
        _base: &MathNode,
        sub: Option<&MathNode>,
        sup: Option<&MathNode>,
        style: MathStyle,
    ) -> Result<Item, Error> {
        let base_it = self.take_item()?;
        self.attach_scripts_to_box(base_it.bx, base_it.class, sub, sup, style)
    }

    fn attach_scripts_to_box(
        &self,
        base: MathBox,
        class: Option<AtomKind>,
        sub: Option<&MathNode>,
        sup: Option<&MathNode>,
        style: MathStyle,
    ) -> Result<Item, Error> {
        if sub.is_none() && sup.is_none() {
            return Ok(Item { bx: base, class });
        }
        let s = self.params.scale(style);
        let simple_character_nucleus = matches!(&base.content, BoxContent::Glyph { .. });
        let after = &self.params.space_after_script * &self.params.scale(style);
        let mut sup_shift = Dim::zero();
        let mut sub_shift = Dim::zero();
        let sup_laid = if let Some(_e) = sup {
            sup_shift = if style.is_cramped() {
                &self.params.superscript_shift_up_cramped * &s
            } else {
                &self.params.superscript_shift_up * &s
            };
            Some(self.take_box()?)
        } else {
            None
        };
        let sub_laid = if let Some(_u) = sub {
            sub_shift = &self.params.subscript_shift_down * &s;
            Some(self.take_box()?)
        } else {
            None
        };
        if simple_character_nucleus {
            if let Some(sp) = &sup_laid {
                let min_bottom = &self.script_placement.superscript_bottom_min * &s;
                sup_shift = sup_shift.max(&(&sp.depth + &min_bottom));
            }

            if let Some(sb) = &sub_laid {
                let max_top = &self.script_placement.subscript_top_max * &s;
                sub_shift = sub_shift.max(&(&sb.height - &max_top).clamp_nonneg());
            }
        }

        self.enforce_paired_script_constraints(
            sup_laid.as_ref(),
            sub_laid.as_ref(),
            &s,
            simple_character_nucleus,
            &mut sup_shift,
            &mut sub_shift,
        );

        let mut kids = vec![base.clone()];
        let mut width = base.width.clone();
        if sup_laid.is_some() && !base.italic.is_zero() {
            kids.push(MathBox::kern(base.italic.clone()));
            width = &width + &base.italic;
        }
        let mut slot_w = Dim::zero();
        let mut slot_h = Dim::zero();
        let mut slot_d = Dim::zero();
        let mut slot_kids = Vec::new();
        if let Some(sp) = sup_laid {
            slot_w = slot_w.max(&sp.width);
            slot_h = slot_h.max(&(&sp.height + &sup_shift));
            slot_d = slot_d.max(&(&sp.depth - &sup_shift).clamp_nonneg());
            slot_kids.push(sp.with_shift(sup_shift));
        }
        if let Some(sb) = sub_laid {
            slot_w = slot_w.max(&sb.width);
            slot_h = slot_h.max(&(&sb.height - &sub_shift).clamp_nonneg());
            slot_d = slot_d.max(&(&sb.depth + &sub_shift));
            slot_kids.push(sb.with_shift(-sub_shift));
        }
        kids.push(MathBox {
            width: slot_w.clone(),
            height: slot_h.clone(),
            depth: slot_d.clone(),
            italic: Dim::zero(),
            shift: Dim::zero(),
            content: BoxContent::Overlap(slot_kids),
        });
        if !after.is_zero() {
            kids.push(MathBox::kern(after.clone()));
        }
        width = &width + &slot_w + &after;
        Ok(Item {
            class,
            bx: MathBox {
                width,
                height: base.height.max(&slot_h),
                depth: base.depth.max(&slot_d),
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: BoxContent::HList(kids),
            },
        })
    }

    fn enforce_paired_script_constraints(
        &self,
        sup: Option<&MathBox>,
        sub: Option<&MathBox>,
        scale: &Dim,
        simple_character_nucleus: bool,
        sup_shift: &mut Dim,
        sub_shift: &mut Dim,
    ) {
        let (Some(sp), Some(sb)) = (sup, sub) else {
            return;
        };

        let gap = &*sup_shift + &*sub_shift - &sp.depth - &sb.height;
        let min_gap = &self.params.sub_superscript_gap_min * scale;

        if matches!(gap.cmp(&min_gap), Some(Ordering::Less)) {
            *sub_shift = &*sub_shift + (&min_gap - &gap);
        }

        if simple_character_nucleus {
            let current_bottom = &*sup_shift - &sp.depth;
            let target_bottom =
                &self.script_placement.superscript_bottom_max_with_subscript * scale;

            if matches!(current_bottom.cmp(&target_bottom), Some(Ordering::Less)) {
                let raise = &target_bottom - &current_bottom;
                let lowered_subscript = &*sub_shift - &raise;

                if !matches!(
                    lowered_subscript.cmp(&Dim::zero()),
                    Some(Ordering::Less) | None
                ) {
                    *sup_shift = &*sup_shift + &raise;
                    *sub_shift = lowered_subscript;
                }
            }
        }
    }
    fn delimited(
        &self,
        open: &Delimiter,
        _body: &MathNode,
        close: &Delimiter,
        style: MathStyle,
    ) -> Result<Item, Error> {
        let body_b = self.take_box()?;
        let s = self.params.scale(style);
        let axis = &self.params.axis_height * &s;
        let needed = self.delimiter_target(&body_b.height, &body_b.depth, &axis);
        let left = self.center_delimiter(self.delim_box(open, &needed, style)?, &axis);
        let right = self.center_delimiter(self.delim_box(close, &needed, style)?, &axis);
        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: shifted_hpack(vec![left, body_b, right]),
        })
    }

    fn delimiter_target(&self, height: &Dim, depth: &Dim, axis: &Dim) -> Dim {
        let above = (height - axis).clamp_nonneg();
        let below = depth + axis;
        let max_distance = above.max(&below);
        let factor_target =
            &max_distance * &Dim::ratio(TEX_DELIMITER_FACTOR_NUM, TEX_DELIMITER_FACTOR_DEN);
        let shortfall_target =
            (&(&max_distance * &Dim::from_i64(2)) - &self.delimiter_shortfall).clamp_nonneg();
        factor_target.max(&shortfall_target)
    }

    fn center_delimiter(&self, mut bx: MathBox, axis: &Dim) -> MathBox {
        if matches!(bx.content, BoxContent::Empty) {
            return bx;
        }
        let center = &(&bx.height - &bx.depth) / &Dim::from_i64(2);
        bx.shift = axis - &center;
        bx
    }

    fn explicit_delim_span(&self, size: DelimSize, style: MathStyle) -> Dim {
        let em = self.params.em(style);
        let n = match size {
            DelimSize::Big => 12,
            DelimSize::Big2 => 18,
            DelimSize::Bigg => 24,
            DelimSize::Bigg2 => 30,
        };
        em * Dim::from_i64(n) / Dim::from_i64(10)
    }

    fn delim_box(&self, d: &Delimiter, needed: &Dim, style: MathStyle) -> Result<MathBox, Error> {
        match d {
            Delimiter::Empty => Ok(MathBox::empty()),
            Delimiter::Char(c) => self.sized_glyph(*c, needed, style),
            Delimiter::Named(n) => {
                let ch = named_delim(n)?;
                self.sized_glyph(ch, needed, style)
            }
        }
    }

    fn sized_glyph(&self, ch: char, needed: &Dim, style: MathStyle) -> Result<MathBox, Error> {
        let base = self.font.glyph(ch)?;
        let mut best = self.glyph(ch, style)?;
        let mut best_span = &best.height + &best.depth;
        for gid in self.font.vertical_variants(base.glyph_id) {
            let cand = self.glyph_id(ch, gid, style)?;
            let span = &cand.height + &cand.depth;
            let meets = span.cmp(needed).is_some_and(|o| o != Ordering::Less);
            let best_short = best_span.cmp(needed).is_some_and(|o| o == Ordering::Less);
            let tighter = span.cmp(&best_span).is_some_and(|o| o == Ordering::Less);
            let taller = span.cmp(&best_span).is_some_and(|o| o == Ordering::Greater);
            if (meets && (best_short || tighter)) || (best_short && taller) {
                best_span = span;
                best = cand;
            }
        }
        Ok(best)
    }

    fn stretch_h(&self, base: MathBox, needed: &Dim, style: MathStyle) -> Result<MathBox, Error> {
        let BoxContent::Glyph { ch, glyph_id, .. } = base.content else {
            return Ok(base);
        };
        let mut best = base;
        let mut best_w = best.width.clone();
        for gid in self.font.horizontal_variants(glyph_id) {
            let cand = self.glyph_id(ch, gid, style)?;
            let wider_needed = best_w.cmp(needed).is_some_and(|o| o == Ordering::Less);
            let fits = cand.width.cmp(needed).is_some_and(|o| o != Ordering::Less);
            let tighter = cand.width.cmp(&best_w).is_some_and(|o| o == Ordering::Less);
            let longer = cand
                .width
                .cmp(&best_w)
                .is_some_and(|o| o == Ordering::Greater);
            if (fits && (wider_needed || tighter)) || (wider_needed && longer) {
                best_w = cand.width.clone();
                best = cand;
            }
        }
        if best_w.cmp(needed).is_some_and(|o| o != Ordering::Less) {
            return Ok(best);
        }
        if let Some(asm) = self.assemble_h(ch, glyph_id, needed, style) {
            if asm
                .width
                .cmp(&best_w)
                .is_some_and(|o| o == Ordering::Greater)
            {
                return Ok(asm);
            }
        }
        Ok(best)
    }

    fn assemble_h(&self, ch: char, gid: u16, needed: &Dim, style: MathStyle) -> Option<MathBox> {
        let parts = self.font.horizontal_assembly_parts(gid);
        if parts.is_empty() {
            return None;
        }
        let s = self.params.scale(style);
        let fu = |n: u16| Dim::from_font_units(i64::from(n), self.params.units_per_em) * &s;
        let sequence = |copies: u32| {
            let mut v = Vec::new();
            for &(id, start, end, adv, ext) in &parts {
                if ext {
                    for _ in 0..copies {
                        v.push((id, start, end, adv));
                    }
                } else {
                    v.push((id, start, end, adv));
                }
            }
            v
        };
        let width_of = |seq: &[(u16, u16, u16, u16)]| {
            if seq.is_empty() {
                return Dim::zero();
            }
            let mut w = fu(seq[0].3);
            for i in 1..seq.len() {
                let overlap = seq[i - 1].2.min(seq[i].1);
                w = &w + &fu(seq[i].3) - &fu(overlap);
            }
            w
        };
        let mut copies = 0u32;
        while copies < 64 {
            if width_of(&sequence(copies))
                .cmp(needed)
                .is_some_and(|o| o != Ordering::Less)
            {
                break;
            }
            copies += 1;
        }
        let seq = sequence(copies);
        if seq.is_empty() {
            return None;
        }
        let mut kids = Vec::new();
        for (i, &(id, start, _, _)) in seq.iter().enumerate() {
            if i > 0 {
                let overlap = seq[i - 1].2.min(start);
                kids.push(MathBox::kern(-(fu(overlap))));
            }
            kids.push(self.glyph_id(ch, id, style).ok()?);
        }
        Some(MathBox::hpack(kids))
    }

    fn large_op(
        &self,
        ch: char,
        lo: Option<&MathNode>,
        hi: Option<&MathNode>,
        style: MathStyle,
        limits_in_display: bool,
    ) -> Result<Item, Error> {
        let min_h = if style.is_display() {
            self.params.display_operator_min_height.clone() * self.params.scale(style)
        } else {
            Dim::zero()
        };
        let mut op = self.sized_glyph(ch, &min_h, style)?;
        let use_limits = limits_in_display && style.is_display();
        if !use_limits {
            return self.attach_limits(op, hi, lo, style, false);
        }

        // Displayed large operators with limits are
        // boxed on the OpenType MATH axis before their limits are positioned.
        let axis = &self.params.axis_height * &self.params.scale(style);
        let center = &(&op.height - &op.depth) / &Dim::from_i64(2);
        op.shift = &axis - &center;
        self.attach_large_op_limits(op, hi, lo, style)
    }

    fn integral_op(
        &self,
        kind: IntegralKind,
        lo: Option<&MathNode>,
        hi: Option<&MathNode>,
        style: MathStyle,
    ) -> Result<Item, Error> {
        let ch = match kind {
            IntegralKind::Int => '∫',
            IntegralKind::Iint => '∬',
            IntegralKind::Iiint => '∭',
            IntegralKind::Oint => '∮',
            IntegralKind::Oiint => '∯',
        };
        let min_h = if style.is_display() {
            self.params.display_operator_min_height.clone() * self.params.scale(style)
        } else {
            Dim::zero()
        };
        let op = self.sized_glyph(ch, &min_h, style)?;

        if !style.is_display() || (lo.is_none() && hi.is_none()) {
            return self.attach_limits(op, hi, lo, style, false);
        }

        self.attach_integral_scripts(op, lo, hi, style)
    }

    fn attach_integral_scripts(
        &self,
        mut op: MathBox,
        sub: Option<&MathNode>,
        sup: Option<&MathNode>,
        style: MathStyle,
    ) -> Result<Item, Error> {
        let scale = self.params.scale(style);

        let sup_laid = match sup {
            Some(_) => Some(self.take_box()?),
            None => None,
        };
        let sub_laid = match sub {
            Some(_) => Some(self.take_box()?),
            None => None,
        };

        // Display integrals are enlarged
        // no-limits operators. Center the nucleus on the MATH axis,
        // then use the OpenType baseline-drop constants for side scripts.
        // Italic correction offsets only the superscript branch and is
        // removed from the common operator width.
        let axis = &self.params.axis_height * &scale;
        let center = &(&op.height - &op.depth) / &Dim::from_i64(2);
        op.shift = &axis - &center;

        let base_height = (&op.height + &op.shift).clamp_nonneg();
        let base_depth = (&op.depth - &op.shift).clamp_nonneg();

        let mut sup_shift = sup_laid.as_ref().map_or_else(Dim::zero, |sup_box| {
            let standard = if style.is_cramped() {
                &self.params.superscript_shift_up_cramped * &scale
            } else {
                &self.params.superscript_shift_up * &scale
            };
            let from_base =
                &base_height - &(&self.script_placement.superscript_baseline_drop_max * &scale);
            let from_bottom =
                &sup_box.depth + &(&self.script_placement.superscript_bottom_min * &scale);

            standard.max(&from_base).max(&from_bottom)
        });

        let mut sub_shift = sub_laid.as_ref().map_or_else(Dim::zero, |sub_box| {
            let standard = &self.params.subscript_shift_down * &scale;
            let from_base =
                &base_depth + &(&self.script_placement.subscript_baseline_drop_min * &scale);
            let from_top = (&sub_box.height - &(&self.script_placement.subscript_top_max * &scale))
                .clamp_nonneg();

            standard.max(&from_base).max(&from_top)
        });

        self.enforce_paired_script_constraints(
            sup_laid.as_ref(),
            sub_laid.as_ref(),
            &scale,
            true,
            &mut sup_shift,
            &mut sub_shift,
        );

        let italic = op.italic.clone();
        let mut slot_width = Dim::zero();
        let mut slot_height = Dim::zero();
        let mut slot_depth = Dim::zero();
        let mut slot_children = Vec::new();

        if let Some(sup_box) = sup_laid {
            let mut branch = sup_box.with_shift(sup_shift);

            if !italic.is_zero() {
                let vertical_shift = branch.shift.clone();
                branch.shift = Dim::zero();
                branch = MathBox::hpack(vec![MathBox::kern(italic.clone()), branch]);
                branch.shift = vertical_shift;
            }

            slot_width = slot_width.max(&branch.width);
            slot_height = slot_height.max(&(&branch.height + &branch.shift).clamp_nonneg());
            slot_depth = slot_depth.max(&(&branch.depth - &branch.shift).clamp_nonneg());
            slot_children.push(branch);
        }

        if let Some(sub_box) = sub_laid {
            let branch = sub_box.with_shift(-sub_shift);

            slot_width = slot_width.max(&branch.width);
            slot_height = slot_height.max(&(&branch.height + &branch.shift).clamp_nonneg());
            slot_depth = slot_depth.max(&(&branch.depth - &branch.shift).clamp_nonneg());
            slot_children.push(branch);
        }

        let slot = MathBox {
            width: slot_width,
            height: slot_height,
            depth: slot_depth,
            italic: Dim::zero(),
            shift: Dim::zero(),
            content: BoxContent::Overlap(slot_children),
        };

        let after = &self.params.space_after_script * &scale;

        let mut children = vec![op];

        if !italic.is_zero() {
            children.push(MathBox::kern(-italic));
        }

        children.push(slot);

        if !after.is_zero() {
            children.push(MathBox::kern(after));
        }

        Ok(Item {
            class: Some(AtomKind::Op),
            bx: shifted_hpack(children),
        })
    }
    fn attach_large_op_limits(
        &self,
        op: MathBox,
        over: Option<&MathNode>,
        under: Option<&MathNode>,
        style: MathStyle,
    ) -> Result<Item, Error> {
        let s = self.params.scale(style);
        let op_shift = op.shift.clone();
        let op_h = (&op.height + &op_shift).clamp_nonneg();
        let op_d = (&op.depth - &op_shift).clamp_nonneg();

        let over_b = match over {
            Some(_) => Some(self.take_box()?),
            None => None,
        };
        let under_b = match under {
            Some(_) => Some(self.take_box()?),
            None => None,
        };

        let mut width = op.width.clone();
        if let Some(ref o) = over_b {
            width = width.max(&o.width);
        }
        if let Some(ref u) = under_b {
            width = width.max(&u.width);
        }

        let mut height = op_h.clone();
        let mut depth = op_d.clone();

        let mut centered_op = center_in(op, &width);
        centered_op.shift = op_shift;
        let mut kids = vec![centered_op];

        if let Some(ob) = over_b {
            let gap = self.params.upper_limit_gap_min.clone() * &s;
            let rise = self.params.upper_limit_baseline_rise_min.clone() * &s;

            // Baseline-rise and edge-gap minima
            // are independent constraints. Limit depth participates only
            // in the edge-gap inequality.
            let offset = rise.max(&(&gap + &ob.depth));
            let sh = &op_h + &offset;

            height = height.max(&(&sh + &ob.height));
            kids.push(center_in(ob, &width).with_shift(sh));
        }

        if let Some(ub) = under_b {
            let gap = self.params.lower_limit_gap_min.clone() * &s;
            let drop = self.params.lower_limit_baseline_drop_min.clone() * &s;

            // The lower relation mirrors the upper relation: limit ascent
            // participates only in the edge-gap inequality.
            let offset = drop.max(&(&gap + &ub.height));
            let sh = &op_d + &offset;

            depth = depth.max(&(&sh + &ub.depth));
            kids.push(center_in(ub, &width).with_shift(-sh));
        }

        Ok(Item {
            class: Some(AtomKind::Op),
            bx: MathBox {
                width,
                height,
                depth,
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: BoxContent::Overlap(kids),
            },
        })
    }

    fn attach_limits(
        &self,
        op: MathBox,
        over: Option<&MathNode>,
        under: Option<&MathNode>,
        style: MathStyle,
        as_limits: bool,
    ) -> Result<Item, Error> {
        if !as_limits {
            return self.attach_scripts_to_box(op, Some(AtomKind::Op), under, over, style);
        }
        let s = self.params.scale(style);
        let op_h = op.height.clone();
        let op_d = op.depth.clone();
        let over_b = match over {
            Some(_) => Some(self.take_box()?),
            None => None,
        };
        let under_b = match under {
            Some(_) => Some(self.take_box()?),
            None => None,
        };
        let mut width = op.width.clone();
        if let Some(ref o) = over_b {
            width = width.max(&o.width);
        }
        if let Some(ref u) = under_b {
            width = width.max(&u.width);
        }
        let mut height = op_h.clone();
        let mut depth = op_d.clone();
        let mut kids = vec![center_in(op, &width)];
        if let Some(ob) = over_b {
            let gap = self.params.upper_limit_gap_min.clone() * &s;
            let rise = self.params.upper_limit_baseline_rise_min.clone() * &s;
            let extra = gap.max(&rise);
            height = &height + &ob.height + &ob.depth + &extra;
            let sh = &op_h + &extra + &ob.depth;
            kids.push(center_in(ob, &width).with_shift(sh));
        }
        if let Some(ub) = under_b {
            let gap = self.params.lower_limit_gap_min.clone() * &s;
            let drop = self.params.lower_limit_baseline_drop_min.clone() * &s;
            let extra = gap.max(&drop);
            depth = &depth + &ub.height + &ub.depth + &extra;
            let sh = -(&op_d + &extra + &ub.height);
            kids.push(center_in(ub, &width).with_shift(sh));
        }
        Ok(Item {
            class: Some(AtomKind::Op),
            bx: MathBox {
                width,
                height,
                depth,
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: BoxContent::Overlap(kids),
            },
        })
    }

    fn not_overlay(&self, base: &MathNode, b: MathBox, style: MathStyle) -> Result<Item, Error> {
        let slash = match self.glyph('\u{0338}', style) {
            Ok(bx) => bx,
            Err(_) => self.glyph('/', style)?,
        };
        let width = b.width.max(&slash.width);
        let two = Dim::from_i64(2);
        let b_axis = &(&b.height - &b.depth) / &two;
        let s_axis = &(&slash.height - &slash.depth) / &two;
        let raise = &b_axis - &s_axis;
        let height = b.height.max(&(&slash.height + &raise).max(&slash.height));
        let depth = b.depth.max(&(&slash.depth - &raise).clamp_nonneg());
        Ok(Item {
            class: class_of(base),
            bx: MathBox {
                width: width.clone(),
                height,
                depth,
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: BoxContent::Overlap(vec![
                    center_in(b, &width),
                    center_in(slash, &width).with_shift(raise),
                ]),
            },
        })
    }

    fn accent(&self, base: &MathNode, kind: AccentKind, style: MathStyle) -> Result<Item, Error> {
        let b = self.take_box()?;
        if kind == AccentKind::Not {
            return self.not_overlay(base, b, style);
        }
        if kind == AccentKind::Boxed {
            return Ok(Item {
                class: Some(AtomKind::Ord),
                bx: self.boxed_frame(b, style),
            });
        }
        if matches!(
            kind,
            AccentKind::Cancel | AccentKind::BCancel | AccentKind::XCancel
        ) {
            let mut kids = vec![b.clone()];
            kids.extend(self.cancel_lines(&b, kind, style));
            return Ok(Item {
                class: Some(AtomKind::Ord),
                bx: MathBox {
                    width: b.width.clone(),
                    height: b.height.clone(),
                    depth: b.depth.clone(),
                    italic: Dim::zero(),
                    shift: Dim::zero(),
                    content: BoxContent::Overlap(kids),
                },
            });
        }
        if matches!(kind, AccentKind::Overline | AccentKind::Underline) {
            return self.bar_rule(b, kind == AccentKind::Underline, style);
        }
        let mut acc = self.accent_glyph(kind, style)?;
        let stretchy = is_stretchy_accent(kind);
        let hat_tilde = is_hat_tilde_accent(kind);

        if matches!(kind, AccentKind::WideHat | AccentKind::WideTilde) {
            acc = self.wide_hat_tilde_glyph(acc, &b.width, kind, style)?;
        } else if stretchy {
            acc = self.stretch_h(acc, &b.width, style)?;
        }

        if is_under_accent(kind) {
            return Ok(Item {
                class: Some(AtomKind::Ord),
                bx: self.place_under(b, acc, style),
            });
        }

        let nucleus_width = hat_tilde_nucleus_width(&b, kind);

        let x_off = if hat_tilde {
            self.hat_tilde_accent_x_off(&b, &acc, style)
        } else if stretchy {
            let extra = &b.width - &acc.width;
            &extra / &Dim::from_i64(2)
        } else {
            self.accent_x_off(&b, &acc, kind)
        };

        // Hat/tilde compatibility keeps AccentBaseHeight even when
        // the recursively laid-out nucleus is cramped. The generic
        // path retains the 2.x flattened-height rule for other accents.
        let raise = if hat_tilde {
            self.hat_tilde_accent_raise(&b, style)
        } else {
            self.accent_raise(&b, kind, style)
        };

        let mut placed = overlay_accent(b, acc, x_off, raise);

        if let Some(width) = nucleus_width {
            placed.width = width;
        }

        Ok(Item {
            class: Some(AtomKind::Ord),
            bx: placed,
        })
    }

    fn accent_glyph(&self, kind: AccentKind, style: MathStyle) -> Result<MathBox, Error> {
        for &ch in accent_candidates(kind) {
            if let Ok(bx) = self.glyph(ch, style) {
                return Ok(bx);
            }
        }
        Err(Error::Unsupported {
            what: format!("accent {}", kind.gold()),
        })
    }

    // STIX exposes wide hat/tilde variants from
    // the combining U+0302/U+0303 constructions, not from the spacing
    // glyph used for the fixed accent. Take the smallest variant at
    // least as wide as the nucleus so the accent can overhang. If none
    // covers, keep the widest. The spacing glyph is the fallback.
    fn wide_hat_tilde_glyph(
        &self,
        fixed: MathBox,
        target_width: &Dim,
        kind: AccentKind,
        style: MathStyle,
    ) -> Result<MathBox, Error> {
        let seed_ch = match kind {
            AccentKind::WideHat => '\u{0302}',
            AccentKind::WideTilde => '\u{0303}',
            _ => return Ok(fixed),
        };

        let seed = self.font.glyph(seed_ch)?;

        let mut selected = fixed;
        let mut selected_width = selected.width.clone();
        let mut covered = selected_width
            .cmp(target_width)
            .is_some_and(|ordering| ordering != Ordering::Less);

        for glyph_id in self.font.horizontal_variants(seed.glyph_id) {
            if glyph_id == seed.glyph_id {
                continue;
            }

            let candidate = self.glyph_id(seed_ch, glyph_id, style)?;

            if candidate.width.is_zero() {
                continue;
            }

            let covers = candidate
                .width
                .cmp(target_width)
                .is_some_and(|ordering| ordering != Ordering::Less);
            let narrower = candidate
                .width
                .cmp(&selected_width)
                .is_some_and(|ordering| ordering == Ordering::Less);
            let wider = candidate
                .width
                .cmp(&selected_width)
                .is_some_and(|ordering| ordering == Ordering::Greater);

            if covers && (!covered || narrower) {
                selected_width = candidate.width.clone();
                selected = candidate;
                covered = true;
            } else if !covered && wider {
                selected_width = candidate.width.clone();
                selected = candidate;
            }
        }

        Ok(selected)
    }

    // MATH TopAccentAttachment is expressed in font em. Box
    // coordinates are already scaled to the current math style,
    // therefore the attachment coordinate must use the same scale.
    fn hat_tilde_accent_x_off(&self, base: &MathBox, acc: &MathBox, style: MathStyle) -> Dim {
        let scale = self.params.scale(style);

        let two = Dim::from_i64(2);

        let base_att = single_glyph_id(base)
            .and_then(|glyph_id| self.font.top_accent_attachment(glyph_id))
            .map_or_else(|| &base.width / &two, |value| value * &scale);

        let acc_att = single_glyph_id(acc)
            .and_then(|glyph_id| self.font.top_accent_attachment(glyph_id))
            .map_or_else(|| &acc.width / &two, |value| value * &scale);

        &base_att - &acc_att
    }

    // AccentBaseHeight is the largest base ink height that needs no
    // vertical raise. Hat/tilde keep this rule for nested cramped
    // nuclei instead of switching to FlattenedAccentBaseHeight.
    fn hat_tilde_accent_raise(&self, base: &MathBox, style: MathStyle) -> Dim {
        let base_height = &self.params.accent_base_height * &self.params.scale(style);

        (&base.height - &base_height).clamp_nonneg()
    }
    fn cancelto(
        &self,
        _value: &MathNode,
        _expr: &MathNode,
        style: MathStyle,
    ) -> Result<Item, Error> {
        let b = self.take_box()?;
        let val = self.take_box()?;
        let mut kids = vec![b.clone()];
        kids.extend(self.cancel_lines(&b, AccentKind::Cancel, style));
        let gap = self.params.space_after_script.clone() * self.params.scale(style);
        let val_x = &b.width + &gap;
        let val_shift = &b.height + &val.depth;
        let val_w = val.width.clone();
        let val_h = val.height.clone();
        kids.push(shift_x(val, val_x.clone()).with_shift(val_shift.clone()));
        let width = &val_x + &val_w;
        let height = b.height.max(&(&val_shift + &val_h));
        Ok(Item {
            class: Some(AtomKind::Ord),
            bx: MathBox {
                width,
                height,
                depth: b.depth.clone(),
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: BoxContent::Overlap(kids),
            },
        })
    }

    fn boxed_frame(&self, inner: MathBox, style: MathStyle) -> MathBox {
        let pad = self.params.mu(style) * Dim::from_i64(3);
        let thick = self.params.fraction_rule_thickness.clone() * self.params.scale(style);
        frame_wrap(thick, None, pad_box(inner, &pad))
    }

    fn bar_rule(&self, b: MathBox, under: bool, style: MathStyle) -> Result<Item, Error> {
        let s = self.params.scale(style);
        let gap = if under {
            self.params.underbar_vertical_gap.clone() * &s
        } else {
            self.params.overbar_vertical_gap.clone() * &s
        };
        let thick = if under {
            self.params.underbar_rule_thickness.clone() * &s
        } else {
            self.params.overbar_rule_thickness.clone() * &s
        };
        let extra = if under {
            self.params.underbar_extra_descender.clone() * &s
        } else {
            self.params.overbar_extra_ascender.clone() * &s
        };
        let mut height = b.height.clone();
        let mut depth = b.depth.clone();
        let bar = if under {
            depth = &depth + &gap + &thick + &extra;
            MathBox::rule(b.width.clone(), thick, Dim::zero()).with_shift(-(&b.depth + &gap))
        } else {
            height = &height + &gap + &thick + &extra;
            MathBox::rule(b.width.clone(), thick, Dim::zero()).with_shift(&b.height + &gap)
        };
        Ok(Item {
            class: Some(AtomKind::Ord),
            bx: MathBox {
                width: b.width.clone(),
                height,
                depth,
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: BoxContent::Overlap(vec![b, bar]),
            },
        })
    }

    fn cancel_lines(&self, b: &MathBox, kind: AccentKind, style: MathStyle) -> Vec<MathBox> {
        let t = self.params.fraction_rule_thickness.clone() * self.params.scale(style);
        let w = b.width.clone();
        let h = b.height.clone();
        let d = b.depth.clone();
        let mk = |x1: Dim, y1: Dim, x2: Dim, y2: Dim| MathBox {
            width: w.clone(),
            height: h.clone(),
            depth: d.clone(),
            italic: Dim::zero(),
            shift: Dim::zero(),
            content: BoxContent::Line {
                x1,
                y1,
                x2,
                y2,
                thickness: t.clone(),
            },
        };
        match kind {
            AccentKind::Cancel => vec![mk(Dim::zero(), -d.clone(), w.clone(), h.clone())],
            AccentKind::BCancel => vec![mk(Dim::zero(), h.clone(), w.clone(), -d.clone())],
            AccentKind::XCancel => vec![
                mk(Dim::zero(), -d.clone(), w.clone(), h.clone()),
                mk(Dim::zero(), h.clone(), w.clone(), -d.clone()),
            ],
            _ => Vec::new(),
        }
    }

    fn accent_x_off(&self, base: &MathBox, acc: &MathBox, kind: AccentKind) -> Dim {
        let two = Dim::from_i64(2);
        let base_att = first_glyph_id(base)
            .and_then(|id| self.font.top_accent_attachment(id))
            .unwrap_or_else(|| (&base.width + &base.italic) / &two);
        let acc_att = first_glyph_id(acc)
            .and_then(|id| self.font.top_accent_attachment(id))
            .unwrap_or_else(|| &acc.width / &two);
        match kind {
            AccentKind::Vec | AccentKind::Overrightarrow | AccentKind::Underrightarrow => {
                &base.width + &base.italic - &acc.width
            }
            AccentKind::Acute => &base_att - &acc_att + &(&acc.width / &Dim::from_i64(4)),
            AccentKind::Grave => &base_att - &acc_att - &(&acc.width / &Dim::from_i64(4)),
            _ => &base_att - &acc_att,
        }
    }

    /// Vertical shift of an over-accent glyph.
    ///
    /// Diacritic glyphs are drawn to sit on a base of `AccentBaseHeight`, so
    /// TeX's rule applies: lift only by how far the base rises above that
    /// height. Arrow and brace glyphs sit on the baseline and clear the base.
    /// The branch is chosen by kind, not glyph advance: STIX spacing
    /// diacritics (`ˆ`, `˙`, ...) have non-zero advance.
    fn accent_raise(&self, base: &MathBox, kind: AccentKind, style: MathStyle) -> Dim {
        let s = self.params.scale(style);
        let abh = if style.is_cramped() {
            &self.params.flattened_accent_base_height * &s
        } else {
            &self.params.accent_base_height * &s
        };
        if is_diacritic_accent(kind) {
            (&base.height - &abh).clamp_nonneg()
        } else {
            base.height.max(&abh)
        }
    }

    fn place_under(&self, base: MathBox, acc: MathBox, style: MathStyle) -> MathBox {
        let s = self.params.scale(style);
        let gap = self.params.underbar_vertical_gap.clone() * &s;
        let extra = self.params.underbar_extra_descender.clone() * &s;
        let raise = -(&base.depth + &gap + &acc.height);
        let width = base.width.max(&acc.width);
        let depth = &base.depth + &gap + &acc.height + &acc.depth + &extra;
        MathBox {
            width: width.clone(),
            height: base.height.clone(),
            depth,
            italic: Dim::zero(),
            shift: Dim::zero(),
            content: BoxContent::Overlap(vec![
                center_in(base, &width),
                center_in(acc, &width).with_shift(raise),
            ]),
        }
    }

    fn take_number(&self) -> Option<String> {
        let i = self.idx.get();
        self.idx.set(i + 1);
        self.numbers.assigned(i).map(str::to_string)
    }

    fn number_box(&self, s: &str, style: MathStyle) -> Result<MathBox, Error> {
        Ok(self.text_run(s, TextStyle::Rm, style)?.bx)
    }

    fn attach_number(&self, body: MathBox, num: Option<MathBox>, style: MathStyle) -> MathBox {
        let Some(num) = num else {
            return body;
        };
        let gap = self.params.em(style);
        MathBox::hpack(vec![body, MathBox::kern(gap), num])
    }

    fn reference(&self, key: &str, style: MathStyle) -> Result<Item, Error> {
        let s = self.numbers.lookup(key).ok_or_else(|| Error::Unsupported {
            what: format!("undefined label {key}"),
        })?;
        self.text_run(s, TextStyle::Rm, style)
    }

    fn tag_box(&self, star: bool, _body: &MathNode, style: MathStyle) -> Result<Item, Error> {
        let inner = self.take_box()?;
        let bx = if star {
            inner
        } else {
            let open = self.glyph('(', style)?;
            let close = self.glyph(')', style)?;
            MathBox::hpack(vec![open, inner, close])
        };
        Ok(Item {
            class: Some(AtomKind::Ord),
            bx,
        })
    }

    fn substack(&self, lines: &[MathNode], style: MathStyle) -> Result<Item, Error> {
        if lines.is_empty() {
            return Ok(Item {
                class: Some(AtomKind::Ord),
                bx: MathBox::empty(),
            });
        }

        // AMSMath subarray rows are always Script style,
        // even when the surrounding expression is already Script.
        let mut laid = Vec::with_capacity(lines.len());

        for _line in lines {
            laid.push(self.take_box()?);
        }

        let width = laid
            .iter()
            .fold(Dim::zero(), |current, row| current.max(&row.width));

        let rows: Vec<_> = laid.into_iter().map(|row| center_in(row, &width)).collect();

        let gaps = self.substack_interrow_gaps(&rows);

        let stack = self.center_amsmath_stack(rows, &gaps, style);

        // Large-operator limit placement overwrites the outer
        // MathBox::shift. Keep substack vcentering on the child.
        Ok(Item {
            class: Some(AtomKind::Ord),
            bx: shifted_hpack(vec![stack]),
        })
    }

    fn substack_interrow_gaps(&self, rows: &[MathBox]) -> Vec<Dim> {
        rows.windows(2)
            .map(|pair| {
                let candidate = &(&self.substack.baseline_skip - &pair[0].depth) - &pair[1].height;

                if candidate
                    .cmp(&self.substack.line_skip)
                    .is_some_and(|ordering| ordering != Ordering::Less)
                {
                    candidate
                } else {
                    self.substack.line_skip.clone()
                }
            })
            .collect()
    }

    fn matrix(
        &self,
        style_m: MatrixStyle,
        spec: &[ColSpec],
        rows: &[EnvRow],
        style: MathStyle,
    ) -> Result<Item, Error> {
        if rows.is_empty() {
            return Ok(Item {
                bx: MathBox::empty(),
                class: Some(AtomKind::Inner),
            });
        }
        let body_style = if style_m.is_display_env() {
            MathStyle::Display
        } else {
            style
        };
        match style_m {
            MatrixStyle::Align => self.align_env(rows, body_style, true),
            MatrixStyle::Aligned => self.amsmath_aligned(rows, body_style),
            MatrixStyle::Split => self.align_env(rows, body_style, false),
            MatrixStyle::Gather => self.gather_env(rows, body_style),
            MatrixStyle::Gathered => self.gathered_env(rows, body_style),
            MatrixStyle::Multline => self.multline_env(rows, body_style),
            MatrixStyle::Equation => self.equation_env(rows, body_style),
            MatrixStyle::Array => self.array_env(spec, rows, body_style),
            MatrixStyle::Cases => self.cases_env(rows, body_style),
            _ => self.centered_matrix(style_m, rows, body_style),
        }
    }

    // AMSMath matrix/cases/aligned layouts have
    // environment-specific cell styles, physical spacing and vertical
    // centering rules that the generic grid does not.
    fn centered_matrix(
        &self,
        style_m: MatrixStyle,
        rows: &[EnvRow],
        style: MathStyle,
    ) -> Result<Item, Error> {
        let data = data_cells(rows)?;

        let cells = self.layout_environment_rows(&data, MathStyle::Text)?;

        let column_gap = self.tex_points_in_root_em(TEX_ARRAY_COLSEP_PT * 2);

        let baseline_skip = self.tex_points_in_root_em(TEX_BASELINE_SKIP_PT);
        let line_skip = self.tex_points_in_root_em(TEX_LINE_SKIP_PT);

        let packed_rows = self.build_amsmath_rows(
            cells,
            &column_gap,
            &baseline_skip,
            |_| ColSpec::Center,
            |column| column > 0,
        );

        let gaps = self.tex_interrow_gaps(&packed_rows, &baseline_skip, &line_skip, &Dim::zero());

        let stack = self.center_amsmath_stack(packed_rows, &gaps, style);

        let bx = self.wrap_amsmath_stack(stack, matrix_delims(style_m), style)?;

        Ok(Item {
            class: Some(AtomKind::Inner),
            bx,
        })
    }

    fn cases_env(&self, rows: &[EnvRow], style: MathStyle) -> Result<Item, Error> {
        let data = data_cells(rows)?;

        let cells = self.layout_environment_rows(&data, MathStyle::Text)?;

        let baseline_skip = self.tex_points_in_root_em(TEX_BASELINE_SKIP_PT);
        let line_skip = self.tex_points_in_root_em(TEX_LINE_SKIP_PT);
        let array_stretch = Dim::ratio(6, 5);

        let packed_rows = self.build_amsmath_rows(
            cells,
            &Dim::one(),
            &(&baseline_skip * &array_stretch),
            |_| ColSpec::Left,
            |column| column > 0,
        );

        let gaps = self.tex_interrow_gaps(&packed_rows, &baseline_skip, &line_skip, &Dim::zero());

        let stack = self.center_amsmath_stack(packed_rows, &gaps, style);

        let bx = self.wrap_amsmath_stack(stack, (Some('{'), None), style)?;

        Ok(Item {
            class: Some(AtomKind::Inner),
            bx,
        })
    }

    fn amsmath_aligned(&self, rows: &[EnvRow], style: MathStyle) -> Result<Item, Error> {
        if rows.iter().any(|row| !matches!(row, EnvRow::Cells { .. })) {
            return self.align_env(rows, style, false);
        }

        let mut cells = Vec::with_capacity(rows.len());

        for row in rows {
            let EnvRow::Cells { cells: row, .. } = row else {
                unreachable!("non-cell aligned rows handled above");
            };

            let mut laid = Vec::with_capacity(row.len());

            for (column, _cell) in row.iter().enumerate() {
                let mut bx = self.take_box()?;

                if column % 2 == 1 {
                    let leading = self.aligned_leading_ord_space()?;

                    if !leading.is_zero() {
                        bx = MathBox::hpack(vec![MathBox::kern(leading), bx]);
                    }
                }

                laid.push(bx);
            }

            cells.push(laid);
        }

        let pair_gap = self.tex_points_in_root_em(TEX_MIN_ALIGN_SEP_PT);

        let packed_rows = self.build_amsmath_rows(
            cells,
            &pair_gap,
            &self.tex_points_in_root_em(TEX_BASELINE_SKIP_PT),
            |column| {
                if column % 2 == 0 {
                    ColSpec::Right
                } else {
                    ColSpec::Left
                }
            },
            |column| column > 0 && column % 2 == 0,
        );

        let gaps = self.aligned_interrow_gaps(&packed_rows);

        let stack = self.center_amsmath_stack(packed_rows, &gaps, style);

        let bx = self.wrap_amsmath_stack(stack, (None, None), style)?;

        Ok(Item {
            class: Some(AtomKind::Inner),
            bx,
        })
    }

    fn tex_points_in_root_em(&self, points: i64) -> Dim {
        Dim::from_i64(points) / &self.root_em_size_pt
    }

    fn layout_environment_rows(
        &self,
        rows: &[Vec<MathNode>],
        _style: MathStyle,
    ) -> Result<Vec<Vec<MathBox>>, Error> {
        rows.iter()
            .map(|row| {
                row.iter()
                    .map(|_cell| self.take_box())
                    .collect::<Result<Vec<_>, _>>()
            })
            .collect()
    }

    fn aligned_leading_ord_space(&self) -> Result<Dim, Error> {
        let bare = self.take_box()?;
        let with_ord = self.take_box()?;
        Ok((&with_ord.width - &bare.width).clamp_nonneg())
    }

    fn amsmath_strut(stretch: &Dim) -> MathBox {
        MathBox::rule(
            Dim::zero(),
            &Dim::ratio(7, 10) * stretch,
            &Dim::ratio(3, 10) * stretch,
        )
    }

    fn build_amsmath_rows(
        &self,
        rows: Vec<Vec<MathBox>>,
        gap: &Dim,
        strut_stretch: &Dim,
        align_for_column: impl Fn(usize) -> ColSpec,
        gap_before_column: impl Fn(usize) -> bool,
    ) -> Vec<MathBox> {
        let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);

        let mut widths = vec![Dim::zero(); ncols];

        for row in &rows {
            for (column, cell) in row.iter().enumerate() {
                widths[column] = widths[column].max(&cell.width);
            }
        }

        rows.into_iter()
            .map(|mut row| {
                while row.len() < ncols {
                    row.push(MathBox::empty());
                }

                let mut parts = Vec::with_capacity(row.len().saturating_mul(2).saturating_add(1));

                parts.push(Self::amsmath_strut(strut_stretch));

                for (column, cell) in row.into_iter().enumerate() {
                    if gap_before_column(column) {
                        parts.push(MathBox::kern(gap.clone()));
                    }

                    parts.push(align_in(cell, &widths[column], align_for_column(column)));
                }

                MathBox::hpack(parts)
            })
            .collect()
    }

    fn aligned_interrow_gaps(&self, rows: &[MathBox]) -> Vec<Dim> {
        let jot = self.tex_points_in_root_em(TEX_JOT_PT);
        let baseline_skip = &self.tex_points_in_root_em(TEX_BASELINE_SKIP_PT) + &jot;
        let line_skip = &self.tex_points_in_root_em(TEX_LINE_SKIP_PT) + &jot;

        self.tex_interrow_gaps(rows, &baseline_skip, &line_skip, &jot)
    }

    // TeX appends \baselineskip - prevdepth - height when that glue is
    // at least \lineskiplimit, and \lineskip otherwise.
    fn tex_interrow_gaps(
        &self,
        rows: &[MathBox],
        baseline_skip: &Dim,
        line_skip: &Dim,
        line_skip_limit: &Dim,
    ) -> Vec<Dim> {
        rows.windows(2)
            .map(|pair| {
                let candidate = &(baseline_skip - &pair[0].depth) - &pair[1].height;

                if matches!(candidate.cmp(line_skip_limit), Some(Ordering::Less)) {
                    line_skip.clone()
                } else {
                    candidate
                }
            })
            .collect()
    }

    fn center_amsmath_stack(&self, rows: Vec<MathBox>, gaps: &[Dim], style: MathStyle) -> MathBox {
        debug_assert_eq!(gaps.len(), rows.len().saturating_sub(1),);

        let mut children = Vec::with_capacity(rows.len().saturating_mul(2).saturating_sub(1));

        for (row_index, row) in rows.into_iter().enumerate() {
            if let Some(gap) = row_index.checked_sub(1).and_then(|index| gaps.get(index)) {
                if !gap.is_zero() {
                    children.push(sep_row(gap.clone()));
                }
            }

            children.push(row);
        }

        if children.is_empty() {
            return MathBox::empty();
        }

        let mut stack = MathBox::vpack(children);

        let span = &stack.height + &stack.depth;

        let axis = &self.params.axis_height * &self.params.scale(style);

        let desired_height = &(&span / &Dim::from_i64(2)) + &axis;

        stack.shift = &desired_height - &stack.height;

        stack
    }

    fn wrap_amsmath_stack(
        &self,
        stack: MathBox,
        delims: (Option<char>, Option<char>),
        style: MathStyle,
    ) -> Result<MathBox, Error> {
        let scale = self.params.scale(style);

        let axis = &self.params.axis_height * &scale;

        let effective_height = (&stack.height + &stack.shift).clamp_nonneg();

        let effective_depth = (&stack.depth - &stack.shift).clamp_nonneg();

        let needed = self.delimiter_target(&effective_height, &effective_depth, &axis);

        let mut children = Vec::with_capacity(3);

        if let Some(ch) = delims.0 {
            children.push(self.center_delimiter(self.sized_glyph(ch, &needed, style)?, &axis));
        }

        children.push(stack);

        if let Some(ch) = delims.1 {
            children.push(self.center_delimiter(self.sized_glyph(ch, &needed, style)?, &axis));
        }

        Ok(shifted_hpack(children))
    }

    fn align_env(&self, rows: &[EnvRow], style: MathStyle, numbered: bool) -> Result<Item, Error> {
        let mut math_rows: Vec<Vec<MathBox>> = Vec::new();
        let mut nums: Vec<Option<MathBox>> = Vec::new();
        let mut extras: Vec<RowKind> = Vec::new();
        let mut ncols = 0;
        for row in rows {
            match row {
                EnvRow::Hline => {
                    extras.push(RowKind::Hline);
                }
                EnvRow::Intertext(_) => {
                    extras.push(RowKind::Intertext(Box::new(self.take_box()?)));
                }
                EnvRow::Cells { cells, .. } => {
                    let mut rboxes = Vec::new();
                    for _cell in cells {
                        rboxes.push(self.take_box()?);
                    }
                    ncols = ncols.max(rboxes.len());
                    math_rows.push(rboxes);
                    extras.push(RowKind::Cells);
                    if numbered {
                        nums.push(match self.take_number() {
                            Some(s) => Some(self.number_box(&s, MathStyle::Text)?),
                            None => None,
                        });
                    }
                }
            }
        }
        self.finish_align(math_rows, nums, extras, ncols, style, numbered)
    }

    fn finish_align(
        &self,
        math_rows: Vec<Vec<MathBox>>,
        nums: Vec<Option<MathBox>>,
        extras: Vec<RowKind>,
        ncols: usize,
        style: MathStyle,
        numbered: bool,
    ) -> Result<Item, Error> {
        let mut col_w = vec![Dim::zero(); ncols];
        for row in &math_rows {
            for (j, cell) in row.iter().enumerate() {
                col_w[j] = col_w[j].max(&cell.width);
            }
        }
        let pair_sep = self.params.em(style);
        let row_sep = self.params.em(style) / Dim::from_i64(5);
        let mut packed = Vec::new();
        let mut mi = 0;
        for extra in extras {
            match extra {
                RowKind::Hline => {
                    return Err(Error::Unsupported {
                        what: "hline in align".into(),
                    });
                }
                RowKind::Intertext(t) => {
                    if !packed.is_empty() {
                        packed.push(sep_row(row_sep.clone()));
                    }
                    packed.push(*t);
                }
                RowKind::Cells => {
                    if !packed.is_empty() {
                        packed.push(sep_row(row_sep.clone()));
                    }
                    let mut parts = Vec::new();
                    let row = pad_row(math_rows[mi].clone(), ncols);
                    for (j, cell) in row.into_iter().enumerate() {
                        if j > 0 && j % 2 == 0 {
                            parts.push(MathBox::kern(pair_sep.clone()));
                        }
                        let align = if j % 2 == 0 {
                            ColSpec::Right
                        } else {
                            ColSpec::Left
                        };
                        parts.push(align_in(cell, &col_w[j], align));
                    }
                    let mut body = MathBox::hpack(parts);
                    if numbered {
                        body = self.attach_number(body, nums[mi].clone(), style);
                    }
                    packed.push(body);
                    mi += 1;
                }
            }
        }
        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: MathBox::vpack(packed),
        })
    }

    fn gathered_env(&self, rows: &[EnvRow], style: MathStyle) -> Result<Item, Error> {
        // TeX accepts `\hline` in gathered and draws the rule: the box
        // grows by exactly the rule thickness, split evenly between height
        // and depth by the axis centring. Alignment tabs stay an error:
        // TeX errors on them too ("Extra alignment tab").
        let mut cells: Vec<Vec<MathBox>> = Vec::with_capacity(rows.len());
        let mut is_rule_row: Vec<bool> = Vec::with_capacity(rows.len());
        for row in rows {
            match row {
                EnvRow::Cells { cells: source, .. } => {
                    if source.len() != 1 {
                        return Err(Error::Unsupported {
                            what: "alignment tabs in gathered".into(),
                        });
                    }
                    is_rule_row.push(false);
                    cells.push(vec![self.take_box()?]);
                }
                EnvRow::Hline => is_rule_row.push(true),
                _ => {
                    return Err(Error::Unsupported {
                        what: "non-math row in gathered".into(),
                    });
                }
            }
        }
        let math_rows = self.build_amsmath_rows(
            cells,
            &Dim::zero(),
            &self.tex_points_in_root_em(TEX_BASELINE_SKIP_PT),
            |_| ColSpec::Center,
            |_| false,
        );
        let math_gaps = self.aligned_interrow_gaps(&math_rows);
        let thick = self.params.array_rule_thickness(style);
        let half_thick = &thick / &Dim::from_i64(2);
        let double_gap = &self.params.double_rule_sep(style) - &thick;
        let max_w = math_rows
            .iter()
            .fold(Dim::zero(), |w, row| w.max(&row.width));
        // Assemble the stack in source order. A rule adds only its own
        // thickness: no gap around it, except the double-rule gap between
        // two adjacent rules. The inter-row gap between two math rows is
        // preserved across an intervening rule, exactly as in arrays: the
        // rule sits in the boundary, it does not replace the row spacing.
        let mut all_rows: Vec<MathBox> = Vec::with_capacity(is_rule_row.len());
        let mut all_gaps: Vec<Dim> = Vec::with_capacity(is_rule_row.len().saturating_sub(1));
        let mut mi = 0;
        let mut pending: Option<Dim> = None;
        let mut prev_rule = false;
        for is_rule in &is_rule_row {
            if !all_rows.is_empty() {
                let gap = if *is_rule {
                    if prev_rule {
                        double_gap.clone()
                    } else {
                        pending.take().unwrap_or_else(Dim::zero)
                    }
                } else if prev_rule {
                    Dim::zero()
                } else {
                    pending.take().unwrap_or_else(Dim::zero)
                };
                all_gaps.push(gap);
            }
            if *is_rule {
                all_rows.push(MathBox::rule(
                    max_w.clone(),
                    half_thick.clone(),
                    half_thick.clone(),
                ));
                prev_rule = true;
            } else {
                all_rows.push(math_rows[mi].clone());
                pending = math_gaps.get(mi).cloned();
                mi += 1;
                prev_rule = false;
            }
        }
        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: self.center_amsmath_stack(all_rows, &all_gaps, style),
        })
    }

    fn gather_env(&self, rows: &[EnvRow], style: MathStyle) -> Result<Item, Error> {
        let row_sep = self.params.em(style) / Dim::from_i64(5);
        let mut bodies = Vec::new();
        let mut kinds = Vec::new();
        for row in rows {
            match row {
                EnvRow::Hline => {
                    return Err(Error::Unsupported {
                        what: "hline in gather".into(),
                    });
                }
                EnvRow::Intertext(_) => {
                    kinds.push(RowKind::Intertext(Box::new(self.take_box()?)));
                }
                EnvRow::Cells { .. } => {
                    bodies.push(self.take_box()?);
                    kinds.push(RowKind::Cells);
                }
            }
        }
        let max_w = bodies.iter().fold(Dim::zero(), |w, b| w.max(&b.width));
        let mut packed = Vec::new();
        let mut bi = 0;
        for kind in kinds {
            if !packed.is_empty() {
                packed.push(sep_row(row_sep.clone()));
            }
            match kind {
                RowKind::Intertext(t) => packed.push(*t),
                RowKind::Cells => {
                    let body = align_in(bodies[bi].clone(), &max_w, ColSpec::Center);
                    let num = match self.take_number() {
                        Some(s) => Some(self.number_box(&s, MathStyle::Text)?),
                        None => None,
                    };
                    packed.push(self.attach_number(body, num, style));
                    bi += 1;
                }
                RowKind::Hline => {}
            }
        }
        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: MathBox::vpack(packed),
        })
    }

    fn multline_env(&self, rows: &[EnvRow], style: MathStyle) -> Result<Item, Error> {
        let data = data_cells(rows)?;
        if data.is_empty() {
            let _ = self.take_number();
            return Ok(Item {
                bx: MathBox::empty(),
                class: Some(AtomKind::Inner),
            });
        }
        let mut bodies = Vec::new();
        for _row in &data {
            bodies.push(self.take_box()?);
        }
        let max_w = bodies.iter().fold(Dim::zero(), |w, b| w.max(&b.width));
        let n = bodies.len();
        let row_sep = self.params.em(style) / Dim::from_i64(5);
        let mut packed = Vec::new();
        for (i, b) in bodies.into_iter().enumerate() {
            if i > 0 {
                packed.push(sep_row(row_sep.clone()));
            }
            let align = if i == 0 {
                ColSpec::Left
            } else if i + 1 == n {
                ColSpec::Right
            } else {
                ColSpec::Center
            };
            packed.push(align_in(b, &max_w, align));
        }
        let mut inner = MathBox::vpack(packed);
        let num = match self.take_number() {
            Some(s) => Some(self.number_box(&s, MathStyle::Text)?),
            None => None,
        };
        inner = self.attach_number(inner, num, style);
        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: inner,
        })
    }

    fn equation_env(&self, rows: &[EnvRow], style: MathStyle) -> Result<Item, Error> {
        let _data = data_cells(rows)?;
        let body = self.take_box()?;
        let num = match self.take_number() {
            Some(s) => Some(self.number_box(&s, MathStyle::Text)?),
            None => None,
        };
        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: self.attach_number(body, num, style),
        })
    }

    fn array_env(
        &self,
        spec: &[ColSpec],
        rows: &[EnvRow],
        style: MathStyle,
    ) -> Result<Item, Error> {
        // TeX `\arrayrulewidth` (0.4 pt at 10 pt): array rules are thinner
        // than the font's fraction rule (0.068 em in STIX Two Math).
        let thick = self.params.array_rule_thickness(style);
        let col_sep = self.params.mu(style) * Dim::from_i64(10);
        let row_sep = self.params.em(style) / Dim::from_i64(5);
        let double_rule_sep = self.params.double_rule_sep(style);
        // Between two adjacent rules TeX leaves `\doublerulesep` minus one
        // rule thickness of space.
        let double_gap = &double_rule_sep - &thick;
        let mut kinds = Vec::new();
        let mut data: Vec<Vec<MathBox>> = Vec::new();
        let mut ncols_data = 0;
        for row in rows {
            match row {
                EnvRow::Hline => kinds.push(RowKind::Hline),
                EnvRow::Intertext(_) => {
                    kinds.push(RowKind::Intertext(Box::new(self.take_box()?)));
                }
                EnvRow::Cells { cells, .. } => {
                    let mut rboxes = Vec::new();
                    for _cell in cells {
                        rboxes.push(self.take_box()?);
                    }
                    ncols_data = ncols_data.max(rboxes.len());
                    data.push(rboxes);
                    kinds.push(RowKind::Cells);
                }
            }
        }
        let mut spec: Vec<ColSpec> = if spec.is_empty() {
            vec![ColSpec::Center; ncols_data]
        } else {
            spec.to_vec()
        };
        let mut ndata = spec.iter().filter(|c| !c.is_rule()).count();
        while ndata < ncols_data {
            spec.push(ColSpec::Center);
            ndata += 1;
        }
        for row in &mut data {
            while row.len() < ndata {
                row.push(MathBox::empty());
            }
        }
        // A rule track has zero width: TeX draws the rule centred in the
        // intercolumn gap, so it adds nothing to the table width. The rule
        // itself is drawn later, as an overlay.
        let mut col_w: Vec<Dim> = vec![Dim::zero(); spec.len()];
        for row in &data {
            let mut dj = 0;
            for (j, sp) in spec.iter().enumerate() {
                if sp.is_rule() {
                    continue;
                }
                if dj < row.len() {
                    col_w[j] = col_w[j].max(&row[dj].width);
                }
                dj += 1;
            }
        }
        // Gap between adjacent spec tracks. A vertical rule adds no width:
        // a single rule between two columns splits the ordinary column gap
        // in half on each side, a `||` group adds `\doublerulesep` between
        // its rules, and a rule at an outer edge adds nothing (latex-rust
        // has no outer margins for it to sit in).
        let mut data_before = vec![false; spec.len()];
        let mut seen_before = false;
        for (j, sp) in spec.iter().enumerate() {
            data_before[j] = seen_before;
            if !sp.is_rule() {
                seen_before = true;
            }
        }
        let mut data_after = vec![false; spec.len()];
        let mut seen_after = false;
        for (j, sp) in spec.iter().enumerate().rev() {
            data_after[j] = seen_after;
            if !sp.is_rule() {
                seen_after = true;
            }
        }
        let half_col_sep = &col_sep / &Dim::from_i64(2);
        let gaps: Vec<Dim> = (0..spec.len().saturating_sub(1))
            .map(|j| match (spec[j].is_rule(), spec[j + 1].is_rule()) {
                (false, false) => col_sep.clone(),
                (true, true) => double_rule_sep.clone(),
                (false, true) => {
                    if data_after[j + 1] {
                        half_col_sep.clone()
                    } else {
                        Dim::zero()
                    }
                }
                (true, false) => {
                    if data_before[j] {
                        half_col_sep.clone()
                    } else {
                        Dim::zero()
                    }
                }
            })
            .collect();
        let mut table_w = Dim::zero();
        for (j, _) in spec.iter().enumerate() {
            if j > 0 {
                table_w = &table_w + &gaps[j - 1];
            }
            table_w = &table_w + &col_w[j];
        }
        // A horizontal rule adds only its own thickness, split evenly
        // between height and depth: TeX grows a box with a rule at its
        // start by half the rule thickness in height and half in depth.
        // Between two adjacent rules TeX leaves the double-rule gap. No
        // other padding surrounds a rule: the inter-row gap belongs to the
        // boundary between two cell rows and is added exactly once per
        // boundary, whether or not rules intervene.
        let half_thick = &thick / &Dim::from_i64(2);
        let mut packed = Vec::new();
        let mut di = 0;
        let mut prev_hline = false;
        let mut seen_row = false;
        for kind in kinds {
            match kind {
                RowKind::Hline => {
                    if prev_hline {
                        packed.push(sep_row(double_gap.clone()));
                    }
                    packed.push(MathBox::rule(
                        table_w.clone(),
                        half_thick.clone(),
                        half_thick.clone(),
                    ));
                    prev_hline = true;
                }
                RowKind::Intertext(t) => {
                    if !packed.is_empty() {
                        packed.push(sep_row(row_sep.clone()));
                    }
                    packed.push(*t);
                    seen_row = true;
                    prev_hline = false;
                }
                RowKind::Cells => {
                    if seen_row {
                        packed.push(sep_row(row_sep.clone()));
                    }
                    let row = &data[di];
                    let mut parts = Vec::new();
                    let mut dj = 0;
                    for (j, sp) in spec.iter().enumerate() {
                        if j > 0 {
                            parts.push(MathBox::kern(gaps[j - 1].clone()));
                        }
                        if sp.is_rule() {
                            // Zero-width track: the rule is an overlay.
                            parts.push(MathBox::kern(Dim::zero()));
                        } else {
                            let cell = row.get(dj).cloned().unwrap_or_else(MathBox::empty);
                            parts.push(align_in(cell, &col_w[j], *sp));
                            dj += 1;
                        }
                    }
                    packed.push(MathBox::hpack(parts));
                    di += 1;
                    seen_row = true;
                    prev_hline = false;
                }
            }
        }
        let mut table = MathBox::vpack(packed);
        // Draw each vertical rule once across the complete table, including
        // row glue and horizontal rules. Per-cell rules leave broken borders.
        // A rule is drawn centred in the intercolumn gap it sits in, so a
        // run of rules is centred in its gap as a group; a run at an outer
        // edge is drawn flush inside the table, which has no outer margin.
        let mut overlays = Vec::new();
        let mut track_x: Vec<Dim> = Vec::with_capacity(spec.len());
        let mut x = Dim::zero();
        for (j, _) in spec.iter().enumerate() {
            if j > 0 {
                x = &x + &gaps[j - 1];
            }
            track_x.push(x.clone());
            x = &x + &col_w[j];
        }
        let mut j = 0;
        while j < spec.len() {
            if !spec[j].is_rule() {
                j += 1;
                continue;
            }
            let start = j;
            while j < spec.len() && spec[j].is_rule() {
                j += 1;
            }
            let end = j - 1;
            let count = end - start + 1;
            let gap_before = if start > 0 {
                gaps[start - 1].clone()
            } else {
                Dim::zero()
            };
            let gap_after = if end + 1 < spec.len() {
                gaps[end].clone()
            } else {
                Dim::zero()
            };
            let span_start = &track_x[start] - &gap_before;
            let span_end = &track_x[end] + &gap_after;
            let group_width = &thick * &Dim::from_i64(count as i64)
                + &double_rule_sep * &Dim::from_i64((count - 1) as i64);
            let group_left = if start == 0 {
                span_start.clone()
            } else if end + 1 == spec.len() {
                &span_end - &group_width
            } else {
                let span = &span_end - &span_start;
                let spare = &span - &group_width;
                &span_start + &(&spare / &Dim::from_i64(2))
            };
            for i in 0..count {
                let rule_x = &group_left + &(&thick + &double_rule_sep) * &Dim::from_i64(i as i64);
                overlays.push(MathBox::hpack(vec![
                    MathBox::kern(rule_x),
                    MathBox::rule(thick.clone(), table.height.clone(), table.depth.clone()),
                ]));
            }
        }
        if !overlays.is_empty() {
            let mut children = vec![table.clone()];
            children.extend(overlays);
            table.content = BoxContent::Overlap(children);
        }
        Ok(Item {
            class: Some(AtomKind::Inner),
            bx: table,
        })
    }
}

fn shifted_hpack(children: Vec<MathBox>) -> MathBox {
    let mut width = Dim::zero();
    let mut height = Dim::zero();
    let mut depth = Dim::zero();
    for child in &children {
        width = &width + &child.width;
        height = height.max(&(&child.height + &child.shift).clamp_nonneg());
        depth = depth.max(&(&child.depth - &child.shift).clamp_nonneg());
    }
    MathBox {
        width,
        height,
        depth,
        italic: Dim::zero(),
        shift: Dim::zero(),
        content: BoxContent::HList(children),
    }
}

enum RowKind {
    Cells,
    Hline,
    Intertext(Box<MathBox>),
}

fn data_cells(rows: &[EnvRow]) -> Result<Vec<Vec<MathNode>>, Error> {
    let mut out = Vec::new();
    for r in rows {
        match r {
            EnvRow::Cells { cells, .. } => out.push(cells.clone()),
            EnvRow::Hline => {
                return Err(Error::Unsupported {
                    what: "hline in this environment".into(),
                });
            }
            EnvRow::Intertext(_) => {
                return Err(Error::Unsupported {
                    what: "intertext in this environment".into(),
                });
            }
        }
    }
    Ok(out)
}

fn sep_row(depth: Dim) -> MathBox {
    MathBox {
        width: Dim::zero(),
        height: Dim::zero(),
        depth,
        italic: Dim::zero(),
        shift: Dim::zero(),
        content: BoxContent::Empty,
    }
}

fn pad_row(mut row: Vec<MathBox>, ncols: usize) -> Vec<MathBox> {
    while row.len() < ncols {
        row.push(MathBox::empty());
    }
    row
}

fn align_in(inner: MathBox, width: &Dim, align: ColSpec) -> MathBox {
    if matches!(align, ColSpec::VRule) || inner.width.eq_dim(width) {
        return inner;
    }
    let extra = width - &inner.width;
    match align {
        ColSpec::Center => center_in(inner, width),
        ColSpec::Left => {
            let h = inner.height.clone();
            let d = inner.depth.clone();
            let mut packed = MathBox::hpack(vec![inner, MathBox::kern(extra)]);
            MathBox {
                width: packed.width.clone(),
                height: h,
                depth: d,
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: std::mem::replace(&mut packed.content, BoxContent::Empty),
            }
        }
        ColSpec::Right => {
            let h = inner.height.clone();
            let d = inner.depth.clone();
            let mut packed = MathBox::hpack(vec![MathBox::kern(extra), inner]);
            MathBox {
                width: packed.width.clone(),
                height: h,
                depth: d,
                italic: Dim::zero(),
                shift: Dim::zero(),
                content: std::mem::replace(&mut packed.content, BoxContent::Empty),
            }
        }
        ColSpec::VRule => inner,
    }
}

fn color_wrap(c: Color, inner: MathBox) -> MathBox {
    MathBox {
        width: inner.width.clone(),
        height: inner.height.clone(),
        depth: inner.depth.clone(),
        italic: inner.italic.clone(),
        shift: inner.shift.clone(),
        content: BoxContent::Color(c, Box::new(inner)),
    }
}

fn back_color_wrap(c: Color, inner: MathBox) -> MathBox {
    MathBox {
        width: inner.width.clone(),
        height: inner.height.clone(),
        depth: inner.depth.clone(),
        italic: inner.italic.clone(),
        shift: inner.shift.clone(),
        content: BoxContent::BackColor(c, Box::new(inner)),
    }
}

fn frame_wrap(thickness: Dim, stroke: Option<Color>, inner: MathBox) -> MathBox {
    MathBox {
        width: inner.width.clone(),
        height: inner.height.clone(),
        depth: inner.depth.clone(),
        italic: Dim::zero(),
        shift: Dim::zero(),
        content: BoxContent::Frame {
            thickness,
            stroke,
            inner: Box::new(inner),
        },
    }
}

fn pad_box(inner: MathBox, pad: &Dim) -> MathBox {
    let w = &inner.width + pad + pad;
    let h = &inner.height + pad;
    let d = &inner.depth + pad;
    MathBox {
        width: w,
        height: h,
        depth: d,
        italic: Dim::zero(),
        shift: Dim::zero(),
        content: BoxContent::HList(vec![
            MathBox::kern(pad.clone()),
            inner,
            MathBox::kern(pad.clone()),
        ]),
    }
}

fn center_in(inner: MathBox, width: &Dim) -> MathBox {
    if inner.width.eq_dim(width) {
        return inner;
    }
    let extra = width - &inner.width;
    let half = &extra / &Dim::from_i64(2);
    let h = inner.height.clone();
    let d = inner.depth.clone();
    let mut packed = MathBox::hpack(vec![
        MathBox::kern(half.clone()),
        inner,
        MathBox::kern(&extra - &half),
    ]);
    MathBox {
        width: packed.width.clone(),
        height: h,
        depth: d,
        italic: Dim::zero(),
        shift: Dim::zero(),
        content: std::mem::replace(&mut packed.content, BoxContent::Empty),
    }
}

fn shift_x(inner: MathBox, x: Dim) -> MathBox {
    if x.is_zero() {
        return inner;
    }
    let h = inner.height.clone();
    let d = inner.depth.clone();
    let mut packed = MathBox::hpack(vec![MathBox::kern(x), inner]);
    MathBox {
        width: packed.width.clone(),
        height: h,
        depth: d,
        italic: Dim::zero(),
        shift: Dim::zero(),
        content: std::mem::replace(&mut packed.content, BoxContent::Empty),
    }
}

fn overlay_accent(base: MathBox, acc: MathBox, x_off: Dim, raise: Dim) -> MathBox {
    let origin = (-x_off.clone()).clamp_nonneg();
    let base_x = origin.clone();
    let acc_x = &origin + &x_off;
    let width = (&base_x + &base.width).max(&(&acc_x + &acc.width));
    let acc_top = &acc.height + &raise;
    let acc_bot = &raise - &acc.depth;
    let height = base.height.max(&acc_top);
    let depth = base.depth.max(&(-acc_bot).clamp_nonneg());
    MathBox {
        width,
        height,
        depth,
        italic: Dim::zero(),
        shift: Dim::zero(),
        content: BoxContent::Overlap(vec![
            shift_x(base, base_x),
            shift_x(acc, acc_x).with_shift(raise),
        ]),
    }
}

fn single_glyph_id(b: &MathBox) -> Option<u16> {
    let mut stack = vec![b];
    let mut found = None;
    while let Some(b) = stack.pop() {
        match &b.content {
            BoxContent::Glyph { glyph_id, .. } => {
                if found.replace(*glyph_id).is_some() {
                    return None;
                }
            }
            BoxContent::HList(children) | BoxContent::VList(children) => {
                for child in children.iter().rev() {
                    if matches!(&child.content, BoxContent::Empty | BoxContent::Kern(_)) {
                        continue;
                    }
                    stack.push(child);
                }
            }
            BoxContent::Color(_, inner)
            | BoxContent::BackColor(_, inner)
            | BoxContent::Frame { inner, .. } => stack.push(inner),
            _ => return None,
        }
    }
    found
}

fn first_glyph_id(b: &MathBox) -> Option<u16> {
    let mut stack = vec![b];
    while let Some(b) = stack.pop() {
        match &b.content {
            BoxContent::Glyph { glyph_id, .. } => return Some(*glyph_id),
            BoxContent::HList(v) | BoxContent::VList(v) | BoxContent::Overlap(v) => {
                for child in v.iter().rev() {
                    stack.push(child);
                }
            }
            BoxContent::Color(_, inner)
            | BoxContent::BackColor(_, inner)
            | BoxContent::Frame { inner, .. } => stack.push(inner),
            _ => {}
        }
    }
    None
}

fn is_tex_accent(kind: AccentKind) -> bool {
    matches!(
        kind,
        AccentKind::Hat
            | AccentKind::Check
            | AccentKind::Breve
            | AccentKind::Acute
            | AccentKind::Grave
            | AccentKind::Tilde
            | AccentKind::Bar
            | AccentKind::Vec
            | AccentKind::Dot
            | AccentKind::Ddot
            | AccentKind::Dddot
            | AccentKind::Ddddot
            | AccentKind::Ring
            | AccentKind::WideHat
            | AccentKind::WideTilde
            | AccentKind::Overleftarrow
            | AccentKind::Overrightarrow
            | AccentKind::Overleftrightarrow
            | AccentKind::Underleftarrow
            | AccentKind::Underrightarrow
            | AccentKind::Underleftrightarrow
            | AccentKind::Overbrace
            | AccentKind::Underbrace
    )
}

fn is_hat_tilde_accent(kind: AccentKind) -> bool {
    matches!(
        kind,
        AccentKind::Hat | AccentKind::WideHat | AccentKind::Tilde | AccentKind::WideTilde
    )
}

// TeX gives hat/tilde accent noads the horizontal width of their
// nucleus and lets the accent overhang. A direct math-character
// nucleus includes its MATH italic correction.
fn hat_tilde_nucleus_width(base: &MathBox, kind: AccentKind) -> Option<Dim> {
    if !matches!(
        kind,
        AccentKind::Hat | AccentKind::WideHat | AccentKind::Tilde | AccentKind::WideTilde
    ) {
        return None;
    }

    Some(match &base.content {
        BoxContent::Glyph { .. } => &base.width + &base.italic,

        _ => base.width.clone(),
    })
}

fn is_stretchy_accent(kind: AccentKind) -> bool {
    matches!(
        kind,
        AccentKind::WideHat
            | AccentKind::WideTilde
            | AccentKind::Overleftarrow
            | AccentKind::Overrightarrow
            | AccentKind::Overleftrightarrow
            | AccentKind::Underleftarrow
            | AccentKind::Underrightarrow
            | AccentKind::Underleftrightarrow
            | AccentKind::Overbrace
            | AccentKind::Underbrace
    )
}

fn is_diacritic_accent(kind: AccentKind) -> bool {
    matches!(
        kind,
        AccentKind::Hat
            | AccentKind::WideHat
            | AccentKind::Check
            | AccentKind::Breve
            | AccentKind::Acute
            | AccentKind::Grave
            | AccentKind::Tilde
            | AccentKind::WideTilde
            | AccentKind::Bar
            | AccentKind::Dot
            | AccentKind::Ddot
            | AccentKind::Dddot
            | AccentKind::Ddddot
            | AccentKind::Ring
    )
}

fn is_under_accent(kind: AccentKind) -> bool {
    matches!(
        kind,
        AccentKind::Underleftarrow
            | AccentKind::Underrightarrow
            | AccentKind::Underleftrightarrow
            | AccentKind::Underbrace
    )
}

fn accent_candidates(kind: AccentKind) -> &'static [char] {
    match kind {
        AccentKind::Hat | AccentKind::WideHat => &['ˆ', '\u{0302}'],
        AccentKind::Check => &['ˇ', '\u{030C}'],
        AccentKind::Breve => &['˘', '\u{0306}'],
        AccentKind::Acute => &['´', '\u{0301}'],
        AccentKind::Grave => &['`', '\u{0300}'],
        AccentKind::Tilde | AccentKind::WideTilde => &['˜', '\u{0303}'],
        AccentKind::Bar => &['¯', '\u{0304}'],
        AccentKind::Vec => &['→', '\u{20D7}'],
        AccentKind::Dot => &['˙', '\u{0307}'],
        AccentKind::Ddot => &['¨', '\u{0308}'],
        AccentKind::Dddot => &['\u{20DB}'],
        AccentKind::Ddddot => &['\u{20DC}'],
        AccentKind::Ring => &['˚', '\u{030A}'],
        AccentKind::Overleftarrow | AccentKind::Underleftarrow => &['←', '\u{27F5}'],
        AccentKind::Overrightarrow | AccentKind::Underrightarrow => &['→', '\u{27F6}'],
        AccentKind::Overleftrightarrow | AccentKind::Underleftrightarrow => &['↔', '\u{27F7}'],
        AccentKind::Overbrace => &['⏞'],
        AccentKind::Underbrace => &['⏟'],
        AccentKind::Not
        | AccentKind::Overline
        | AccentKind::Underline
        | AccentKind::Cancel
        | AccentKind::BCancel
        | AccentKind::XCancel
        | AccentKind::Boxed => &[],
    }
}

fn frac_math_style(kind: FracStyle, ambient: MathStyle) -> MathStyle {
    match kind {
        FracStyle::Frac => ambient,
        FracStyle::Dfrac | FracStyle::Cfrac => MathStyle::Display,
        FracStyle::Tfrac => MathStyle::Text,
    }
}

fn class_of(n: &MathNode) -> Option<AtomKind> {
    let mut n = n;
    loop {
        match n {
            MathNode::Atom(_, k) => return Some(*k),
            MathNode::Symbol(s) => return Some(symbol_class(s)),
            MathNode::Operator(_, _)
            | MathNode::Sum(_, _)
            | MathNode::Product(_, _)
            | MathNode::Integral(_, _, _)
            | MathNode::Limit(_) => return Some(AtomKind::Op),
            MathNode::Fraction(_, _, _)
            | MathNode::Radical(_, _)
            | MathNode::Matrix(_, _, _)
            | MathNode::Substack(_)
            | MathNode::Delimited(_, _, _) => return Some(AtomKind::Inner),
            MathNode::SizedDelim(_, _, k) => return Some(*k),
            MathNode::Superscript(b, _)
            | MathNode::Subscript(b, _)
            | MathNode::SubSup(b, _, _)
            | MathNode::Accent(b, _)
            | MathNode::OverUnder(b, _, _)
            | MathNode::CancelTo(_, b)
            | MathNode::Tag { body: b, .. }
            | MathNode::Intertext(b)
            | MathNode::Color(_, b)
            | MathNode::TextColor(_, b)
            | MathNode::ColorBox(_, b)
            | MathNode::FColorBox(_, _, b)
            | MathNode::Phantom(_, b) => n = b,
            MathNode::Text(_, _) | MathNode::Ref(_) => return Some(AtomKind::Ord),
            MathNode::Row(v) if v.len() == 1 => n = &v[0],
            MathNode::Row(_) => return Some(AtomKind::Ord),
            MathNode::Space(_)
            | MathNode::Strut(_, _)
            | MathNode::Label(_)
            | MathNode::NoNumber
            | MathNode::Hline => return None,
        }
    }
}

fn single_glyph(name: &str) -> Option<char> {
    let e = lookup(name)?;
    let mut chars = e.glyph.chars();
    match (chars.next(), chars.next()) {
        (Some(c), None) => Some(c),
        _ => None,
    }
}

/// TeX's math-mode glyph for a bare source character.
///
/// `-` in math mode is `\mathchar"2200`, the minus sign, not the text hyphen.
/// The atom keeps its class, so binary-operator spacing is unchanged; `-`
/// inside `\text{...}` arrives as [`MathNode::Text`] and is not mapped.
fn math_char(c: char) -> char {
    match c {
        '-' => '\u{2212}',
        other => other,
    }
}

/// TeX's default math-italic face for a variable letter.
///
/// Latin letters and lowercase Greek (with its variant forms) are drawn from
/// the Mathematical Italic block, as plain TeX's `\fam1` does. Uppercase
/// Greek, digits and everything else stay upright. Explicit font commands
/// (`\mathrm`, `\text`, ...) arrive as [`MathNode::Text`] and bypass this.
fn is_default_math_variable(c: char) -> bool {
    let lower_greek = ('\u{03B1}'..='\u{03C9}').contains(&c);

    c.is_ascii_alphabetic() || lower_greek || matches!(c, 'ϵ' | 'ϑ' | 'ϰ' | 'ϕ' | 'ϱ' | 'ϖ')
}

fn math_italic(c: char) -> char {
    if is_default_math_variable(c) {
        styled_char(c, TextStyle::It)
    } else {
        c
    }
}

// TeX appends a math-character italic correction when a bare variable
// participates directly in a row. Script attachment already owns the
// correction needed by scripted nuclei, so row packing must not add it
// again for Superscript/Subscript/SubSup nodes.
fn row_needs_math_italic_kern(node: &MathNode) -> bool {
    match node {
        MathNode::Atom(ch, class) => *class == AtomKind::Ord && is_default_math_variable(*ch),

        MathNode::Symbol(name) => {
            symbol_class(name) == AtomKind::Ord
                && symbol_char(name).ok().is_some_and(is_default_math_variable)
        }

        _ => false,
    }
}

fn symbol_char(name: &str) -> Result<char, Error> {
    single_glyph(name).ok_or_else(|| Error::Unsupported {
        what: format!("symbol \\{name}"),
    })
}

fn symbol_class(name: &str) -> AtomKind {
    symbol_atom_kind(name)
}

fn named_delim(n: &str) -> Result<char, Error> {
    let c = match n {
        "{" => '{',
        "}" => '}',
        "|" | "Vert" | "lVert" | "rVert" => '‖',
        "vert" | "lvert" | "rvert" => '|',
        "langle" => '⟨',
        "rangle" => '⟩',
        "lfloor" => '⌊',
        "rfloor" => '⌋',
        "lceil" => '⌈',
        "rceil" => '⌉',
        "backslash" => '\\',
        "uparrow" => '↑',
        "downarrow" => '↓',
        "Uparrow" => '⇑',
        "Downarrow" => '⇓',
        "updownarrow" => '↕',
        "Updownarrow" => '⇕',
        other => {
            return Err(Error::Unsupported {
                what: format!("delimiter {other}"),
            });
        }
    };
    Ok(c)
}

fn matrix_delims(s: MatrixStyle) -> (Option<char>, Option<char>) {
    match s {
        MatrixStyle::Pmatrix => (Some('('), Some(')')),
        MatrixStyle::Bmatrix => (Some('['), Some(']')),
        MatrixStyle::Vmatrix => (Some('|'), Some('|')),
        MatrixStyle::VVmatrix => (Some('‖'), Some('‖')),
        MatrixStyle::BBmatrix => (Some('{'), Some('}')),
        MatrixStyle::Cases => (Some('{'), None),
        _ => (None, None),
    }
}