texrs 0.6.8

A TeX engine: Knuth's mouth and expander, lowered for a bytecode VM
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
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
//! The smallest honest stomach: text and font metrics into DVI pages.
//!
//! texrs could read a document and say what its words were, and could read and
//! write the DVI format, and had nothing joining the two -- `dvi::Writer` was
//! never called outside its own tests. So a book "ran" and produced no page.
//! This is the join: measure each character in a real font, break the text into
//! lines at a measure, stack the lines down a page, and ship the result.
//!
//! Both paths break a paragraph the way TeX does: `linebreak::break_paragraph`
//! minimises total badness over every feasible sequence of breakpoints
//! (§813-§890) and hyphenates with Knuth's own patterns. The DVI path took the
//! first break that fits until it could SHIP a box tree, because a breaker
//! that prices glue asks for some lines to be shrunk and a writer that set
//! runs of characters at their natural widths had nowhere to put that answer.
//! It builds a `\vbox` of `\hbox`es now and hands it to `shipout::ship_out`
//! (§619-§640): `hpack` distributes the slack (§658) and `hlist_out` writes
//! each piece of glue at the width it was set to (§625), so a full line
//! reaches the measure in the file.
//!
//! What is still NOT `tex.web`'s stomach here: pages are stacked by line count
//! rather than broken by penalty on the DVI path, there is one type size, and
//! a document's own boxes are not nested. A paragraph set here and the same
//! paragraph set by tex will not agree line for line.
//!
//! It is a page you can open, which is the difference between a document that
//! produces nothing and one that produces something imperfect.

use crate::dvi::Writer;
use crate::ir::Cmd;
use crate::node::{BoxNode, CharNode, GlueNode, Node, Scaled};
use crate::tfm::Tfm;

/// DVI's unit: 1 sp, of which there are 65536 to the printer's point.
const SP: f64 = 65536.0;

/// The page and paragraph shape, in points.
#[derive(Clone, Debug, PartialEq)]
pub struct Layout {
    /// Text width, TeX's `\hsize`.
    pub measure: f64,
    /// Text height, TeX's `\vsize`.
    pub height: f64,
    /// Distance between baselines, TeX's `\baselineskip`.
    pub leading: f64,
    /// Where the text starts, from the top-left of the page.
    pub margin: f64,
    /// The font's design size, at which its metrics are stated.
    pub size: f64,
    /// What the line breaker reads (`tex.web` §236's `\tolerance` and the
    /// rest) for a paragraph that carries no `BREAK_PARAMS` marker -- the
    /// lowerer marks every paragraph whose values are not plain.tex's.
    pub breaking: crate::linebreak::Params,
    /// What the page builder charges between a paragraph's lines
    /// (`\clubpenalty`, `\widowpenalty`, `\brokenpenalty`), taken from the
    /// document by the lowerer.
    pub paging: PageParams,
}

impl Default for Layout {
    fn default() -> Self {
        // plain.tex's own page: 6.5in by 8.9in of text, 12pt leading, 1in
        // margins. A reader comparing against a tex run should not first have
        // to account for a different page.
        Self {
            measure: 469.75,
            height: 643.20,
            leading: 12.0,
            margin: 72.0,
            size: 10.0,
            breaking: crate::linebreak::Params::default(),
            paging: PageParams::default(),
        }
    }
}

/// The paper the corpus is set on, and the only paper `pdf::Page` makes: 8.5
/// by 11 inches, in PDF's points.
const PAPER_WIDTH: f64 = 612.0;
const PAPER_HEIGHT: f64 = 792.0;

/// PDF's point is 1/72in; TeX's is 1/72.27in, and every dimension a LaTeX
/// preamble states is in TeX's. The page they land on is 612 by 792 of PDF's,
/// so the two cannot be used interchangeably. Measured, in the content stream
/// of the lualatex-built scifi2/docs/book.pdf: every body line begins at
/// x=68.4, which is 0.95in of PDF points and not of TeX's 68.66.
const BP_PER_PT: f64 = 72.0 / 72.27;

impl Layout {
    /// Take the type size from `\documentclass[11pt]{extreport}`, and with it
    /// the leading LaTeX pairs with that size.
    ///
    /// Every book in the corpus states a size and texrs set all of them at
    /// plain TeX's 10pt on 12pt leading regardless, so an 11pt book got 53
    /// lines on a page where lualatex gives it 48 -- and came out short by
    /// that ratio.
    pub fn absorb_class_options(&mut self, options: &str) {
        for option in options.split(',') {
            let Some(size) = option
                .trim()
                .strip_suffix("pt")
                .and_then(|n| n.parse::<f64>().ok())
                .filter(|size| *size > 0.0)
            else {
                continue;
            };
            self.size = size * BP_PER_PT;
            self.leading = normal_leading(size) * BP_PER_PT;
        }
    }

    /// Take the margins from `\usepackage[margin=0.95in]{geometry}`, and with
    /// them the measure and the text height they leave on the paper.
    ///
    /// Only `margin`, which sets all four sides at once: that is what pandoc
    /// writes and what every book in the corpus asks for. `left`, `top` and
    /// their siblings can each differ, and a `Layout` has ONE margin for all
    /// four sides, so honouring them here would put the text somewhere the
    /// document did not ask for rather than leave it where it was.
    pub fn absorb_geometry_options(&mut self, options: &str) {
        for option in options.split(',') {
            let Some((key, value)) = option.split_once('=') else {
                continue;
            };
            if key.trim() != "margin" {
                continue;
            }
            let Some(margin) = dimen_bp(value.trim()) else {
                continue;
            };
            self.margin = margin;
            self.measure = PAPER_WIDTH - 2.0 * margin;
            self.height = PAPER_HEIGHT - 2.0 * margin;
        }
    }
}

/// The leading LaTeX sets a type size on, taken from the class option files
/// that decide it: `size10.clo:48` sets 10pt on 12, `size11.clo:48` sets 11pt
/// on 13.6, `size12.clo:48` sets 12pt on 14.5, and extsizes' own
/// `size8/9/14/17/20.clo:12` carry the sizes `extreport` adds. A size no file
/// names is set on 1.2 of itself, which is what those files come to and what
/// TeX's `\baselineskip` assumes.
fn normal_leading(size: f64) -> f64 {
    let named = [
        (8.0, 9.5),
        (9.0, 11.0),
        (10.0, 12.0),
        (11.0, 13.6),
        (12.0, 14.5),
        (14.0, 17.0),
        (17.0, 22.0),
        (20.0, 25.0),
    ];
    match named.iter().find(|(pt, _)| *pt == size) {
        Some((_, on)) => *on,
        None => size * 1.2,
    }
}

/// A LaTeX dimension -- `0.95in`, `25mm`, `72bp` -- in PDF points.
///
/// Every TeX unit is two letters, so the suffix that matches is the only one
/// that can.
fn dimen_bp(text: &str) -> Option<f64> {
    let units = [
        ("in", 72.0),
        ("bp", 1.0),
        ("pt", BP_PER_PT),
        ("pc", 12.0 * BP_PER_PT),
        ("mm", 72.0 / 25.4),
        ("cm", 72.0 / 2.54),
    ];
    let (unit, per_unit) = units.iter().find(|(unit, _)| text.ends_with(unit))?;
    let number: f64 = text.strip_suffix(unit)?.trim().parse().ok()?;
    Some(number * per_unit)
}

/// Set `text` in `font`, and return a DVI file.
///
/// The font is named in the DVI by `font_name` so a driver can find it; the
/// metrics come from the `.tfm` the caller opened, which is the same file the
/// driver will use to place the characters.
pub fn to_dvi(text: &str, font: &Tfm, font_name: &str, layout: &Layout) -> Vec<u8> {
    // The single-font path, kept for callers that have one .tfm and want it
    // used literally. Everything else goes through the chain.
    let chain = FontChain {
        fonts: vec![Loaded {
            tfm: font.clone(),
            name: font_name.to_string(),
        }],
        map: Vec::new(),
    };
    to_dvi_chain(text, &chain, layout)
}

/// Set `text` through a font chain, falling back per glyph.
pub fn to_dvi_chain(text: &str, chain: &FontChain, layout: &Layout) -> Vec<u8> {
    let mut w = Writer::new("texrs");
    let at = (layout.size * SP) as i32;
    for (i, f) in chain.fonts.iter().enumerate() {
        // The design size and checksum have to match the .tfm or a driver
        // refuses the file: they are how it checks it has the font the document
        // was set in.
        w.define_font(i as u32, &f.name, at, f.tfm.checksum, at);
    }

    // A `\ref` asks for the number of the sectioning unit its label stands in,
    // which is a fact about the document's structure and needs no page broken:
    // this path can answer it, though it has neither a contents nor a page
    // numbering to answer a `\pageref` with. See `REF`.
    let text = refs_numbered(text);
    let lines = broken_lines(&text, chain, layout);
    let per_page = ((layout.height / layout.leading).floor() as usize).max(1);

    // A page here is its own lines and its number, nothing a page before it
    // left behind, so each is built and encoded independently and the pages
    // are joined in order: the file is the same whatever the thread count.
    let encode = |(page, chunk): (usize, &[BrokenLine])| {
        let counts = [page as i32 + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        // The page is a BOX now, and `shipout` draws it: every position in the
        // file below comes out of `hpack`/`vpack`'s arithmetic rather than
        // being computed here. That is what lets a full line be set to the
        // measure -- its glue is written at the width `hpack` set it to
        // (`tex.web` §625) -- which is the reason this path could not use a
        // breaker that prices glue before.
        let page_box = page_box(chunk, page + 1, chain, layout);
        let mut one = Writer::page();
        crate::shipout::ship_out(
            &mut one,
            &page_box,
            counts,
            sp(layout.margin),
            sp(layout.margin),
        );
        one.into_page()
    };
    let work: Vec<_> = lines.chunks(per_page).enumerate().collect();
    let pages: Vec<_> = match work.len() >= PARALLEL_PAGES {
        true => {
            use rayon::prelude::*;
            work.into_par_iter().map(encode).collect()
        }
        false => work.into_iter().map(encode).collect(),
    };
    for page in pages {
        w.append_page(page);
    }
    w.finish()
}

/// Points to scaled points, which is the unit every node carries (§101).
fn sp(points: f64) -> Scaled {
    (points * SP) as Scaled
}

/// `\baselineskip` for `plain.tex`'s footline: 24pt below the page body.
const FOOTLINE_SKIP: f64 = 24.0;

/// The page number at the foot of the page, where `plain.tex`'s output routine
/// puts it.
///
/// A page is not the text alone. `\output` in `plain.tex` is `\plainoutput`,
/// which ships `\vbox{\makeheadline\pagebody\makefootline}`, and
/// `\makefootline` is `\baselineskip24pt \line{\the\footline}` with
/// `\footline={\hss\tenrm\folio\hss}` — an `\hbox to \hsize` holding the folio
/// between two `\hss`. So every page `tex` writes carries its number, and a
/// DVI without one differs from `tex`'s in the last character of every page.
///
/// The centring is not a division: it is `hpack` distributing the slack
/// between the two `\hss` glues (`tex.web` §658, §625), which is what puts the
/// odd scaled point on one side rather than losing it. The same code sets
/// every other box, so the folio is centred the way `\centerline` is.
fn footline_box(folio: usize, chain: &FontChain, layout: &Layout) -> BoxNode {
    let mut list = vec![Node::Glue(GlueNode::new(crate::box_::fill::ss()))];
    list.extend(line_hlist(&folio.to_string(), chain, layout));
    list.push(Node::Glue(GlueNode::new(crate::box_::fill::ss())));
    crate::pack::hpack(
        list,
        crate::pack::Spec::Exactly(sp(layout.measure)),
        crate::pack::Tolerances::plain(),
        None,
    )
    .node
}

/// One page as a `\vbox`: the lines, the glue between their baselines, and the
/// folio at the foot.
///
/// `plain.tex`'s output routine ships `\vbox{\makeheadline\pagebody
/// \makefootline}`, and this is that box with no headline. Everything about
/// where the ink lands is in the box's own dimensions from here on -- nothing
/// downstream computes a position.
fn page_box(lines: &[BrokenLine], folio: usize, chain: &FontChain, layout: &Layout) -> BoxNode {
    let mut list: Vec<Node> = Vec::with_capacity(lines.len() * 2 + 2);
    // §679: `prev_depth` is `ignore_depth` before the first box on a list.
    let mut prev_depth = crate::node::IGNORE_DEPTH;
    // Where `vlist_out` will be, measured from the top of the text.
    let mut at: Scaled = 0;
    for line in lines {
        let b = line_box(line, chain, layout);
        let skip = interline(prev_depth, b.height, layout);
        at += skip + b.height + b.depth;
        prev_depth = b.depth;
        list.push(Node::Kern {
            width: skip,
            explicit: false,
        });
        list.push(Node::Box(b));
    }
    let foot = footline_box(folio, chain, layout);
    // `\makefootline` is `\baselineskip24pt\line{\the\footline}`, so the folio's
    // baseline is 24pt below the bottom of the text.
    let drop = sp(layout.height + FOOTLINE_SKIP) - at - foot.height;
    list.push(Node::Kern {
        width: drop,
        explicit: false,
    });
    list.push(Node::Box(foot));
    crate::pack::vpack(list, crate::pack::NATURAL, crate::pack::Tolerances::plain()).node
}

/// §679: the glue that separates two baselines.
///
/// `\baselineskip` less the depth of what is above and the height of what is
/// below, so consecutive baselines are one `\baselineskip` apart however tall
/// the lines are -- and `\lineskip` instead when two lines would otherwise
/// touch.
fn interline(prev_depth: Scaled, height: Scaled, layout: &Layout) -> Scaled {
    // plain.tex: `\lineskiplimit=0pt`, `\lineskip=1pt`.
    const LINE_SKIP_LIMIT: Scaled = 0;
    // Before the first box, `prev_depth` is `ignore_depth` and TeX puts
    // `\topskip` in rather than interline glue. This path sets `\topskip` to
    // `\baselineskip`, which is what puts the first baseline one leading below
    // the top margin.
    let above = match prev_depth <= crate::node::IGNORE_DEPTH {
        true => 0,
        false => prev_depth,
    };
    let d = sp(layout.leading) - above - height;
    match d < LINE_SKIP_LIMIT {
        true => sp(1.0),
        false => d,
    }
}

/// One line as an `\hbox`.
///
/// A full line is set TO the measure, so `hpack` distributes the slack over its
/// interword glue and `hlist_out` writes each piece at the width it was set to
/// (§625). The line that ends a paragraph is left at its natural width, which
/// is what `\parfillskip` amounts to here (§816).
fn line_box(line: &BrokenLine, chain: &FontChain, layout: &Layout) -> BoxNode {
    let spec = match line.justify {
        true => crate::pack::Spec::Exactly(sp(layout.measure)),
        false => crate::pack::NATURAL,
    };
    crate::pack::hpack(
        line_hlist(&line.text, chain, layout),
        spec,
        crate::pack::Tolerances::plain(),
        None,
    )
    .node
}

/// One line's horizontal list: `tex.web` §1030-§1041's main loop, over text
/// that has already been broken.
///
/// Ordinary characters are gathered rather than turned into nodes one at a
/// time: a ligature is a fact about two NEIGHBOURING characters, so the run has
/// to be whole before any of it becomes a node. Everything below that is not an
/// ordinary character ends the run before it does its own work, which is also
/// what §545 requires -- a ligature never reaches across a `\special`, a font
/// change or a piece of glue.
fn line_hlist(line: &str, chain: &FontChain, layout: &Layout) -> Vec<Node> {
    let mut out: Vec<Node> = Vec::new();
    let mut pending = String::new();
    let mut chars = line.chars().peekable();
    while let Some(ch) = chars.next() {
        // Colour arrives in the text stream as U+0001 r,g,b U+0002 ... U+0003,
        // which the runtime writes where `\textcolor` was. DVI has no colour of
        // its own; a driver is told through a `\special`, and this pair is the
        // one dvipdfmx and dvips both read.
        if ch == '\u{1}' {
            append_carried(&mut out, &std::mem::take(&mut pending), chain, layout);
            let mut spec = String::new();
            for c in chars.by_ref() {
                if c == '\u{2}' {
                    break;
                }
                spec.push(c);
            }
            let parts: Vec<&str> = spec.split(',').collect();
            if parts.len() == 3 {
                out.push(Node::Whatsit(format!(
                    "color push rgb {} {} {}",
                    parts[0], parts[1], parts[2]
                )));
            }
            continue;
        }
        if ch == '\u{3}' {
            append_carried(&mut out, &std::mem::take(&mut pending), chain, layout);
            out.push(Node::Whatsit("color pop".to_string()));
            continue;
        }
        // A face marker names a font this path does not have: the chain is
        // Computer Modern and its fallbacks, chosen by which glyph is where,
        // not by what the document asked for. Skipping it is not just a
        // refusal to honour it -- the code character after U+000E is a LETTER,
        // so leaving the pair in the stream sets an `m` in the middle of every
        // \texttt in the book. It ends the run as well, because `tex` sets the
        // two sides of a face change in different fonts and §545's implicit
        // boundary stands between them.
        if ch == FACE_PUSH {
            append_carried(&mut out, &std::mem::take(&mut pending), chain, layout);
            let _ = chars.next();
            continue;
        }
        if ch == FACE_POP {
            append_carried(&mut out, &std::mem::take(&mut pending), chain, layout);
            continue;
        }
        // The list indent names a position this path does not honour -- it sets
        // every line at the margin -- and the depth digit after it is an
        // ordinary character, so leaving the pair in would put a `1` in front
        // of every list item.
        if ch == LIST_INDENT {
            append_carried(&mut out, &std::mem::take(&mut pending), chain, layout);
            let _ = chars.next();
            continue;
        }
        // A cross-reference span is the marker, the code saying which of the
        // three it is, the label key, and the marker again -- and the whole of
        // it is skipped. The key is ordinary letters, so leaving it in would
        // SET it: a pandoc label is a sentence of hyphenated words, and every
        // heading in every book carries one.
        if ch == REF {
            append_carried(&mut out, &std::mem::take(&mut pending), chain, layout);
            for c in chars.by_ref() {
                if c == REF {
                    break;
                }
            }
            continue;
        }
        pending.push(ch);
    }
    append_carried(&mut out, &pending, chain, layout);
    out
}

/// Turn a stretch of ordinary text into nodes: the characters its fonts
/// actually set, the kerns between them, and glue for each interword space.
///
/// The translation from what the document holds to what the page carries is
/// `FontChain::carried` -- §1034-§1040's main loop -- so this builds what
/// `FontChain::width_of` measured rather than a second reading of the string.
fn append_carried(out: &mut Vec<Node>, text: &str, chain: &FontChain, layout: &Layout) {
    for item in chain.carried(text.chars()) {
        match item {
            // An interword space is GLUE (§1041), so what reaches the file is a
            // movement rather than a glyph (§625). `tex` writes no character
            // for a space, and the glyph cmr10 has at code 32 is a Polish
            // suppressed-l, so a DVI that set one differed from tex's in the
            // very first word of every document.
            Carried::Space => out.push(Node::Glue(GlueNode::new(interword_glue(chain, layout)))),
            Carried::Set { font, sets } => {
                for set in sets {
                    match set {
                        crate::tfm::Set::Char(code) => {
                            let m = chain.fonts[font].tfm.char(code).unwrap_or_default();
                            out.push(Node::Char(CharNode {
                                font,
                                // The DVI file names a font SLOT, and this is
                                // the slot the chain resolved.
                                character: char::from(code),
                                width: sp(m.width * layout.size),
                                height: sp(m.height * layout.size),
                                depth: sp(m.depth * layout.size),
                            }));
                        }
                        // §625 again: a kern is a movement, not a glyph.
                        crate::tfm::Set::Kern(by) => out.push(Node::Kern {
                            width: sp(by * layout.size),
                            explicit: false,
                        }),
                    }
                }
            }
        }
    }
}

/// §1042: an interword space is the font's own `\fontdimen2`, stretching by
/// `\fontdimen3` and shrinking by `\fontdimen4`.
///
/// Each font's own, not cmr10's fractions applied to everything: those three
/// numbers are why a monospaced face does not stretch and a text face does.
fn interword_glue(chain: &FontChain, layout: &Layout) -> crate::glue::Glue {
    let p = chain.fonts[0].tfm.params;
    crate::glue::Glue {
        natural: sp(p.space * layout.size),
        stretch: sp(p.stretch * layout.size),
        stretch_order: 0,
        shrink: sp(p.shrink * layout.size),
        shrink_order: 0,
    }
}

/// One line of the DVI path, and what is to be done with it.
#[derive(Clone, Debug, PartialEq)]
pub struct BrokenLine {
    pub text: String,
    /// Whether the line is set TO the measure. A FULL line is: `hpack`
    /// distributes the slack over its interword glue and the shipper writes
    /// each piece at the width it was set to (`tex.web` §625). The line that
    /// ends a paragraph is not -- that is what `\parfillskip` amounts to
    /// (§816) -- and neither is a line the author broke.
    pub justify: bool,
}

/// Break `text` into lines that fit the measure, for the DVI path.
///
/// The same breaker the PDF path uses: `linebreak::break_paragraph` minimises
/// the total demerits of the WHOLE paragraph over every feasible set of
/// breakpoints (§813-§890) and hyphenates with Knuth's patterns (§891). This
/// path took the first break that fitted until there was a node-list shipper,
/// because a breaker that prices glue asks for some lines to be SHRUNK and
/// there was nowhere to put that answer: the writer set a run of characters at
/// their natural widths and a shrunk line drew out past the measure. `hpack`
/// sets the glue now and `hlist_out` writes it at the width it was set to, so
/// the answer has somewhere to go.
pub fn break_lines(text: &str, font: &Tfm, layout: &Layout) -> Vec<String> {
    let chain = FontChain {
        fonts: vec![Loaded {
            tfm: font.clone(),
            name: String::from("cmr10"),
        }],
        map: Vec::new(),
    };
    break_lines_chain(text, &chain, layout)
}

/// The same, measuring through a font chain.
pub fn break_lines_chain(text: &str, chain: &FontChain, layout: &Layout) -> Vec<String> {
    broken_lines(text, chain, layout)
        .into_iter()
        .map(|line| line.text)
        .collect()
}

/// The same again, keeping what the shipper needs to know about each line.
pub fn broken_lines(text: &str, chain: &FontChain, layout: &Layout) -> Vec<BrokenLine> {
    use rayon::prelude::*;
    // Paragraph-parallel. A paragraph is broken independently of its
    // neighbours: the measure is the same for all of them, and no state crosses
    // the blank line between two, so this fans out with nothing to
    // synchronise. `map` keeps them in order, which matters -- a book whose
    // paragraphs arrived in completion order would be a different book.
    let paras: Vec<&str> = text.split("\n\n").collect();
    paras
        .par_iter()
        .map(|para| break_paragraph(para, chain, layout))
        .reduce(Vec::new, |mut acc, mut more| {
            acc.append(&mut more);
            acc
        })
}

/// One paragraph, by total demerits (§813).
fn break_paragraph(para: &str, chain: &FontChain, layout: &Layout) -> Vec<BrokenLine> {
    // The parameters this paragraph ended under, and the paragraph without
    // the marker that carried them.
    let (params, para) = paragraph_params(para, &layout.breaking);
    let para: &str = &para;
    // A line the author broke is set as it stands: a code listing is what the
    // program is, and a table's rows are rows. Neither is stretched to the
    // measure, and neither is offered to the breaker.
    let fixed = |lines: Vec<String>| -> Vec<BrokenLine> {
        lines
            .into_iter()
            .map(|text| BrokenLine {
                text,
                justify: false,
            })
            .collect()
    };
    // A picture sets nothing on this path, and says so by setting nothing.
    //
    // DVI has no path model: a drawing reaches a driver as a `\special`, which
    // every driver reads differently and which dvipdfmx answers by running
    // PostScript. Emitting the picture's source as characters would set several
    // hundred glyphs of TikZ where the document asked for a diagram, and
    // emitting a rule in its place would draw something the document does not
    // contain. So `--dvi` leaves the room empty and draws nothing: what a
    // picture comes to there is the PDF path, and this refuses rather than
    // guesses. See `PICTURE`.
    if is_picture_para(para) {
        return Vec::new();
    }
    // A code listing is already broken, by the author. Its lines are what the
    // program is; the measure has no say in where they end.
    if let Some(code) = listing_lines(para) {
        return fixed(code.map(str::to_string).collect());
    }
    // A table's rows are lines too. This path has no column measure of its own
    // and no way to draw a rule, so the cells are spaced and the rules left
    // out -- but the rows stop running into one another, and no table mark
    // reaches the shipper to be drawn as whatever glyph the font has in that
    // slot.
    if para.contains(TABLE_ROW) {
        return fixed(
            table_entries(para)
                .into_iter()
                .filter_map(|entry| match entry {
                    Entry::Row(cells) => Some(cells.join("  ")),
                    Entry::Rule(_) => None,
                })
                .collect(),
        );
    }

    // Everything else goes through §813's breaker. The pieces are the same
    // ones the PDF path measures -- a word, or the fragments a hyphenation
    // point cuts it into -- measured through this chain rather than through a
    // face, because this path has one face.
    let width_of = |text: &str, _face: Face, size: f64| chain.width_of(text, size);
    let mut colours: Vec<Spec> = Vec::new();
    let mut faces: Vec<Face> = Vec::new();
    let mut sizes: Vec<TypeSize> = vec![TypeSize {
        size: layout.size,
        leading: layout.leading,
    }];
    let mut pieces: Vec<crate::linebreak::Piece> = Vec::new();
    for word in words_carrying_refs(para) {
        if let Some(previous) = pieces.last_mut() {
            previous.after = crate::linebreak::After::Glue(chain.width(' ', layout.size));
        }
        measure_word(
            &word,
            &mut colours,
            &mut faces,
            &mut sizes,
            &width_of,
            &mut pieces,
        );
    }
    let breaks = crate::linebreak::break_paragraph(&pieces, layout.measure, &params);

    let mut lines = Vec::with_capacity(breaks.len());
    let mut from = 0usize;
    for (number, end) in breaks.iter().enumerate() {
        let mut text = String::new();
        for (offset, piece) in pieces[from..*end].iter().enumerate() {
            // The pieces of one word run together; two words are joined by the
            // space that stood between them.
            if offset > 0
                && matches!(
                    pieces[from + offset - 1].after,
                    crate::linebreak::After::Glue(_)
                )
            {
                text.push(' ');
            }
            text.push_str(&piece.text);
        }
        // A line ending inside a word carries the hyphen the word did not
        // write. One ending after a hyphen the AUTHOR wrote already has it.
        if matches!(
            pieces[*end - 1].after,
            crate::linebreak::After::Discretionary(_)
        ) {
            text.push('-');
        }
        from = *end;
        lines.push(BrokenLine {
            justify: number + 1 != breaks.len(),
            text,
        });
    }
    lines
}

/// Find a `.tfm` by name, asking the TeX installation first.
///
/// `kpsewhich` is how every TeX program answers this question, so asking it
/// gets the same answer the driver will get when it goes looking for the same
/// font. The fixed paths are the fallback for a machine without it.
pub fn find_font(name: &str) -> Option<std::path::PathBuf> {
    // Answered once per name per run. Finding a .tfm means spawning kpsewhich,
    // which reads TeX Live's ls-R databases and costs the better part of a
    // second; the typesetting path asks for the same handful of fonts over and
    // over, and that -- not the typesetting -- was why setting a three-line
    // document took twenty-four seconds.
    static SEEN: std::sync::OnceLock<
        std::sync::Mutex<std::collections::HashMap<String, Option<std::path::PathBuf>>>,
    > = std::sync::OnceLock::new();
    let seen = SEEN.get_or_init(Default::default);
    if let Some(hit) = seen.lock().ok().and_then(|m| m.get(name).cloned()) {
        return hit;
    }
    let found = find_font_uncached(name);
    if let Ok(mut m) = seen.lock() {
        m.insert(name.to_string(), found.clone());
    }
    found
}

/// The lookup itself, which is what costs.
fn find_font_uncached(name: &str) -> Option<std::path::PathBuf> {
    let file = format!("{name}.tfm");
    if let Some(p) = crate::kpse::locate(&file) {
        return Some(p);
    }
    for root in [
        "/usr/local/texlive",
        "/Library/TeX/texbin/../../texmf-dist",
        "/usr/share/texmf-dist",
    ] {
        let hit = std::process::Command::new("find")
            .args([root, "-name", &file, "-maxdepth", "8"])
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map(|o| {
                String::from_utf8_lossy(&o.stdout)
                    .lines()
                    .next()
                    .unwrap_or("")
                    .to_string()
            })
            .filter(|p| !p.is_empty());
        if let Some(p) = hit {
            return Some(std::path::PathBuf::from(p));
        }
    }
    None
}

/// A font and the name a DVI file calls it by.
pub struct Loaded {
    pub tfm: Tfm,
    pub name: String,
}

/// A chain of fonts, tried in order for each character.
///
/// This is `luaotfload.add_fallback` in a TFM world, and it is the reason the
/// publication scripts required LuaTeX: a per-glyph fallback fixes missing
/// arrows, box drawing and symbols in EVERY context, verbatim code included,
/// and no other engine offered one. A `.tfm` addresses 256 slots, so a chain
/// here is not "another Unicode font" but another 256-slot font plus the map
/// saying which character lives in which of its slots.
///
/// Resolution order per character: the primary font's own map, then each
/// fallback in turn, then an ASCII stand-in for the shapes Computer Modern
/// simply does not have. What it never does is drop the character silently --
/// a glyph that vanishes takes the meaning of a line with it, and a line that
/// reads `a -- b` where the source said `a → b` is worse than one that says so.
pub struct FontChain {
    pub fonts: Vec<Loaded>,
    /// Where a character lives: which font of the chain, and which slot.
    map: Vec<(char, usize, u8)>,
}

/// Computer Modern's own positions for the characters these documents use.
///
/// `cmr10` is the text font; `cmsy10` is the symbol font and carries the
/// arrows, the set operators AND the section and paragraph marks -- those last
/// two are not in the text font, which is the mistake this table was written
/// with the first time: `§` was pointed at cmr10 slot 120 and printed an `x`.
///
/// The slots are read off what `tex` itself emits for `\S`, `\P`,
/// `\rightarrow`, `\leftarrow`, `\cup` and `\times` -- `dvitype` on its
/// output names the character each one set. A wrong slot here prints a wrong
/// glyph in silence, so guessing at them is not good enough.
const CM_SYMBOLS: &[(char, &str, u8)] = &[
    ('→', "cmsy10", 33),
    ('←', "cmsy10", 32),
    ('↔', "cmsy10", 36),
    ('−', "cmsy10", 0),
    ('×', "cmsy10", 2),
    ('÷', "cmsy10", 4),
    ('±', "cmsy10", 6),
    ('∪', "cmsy10", 91),
    ('∩', "cmsy10", 92),
    ('≤', "cmsy10", 20),
    ('≥', "cmsy10", 21),
    ('≠', "cmsy10", 54),
    ('·', "cmsy10", 1),
    ('∞', "cmsy10", 49),
    ('§', "cmsy10", 120),
    ('', "cmsy10", 123),
    ('†', "cmsy10", 121),
    ('‡', "cmsy10", 122),
];

/// Shapes Computer Modern has no glyph for, and the nearest honest stand-in.
///
/// Box drawing is the case that matters here: the documents draw trees with it,
/// and cm has no box-drawing at all. A rule could be drawn for each, but a
/// character grid built out of rules is a different picture; the ASCII shapes
/// keep the tree readable and keep the columns lined up, which is what the
/// drawing is for.
const APPROXIMATIONS: &[(char, &str)] = &[
    // Computer Modern has no copyright sign; `(c)` is what a reader of the text
    // would have written anyway.
    ('©', "(c)"),
    ('®', "(R)"),
    ('™', "(TM)"),
    ('—', "---"),
    ('–', "--"),
    ('…', "..."),
    ('─', "-"),
    ('│', "|"),
    ('├', "|-"),
    ('└', "`-"),
    ('┌', ",-"),
    ('┐', "-."),
    ('┘', "-'"),
    ('┬', "-,-"),
    ('┴', "-'-"),
    ('┼', "-+-"),
    ('•', "*"),
    ('“', "``"),
    ('”', "''"),
    ('‘', "`"),
    ('’', "'"),
    // The double rules, the blocks and the marks the corpus draws with, none of
    // which any of the three sources above carries: not Computer Modern, not
    // WinAnsi, not the Symbol font. Counted over the 41 books, U+2500 appears
    // 9,134 times, U+2550 700 and U+2588 473, so without a stand-in the tables
    // and the bars in them are holes on the page.
    ('═', "="),
    ('║', "|"),
    ('╔', ",="),
    ('╗', "=."),
    ('╚', "`="),
    ('╝', "='"),
    ('╠', "|="),
    ('╣', "=|"),
    ('╦', "=,="),
    ('╩', "='="),
    ('╬', "=+="),
    ('█', "#"),
    ('▉', "#"),
    ('▊', "#"),
    ('▋', "#"),
    ('▌', "|"),
    ('▍', "|"),
    ('▎', "|"),
    ('▏', "|"),
    ('▄', "_"),
    ('▅', "_"),
    ('▂', "_"),
    ('●', "*"),
    ('○', "o"),
    ('◆', "*"),
    ('◇', "o"),
    ('★', "*"),
    ('☆', "*"),
    ('▲', "^"),
    ('▼', "v"),
    ('►', ">"),
    ('▶', ">"),
    ('◀', "<"),
    ('❯', ">"),
    // A tick and a cross, as a terminal writes them when it has no glyph
    // either. A checklist whose ticks vanished reads as a list of things that
    // were NOT done, which is the opposite of what it says.
    ('✓', "+"),
    ('✔', "+"),
    ('✗', "x"),
    ('✘', "x"),
    // The arrows no font on either path carries. The length is part of what a
    // long arrow says, so a long one is not set as a short one.
    ('↕', "|"),
    ('⟶', "-->"),
    ('⟵', "<--"),
    ('⟷', "<->"),
    ('⟹', "==>"),
    ('⟸', "<=="),
    ('↦', "|->"),
    ('↪', "->"),
    ('↩', "<-"),
    ('↗', "/"),
    ('↘', "\\"),
    ('↙', "/"),
    ('↖', "\\"),
    ('∓', "-+"),
    ('∘', "o"),
    ('↯', "!"),
    ('⚠', "!"),
    ('ℹ', "i"),
    ('┤', "-|"),
    ('╭', ",-"),
    ('╮', "-."),
    ('╰', "`-"),
    ('╯', "-'"),
    ('▁', "_"),
    ('▃', "_"),
    ('▆', "#"),
    ('▇', "#"),
    ('░', "."),
    ('▒', ":"),
    ('▓', "#"),
    ('▸', ">"),
    ('▹', ">"),
    ('◂', "<"),
    // The superscript and subscript digits. WinAnsi has ¹ ² ³ and stops, so
    // the rest of a footnote's numbering came out as nothing at all.
    ('⁰', "0"),
    ('⁴', "4"),
    ('⁵', "5"),
    ('⁶', "6"),
    ('⁷', "7"),
    ('⁸', "8"),
    ('⁹', "9"),
    ('ⁿ', "n"),
    ('₀', "0"),
    ('₁', "1"),
    ('₂', "2"),
    ('₃', "3"),
    ('₄', "4"),
    // The Mac modifier keys, which these books name in every keybinding table.
    // Spelling them is what a reader without the glyph needs; dropping them
    // leaves a shortcut with no key in it.
    ('⌘', "Cmd"),
    ('⌥', "Opt"),
    ('⌃', "Ctrl"),
    ('⇧', "Shift"),
];

/// The characters a document spells as a control sequence.
///
/// `\rightarrow` is not decoration: a document that writes one and meets an
/// engine that has never heard of it stops dead -- `! Undefined control
/// sequence \rightarrow.` -- and produces no page at all. Each name yields the
/// CHARACTER it means and nothing else, so every table that decides how a
/// character is DRAWN -- `CM_SYMBOLS` for the DVI path, `SYMBOL_FONT` and
/// `APPROXIMATIONS` for the PDF one -- stays the only place that decides it. A
/// name mapped straight to a font slot would be a second such table, and it
/// would drift from the first the moment either was touched.
///
/// The characters are the ones LaTeX's own `fontmath.ltx` and `latex.ltx` give
/// these names, read as Unicode: `\to` and `\rightarrow` are one macro in TeX
/// and are one entry here.
pub const SYMBOL_MACROS: &[(&str, char)] = &[
    // Arrows. `\to` and `\gets` are plain TeX's names for the first two.
    ("rightarrow", '→'),
    ("to", '→'),
    ("leftarrow", '←'),
    ("gets", '←'),
    ("uparrow", '↑'),
    ("downarrow", '↓'),
    ("leftrightarrow", '↔'),
    ("updownarrow", '↕'),
    ("Rightarrow", '⇒'),
    ("Leftarrow", '⇐'),
    ("Leftrightarrow", '⇔'),
    ("Uparrow", '⇑'),
    ("Downarrow", '⇓'),
    ("longrightarrow", '⟶'),
    ("longleftarrow", '⟵'),
    ("longleftrightarrow", '⟷'),
    ("Longrightarrow", '⟹'),
    ("Longleftarrow", '⟸'),
    ("mapsto", '↦'),
    ("hookrightarrow", '↪'),
    ("hookleftarrow", '↩'),
    ("nearrow", '↗'),
    ("searrow", '↘'),
    ("swarrow", '↙'),
    ("nwarrow", '↖'),
    // Greek, lower case. TeX has no `\omicron`: it is the letter `o`, and a
    // document writes it as one.
    ("alpha", 'α'),
    ("beta", 'β'),
    ("gamma", 'γ'),
    ("delta", 'δ'),
    // `\epsilon` is the lunate U+03F5 in TeX and `\varepsilon` the open one;
    // neither the Symbol font nor a text face carries the lunate, so both are
    // read as U+03B5, which is the letter either way.
    ("epsilon", 'ε'),
    ("varepsilon", 'ε'),
    ("zeta", 'ζ'),
    ("eta", 'η'),
    ("theta", 'θ'),
    ("vartheta", 'ϑ'),
    ("iota", 'ι'),
    ("kappa", 'κ'),
    ("lambda", 'λ'),
    ("mu", 'μ'),
    ("nu", 'ν'),
    ("xi", 'ξ'),
    ("pi", 'π'),
    ("varpi", 'ϖ'),
    ("rho", 'ρ'),
    ("sigma", 'σ'),
    ("varsigma", 'ς'),
    ("tau", 'τ'),
    ("upsilon", 'υ'),
    ("phi", 'φ'),
    ("varphi", 'ϕ'),
    ("chi", 'χ'),
    ("psi", 'ψ'),
    ("omega", 'ω'),
    // Greek, upper case. Only the letters that differ from a Latin capital
    // have a name in TeX, which is why there is no `\Alpha`.
    ("Gamma", 'Γ'),
    ("Delta", 'Δ'),
    ("Theta", 'Θ'),
    ("Lambda", 'Λ'),
    ("Xi", 'Ξ'),
    ("Pi", 'Π'),
    ("Sigma", 'Σ'),
    ("Upsilon", 'Υ'),
    ("Phi", 'Φ'),
    ("Psi", 'Ψ'),
    ("Omega", 'Ω'),
    // Relations.
    ("le", '≤'),
    ("leq", '≤'),
    ("ge", '≥'),
    ("geq", '≥'),
    ("ne", '≠'),
    ("neq", '≠'),
    ("approx", '≈'),
    ("equiv", '≡'),
    ("sim", '∼'),
    ("cong", '≅'),
    ("propto", '∝'),
    ("subset", '⊂'),
    ("supset", '⊃'),
    ("subseteq", '⊆'),
    ("supseteq", '⊇'),
    ("in", '∈'),
    ("notin", '∉'),
    ("ni", '∋'),
    ("perp", '⊥'),
    // Operators and the rest of the mathematics these books write.
    ("times", '×'),
    ("div", '÷'),
    ("pm", '±'),
    ("mp", '∓'),
    ("cdot", '⋅'),
    ("bullet", '•'),
    ("ast", '∗'),
    ("circ", '∘'),
    ("oplus", '⊕'),
    ("otimes", '⊗'),
    ("cup", '∪'),
    ("cap", '∩'),
    ("emptyset", '∅'),
    ("varnothing", '∅'),
    ("forall", '∀'),
    ("exists", '∃'),
    ("neg", '¬'),
    ("lnot", '¬'),
    ("land", '∧'),
    ("wedge", '∧'),
    ("lor", '∨'),
    ("vee", '∨'),
    ("sum", '∑'),
    ("prod", '∏'),
    ("int", '∫'),
    ("partial", '∂'),
    ("nabla", '∇'),
    ("infty", '∞'),
    ("surd", '√'),
    ("angle", '∠'),
    ("therefore", '∴'),
    ("aleph", 'ℵ'),
    ("prime", '′'),
    ("diamond", '◆'),
    ("star", '★'),
    ("dagger", '†'),
    ("ddagger", '‡'),
    // The text symbols that are spelled as a control sequence and are not
    // characters a keyboard has. `\S` and `\P` are Computer Modern's section
    // and paragraph marks, which `CM_SYMBOLS` already places.
    ("S", '§'),
    ("P", ''),
    ("dag", '†'),
    ("ddag", '‡'),
    ("copyright", '©'),
    ("textcopyright", '©'),
    ("textregistered", '®'),
    ("texttrademark", '™'),
    ("pounds", '£'),
    ("textsterling", '£'),
    ("texteuro", '€'),
    ("euro", '€'),
    ("textdegree", '°'),
    ("textbullet", '•'),
    ("textperiodcentered", '·'),
    ("textemdash", '—'),
    ("textendash", '–'),
    ("textellipsis", '…'),
    ("textmu", 'µ'),
    ("textpm", '±'),
    ("texttimes", '×'),
    ("textdiv", '÷'),
];

/// The character `\name` stands for, if it is one of the symbols above.
///
/// Asked only where a control sequence would otherwise be undefined, so a
/// document that defines its own `\star` keeps it.
pub fn symbol_char(name: &str) -> Option<char> {
    SYMBOL_MACROS
        .iter()
        .find(|(macro_name, _)| *macro_name == name)
        .map(|(_, ch)| *ch)
}

/// The characters of `text` that will actually be SET, with the colour and face
/// markers dropped.
///
/// A marker's SPEC -- the `r,g,b` between U+0001 and U+0002 -- has to be
/// skipped whole. Charging the three control characters nothing is not enough:
/// the digits and commas between them are ordinary characters the font does
/// have, so a coloured word measured that way comes out wider than it sets and
/// every line after it breaks short. The DVI side learned that first and the
/// PDF side kept charging for them, breaking its lines at a quarter of the
/// measure -- so the skip lives here, where both measuring paths reach it,
/// rather than being written out twice and drifting apart again.
///
/// A face marker is the same shape and skipped the same way: U+000E and the
/// ONE character naming the face, U+000F on its own.
pub fn printing_chars(text: &str) -> impl Iterator<Item = char> + '_ {
    let mut in_spec = false;
    let mut face_code = false;
    let mut in_ref = false;
    let mut in_picture = false;
    let mut in_size_spec = false;
    let mut in_image = false;
    text.chars().filter(move |&ch| match ch {
        // A cross-reference span -- the marker, its code, the label key, and
        // the marker again -- is a question the typesetter answers by
        // REPLACING it, so nothing inside one is ever drawn. A label survives
        // to the page because that is how `label_pages` finds which page it
        // fell on, and it must measure nothing where it stands.
        REF => {
            in_ref = !in_ref;
            false
        }
        _ if in_ref => false,
        // A picture span is the same shape and is measured the same way: it is
        // a block DRAWN on the page, not a run of characters set into a line,
        // so nothing in it -- neither the marker nor the base64 between the two
        // -- has a width. Charging the font for it would push a line off the
        // measure by several hundred characters of picture source.
        PICTURE => {
            in_picture = !in_picture;
            false
        }
        _ if in_picture => false,
        // An image is a block DRAWN on the page, not a run of characters:
        // neither the marker nor the base64 path between the two has a width.
        IMAGE => {
            in_image = !in_image;
            false
        }
        _ if in_image => false,
        '\u{1}' => {
            in_spec = true;
            false
        }
        '\u{2}' => {
            in_spec = false;
            false
        }
        '\u{3}' => false,
        // The centring and vertical-space markers are instructions to the
        // page, not glyphs: a centred line carries one at its head, and
        // measuring it would push the line off centre by whatever the font
        // happens to have in that slot.
        CENTRE | CENTRE_END | VERTICAL_SPACE | JUSTIFY => false,
        // The table marks are instructions too: a cell boundary and a row end
        // are where the columns are, and a rule is drawn rather than set.
        TABLE_CELL | TABLE_ROW => false,
        // The list indent is a position, not a character: it says how far in
        // this line starts. Its depth digit is skipped the way a face code is,
        // below.
        LIST_INDENT => {
            face_code = true;
            false
        }
        FACE_PUSH => {
            face_code = true;
            false
        }
        FACE_POP => false,
        // A size marker's spec is digits, a semicolon and a dot, every one of
        // which the font has a real width for. Measuring it would charge a
        // heading for the number it was set at -- which is the fault the
        // colour spec already had, and it cost whole pages.
        SIZE_PUSH => {
            in_size_spec = !in_size_spec;
            false
        }
        _ if in_size_spec => false,
        SIZE_POP => false,
        // Its code character goes the same way the face's does, and so does
        // the code saying which part of a longtable a line is -- and the code
        // on a contents mark, which says whether the mark is a request, a
        // heading the contents lists, or where the page numbering starts.
        TABLE_MARK | LONGTABLE | TOC => {
            face_code = true;
            false
        }
        _ if face_code => {
            face_code = false;
            false
        }
        _ => !in_spec,
    })
}

impl FontChain {
    /// Load `primary` and each fallback by name, skipping any that is missing.
    ///
    /// A missing fallback is not an error: the chain degrades to what is
    /// installed, and the approximations catch what no loaded font carries.
    pub fn load(primary: &str, fallbacks: &[&str]) -> Result<FontChain, String> {
        let mut fonts = Vec::new();
        let path = find_font(primary).ok_or_else(|| format!("{primary}.tfm not found"))?;
        fonts.push(Loaded {
            tfm: Tfm::open(&path)?,
            name: primary.to_string(),
        });
        for f in fallbacks {
            if let Some(p) = find_font(f) {
                if let Ok(tfm) = Tfm::open(&p) {
                    fonts.push(Loaded {
                        tfm,
                        name: (*f).to_string(),
                    });
                }
            }
        }
        let mut map = Vec::new();
        for (ch, font_name, slot) in CM_SYMBOLS {
            if let Some(i) = fonts.iter().position(|f| f.name == *font_name) {
                // Only claim the slot if the font really defines it.
                if fonts[i].tfm.char(*slot).is_some() {
                    map.push((*ch, i, *slot));
                }
            }
        }
        Ok(FontChain { fonts, map })
    }

    /// Which font and slot carries `ch`, if any font in the chain does.
    pub fn resolve(&self, ch: char) -> Option<(usize, u8)> {
        // ASCII is the primary font's own, which is the common case and worth
        // answering before any search.
        if ch.is_ascii() && self.fonts[0].tfm.char(ch as u8).is_some() {
            return Some((0, ch as u8));
        }
        self.map
            .iter()
            .find(|(c, _, _)| *c == ch)
            .map(|(_, f, s)| (*f, *s))
    }

    /// The ASCII stand-in for a character no font in the chain carries.
    pub fn approximate(ch: char) -> Option<&'static str> {
        APPROXIMATIONS
            .iter()
            .find(|(c, _)| *c == ch)
            .map(|(_, s)| *s)
    }

    /// The width of `ch` in points at `size`, however it is being rendered.
    pub fn width(&self, ch: char, size: f64) -> f64 {
        // The colour markers are instructions to the driver, not glyphs: they
        // occupy no space on the page, and measuring them would push words onto
        // the next line for text that is not there.
        if matches!(ch, '\u{1}' | '\u{2}' | '\u{3}') || ch.is_control() {
            return 0.0;
        }
        // An interword space is GLUE, not a character (`tex.web` §1041): its
        // width is the font's `\fontdimen2`, and no glyph is set for it.
        //
        // Resolving it as a character finds one -- cmr10 defines code 32, and
        // in OT1 that slot holds the Polish suppressed-l, 0.27778em wide
        // against the space's 0.33333em. So every space in a DVI was drawn as
        // a wrong glyph at a wrong width, and every line measured 0.056em per
        // space too narrow.
        if ch == ' ' {
            return self.fonts[0].tfm.params.space * size;
        }
        if let Some((f, slot)) = self.resolve(ch) {
            return self.fonts[f].tfm.char(slot).map(|m| m.width).unwrap_or(0.0) * size;
        }
        if let Some(text) = Self::approximate(ch) {
            return self.fonts[0].tfm.width_of(text) * size;
        }
        0.0
    }

    /// The width of a whole string, resolving each character through the chain.
    ///
    /// The colour markers and their spec are not measured -- see
    /// `printing_chars`, which the PDF path measures through as well.
    ///
    /// This measures what will be DRAWN, not what the string holds: `carried`
    /// runs each font's ligature and kern program first, so `fi` is measured
    /// as the one character cmr10 sets it as and `AV` carries its kern. A
    /// measure that skipped that would break lines at widths the shipper then
    /// contradicts.
    pub fn width_of(&self, text: &str, size: f64) -> f64 {
        self.carried(printing_chars(text))
            .iter()
            .map(|item| match item {
                Carried::Space => self.fonts[0].tfm.params.space * size,
                Carried::Set { font, sets } => self.run_width(*font, sets) * size,
            })
            .sum()
    }

    /// The design-size width of one resolved run.
    fn run_width(&self, font: usize, sets: &[crate::tfm::Set]) -> f64 {
        sets.iter()
            .map(|set| match set {
                crate::tfm::Set::Char(c) => self.fonts[font]
                    .tfm
                    .char(*c)
                    .map(|m| m.width)
                    .unwrap_or(0.0),
                crate::tfm::Set::Kern(by) => *by,
            })
            .sum()
    }

    /// Resolve `chars` into the runs a page is actually made of.
    ///
    /// `tex.web` §1034-§1040's main loop builds a list of characters ONE FONT
    /// at a time and lets that font's ligature and kern program rewrite it
    /// before anything is drawn. §545 says how far a run reaches: "TeX puts
    /// implicit boundary characters before and after each consecutive string
    /// of characters from the same font", so a space -- which is glue, not a
    /// character (§1041) -- and a change of font each end one, and no ligature
    /// or kern is looked for across either.
    pub fn carried(&self, chars: impl Iterator<Item = char>) -> Vec<Carried> {
        let mut out = Vec::new();
        let mut run: Vec<u8> = Vec::new();
        let mut run_font = 0usize;
        for ch in chars {
            if ch == ' ' {
                self.push_run(&mut out, &mut run, run_font);
                out.push(Carried::Space);
                continue;
            }
            // Every marker this path understands has been taken out by the
            // caller; a control character that is left is not a glyph.
            if ch.is_control() {
                continue;
            }
            match self.resolve(ch) {
                Some((f, slot)) => {
                    if f != run_font {
                        self.push_run(&mut out, &mut run, run_font);
                        run_font = f;
                    }
                    run.push(slot);
                }
                // No font in the chain has it. The stand-in is set in the
                // primary font rather than dropped: a glyph that vanishes
                // takes the meaning of the line with it.
                None => {
                    let Some(text) = Self::approximate(ch) else {
                        continue;
                    };
                    if run_font != 0 {
                        self.push_run(&mut out, &mut run, run_font);
                        run_font = 0;
                    }
                    run.extend(text.bytes());
                }
            }
        }
        self.push_run(&mut out, &mut run, run_font);
        out
    }

    /// Close the run being gathered, putting it through its font's own
    /// ligature and kern program on the way out.
    fn push_run(&self, out: &mut Vec<Carried>, run: &mut Vec<u8>, font: usize) {
        if run.is_empty() {
            return;
        }
        let sets = self.fonts[font].tfm.set_run(run);
        run.clear();
        out.push(Carried::Set { font, sets });
    }
}

/// What a page actually carries for a stretch of text.
///
/// The characters a document holds are not the characters TeX draws: cmr10
/// sets `f` then `i` as the single character 0o14, and puts a negative
/// movement between `A` and `V`. `FontChain::carried` is where that
/// translation happens, and both the measure and the shipper go through it so
/// they cannot disagree.
#[derive(Debug, Clone, PartialEq)]
pub enum Carried {
    /// Characters of one font of the chain, and the kerns between them.
    Set {
        font: usize,
        sets: Vec<crate::tfm::Set>,
    },
    /// An interword space. Glue (§1041), so the file carries a movement
    /// rather than a glyph (§625).
    Space,
}

/// The name every PDF reader knows the fallback font by.
///
/// Symbol is one of the fourteen a reader is required to have, so naming it
/// costs nothing in the file and works everywhere -- which is the only reason a
/// per-glyph fallback can be had here at all: an arbitrary system font would
/// have to be embedded AND addressed, and a simple font's encoding has 256
/// slots to address it with.
pub const SYMBOL_FONT_NAME: &str = "Symbol";

/// The Symbol font's own encoding: the code that draws a character, and what
/// that code advances, in 1/1000 em.
///
/// This IS the per-glyph fallback. `luaotfload.add_fallback` is what the
/// publication scripts needed LuaTeX for -- a character the chosen face has no
/// glyph for is fetched from another font, in every context including verbatim
/// -- and this is the same thing with the other font fixed at the one every
/// reader already has. It carries the arrows, the Greek and the relations,
/// which is most of what a text face is missing.
///
/// Read off `psyr.afm`, Adobe's own metrics for the font, joined to Unicode
/// through `glyphlist.txt`: `C 174 ; WX 987 ; N arrowright` and
/// `arrowright;2192`. Both files ship with every TeX installation. A wrong code
/// here draws a wrong glyph in silence, so they are not guessed.
const SYMBOL_FONT: &[(char, u8, i64)] = &[
    ('\u{AC}', 216, 713),    // logicalnot
    ('\u{B0}', 176, 400),    // degree
    ('\u{B1}', 177, 549),    // plusminus
    ('\u{B5}', 109, 576),    // mu
    ('\u{D7}', 180, 549),    // multiply
    ('\u{F7}', 184, 549),    // divide
    ('\u{192}', 166, 500),   // florin
    ('\u{391}', 65, 722),    // Alpha
    ('\u{392}', 66, 667),    // Beta
    ('\u{393}', 71, 603),    // Gamma
    ('\u{395}', 69, 611),    // Epsilon
    ('\u{396}', 90, 611),    // Zeta
    ('\u{397}', 72, 722),    // Eta
    ('\u{398}', 81, 741),    // Theta
    ('\u{399}', 73, 333),    // Iota
    ('\u{39A}', 75, 722),    // Kappa
    ('\u{39B}', 76, 686),    // Lambda
    ('\u{39C}', 77, 889),    // Mu
    ('\u{39D}', 78, 722),    // Nu
    ('\u{39E}', 88, 645),    // Xi
    ('\u{39F}', 79, 722),    // Omicron
    ('\u{3A0}', 80, 768),    // Pi
    ('\u{3A1}', 82, 556),    // Rho
    ('\u{3A3}', 83, 592),    // Sigma
    ('\u{3A4}', 84, 611),    // Tau
    ('\u{3A5}', 85, 690),    // Upsilon
    ('\u{3A6}', 70, 763),    // Phi
    ('\u{3A7}', 67, 722),    // Chi
    ('\u{3A8}', 89, 795),    // Psi
    ('\u{3B1}', 97, 631),    // alpha
    ('\u{3B2}', 98, 549),    // beta
    ('\u{3B3}', 103, 411),   // gamma
    ('\u{3B4}', 100, 494),   // delta
    ('\u{3B5}', 101, 439),   // epsilon
    ('\u{3B6}', 122, 494),   // zeta
    ('\u{3B7}', 104, 603),   // eta
    ('\u{3B8}', 113, 521),   // theta
    ('\u{3B9}', 105, 329),   // iota
    ('\u{3BA}', 107, 549),   // kappa
    ('\u{3BB}', 108, 549),   // lambda
    ('\u{3BD}', 110, 521),   // nu
    ('\u{3BE}', 120, 493),   // xi
    ('\u{3BF}', 111, 549),   // omicron
    ('\u{3C0}', 112, 549),   // pi
    ('\u{3C1}', 114, 549),   // rho
    ('\u{3C2}', 86, 439),    // sigma1
    ('\u{3C3}', 115, 603),   // sigma
    ('\u{3C4}', 116, 439),   // tau
    ('\u{3C5}', 117, 576),   // upsilon
    ('\u{3C6}', 102, 521),   // phi
    ('\u{3C7}', 99, 549),    // chi
    ('\u{3C8}', 121, 686),   // psi
    ('\u{3C9}', 119, 686),   // omega
    ('\u{3D1}', 74, 631),    // theta1
    ('\u{3D2}', 161, 620),   // Upsilon1
    ('\u{3D5}', 106, 603),   // phi1
    ('\u{3D6}', 118, 713),   // omega1
    ('\u{2022}', 183, 460),  // bullet
    ('\u{2026}', 188, 1000), // ellipsis
    ('\u{2032}', 162, 247),  // minute
    ('\u{2033}', 178, 411),  // second
    ('\u{2044}', 164, 167),  // fraction
    ('\u{2111}', 193, 686),  // Ifraktur
    ('\u{2118}', 195, 987),  // weierstrass
    ('\u{211C}', 194, 795),  // Rfraktur
    ('\u{2126}', 87, 768),   // Omega
    ('\u{2135}', 192, 823),  // aleph
    ('\u{2190}', 172, 987),  // arrowleft
    ('\u{2191}', 173, 603),  // arrowup
    ('\u{2192}', 174, 987),  // arrowright
    ('\u{2193}', 175, 603),  // arrowdown
    ('\u{2194}', 171, 1042), // arrowboth
    ('\u{21B5}', 191, 658),  // carriagereturn
    ('\u{21D0}', 220, 987),  // arrowdblleft
    ('\u{21D1}', 221, 603),  // arrowdblup
    ('\u{21D2}', 222, 987),  // arrowdblright
    ('\u{21D3}', 223, 603),  // arrowdbldown
    ('\u{21D4}', 219, 1042), // arrowdblboth
    ('\u{2200}', 34, 713),   // universal
    ('\u{2202}', 182, 494),  // partialdiff
    ('\u{2203}', 36, 549),   // existential
    ('\u{2205}', 198, 823),  // emptyset
    ('\u{2206}', 68, 612),   // Delta
    ('\u{2207}', 209, 713),  // gradient
    ('\u{2208}', 206, 713),  // element
    ('\u{2209}', 207, 713),  // notelement
    ('\u{220B}', 39, 439),   // suchthat
    ('\u{220F}', 213, 823),  // product
    ('\u{2211}', 229, 713),  // summation
    ('\u{2212}', 45, 549),   // minus
    ('\u{2217}', 42, 500),   // asteriskmath
    ('\u{221A}', 214, 549),  // radical
    ('\u{221D}', 181, 713),  // proportional
    ('\u{221E}', 165, 713),  // infinity
    ('\u{2220}', 208, 768),  // angle
    ('\u{2227}', 217, 603),  // logicaland
    ('\u{2228}', 218, 603),  // logicalor
    ('\u{2229}', 199, 768),  // intersection
    ('\u{222A}', 200, 768),  // union
    ('\u{222B}', 242, 274),  // integral
    ('\u{2234}', 92, 863),   // therefore
    ('\u{223C}', 126, 549),  // similar
    ('\u{2245}', 64, 549),   // congruent
    ('\u{2248}', 187, 549),  // approxequal
    ('\u{2260}', 185, 549),  // notequal
    ('\u{2261}', 186, 549),  // equivalence
    ('\u{2264}', 163, 549),  // lessequal
    ('\u{2265}', 179, 549),  // greaterequal
    ('\u{2282}', 204, 713),  // propersubset
    ('\u{2283}', 201, 713),  // propersuperset
    ('\u{2284}', 203, 713),  // notsubset
    ('\u{2286}', 205, 713),  // reflexsubset
    ('\u{2287}', 202, 713),  // reflexsuperset
    ('\u{2295}', 197, 768),  // circleplus
    ('\u{2297}', 196, 768),  // circlemultiply
    ('\u{22A5}', 94, 658),   // perpendicular
    ('\u{22C5}', 215, 250),  // dotmath
    ('\u{2320}', 243, 686),  // integraltp
    ('\u{2321}', 245, 686),  // integralbt
    ('\u{2329}', 225, 329),  // angleleft
    ('\u{232A}', 241, 329),  // angleright
    ('\u{25CA}', 224, 494),  // lozenge
    ('\u{2660}', 170, 753),  // spade
    ('\u{2663}', 167, 753),  // club
    ('\u{2665}', 169, 753),  // heart
    ('\u{2666}', 168, 753),  // diamond
    // Three glyphs the Adobe list names for their MATHEMATICAL character when
    // the Greek letter is the same shape and the same slot: `mu` is U+00B5 the
    // micro sign, `Delta` U+2206 the increment, `Omega` U+2126 the ohm. A
    // document writing Greek writes U+03BC, U+0394 and U+03A9, and with only
    // the names above those three fell past every table and were dropped --
    // measured on zshrs/docs/book.tex, whose two U+03BC reached no page.
    ('\u{3BC}', 109, 576), // mu, as the letter
    ('\u{394}', 68, 612),  // Delta, as the letter
    ('\u{3A9}', 87, 768),  // Omega, as the letter
];

/// WinAnsi's own codes, for the characters that are not where Unicode puts
/// them.
///
/// A PDF font here is written with `/Encoding /WinAnsiEncoding`, so a code IS a
/// WinAnsi code. From U+00A0 up WinAnsi is Latin-1 and the code is the
/// codepoint; between 0x80 and 0x9F it is Windows' own set of punctuation, and
/// that is where the em dash, the ellipsis and the curly quotes live -- 2,063
/// em dashes and 3,486 ellipses in the corpus, every one of them written into
/// the file as its UTF-8 bytes and drawn as two or three wrong letters.
const WINANSI_PUNCTUATION: &[(char, u8)] = &[
    ('€', 0x80),
    ('‚', 0x82),
    ('ƒ', 0x83),
    ('„', 0x84),
    ('…', 0x85),
    ('†', 0x86),
    ('‡', 0x87),
    ('ˆ', 0x88),
    ('‰', 0x89),
    ('Š', 0x8A),
    ('‹', 0x8B),
    ('Œ', 0x8C),
    ('Ž', 0x8E),
    ('‘', 0x91),
    ('’', 0x92),
    ('“', 0x93),
    ('”', 0x94),
    ('•', 0x95),
    ('–', 0x96),
    ('—', 0x97),
    ('˜', 0x98),
    ('™', 0x99),
    ('š', 0x9A),
    ('›', 0x9B),
    ('œ', 0x9C),
    ('ž', 0x9E),
    ('Ÿ', 0x9F),
];

/// The WinAnsi code for a character, if WinAnsi has one.
pub fn winansi_code(ch: char) -> Option<u8> {
    match ch {
        ' '..='~' => Some(ch as u8),
        '\u{A0}'..='\u{FF}' => Some(ch as u8),
        _ => WINANSI_PUNCTUATION
            .iter()
            .find(|(c, _)| *c == ch)
            .map(|(_, code)| *code),
    }
}

/// What a WinAnsi code means, which is what a font's `cmap` has to be asked
/// for.
///
/// A reader resolves a code in a non-symbolic TrueType font by its WinAnsi
/// GLYPH NAME and that name's Unicode value, so the width written beside the
/// code has to be looked up the same way. Reading code 0x97 as U+0097 finds
/// nothing and writes `.notdef`'s width where the em dash's belongs.
pub fn winansi_unicode(code: u8) -> Option<char> {
    match code {
        0x20..=0x7E => Some(code as char),
        0xA0..=0xFF => Some(code as char),
        _ => WINANSI_PUNCTUATION
            .iter()
            .find(|(_, c)| *c == code)
            .map(|(ch, _)| *ch),
    }
}

/// Where one character comes from when it is drawn.
///
/// The order the answer is looked for in is the chain: the face the document
/// asked for, then the fallback font, then a stand-in built out of characters
/// every face has. What it never does is drop the character -- a glyph that
/// vanishes takes the meaning of the line with it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Glyph {
    /// A code in the face in force, which HAS the character.
    Own(u8),
    /// A code in the Symbol font, which has it where the face does not.
    Fallback(u8),
    /// A glyph in one of the faces the DOCUMENT named as its fallback chain:
    /// which face of the chain, and which glyph of that face.
    Outside(usize, u16),
    /// ASCII the face draws itself, standing in for a shape nothing has.
    StandIn(&'static str),
}

/// How `ch` reaches the page, given what the face in force can draw.
///
/// `covers` answers from the font file's own `cmap`, which `embed_file` already
/// reads: whether a face HAS a codepoint is a question the file answers, and
/// asking it is the difference between a glyph and a blank.
///
/// `outside` is the document's own fallback chain, asked after the Symbol font
/// and before the stand-ins. After Symbol, because Symbol is one of the
/// fourteen and costs the file nothing where it has the character; before the
/// stand-ins, because `─` set as `-` is a picture redrawn and `─` set from a
/// face that has it is the picture.
pub fn glyph_for(
    ch: char,
    covers: &dyn Fn(char) -> bool,
    outside: &dyn Fn(char) -> Option<(usize, u16)>,
) -> Option<Glyph> {
    if let Some(code) = winansi_code(ch) {
        if ch.is_ascii() || covers(ch) {
            return Some(Glyph::Own(code));
        }
    }
    if let Some((_, code, _)) = SYMBOL_FONT.iter().find(|(c, _, _)| *c == ch) {
        return Some(Glyph::Fallback(*code));
    }
    if let Some((face, glyph)) = outside(ch) {
        return Some(Glyph::Outside(face, glyph));
    }
    FontChain::approximate(ch).map(Glyph::StandIn)
}

/// The faces a document named to fetch a missing glyph from, loaded.
///
/// This is `luaotfload.add_fallback` itself rather than the fixed stand-in for
/// it: the chain is the document's, the answer per character comes out of each
/// face's own `cmap`, and what is drawn is that face's glyph. A face that
/// cannot be found, or that carries PostScript outlines a `/FontFile2` may not
/// hold, is skipped -- the chain then degrades to the next one, and to the
/// stand-ins after that, exactly as it did before there was a chain at all.
#[derive(Default)]
pub struct Fallbacks {
    faces: Vec<Outside>,
    /// Each face as the file will carry it, built once `reserve` has been told
    /// every character the document draws. Building it per piece instead would
    /// subset a 23 MB face thirty thousand times over.
    carried: Vec<Option<std::sync::Arc<crate::pdf::Font>>>,
}

/// One face of the chain: enough of its file to answer for a character, and the
/// glyphs the document has asked it for so far.
struct Outside {
    name: String,
    bytes: Vec<u8>,
    cmap: std::collections::BTreeMap<u32, u16>,
    advances: Vec<u16>,
    upem: f64,
    bbox: [i64; 4],
    ascent: i64,
    descent: i64,
    /// Glyph id to the character it was fetched for. A `BTreeMap` so the `/W`
    /// array and the `/ToUnicode` map come out in the same order every run,
    /// which is what makes two runs of the same book the same file.
    used: std::collections::BTreeMap<u16, char>,
}

impl Fallbacks {
    /// Load each family of the chain, skipping any that cannot be embedded.
    pub fn load(families: &[String]) -> Fallbacks {
        let mut faces = Vec::new();
        for family in families {
            let Some(path) = find_fallback_family(family) else {
                continue;
            };
            let Some(face) = Outside::open(&path) else {
                continue;
            };
            faces.push(face);
        }
        Fallbacks {
            faces,
            carried: Vec::new(),
        }
    }

    /// Which face of the chain has `ch`, and which of its glyphs it is.
    ///
    /// Glyph 0 is `.notdef` -- the empty box -- so a `cmap` that answers with
    /// it has not answered, and the search goes on to the next face.
    pub fn glyph(&self, ch: char) -> Option<(usize, u16)> {
        self.faces.iter().enumerate().find_map(|(at, face)| {
            match face.cmap.get(&(ch as u32)).copied() {
                Some(gid) if gid != 0 => Some((at, gid)),
                _ => None,
            }
        })
    }

    /// Note that the document draws `ch`, so the file carries a width and a
    /// meaning for the glyph it comes out as.
    pub fn reserve(&mut self, ch: char) {
        if let Some((at, gid)) = self.glyph(ch) {
            self.faces[at].used.insert(gid, ch);
        }
    }

    /// What one glyph of one face advances, in points at `size`.
    pub fn width(&self, face: usize, glyph: u16, size: f64) -> f64 {
        self.faces
            .get(face)
            .map(|f| f.width(glyph) as f64 / 1000.0 * size)
            .unwrap_or(0.0)
    }

    /// Build each face into the font the file will carry, now that every
    /// character the document draws has been reserved.
    pub fn settle(&mut self) {
        self.carried = self
            .faces
            .iter()
            .map(|face| face.font().map(std::sync::Arc::new))
            .collect();
    }

    /// One face of the chain as a font the file can carry.
    pub fn font(&self, face: usize) -> Option<&std::sync::Arc<crate::pdf::Font>> {
        self.carried.get(face)?.as_ref()
    }

    /// Whether the chain resolved to anything at all.
    pub fn is_empty(&self) -> bool {
        self.faces.is_empty()
    }
}

impl Outside {
    fn open(path: &std::path::Path) -> Option<Outside> {
        let bytes = std::fs::read(path).ok()?;
        let sfnt = crate::sfnt::Sfnt::parse(bytes.clone()).ok()?;
        // A CFF-flavoured OpenType carries PostScript outlines, which a
        // `/FontFile2` must not: that entry means a TrueType font program.
        if sfnt.is_cff() {
            return None;
        }
        let head = sfnt.head().ok()?;
        let hhea = sfnt.hhea().ok()?;
        let upem = f64::from(head.units_per_em.max(1));
        let scale = |v: f64| (v * 1000.0 / upem).round() as i64;
        Some(Outside {
            name: path.file_stem()?.to_string_lossy().replace(' ', ""),
            cmap: sfnt.cmap().ok()?,
            advances: sfnt.advance_widths().ok()?,
            upem,
            bbox: [
                scale(f64::from(head.x_min)),
                scale(f64::from(head.y_min)),
                scale(f64::from(head.x_max)),
                scale(f64::from(head.y_max)),
            ],
            ascent: scale(f64::from(hhea.ascender)),
            descent: scale(f64::from(hhea.descender)),
            bytes,
            used: std::collections::BTreeMap::new(),
        })
    }

    /// A glyph's advance in 1/1000 em, which is what a PDF width is.
    ///
    /// `hmtx` runs short of `maxp` by design: every glyph past the last entry
    /// advances what that entry does, which is how a monospace face stores one
    /// width for thousands of glyphs.
    fn width(&self, glyph: u16) -> i64 {
        let adv = self
            .advances
            .get(glyph as usize)
            .or_else(|| self.advances.last())
            .copied()
            .unwrap_or(0);
        (f64::from(adv) * 1000.0 / self.upem).round() as i64
    }

    /// The face as the file will carry it: the glyphs this document borrowed,
    /// and nothing else of a face that may hold fifty thousand.
    ///
    /// `None` when nothing was borrowed from it, and when the subset cannot be
    /// built -- a face whose `glyf` or `loca` cannot be read is one nothing
    /// here can embed, and the chain has already fallen through to it.
    fn font(&self) -> Option<crate::pdf::Font> {
        if self.used.is_empty() {
            return None;
        }
        let sfnt = crate::sfnt::Sfnt::parse(self.bytes.clone()).ok()?;
        let bytes = sfnt.subset(&self.used.keys().copied().collect()).ok()?;
        Some(crate::pdf::Font::Glyphs {
            name: self.name.clone(),
            bytes,
            glyphs: self
                .used
                .iter()
                .map(|(gid, ch)| (*gid, *ch, self.width(*gid)))
                .collect(),
            bbox: self.bbox,
            ascent: self.ascent,
            descent: self.descent,
        })
    }
}

/// The file for a family named in a fallback chain.
///
/// Looser than `find_family` in one way, and deliberately: a chain names
/// families as a person writes them -- `Arial Unicode MS` -- and the file is
/// `Arial Unicode.ttf`, so a rule that only accepts a stem STARTING with the
/// name asked for rejects the very font the chain was written for. Here either
/// may be the longer, which resolves that pair and still refuses `Arial` for
/// `Helvetica`. The strict rule is left alone where `\setmainfont` uses it: a
/// body face resolved loosely would set a whole book in the wrong one, while a
/// fallback resolved loosely draws one glyph from a near neighbour.
pub fn find_fallback_family(family: &str) -> Option<std::path::PathBuf> {
    let wanted = normalise(family);
    // Too short a name matches half the system: `MS` would take `MSGothic`.
    if wanted.len() < 4 {
        return None;
    }
    let close = |path: &std::path::Path| {
        let stem = path
            .file_stem()
            .map(|s| normalise(&s.to_string_lossy()))
            .unwrap_or_default();
        stem.len() >= 4 && (stem.starts_with(&wanted) || wanted.starts_with(&stem))
    };
    if let Ok(out) = std::process::Command::new("fc-match")
        .args(["-f", "%{file}", family])
        .output()
    {
        if out.status.success() {
            let answer = String::from_utf8_lossy(&out.stdout).trim().to_string();
            let path = std::path::Path::new(&answer);
            // fc-match ALWAYS answers, with a default when it has no match, so
            // the answer is only useful if it looks like the family asked for.
            if path.exists() && close(path) {
                return Some(path.to_path_buf());
            }
        }
    }
    for dir in [
        "/System/Library/Fonts",
        "/System/Library/Fonts/Supplemental",
        "/Library/Fonts",
        "/usr/share/fonts",
        "/usr/local/share/fonts",
    ] {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let ext = path
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("")
                .to_ascii_lowercase();
            if ext != "ttf" && ext != "otf" {
                continue;
            }
            if close(&path) {
                return Some(path);
            }
        }
    }
    None
}

/// What a code in the fallback font MEANS, as against which glyph it draws.
///
/// A PDF says only the second, so a page that draws an arrow from the fallback
/// is a page nobody can search for one: `pdftotext` on the first run of these
/// came back with the arrow simply missing from the text. The driver writes
/// this out as the font's `/ToUnicode`.
pub fn symbol_unicode(code: u8) -> Option<char> {
    SYMBOL_FONT
        .iter()
        .find(|(_, c, _)| *c == code)
        .map(|(ch, _, _)| *ch)
}

/// What a Symbol code advances, in 1/1000 em.
fn symbol_width(code: u8) -> i64 {
    SYMBOL_FONT
        .iter()
        .find(|(_, c, _)| *c == code)
        .map(|(_, _, w)| *w)
        .unwrap_or(500)
}

/// The typefaces a document asked for.
///
/// `\setmainfont{Arimo}` is a statement about the book, and setting it in
/// Computer Modern anyway is the thing this exists to stop. What texrs can
/// honour depends on the output: a DVI names `.tfm` fonts and cannot carry an
/// OpenType one at all, while a PDF can name the fourteen fonts every reader
/// has. Arimo is metric-compatible with Arial, which is metric-compatible with
/// Helvetica, so that substitution is a real one rather than a shrug.
/// Where a document keeps the font it supplied with itself.
///
/// fontspec's `\setmainfont{Arimo}[Path=..., Extension=.ttf,
/// UprightFont=Arimo-VF]` does not name an INSTALLED family: it names a file
/// that ships beside the document. Looking that name up among the installed
/// families finds nothing, and `fc-match` answers anyway, with its default --
/// so the book was set in whatever that default happened to be, which is the
/// "everything comes out in the wrong face" complaint exactly.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FontFile {
    /// `Path=` -- a directory, written with a trailing separator.
    pub path: Option<String>,
    /// `UprightFont=` -- the file's name, without its extension.
    pub upright: Option<String>,
    /// `BoldFont=` -- the file `\textbf` is set from, when there is one.
    pub bold: Option<String>,
    /// `ItalicFont=` -- the file `\emph` and `\textit` are set from.
    pub italic: Option<String>,
    /// `Scale=` -- a number, or `MatchLowercase` to match the main face's
    /// x-height. A display family set beside a text family at the same
    /// nominal size looks wrong when their x-heights differ, and this is what
    /// a document writes to fix that -- usually once, through
    /// `\defaultfontfeatures`, for every family it loads.
    pub scale: Option<String>,
    /// `Extension=` -- `.ttf`, including the dot.
    pub extension: Option<String>,
}

impl FontFile {
    /// Read the options fontspec was given: `Key=Value` separated by commas,
    /// with `{...}` groups around values that contain commas of their own.
    pub fn parse(options: &str) -> FontFile {
        let mut out = FontFile::default();
        for (key, value) in top_level_pairs(options) {
            let value = value.trim().trim_matches(|c| c == '{' || c == '}');
            match key.trim() {
                "Path" => out.path = Some(value.to_string()),
                "UprightFont" => out.upright = Some(value.to_string()),
                // The faces `\textbf` and `\emph` ask for. A book names them in
                // the same option list as the upright file and every one of the
                // corpus books ships the files, so the only thing that ever
                // stopped `\emph` from being italic was that these two keys
                // were read past.
                "BoldFont" => out.bold = Some(value.to_string()),
                "ItalicFont" => out.italic = Some(value.to_string()),
                "Extension" => out.extension = Some(value.to_string()),
                "Scale" => out.scale = Some(value.trim().to_string()),
                _ => {}
            }
        }
        out
    }

    /// Let the mandatory `{...}` argument name the FILE, when it names one.
    ///
    /// fontspec has two spellings for the same thing, and lualatex honours
    /// both: `\setmainfont{Arimo}[Path=..., Extension=.ttf,
    /// UprightFont=Arimo-VF]` names the family and describes the file, while
    /// `\setmainfont{Arimo-VF.ttf}[Path=...]` names the file outright. The
    /// second spelling put the filename nowhere near the file resolution --
    /// `upright` stayed empty, no path was ever built, and the document was
    /// set in one of the fourteen without a word about it.
    ///
    /// The option list wins wherever it said anything: it is the more specific
    /// statement, and a document that writes both meant the keys.
    pub fn absorb_filename(&mut self, name: &str) {
        let Some((stem, extension)) = split_font_filename(name.trim()) else {
            return;
        };
        if self.upright.is_none() {
            self.upright = Some(stem.to_string());
        }
        if self.extension.is_none() {
            self.extension = Some(extension.to_string());
        }
    }

    /// The file this names, looked for where it might actually be.
    ///
    /// `Path=` is written by whatever produced the document and is regularly an
    /// absolute path into a directory that no longer exists -- a build
    /// scratchpad, another machine. The fonts themselves ship beside the
    /// document, so a path that has gone stale is retried by its last
    /// component against the document's own directory.
    pub fn resolve(&self, near: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
        self.resolve_face(Face::MAIN, near)
    }

    /// The file for one face, looked for in the same two places.
    ///
    /// `BoldFont=` and `ItalicFont=` name a file the way `UprightFont=` does
    /// and live in the same directory, so they are resolved by the same rules
    /// rather than by a second copy of them. A face the document named no file
    /// for resolves to nothing, and the caller falls back to the main face.
    pub fn resolve_face(
        &self,
        face: Face,
        near: Option<&std::path::Path>,
    ) -> Option<std::path::PathBuf> {
        // The series and the shape choose the file; the FAMILY chose which
        // `FontFile` this is, before the call. A document that ships a bold
        // cut of only one family gets it for that family alone.
        //
        // There is no `BoldItalicFont=` field, so a face wanting both takes
        // the italic file -- the shape is the one a reader notices missing.
        // Falling back to upright would set an emphasis as ordinary text.
        let named = match (face.bold, face.italic) {
            (_, true) => self.italic.as_deref().or(self.bold.as_deref()),
            (true, false) => self.bold.as_deref(),
            (false, false) => self.upright.as_deref(),
        }
        .or(self.upright.as_deref())?;
        let extension = self.extension.as_deref().unwrap_or(".ttf");
        let file = format!("{named}{extension}");
        if let Some(path) = &self.path {
            let full = std::path::Path::new(path).join(&file);
            if full.is_file() {
                return Some(full);
            }
            // The stale-path case: keep the directory the fonts are IN and look
            // for it beside the document instead.
            if let (Some(dir), Some(near)) = (last_component(path), near) {
                let beside = near.join(dir).join(&file);
                if beside.is_file() {
                    return Some(beside);
                }
            }
        }
        let beside = near?.join(&file);
        beside.is_file().then_some(beside)
    }
}

/// The extensions that make a fontspec argument a FILENAME rather than a
/// family name, without their dots and in lower case.
///
/// `.ttc` and `.otc` are collections; naming one resolves to a real file and
/// falls back on its own if the collection cannot be read as a single font.
const FONT_FILE_EXTENSIONS: [&str; 4] = ["ttf", "otf", "ttc", "otc"];

/// `Arimo-VF.ttf` as its stem and its extension, or `None` for a family name.
///
/// The test is the extension, which is how fontspec itself tells the two
/// spellings apart. It is case-insensitive because the file on disk is
/// regularly `.TTF` and a document names it as it is written there; the
/// extension is returned as WRITTEN, since that is the name to be opened on a
/// case-sensitive filesystem.
pub fn split_font_filename(name: &str) -> Option<(&str, &str)> {
    let dot = name.rfind('.')?;
    let (stem, extension) = name.split_at(dot);
    if stem.is_empty() {
        return None;
    }
    FONT_FILE_EXTENSIONS
        .iter()
        .any(|known| extension[1..].eq_ignore_ascii_case(known))
        .then_some((stem, extension))
}

/// The family a mandatory fontspec argument stands for.
///
/// A filename stands for the family its stem names: the family lookup strips
/// every non-alphanumeric character before comparing, so `Arimo-VF.ttf` asked
/// it for `arimovfttf` and matched nothing installed either. A name that is
/// not a filename is its own family and is returned untouched.
pub fn font_family_name(name: &str) -> &str {
    split_font_filename(name).map_or(name, |(stem, _)| stem)
}

/// The last directory of a path written with a trailing separator.
fn last_component(path: &str) -> Option<&str> {
    path.trim_end_matches('/')
        .rsplit('/')
        .next()
        .filter(|c| !c.is_empty())
}

/// `Key=Value` pairs, splitting only on the commas that are not inside braces.
///
/// fontspec values nest: `UprightFeatures={RawFeature={axis={wght=400}}}` holds
/// commas in some documents, and splitting on every comma tears it apart and
/// makes the keys after it unreadable.
fn top_level_pairs(options: &str) -> Vec<(&str, &str)> {
    let mut out = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;
    let bytes = options.as_bytes();
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'{' | b'[' => depth += 1,
            b'}' | b']' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => {
                if let Some(pair) = split_pair(&options[start..i]) {
                    out.push(pair);
                }
                start = i + 1;
            }
            _ => {}
        }
    }
    if let Some(pair) = split_pair(&options[start..]) {
        out.push(pair);
    }
    out
}

fn split_pair(text: &str) -> Option<(&str, &str)> {
    let at = text.find('=')?;
    Some((&text[..at], &text[at + 1..]))
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct Families {
    pub main: Option<String>,
    /// The file `\setmainfont`s options named, when the document ships its
    /// own font rather than naming an installed one.
    pub main_file: FontFile,
    pub sans: Option<String>,
    /// And the file `\setsansfont` named, which the corpus books ship beside
    /// themselves exactly as they ship the other two.
    pub sans_file: FontFile,
    pub mono: Option<String>,
    /// The same for `\setmonofont`: every corpus book ships its monospace face
    /// beside itself, so the family name alone resolves to nothing and
    /// `\texttt` would be set in the body font after all.
    pub mono_file: FontFile,
    /// The families a character none of the above can draw is fetched from,
    /// in the order the document listed them.
    ///
    /// A book SHIPS its faces -- `\setmainfont{Arimo}` with `Path=` and
    /// `UprightFont=`, embedded whole -- and a character Arimo has no glyph for
    /// has nowhere to go: the Symbol font covers the arrows and the Greek and
    /// nothing else, so U+2500 fell to an ASCII stand-in and the box drawing
    /// came out as hyphens. This is the chain the document itself names, and
    /// naming it is the reason its build required LuaTeX.
    pub fallbacks: Vec<String>,
}

/// The families named by `luaotfload.add_fallback`, in the order given.
///
/// Every book in the corpus opens with one statement of where a missing glyph
/// comes from:
///
/// ```text
/// \directlua{luaotfload.add_fallback("symfb", {"Arial Unicode MS:mode=base;",
///   "Arial:mode=base;", "STIX Two Math:mode=base;", "Noto Emoji:mode=base;"})}
/// ```
///
/// This READS the chunk rather than running it -- `crate::lua` runs it, and the
/// two are asked for different things. What is wanted here is the list of family
/// names, and a name is everything before the `:` that
/// introduces luaotfload's own options. Anything else inside `\directlua`
/// yields nothing, which leaves the document with no chain and the stand-ins it
/// had before.
pub fn fallback_chain(chunk: &str) -> Vec<String> {
    let Some(rest) = chunk.split_once("add_fallback").map(|(_, r)| r) else {
        return Vec::new();
    };
    // The braced table is the second argument; the first is the chain's own
    // name, which nothing here refers to.
    let Some(table) = rest.split_once('{').and_then(|(_, r)| r.split_once('}')) else {
        return Vec::new();
    };
    table
        .0
        .split(',')
        .filter_map(|item| {
            let quoted = item.trim().trim_matches('"');
            let name = quoted.split(':').next().unwrap_or("").trim();
            match name.is_empty() {
                true => None,
                false => Some(name.to_string()),
            }
        })
        .collect()
}

/// The face a stretch of text is set in.
///
/// `\texttt` appears 683,577 times in the corpus, `\emph` 35,369 and `\textbf`
/// 34,159, and all three were set in the body face: nothing between the mouth
/// and the page carried WHICH face was asked for, so a PDF came out with one
/// font resource and one `Tf` operator, and every code identifier in every book
/// was set in the prose font.
/// Which of the three families a face is set from.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Family {
    /// `\rmfamily` -- what `\setmainfont` named, and the document's prose.
    #[default]
    Roman,
    /// `\sffamily` -- what `\setsansfont` named, and what a book sets its
    /// headings in.
    Sans,
    /// `\ttfamily` -- what `\setmonofont` named, and what `\texttt` is.
    Mono,
}

/// The face a stretch of text is set in: a family, a series and a shape,
/// independently.
///
/// It was one slot, and NFSS has three axes. `{\sffamily\bfseries\Huge}` --
/// which is how every book in the corpus writes a heading -- came out BOLD and
/// not sans, because the second switch replaced the first instead of joining
/// it. There was no slot for a bold cut of the sans family, so no marker could
/// have named one even if the lowerer had emitted it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Face {
    pub family: Family,
    /// `\bfseries`, which is what `\textbf` is.
    pub bold: bool,
    /// `\itshape`, which is what `\emph` and `\textit` are.
    pub italic: bool,
}

impl Face {
    /// The document's prose: roman, medium, upright.
    pub const MAIN: Face = Face {
        family: Family::Roman,
        bold: false,
        italic: false,
    };

    /// Every face a page can be set in -- three families by two series by two
    /// shapes. Iterated once for the document rather than once a line, to ask
    /// each whether a character needs fetching from outside it.
    pub const ALL: [Face; 12] = {
        let mut all = [Face::MAIN; 12];
        let mut i = 0;
        while i < 12 {
            all[i] = Face {
                family: match i / 4 {
                    0 => Family::Roman,
                    1 => Family::Sans,
                    _ => Family::Mono,
                },
                bold: i % 4 >= 2,
                italic: i % 2 == 1,
            };
            i += 1;
        }
        all
    };

    /// The one character that names this face inside a marker.
    ///
    /// Twelve faces and one character, because widening the payload would move
    /// six readers that each consume exactly one -- `printing_chars`,
    /// `without_marks`, `absorb`, `styled_runs`, the DVI `line_hlist`, and the
    /// lowerer re-reading its own output -- plus the `MARKERS` registry, whose
    /// second field is a BOOLEAN rather than a count.
    pub fn code(self) -> char {
        const CODES: [char; 12] = [
            'r', 'i', 'b', 'B', // roman
            's', 'j', 'S', 'J', // sans
            'm', 'k', 'M', 'K', // mono
        ];
        CODES[self.index()]
    }

    /// The face a marker names, applied to the face already in force.
    ///
    /// The code is a MODIFIER and not a whole face, which is what LaTeX's own
    /// declarations are: `\bfseries` sets the series and leaves the family
    /// alone, `\sffamily` sets the family and leaves the series alone. That is
    /// what lets the prelude keep emitting one letter per command and still
    /// compose -- `\textbf` inside a `\sffamily` group reaches the page as the
    /// sans bold face rather than replacing the family.
    ///
    /// A code that names nothing leaves the face as it stands: a marker that
    /// arrives damaged must not take the rest of the document with it.
    pub fn from_code(code: char, current: Face) -> Face {
        match code {
            // The families, which say nothing about series or shape.
            'r' => Face {
                family: Family::Roman,
                ..current
            },
            's' => Face {
                family: Family::Sans,
                ..current
            },
            'm' => Face {
                family: Family::Mono,
                ..current
            },
            // The series and the shape, which say nothing about the family.
            'b' => Face {
                bold: true,
                ..current
            },
            'i' => Face {
                italic: true,
                ..current
            },
            // `\normalfont` and `\textnormal`, which undo all three at once.
            'n' => Face::MAIN,
            // The whole-face codes, which `Face::code` writes so a face can be
            // restated in one character -- `absorb` reopens a run this way
            // across a line break inside a table cell.
            'B' => Face {
                family: Family::Roman,
                bold: true,
                italic: true,
            },
            'j' => Face {
                family: Family::Sans,
                bold: false,
                italic: true,
            },
            'S' => Face {
                family: Family::Sans,
                bold: true,
                italic: false,
            },
            'J' => Face {
                family: Family::Sans,
                bold: true,
                italic: true,
            },
            'k' => Face {
                family: Family::Mono,
                bold: false,
                italic: true,
            },
            'M' => Face {
                family: Family::Mono,
                bold: true,
                italic: false,
            },
            'K' => Face {
                family: Family::Mono,
                bold: true,
                italic: true,
            },
            _ => current,
        }
    }

    /// Where this face's font sits in the twelve the page is set from.
    fn index(self) -> usize {
        let family = match self.family {
            Family::Roman => 0,
            Family::Sans => 1,
            Family::Mono => 2,
        };
        family * 4 + usize::from(self.bold) * 2 + usize::from(self.italic)
    }
}

/// A face marker opens: U+000E and one [`Face::code`] character.
///
/// Colour travels the text as a marker because it wraps a run of characters
/// rather than being one; a face is the same shape of thing and travels the
/// same way. Two characters rather than colour's variable-length spec, because
/// there are four faces and no spec to carry.
pub const FACE_PUSH: char = '\u{11}';

/// Whether `c` is one of the control characters texrs carries typesetting
/// instructions in, in-band, through its text and its messages (a face, a
/// size, a reference, a table cell, ...). `crate::ir::printed` leaves these
/// alone so that `without_marks` still finds them.
pub fn is_marker(c: char) -> bool {
    [
        FACE_PUSH,
        FACE_POP,
        SIZE_PUSH,
        SIZE_POP,
        TOC,
        REF,
        LIST_INDENT,
        PAGE_BREAK,
        PICTURE,
        IMAGE,
        LISTING_BREAK,
        TABLE_CELL,
        TABLE_ROW,
        TABLE_MARK,
        LONGTABLE,
        CENTRE,
        CENTRE_END,
        JUSTIFY,
        VERTICAL_SPACE,
        crate::math::RUN,
    ]
    .contains(&c)
}

/// A face marker closes. The stack under it is what `\ttfamily` inside a
/// `\textbf` needs: the outer face comes back when the inner one ends.
pub const FACE_POP: char = '\u{12}';

/// The size a run is set at, and the leading its line is set on.
///
/// The two travel together because `\@setfontsize` receives both and because
/// setting one without the other is what makes a heading's own lines collide.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TypeSize {
    /// The type size in PDF points, which is what a `Tf` operator states.
    pub size: f64,
    /// `\baselineskip` in PDF points, which is what the line under this one
    /// drops by.
    pub leading: f64,
}

impl Default for TypeSize {
    /// plain.tex's, matching [`Layout::default`]: a size marker that arrives
    /// damaged must leave the document readable rather than set at nothing.
    fn default() -> Self {
        TypeSize {
            size: 10.0,
            leading: 12.0 * BP_PER_PT,
        }
    }
}

/// The size in force, which is the top of the stack the caller carries.
pub fn current_size(sizes: &[TypeSize]) -> TypeSize {
    sizes.last().copied().unwrap_or_default()
}

/// What each of LaTeX's ten size commands sets, in TeX points.
///
/// Read off `size10.clo`, `size11.clo` and `size12.clo` -- the class option
/// files themselves -- joined to the point values `latex.ltx` gives their
/// roman-numeral names (`\@xivpt` is 14.4, `\@xxvpt` is 24.88). The three
/// tables are NOT one table scaled: `\footnotesize` is 8pt in a 10pt document
/// and 10pt in a 12pt one, and `\Large` is 14.4pt in both a 10pt and an 11pt
/// document. Scaling one of them by the base size would be a guess that looks
/// right for `\large` and is wrong for half the rest.
///
/// Each entry is `(name, size, baselineskip)`.
const SIZE_STEPS_10: &[(&str, f64, f64)] = &[
    ("tiny", 5.0, 6.0),
    ("scriptsize", 7.0, 8.0),
    ("footnotesize", 8.0, 9.5),
    ("small", 9.0, 11.0),
    ("normalsize", 10.0, 12.0),
    ("large", 12.0, 14.0),
    ("Large", 14.4, 18.0),
    ("LARGE", 17.28, 22.0),
    ("huge", 20.74, 25.0),
    ("Huge", 24.88, 30.0),
];

/// The 11pt class's table. See [`SIZE_STEPS_10`].
const SIZE_STEPS_11: &[(&str, f64, f64)] = &[
    ("tiny", 6.0, 7.0),
    ("scriptsize", 8.0, 9.5),
    ("footnotesize", 9.0, 11.0),
    ("small", 10.0, 12.0),
    ("normalsize", 10.95, 13.6),
    ("large", 12.0, 14.0),
    ("Large", 14.4, 18.0),
    ("LARGE", 17.28, 22.0),
    ("huge", 20.74, 25.0),
    ("Huge", 24.88, 30.0),
];

/// The 12pt class's table, where the top two steps meet: `\huge` and `\Huge`
/// are both 24.88pt, as `size12.clo` sets them. See [`SIZE_STEPS_10`].
const SIZE_STEPS_12: &[(&str, f64, f64)] = &[
    ("tiny", 6.0, 7.0),
    ("scriptsize", 8.0, 9.5),
    ("footnotesize", 10.0, 12.0),
    ("small", 10.95, 13.6),
    ("normalsize", 12.0, 14.5),
    ("large", 14.4, 18.0),
    ("Large", 17.28, 22.0),
    ("LARGE", 20.74, 25.0),
    ("huge", 24.88, 30.0),
    ("Huge", 24.88, 30.0),
];

/// What a size command sets, in PDF points, for a document whose body size is
/// `base` PDF points.
///
/// `None` for a command that is not one of the ten, which is how the lowerer
/// tells a size declaration from every other control sequence.
pub fn size_step(name: &str, base: f64) -> Option<TypeSize> {
    // The class the document was loaded with, back from the body size it left
    // behind. A base that is none of the three takes the 10pt table, which is
    // what `\documentclass` itself falls back to.
    let table = match (base / BP_PER_PT).round() as i64 {
        11 => SIZE_STEPS_11,
        12 => SIZE_STEPS_12,
        _ => SIZE_STEPS_10,
    };
    table
        .iter()
        .find(|(step, _, _)| *step == name)
        .map(|(_, size, leading)| TypeSize {
            size: size * BP_PER_PT,
            leading: leading * BP_PER_PT,
        })
}

/// A size marker opens, and closes its own spec: U+0019, the size and the
/// baselineskip it was set with, and U+0019 again.
///
/// A face needs one character because there are four faces; a size cannot,
/// because `\fontsize{14.4}{18}` names a number rather than one of a fixed
/// set. So this carries a spec the way colour does and delimits it the way
/// `PICTURE` does -- the same marker at both ends -- rather than spending two
/// more control characters on it.
///
/// The pair is `size;baselineskip`, both in PDF points, because the two travel
/// together: `\@setfontsize` receives both, and a heading that is set larger
/// and led the same is a heading whose lines collide.
pub const SIZE_PUSH: char = '\u{19}';

/// A size marker closes, restoring the size under it. `\large` inside a
/// `\Large` heading gets the `\Large` back, which is the same stack the face
/// and the colour markers keep and for the same reason.
pub const SIZE_POP: char = '\u{1a}';

/// The size and baselineskip a size marker carries, in PDF points.
///
/// `None` for a marker that arrives damaged: a document must not lose its
/// remaining pages to one unreadable spec, so the reader falls back to the
/// size already in force rather than to zero.
pub fn size_spec(spec: &str) -> Option<(f64, f64)> {
    let (size, leading) = spec.split_once(';')?;
    Some((size.trim().parse().ok()?, leading.trim().parse().ok()?))
}

/// A size marker wrapping `body`, stated at `size` with `leading`.
pub fn size_span(size: f64, leading: f64, body: &str) -> String {
    format!("{SIZE_PUSH}{size};{leading}{SIZE_PUSH}{body}{SIZE_POP}")
}

/// The line breaker's parameters for the paragraph this marker ends: U+001C,
/// the eight §236 values, and U+001C again.
///
/// `tex.web` §816 reads `\tolerance` and the rest when `line_break` runs, at
/// the `\par` that ends a paragraph, so each paragraph is broken with the
/// values in force THERE -- a document that sets `\hyphenpenalty=10000` for
/// one paragraph and back for the next gets one of each. The lowerer knows
/// those values paragraph by paragraph; the typesetter, which breaks the
/// text long after lowering finished, does not. So the lowerer writes them
/// into the text in front of each paragraph end whose values differ from
/// plain.tex's, the typesetter reads them back off the paragraph
/// ([`paragraph_params`]), and a paragraph without one is broken at the
/// layout's own. Riding in the text is what carries them through the bytecode
/// cache and into `--dvi`, whose caller hands it no layout of the document's.
///
/// Spanned by the same marker at both ends, as `SIZE_PUSH` is, rather than
/// spending a second control character on a close.
pub const BREAK_PARAMS: char = '\u{1c}';

/// The marker carrying `p`, for the lowerer to write at a paragraph end.
pub fn break_params_span(p: &crate::linebreak::Params) -> String {
    format!(
        "{BREAK_PARAMS}{},{},{},{},{},{},{},{}{BREAK_PARAMS}",
        p.pretolerance,
        p.tolerance,
        p.line_penalty,
        p.hyphen_penalty,
        p.ex_hyphen_penalty,
        p.adj_demerits,
        p.double_hyphen_demerits,
        p.final_hyphen_demerits
    )
}

/// The breaker's parameters for one paragraph, and the paragraph without the
/// marker that carried them: the last marker in it, or `base` when it has
/// none or the one it has is damaged.
pub fn paragraph_params<'a>(
    para: &'a str,
    base: &crate::linebreak::Params,
) -> (crate::linebreak::Params, std::borrow::Cow<'a, str>) {
    if !para.contains(BREAK_PARAMS) {
        return (*base, std::borrow::Cow::Borrowed(para));
    }
    let mut text = String::with_capacity(para.len());
    let mut params = *base;
    let mut parts = para.split(BREAK_PARAMS);
    text.push_str(parts.next().unwrap_or(""));
    while let Some(spec) = parts.next() {
        if let Some(read) = break_params_spec(spec) {
            params = read;
        }
        text.push_str(parts.next().unwrap_or(""));
    }
    (params, std::borrow::Cow::Owned(text))
}

/// The eight values a [`break_params_span`] carries.
fn break_params_spec(spec: &str) -> Option<crate::linebreak::Params> {
    let v: Vec<f64> = spec
        .split(',')
        .map(|n| n.trim().parse().ok())
        .collect::<Option<_>>()?;
    let [pretolerance, tolerance, line_penalty, hyphen_penalty, ex_hyphen_penalty, adj_demerits, double_hyphen_demerits, final_hyphen_demerits] =
        v[..]
    else {
        return None;
    };
    Some(crate::linebreak::Params {
        pretolerance,
        tolerance,
        line_penalty,
        hyphen_penalty,
        ex_hyphen_penalty,
        adj_demerits,
        double_hyphen_demerits,
        final_hyphen_demerits,
    })
}

/// What a requested family maps to among the fourteen fonts a PDF reader has.
///
/// The mapping is by what the face IS, not by its name: Arimo is Arial's
/// metrics, Liberation Sans is Arial's metrics, and Arial is Helvetica's, so
/// all three set at the same widths as Helvetica. A monospace request goes to
/// Courier whatever it was called. A name nothing is known about falls to
/// Helvetica rather than to Computer Modern, because a document that asked for
/// a font at all was asking not to be set in a book face.
pub fn base14_for(family: &str) -> &'static str {
    let f = family.to_ascii_lowercase();
    let mono = [
        "mono",
        "courier",
        "consolas",
        "menlo",
        "inconsolata",
        "sharetechmono",
        "jetbrains",
        "fira code",
        "source code",
    ];
    if mono.iter().any(|m| f.contains(m)) {
        return "Courier";
    }
    let serif = [
        "times",
        "serif",
        "georgia",
        "garamond",
        "minion",
        "palatino",
        "book",
        "charter",
        "libertine",
        "stix",
    ];
    if serif.iter().any(|m| f.contains(m)) {
        return "Times-Roman";
    }
    "Helvetica"
}

/// The member of the fourteen that carries one face of `base`.
///
/// The fourteen are four faces of three families plus two symbol fonts, so a
/// document that named a family but shipped no file for its bold or italic
/// still gets a face that is bold or italic -- which is the whole request. The
/// names are not built the same way for all three: Helvetica and Courier take
/// `-Bold` and `-Oblique`, and Times-Roman's siblings drop the `Roman` for
/// `Times-Bold` and `Times-Italic`. Getting that wrong names a font no reader
/// has and the substitution is silent.
pub fn base14_face(base: &str, face: Face) -> String {
    // The family first, INDEPENDENTLY of the series and the shape. Reading the
    // family last is what made `Helvetica-Bold` unreachable as a request: a
    // sans face answered "Helvetica" before any bold arm was tried, so no path
    // could name a bold cut of it.
    //
    // Courier IS the mono of the fourteen and Helvetica the sans, whatever the
    // body face is: a document that asked for one of them and shipped no file
    // wants that family, not its own serif again.
    let stem = match face.family {
        Family::Mono => "Courier",
        Family::Sans => "Helvetica",
        Family::Roman => base,
    };
    // Times-Roman's siblings drop the `Roman`; Helvetica's and Courier's take
    // the suffix whole. Getting that wrong names a font no reader has and the
    // substitution is silent.
    let (bold, italic, both) = match stem {
        "Times-Roman" => ("Times-Bold", "Times-Italic", "Times-BoldItalic"),
        _ => ("-Bold", "-Oblique", "-BoldOblique"),
    };
    match (face.bold, face.italic) {
        (false, false) => stem.to_string(),
        (true, false) if stem == "Times-Roman" => bold.to_string(),
        (false, true) if stem == "Times-Roman" => italic.to_string(),
        (true, true) if stem == "Times-Roman" => both.to_string(),
        (true, false) => format!("{stem}{bold}"),
        (false, true) => format!("{stem}{italic}"),
        (true, true) => format!("{stem}{both}"),
    }
}

/// The twelve faces a PDF is set in, and what a word measures in them.
///
/// Read off the families the document named and the directory it was read
/// from, and -- for the glyphs a fallback face lends -- off the text: the
/// distinct characters no face draws are reserved before anything is
/// measured. With no fallback family named, nothing is reserved and the text
/// does not matter.
pub(crate) struct Faces {
    fonts: Vec<std::sync::Arc<crate::pdf::Font>>,
    main_shared: std::sync::Arc<crate::pdf::Font>,
    scales: Vec<f64>,
    embedded_widths: Vec<Option<Vec<i64>>>,
    coverage: Vec<Option<std::collections::BTreeSet<u32>>>,
    fallbacks: Fallbacks,
    metrics: Option<Tfm>,
}

/// Whether `face` draws `ch` itself. A face with no file to read is one of the
/// fourteen, and carrying all of WinAnsi is what being one of them means.
fn covered(coverage: &[Option<std::collections::BTreeSet<u32>>], ch: char, face: Face) -> bool {
    match &coverage[face.index()] {
        Some(has) => has.contains(&(ch as u32)),
        None => true,
    }
}

impl Faces {
    pub(crate) fn new(families: &Families, near: Option<&std::path::Path>, text: &str) -> Faces {
        use crate::pdf::Font;

        // The font the document asked for, EMBEDDED if it can be found: that is
        // the difference between a page set in Arimo's metrics and one set in
        // Arimo. Failing that, one of the fourteen, which gets the widths right
        // and the shapes wrong -- better than refusing to typeset.
        let requested = families.main.as_deref();
        // A font the document SHIPS is tried first: it is the one the document
        // actually meant, and its family name is regularly not installed at all.
        let embedded = families
            .main_file
            .resolve(near)
            .and_then(|file| embed_file(&file))
            .or_else(|| requested.and_then(embed_family));
        let main = embedded.clone().unwrap_or_else(|| match requested {
            // A document that asked for a family and did not get it falls to the
            // member of the fourteen with that family's metrics.
            Some(family) => Font::Base14(base14_for(family).to_string()),
            // A document that asked for NO family is a TeX document, and TeX's text
            // font is cmr10 -- which is the face luatex embeds. Naming Helvetica
            // here set every plain document in a typeface no TeX engine uses.
            None => crate::pdf::Font::computer_modern()
                .unwrap_or_else(|| Font::Base14("Helvetica".to_string())),
        });

        // The other three faces, in the order `Face::index` puts them: main, mono,
        // bold, italic. Each is the file the document named for it, then the family
        // it named, then the member of the fourteen that carries that face -- and
        // the main font when the document asked for none of those, so a `\texttt`
        // in a document with no monospace family still sets rather than vanishing.
        let main_shared = std::sync::Arc::new(main.clone());
        let base = match &main {
            Font::Base14(name) => name.clone(),
            _ => requested.map(base14_for).unwrap_or("Helvetica").to_string(),
        };
        let mono = families
            .mono_file
            .resolve(near)
            .and_then(|file| embed_file(&file))
            .or_else(|| families.mono.as_deref().and_then(embed_family))
            .or_else(|| {
                families
                    .mono
                    .as_deref()
                    .map(|f| Font::Base14(base14_for(f).to_string()))
            })
            .unwrap_or_else(|| main.clone());
        // A bold or italic FILE is what the corpus books ship: `BoldFont=Arimo-VF`
        // beside `UprightFont=Arimo-VF`. Where the two name the same file the font
        // is the same font, `Page::text_in` recognises it as one and the page is
        // set in the main face -- which is the honest outcome, since a variable
        // font's weight axis is not something this can instantiate.
        // Which `FontFile` a family's files come from. `\setsansfont{X}[BoldFont=Y]`
        // populated `sans_file.bold` and NOTHING read it: every face resolved
        // against `main_file`, so a bold cut of the sans family had no file to
        // come from and no slot to sit in.
        let file_for = |family: Family| match family {
            Family::Roman => &families.main_file,
            Family::Sans => &families.sans_file,
            Family::Mono => &families.mono_file,
        };
        let face_file = |face: Face| {
            file_for(face.family)
                .resolve_face(face, near)
                .and_then(|file| embed_file(&file))
        };
        // The sans family, resolved exactly as the mono one is. A book sets its
        // headings in this -- `\titleformat{\chapter}{\sffamily\bfseries\Huge}` --
        // and with `\sffamily` answering the main face, every heading in every
        // book came out in the body typeface. lualatex embeds Orbitron twice for
        // `arb`; texrs embedded no Orbitron at all.
        let sans = families
            .sans_file
            .resolve(near)
            .and_then(|file| embed_file(&file))
            .or_else(|| families.sans.as_deref().and_then(embed_family))
            .or_else(|| {
                families
                    .sans
                    .as_deref()
                    .map(|f| Font::Base14(base14_for(f).to_string()))
            })
            .unwrap_or_else(|| main.clone());
        // The upright, medium face of each family -- what the rest of that family
        // falls back to when the document shipped no file for a bold or italic cut
        // of it.
        let upright = |family: Family| match family {
            Family::Roman => main.clone(),
            Family::Sans => sans.clone(),
            Family::Mono => mono.clone(),
        };
        // Twelve faces, in `Face::index` order. Each is the file the document
        // named for that family and that cut, then the member of the fourteen
        // carrying it, then the family's own upright face -- so a `\textbf` in a
        // document that shipped no bold still sets rather than vanishing.
        let fonts: Vec<std::sync::Arc<Font>> = Face::ALL
            .iter()
            .map(|face| {
                // The upright, medium face of a family is the one resolved above,
                // and it must be USED rather than rebuilt: a document naming no
                // family at all is set in Computer Modern, which no amount of
                // base-14 reasoning reconstructs.
                if !face.bold && !face.italic {
                    return upright(face.family);
                }
                // A cut the document shipped a file for; failing that, the member
                // of the fourteen carrying that cut of that family -- all twelve
                // exist. A DIFFERENT typeface that is really bold beats the same
                // typeface that is not: a description term set in the face of its
                // own meaning has lost the only thing the markup was for.
                face_file(*face).unwrap_or_else(|| Font::Base14(base14_face(&base, *face)))
            })
            .map(std::sync::Arc::new)
            .collect();
        // What each family is scaled by. A document writes `Scale=MatchLowercase`
        // so a display family sits beside its text family rather than looming over
        // it, usually once through `\defaultfontfeatures` for everything it loads
        // -- and unapplied, every heading in that family is set larger than the
        // document asked for. The bold and italic faces are cuts of the MAIN
        // family, so they take its scale rather than one of their own.
        let main_path = families.main_file.resolve(near);
        let scale_for = |file: &FontFile| {
            face_scale(
                file.scale.as_deref(),
                file.resolve(near).as_deref(),
                main_path.as_deref(),
            )
        };
        // Per FAMILY, and every cut of a family takes its family's scale. The old
        // five-slot array gave bold and italic the MAIN family's scale, so a bold
        // cut of the sans family had no scale slot at all.
        let scales: Vec<f64> = Face::ALL
            .iter()
            .map(|face| scale_for(file_for(face.family)))
            .collect();

        // Measure in the face that will be printed. An embedded font carries its
        // own widths; without one, cmr10's are the closest thing installed, and a
        // line may then run a little long or short of the measure.
        let embedded_widths: Vec<Option<Vec<i64>>> = fonts
            .iter()
            .map(|f| match &**f {
                Font::TrueType { widths, .. } => Some(widths.clone()),
                _ => None,
            })
            .collect();
        // Which characters each face can actually draw, from the font file's own
        // cmap. This is the question `luaotfload.add_fallback` asks per glyph, and
        // it is the reason the publication scripts required LuaTeX at all: a
        // character the face has no glyph for has to come from somewhere else, and
        // it cannot be fetched without first knowing that it is missing.
        let coverage: Vec<Option<std::collections::BTreeSet<u32>>> =
            fonts.iter().map(|f| face_coverage(f)).collect();
        // A face with no file to read is one of the fourteen, and carrying all of
        // WinAnsi is what being one of them means.
        let covers = |ch: char, face: Face| covered(&coverage, ch, face);
        // The faces the DOCUMENT named to fetch a missing glyph from, and the
        // glyphs it is about to ask them for. Reserving them first is what keeps
        // the file's `/W` array to the nine glyphs a book borrowed rather than to
        // all fifty thousand a broad face carries; the scan is over the DISTINCT
        // characters, so it costs one pass whatever the book's length.
        let mut fallbacks = Fallbacks::load(&families.fallbacks);
        if !fallbacks.is_empty() {
            let distinct: std::collections::BTreeSet<char> =
                printing_chars(text).filter(|c| !c.is_ascii()).collect();
            for ch in distinct {
                // Only what a face cannot draw and the Symbol font has not got:
                // asking for the rest would carry glyphs nothing ever draws.
                let drawn_already = SYMBOL_FONT.iter().any(|(c, _, _)| *c == ch)
                    || Face::ALL
                        .iter()
                        .all(|face| winansi_code(ch).is_some() && covers(ch, *face));
                if !drawn_already {
                    fallbacks.reserve(ch);
                }
            }
            fallbacks.settle();
        }
        Faces {
            fonts,
            main_shared,
            scales,
            embedded_widths,
            coverage,
            fallbacks,
            metrics: find_font("cmr10").and_then(|p| Tfm::open(&p).ok()),
        }
    }

    fn covers(&self, ch: char, face: Face) -> bool {
        covered(&self.coverage, ch, face)
    }

    fn outside(&self, ch: char) -> Option<(usize, u16)> {
        self.fallbacks.glyph(ch)
    }

    /// What a stretch the face draws ITSELF costs. The codes are what the file
    /// will hold and the characters are what the document wrote; the two
    /// differ wherever WinAnsi puts a character somewhere other than its
    /// codepoint, and each table is indexed by the one it is stated in.
    fn own_width(&self, codes: &str, source: &str, face: Face, size: f64) -> f64 {
        // The family's own scale, so a face set at MatchLowercase is MEASURED
        // at what it will be DRAWN at. The two must come from one number.
        let size = size * self.scales[face.index()];
        if let Some(Some(w)) = self.embedded_widths.get(face.index()) {
            // PDF widths are 1/1000 em, and codes below 32 are not in the table.
            return codes
                .chars()
                .map(|c| {
                    let at = (c as usize).saturating_sub(32);
                    let mille = w.get(at).copied().unwrap_or(500);
                    mille as f64 / 1000.0 * size
                })
                .sum();
        }
        match &self.metrics {
            // The .tfm reader kerns and ligatures across neighbouring
            // characters, so it needs the string whole rather than an iterator.
            Some(f) => f.width_of(source) * size,
            None => source.chars().count() as f64 * size * 0.5,
        }
    }

    fn piece_width(&self, piece: &Piece, face: Face, size: f64) -> f64 {
        match piece.from {
            // The fallback font's metrics are its own, and they are nothing
            // like the face's: `arrowright` is 987/1000 em where a letter is
            // about 500. Charging the face's widths for it would push every
            // line holding an arrow off the measure.
            Source::Symbol => piece
                .codes
                .chars()
                .map(|c| symbol_width(c as u8) as f64 / 1000.0 * size)
                .sum(),
            // A borrowed face's metrics are its own for the same reason, and
            // they are read from its `hmtx` by the glyph the piece names --
            // two bytes to the glyph, so the codes are taken in pairs.
            Source::Outside(at) => glyph_ids(&piece.codes)
                .map(|glyph| self.fallbacks.width(at, glyph, size))
                .sum(),
            Source::Face => self.own_width(&piece.codes, &piece.source, face, size),
        }
    }

    /// What `word` measures in `face` at `size`.
    ///
    /// Every branch measures through `printing_chars`. A marker's spec is
    /// digits and commas, which every one of these tables has a real width
    /// for, so a word inside one \textcolor was charged for its five letters
    /// plus fourteen spec characters plus three markers -- and a line of them
    /// broke after four words where the same line uncoloured holds seventeen.
    /// It cost whole pages: rubyrs/docs/book.tex set in 340 and sets in 186
    /// with them skipped.
    pub(crate) fn width_of(&self, word: &str, face: Face, size: f64) -> f64 {
        // A formula measures what `mlist_to_hlist` made it, not what its
        // characters come to in the text face: the width of `$\frac{1}{2}$` is
        // the fraction's, and nothing about it can be read off the glyphs.
        if let Some(w) = crate::math::run_width(word) {
            return w;
        }
        // Plain ASCII is the case that runs a million times a book: every face
        // draws it, and the code and the character are the same number, so
        // there is nothing to decide per character. Answering it here keeps an
        // ordinary word measured exactly as it was before any of this.
        if word.is_ascii() {
            let plain: String = printing_chars(word).collect();
            return self.own_width(&plain, &plain, face, size);
        }
        drawn(word, &|c| self.covers(c, face), &|c| self.outside(c))
            .iter()
            .map(|piece| self.piece_width(piece, face, size))
            .sum()
    }
}

/// Set a document straight to PDF, honouring the font it asked for.
///
/// The DVI path names `.tfm` fonts and so can only ever set in Computer Modern;
/// a PDF can name the fourteen faces every reader has, which is how
/// `\setmainfont{Arimo}` becomes Helvetica's metrics rather than a book face.
/// Colour travels the same markers the DVI path reads and comes out as PDF's
/// own `rg` operator.
/// `page` is what `\pagecolor` asked for, painted under everything else.
/// `near` is the directory the document was read from, which is where a font
/// it ships with itself is looked for.
///
/// The page count goes back beside the bytes because the writer is the one
/// place that knows it without reading the finished file back: the pages are
/// inside a compressed object stream, and counting them afterwards meant
/// inflating the whole PDF.
pub fn to_pdf(
    text: &str,
    families: &Families,
    layout: &Layout,
    page_colour: Option<crate::colour::Rgb>,
    near: Option<&std::path::Path>,
) -> crate::Pdf {
    to_pdf_ahead(text, families, layout, page_colour, near, None)
}

/// [`to_pdf`], taking the paragraphs a [`Pipeline`] broke while the document
/// was still being lowered.
///
/// They are used only where they are provably what breaking `text` here would
/// make: the faces they were measured in were read off the same families,
/// with no fallback family whose borrowed glyphs depend on the whole text; the
/// layout is this one (the page penalties aside, which the lowerer settles at
/// the end and the breaker never reads); and the text they were read from is
/// a prefix of `text` as it stands after the references and the contents
/// have been resolved. Anything else -- a font, a page geometry or a colour
/// switched after they were read, a conditional the run decided, a forward
/// reference -- shows up as a difference in one of the three, and the whole
/// of `text` is broken here instead.
pub fn to_pdf_ahead(
    text: &str,
    families: &Families,
    layout: &Layout,
    page_colour: Option<crate::colour::Rgb>,
    near: Option<&std::path::Path>,
    ahead: Option<Ahead>,
) -> crate::Pdf {
    use crate::pdf::{document_from, Font, Page, Set};

    // The faces, and what a word measures in them. See `Faces`.
    let (faces, ahead) = match ahead.filter(|a| a.measured_as(families, layout)) {
        Some(Ahead { faces, broken, .. }) => (faces, Some(broken)),
        None => (Faces::new(families, near, text), None),
    };
    let Faces {
        fonts,
        main_shared,
        scales,
        fallbacks,
        ..
    } = &faces;
    let covers = |ch: char, face: Face| faces.covers(ch, face);
    let outside = |ch: char| faces.outside(ch);
    let piece_width = |piece: &Piece, face: Face, size: f64| faces.piece_width(piece, face, size);
    let width_of = |word: &str, face: Face, size: f64| faces.width_of(word, face, size);

    // The contents, if the document asked for one: set here rather than where
    // `\tableofcontents` stood, because an entry names the page its chapter
    // starts on and no such page exists until the whole document has been
    // broken and paginated. See `TOC`.
    // A `\ref` is the number of the sectioning unit its label stands in, which
    // no page has to be broken to know -- so it is resolved BEFORE the
    // contents, and its digits are on the lines the contents then counts. See
    // `REF`.
    let numbered = refs_numbered(text);
    let contented = contents_set(&numbered, layout, &width_of);
    // A `\pageref` is the page its label fell on, which the contents moves:
    // resolved after it, off the pages the contents itself is part of.
    let text = refs_paged(&contented, layout, &width_of);
    // A picture's node text is sized by the face the page is set in, through
    // the same widths every word on it is measured by -- `tikz::Estimate`,
    // which is all the lowerer had, charges half an em a character and sizes
    // every node box wrong.
    //
    // Each picture's reserved height is restated against those metrics before
    // anything is fitted, so the room the page keeps for a drawing and the room
    // the drawing is given below are the same number. See `PICTURE`.
    //
    // An image's lengths are resolved here for the same reason a picture's
    // height is: `width=0.8\textwidth` is a fraction of a measure, and the
    // natural size is a fact about a file, and the lowerer had neither.
    // Resolved BEFORE the page is fitted, so the room the fitter keeps for a
    // figure and the room the figure is given below are one number.
    let broken = break_lines_from(&text, layout, &width_of, ahead);
    // Every file the image lines name, found and read before any of them is
    // measured or drawn. See `images_read`.
    let images = images_read(&broken, near);
    let remeasure = |line: String| -> String {
        let picture_metrics = FaceMetrics {
            measure: &width_of,
            size: layout.size,
        };
        image_remeasured(picture_remeasured(line, &picture_metrics), layout, &images)
    };
    // A line's remeasure reads that line, the fonts and the files it names,
    // and nothing another line wrote: no TeX state, no style stack, no shared
    // mutable table. So the lines are remeasured independently and collected
    // in document order -- the same lines whatever the thread count -- once
    // there are enough drawings to pay for the fan-out.
    //
    // Counted by the span's opening character, which is where `picture_parts`
    // and `image_parts` look for it: a formula's line is long, and searching
    // the whole of every line for a marker cost more than remeasuring them.
    let blocks = broken
        .iter()
        .filter(|line| {
            let inner = line.trim_start();
            let inner = inner.strip_prefix(CENTRE).unwrap_or(inner);
            inner.starts_with([PICTURE, IMAGE])
        })
        .count();
    let lines: Vec<String> = match blocks >= PARALLEL_BLOCKS {
        true => {
            use rayon::prelude::*;
            broken.into_par_iter().map(remeasure).collect()
        }
        false => broken.into_iter().map(remeasure).collect(),
    };

    // The colour stack, seeded with what the document is set in where it has
    // not said otherwise. Seeding it means a run with nothing pushed still
    // carries a colour, so every run is emitted with an explicit `rg` and none
    // inherits whatever the run before it left behind.
    //
    // It lives out here, across lines and across pages, because a `\color` is
    // in force until its group closes and a book says `\color{textPrim}` ONCE,
    // above everything. Restarting it per line put that colour back to black
    // on the second line of the document.
    let colours: Vec<Spec> = vec![(
        DEFAULT_COLOUR.0.to_string(),
        DEFAULT_COLOUR.1.to_string(),
        DEFAULT_COLOUR.2.to_string(),
    )];
    // The face stack, for the same reason: `\ttfamily` holds until its group
    // closes, and a group can hold a paragraph.
    let faces: Vec<Face> = vec![Face::MAIN];
    // Seeded with the document's own size, which is the entry never popped:
    // an unbalanced size marker leaves the body size in force.
    let sizes: Vec<TypeSize> = vec![TypeSize {
        size: layout.size,
        leading: layout.leading,
    }];

    // Page BREAKING is sequential, but drawing a page is not: it reads only its
    // own lines, the style stacks as they stood where the page begins, and its
    // folio. A serial pass over the lines records those three per page, and
    // the pages are then drawn independently and collected in page order, so
    // the file is the same whatever the thread count.
    let chunks = paginate(&lines, layout);
    let starts = page_starts(&chunks, colours, faces, sizes);
    let draw_page = |(chunk, start): (&Vec<&str>, &PageStart)| -> Page {
        let PageStart {
            mut colours,
            mut faces,
            mut sizes,
            folio,
        } = start.clone();
        let picture_metrics = FaceMetrics {
            measure: &width_of,
            size: layout.size,
        };
        let mut page = Page::letter();
        // The page is painted first, and only first: a fill drawn after the
        // text covers it, and a document that sets a dark page sets light
        // text to go on it -- so getting the order wrong loses the words.
        if let Some((r, g, b)) = page_colour {
            page.content.push_str(&format!(
                "{r} {g} {b} rg\n0 0 {} {} re\nf\n0 0 0 rg\n",
                page.width, page.height
            ));
        }
        let mut y = layout.height + layout.margin - layout.leading;
        for &line in chunk {
            // Which part of a table a line is was a question for `paginate`,
            // which has answered it: the page draws the line.
            let line = without_longtable(line);
            // A line of vertical space is space: the baseline moves down by
            // what that space measures -- see `line_height` -- and nothing is
            // drawn on it. Falling through to the run loop below would draw the
            // marker itself as a character.
            if is_space_line(line) {
                y -= line_height(line, leading_on(line, &mut sizes.clone()));
                continue;
            }
            // A picture is DRAWN where the line it stands on is, in the
            // operators `tikz::draw_on` writes: paths, arrow tips, node borders
            // and node text, with the `/ExtGState` and `/Shading` entries any
            // of them name registered on this page.
            //
            // It hangs BELOW the baseline the line above it left -- its box top
            // is at `y` and its bottom a bounding box lower -- because a
            // picture is a block and not a word, and drawing it up from `y`
            // would put it through the descenders of the line before. The
            // origin is chosen so the box's bottom left corner lands at the
            // margin: a picture's coordinates are its own and regularly
            // negative, and `bounds` is where they actually reach.
            // An image is drawn where the fitter reserved room for it. Both
            // lengths are already points -- `image_remeasured` resolved them
            // against the layout and the file before anything was fitted.
            if let Some((width, height, path)) = image_parts(line) {
                let (Ok(w), Ok(h)) = (width.parse::<f64>(), height.parse::<f64>()) else {
                    continue;
                };
                let left = match is_centred(line) {
                    true => layout.margin + (layout.measure - w).max(0.0) / 2.0,
                    false => layout.margin,
                };
                // A file found and not readable leaves the room its stated
                // lengths reserved and nothing in it, which is what LaTeX
                // does with a figure it cannot use. Every use of a file draws
                // the one picture read from it.
                if let Some(image) = images.get(&path).and_then(|read| read.image.as_ref()) {
                    page.image(std::sync::Arc::clone(image), left, y - h, w, h);
                }
                // Exactly what `line_height` reserved, or the line after the
                // figure is set somewhere the fitter did not put it.
                y -= h + leading_on(line, &mut sizes.clone());
                continue;
            }
            if let Some((height, options, body)) = picture_parts(line) {
                let picture = crate::tikz::parse_document(
                    &options,
                    &body,
                    crate::colour::Colours::predefined(),
                    &picture_metrics,
                );
                let (min_x, min_y, max_x, _) = picture.bounds();
                // A centred picture is placed by its own width, exactly as a
                // centred line of text is -- `\begin{center}` around a
                // `tikzpicture` is how most documents put a drawing on a page.
                let left = match is_centred(line) {
                    true => layout.margin + (layout.measure - (max_x - min_x)).max(0.0) / 2.0,
                    false => layout.margin,
                };
                let bottom = y - height;
                crate::tikz::draw_on(
                    &picture,
                    &mut page,
                    left - min_x,
                    bottom - min_y,
                    std::sync::Arc::clone(main_shared),
                );
                // Exactly what `line_height` reserved for it, or the line after
                // the picture is set somewhere the fitter did not put it.
                y -= height + layout.leading;
                continue;
            }
            // A booktabs rule is DRAWN, not set: the breaker's line carries the
            // mark, the code saying which rule it is, and the spaces that
            // measure how far the table runs. See `rule_line`.
            if let Some(rest) = line.strip_prefix(TABLE_MARK) {
                let mut rest = rest.chars();
                let kind = rest.next().unwrap_or(RULE_MID);
                let span = width_of(
                    rest.as_str(),
                    current_face(&faces),
                    current_size(&sizes).size,
                );
                // booktabs' own weights, relative to the type size:
                // `\heavyrulewidth` above and below the table, `\lightrulewidth`
                // between its head and its body (booktabs.sty).
                let em = match kind == RULE_MID {
                    true => 0.05,
                    false => 0.08,
                };
                let weight = em * layout.size;
                // In the colour the text around it is in, so a rule in a book
                // with a dark page is not drawn in the black it inherited.
                let (r, g, b) = colours.last().cloned().unwrap_or_else(|| {
                    (
                        DEFAULT_COLOUR.0.to_string(),
                        DEFAULT_COLOUR.1.to_string(),
                        DEFAULT_COLOUR.2.to_string(),
                    )
                });
                page.content.push_str(&format!("{r} {g} {b} rg\n"));
                page.rule(layout.margin, y + layout.size * 0.25, span, weight);
                y -= layout.leading;
                continue;
            }
            // A centred line is positioned by its measured width rather than
            // at the margin -- that is the whole of what centring is here.
            // The marker is a PREFIX the breaker put on, so it comes off
            // before the line is measured or drawn.
            let (centred, line) = match line.strip_prefix(CENTRE) {
                Some(rest) => (true, rest),
                None => (false, line),
            };
            // A full line is set TO the measure; a ragged one is set at
            // whatever it comes to. The breaker decides which -- only a line
            // the next word would not fit on is full -- and says so with the
            // same kind of prefix. A centred line never carries it.
            let (justified, line) = match line.strip_prefix(JUSTIFY) {
                Some(rest) => (true, rest),
                None => (false, line),
            };
            // A list item's lines start in from the margin, and every line of
            // the item -- the one carrying the bullet and the three it wrapped
            // onto -- carries the same depth, so they stack at one left edge.
            let (depth, line) = strip_indent(line);
            let indent = list_indent(depth, layout);
            // A line is a sequence of RUNS, each with its own colour: the
            // markers turn colour on and off part way along it. Collapsing the
            // line to one colour state was the first attempt and drew none at
            // all, because the closing marker put the state back before
            // anything was emitted.
            // A line is a sequence of RUNS, each with its own colour and face:
            // the markers turn both on and off part way along it. Collapsing the
            // line to one colour state was the first attempt and drew none at
            // all, because the closing marker put the state back before
            // anything was emitted.
            //
            // A centred line is measured the way it will be DRAWN, each run in
            // its own face, because a line of code centred on the prose font's
            // widths sits off centre by the difference. The splitter is asked
            // on copies of the stacks so the drawing pass below still walks
            // them for real.
            let width: f64 = match centred {
                true => {
                    let (mut c, mut f, mut s) = (colours.clone(), faces.clone(), sizes.clone());
                    styled_runs(line, &mut c, &mut f, &mut s)
                        .iter()
                        .map(|(plain, _, face, ts)| width_of(plain, *face, ts.size))
                        .sum()
                }
                false => 0.0,
            };
            // What each space on a justified line is widened by: the room left
            // over at the measure, shared out between them. Measured the same
            // way a centred line is, on copies of the stacks, because it is the
            // same question -- what does this line come to as it will be drawn.
            // A line with no space in it has nothing to share the room between
            // and is set where it stands.
            let extra: f64 = match justified {
                true => {
                    let (mut c, mut f, mut s) = (colours.clone(), faces.clone(), sizes.clone());
                    let runs = styled_runs(line, &mut c, &mut f, &mut s);
                    let natural: f64 = runs
                        .iter()
                        .map(|(plain, _, face, ts)| width_of(plain, *face, ts.size))
                        .sum();
                    let spaces: usize = runs
                        .iter()
                        .map(|(plain, _, _, _)| plain.chars().filter(|c| *c == ' ').count())
                        .sum();
                    match spaces {
                        0 => 0.0,
                        // Against the NARROWED measure: a justified line inside
                        // a list is set to the list's right edge, not out to
                        // the page's, or the indent would be paid for twice.
                        n => (layout.measure - indent - natural) / n as f64,
                    }
                }
                false => 0.0,
            };
            // Asked on a COPY: `styled_runs` below walks the real stack for
            // this same line, and advancing it twice would lose a size.
            let led = leading_on(line, &mut sizes.clone());
            let mut x = match centred {
                true => layout.margin + (layout.measure - width).max(0.0) / 2.0,
                false => layout.margin + indent,
            };
            for (plain, (r, g, b), face, run) in
                styled_runs(line, &mut colours, &mut faces, &mut sizes)
            {
                if plain.is_empty() {
                    continue;
                }
                // Every run says its colour, so the run after a `\textcolor`
                // gets the colour it was NESTED IN back. Resetting to `0 g`
                // instead is what drew the rest of a dark-paged book black.
                page.content.push_str(&format!("{r} {g} {b} rg\n"));
                // A formula is DRAWN where `mlist_to_hlist` put every glyph of
                // it -- each at its own position, in its own size, with the
                // fraction bars and radical rules between them -- rather than
                // set as a run of characters. Each glyph still goes through the
                // font chain, because which face can draw a sigma is a question
                // about the document's fonts and not about the formula.
                if let Some(set) = crate::math::run_setting(&plain) {
                    for (glyph, gx, gy, size) in crate::math::glyphs(&set) {
                        for piece in drawn(&glyph, &|c| covers(c, face), &outside) {
                            let font = match piece.from {
                                Source::Symbol => {
                                    std::sync::Arc::new(Font::Base14(SYMBOL_FONT_NAME.to_string()))
                                }
                                Source::Outside(at) => match fallbacks.font(at) {
                                    Some(font) => std::sync::Arc::clone(font),
                                    None => continue,
                                },
                                Source::Face => std::sync::Arc::clone(&fonts[face.index()]),
                            };
                            let at = Set {
                                natural: 0.0,
                                width: 0.0,
                            };
                            // At the family's own scale, as the text path is.
                            // Without this a formula inside a `\ttfamily` run
                            // is drawn at the UNSCALED body size while the
                            // text around it is scaled -- and since a scaled
                            // family's body size is a different number, a size
                            // histogram counts those glyphs as body text.
                            let drawn_at = match piece.from {
                                Source::Face => size * scales[face.index()],
                                _ => size,
                            };
                            page.text_set(font, drawn_at, x + gx, y + gy, &piece.codes, at);
                        }
                    }
                    for (rx, ry, rw, rh) in crate::math::rules(&set) {
                        page.rule(x + rx, y + ry, rw, rh);
                    }
                    x += crate::math::pt(set.width);
                    continue;
                }
                // A run is not necessarily one font either: a character the
                // face cannot draw is drawn from the fallback, which is a
                // different font resource and so a `Tf` of its own. The pieces
                // are positioned exactly as the runs are, each one advancing x
                // by what it just drew.
                for piece in drawn(&plain, &|c| covers(c, face), &outside) {
                    let font = match piece.from {
                        Source::Symbol => {
                            std::sync::Arc::new(Font::Base14(SYMBOL_FONT_NAME.to_string()))
                        }
                        // The face the chain answered with, carried in the file
                        // as the glyphs this document borrowed from it.
                        Source::Outside(at) => match fallbacks.font(at) {
                            Some(font) => std::sync::Arc::clone(font),
                            None => continue,
                        },
                        Source::Face => std::sync::Arc::clone(&fonts[face.index()]),
                    };
                    // The piece takes its share of the room: what it measures,
                    // plus the widening for each space that falls inside it.
                    // x advances by what was actually SET and not by what the
                    // glyphs come to, or the piece after it would be drawn back
                    // over the space just widened.
                    let natural = piece_width(&piece, face, run.size);
                    // A borrowed face's codes are glyph ids, and a byte 0x20
                    // inside one is half an id rather than a space: there is
                    // nothing on such a piece for the room to be shared over.
                    let spaces = match piece.from {
                        Source::Outside(_) => 0.0,
                        _ => piece.codes.chars().filter(|c| *c == ' ').count() as f64,
                    };
                    let set = Set {
                        natural,
                        width: natural + extra * spaces,
                    };
                    // At the run's own size, not the document's: this is the
                    // `Tf` operator, and a heading set at the body size is
                    // exactly what made every book short. The width above was
                    // measured at the same number, so the two agree.
                    // Scaled for the same reason the width above is: a family set
                    // at MatchLowercase is drawn at the size it was measured at.
                    // A borrowed or Symbol piece carries its own metrics and is
                    // not the face the scale belongs to.
                    let drawn_at = match piece.from {
                        Source::Face => run.size * scales[face.index()],
                        _ => run.size,
                    };
                    page.text_set(font, drawn_at, x, y, &piece.codes, set);
                    x += set.width;
                }
            }
            // The same step the fitter charged for this line: `leading_on` is
            // asked once here and once there, never spelled twice.
            y -= led;
        }
        // The page number, as LaTeX's `plain` style sets it: centred at the
        // foot. texrs drew none at all, and it is the ONE thing that held every
        // case of the parity ladder at PAGESIZE -- lualatex's text for
        // `Hello world.` is "Hello world. 1" against texrs's "Hello world.",
        // one word apart, and that word is the folio on every document.
        //
        // Numbered the way the contents numbers it (`heading_pages`), so the
        // page a contents entry names is the number printed on that page: a
        // title page resets the count, since `\end{titlepage}` does.
        let shown = folio.to_string();
        let width = width_of(&shown, Face::MAIN, layout.size);
        page.text_in(
            std::sync::Arc::clone(main_shared),
            layout.size,
            (page.width - width) / 2.0,
            page.height - layout.margin - layout.height - FOOTSKIP,
            &shown,
        );
        page
    };
    // Fanning out costs more than a few pages of drawing are worth.
    let work: Vec<_> = chunks.iter().zip(&starts).collect();
    let pages: Vec<Page> = match work.len() >= PARALLEL_PAGES {
        true => {
            use rayon::prelude::*;
            work.into_par_iter().map(draw_page).collect()
        }
        false => work.into_iter().map(draw_page).collect(),
    };
    let count = pages.len();
    crate::Pdf {
        bytes: document_from(pages),
        pages: count,
    }
}

/// The document's own face, as the metrics a picture's nodes are sized by.
///
/// A node's border is drawn around its text, so its size is not in the source:
/// it has to be measured, and measuring it is a question about the fonts this
/// page is being set in. `to_pdf` answers exactly that question for every word
/// it sets, so a node's text is measured the same way rather than by a second
/// idea of what the document's font is.
struct FaceMetrics<'a> {
    /// `to_pdf`'s own `width_of`, which measures at `size`.
    measure: &'a dyn Fn(&str, Face, f64) -> f64,
    /// The size those widths are stated at: the document's type size.
    size: f64,
}

impl crate::tikz::Metrics for FaceMetrics<'_> {
    /// A node is set in the body face -- `\node[font=\ttfamily]` is a font
    /// option this does not read -- and a font's widths scale with its size.
    fn width_of(&self, text: &str, size: f64) -> f64 {
        (self.measure)(text, Face::MAIN, self.size) * size / self.size
    }
}

/// One stretch of a run that a single font draws.
struct Piece {
    /// What goes in the content stream: one byte a glyph, in that font's own
    /// encoding, held as `char`s that are all under 256.
    codes: String,
    /// The document's own characters, for a face whose widths are not in the
    /// file and are measured out of `cmr10` instead.
    source: String,
    /// Which font of the chain draws this stretch.
    from: Source,
}

/// The glyph ids a borrowed face's piece names, out of its two-byte codes.
///
/// The codes are held as `char`s under 256 and not as bytes, because that is
/// what the content stream escapes one at a time; reading them back as UTF-8
/// bytes would split every code above 127 into two.
fn glyph_ids(codes: &str) -> impl Iterator<Item = u16> + '_ {
    let mut chars = codes.chars();
    std::iter::from_fn(move || {
        let hi = chars.next()?;
        let lo = chars.next()?;
        Some((hi as u16) << 8 | lo as u16)
    })
}

/// Which font of the chain a piece is drawn from.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Source {
    /// The face in force, in its own WinAnsi codes.
    Face,
    /// The Symbol font, in its own codes.
    Symbol,
    /// One face of the document's own fallback chain, in glyph ids: two bytes
    /// a glyph, because that is what `/Identity-H` addresses.
    Outside(usize),
}

/// Resolve a run through the chain, into the stretches each font draws.
///
/// Neighbouring characters that land in the same font are one piece, so a line
/// of prose is still one `Tj` and only the arrow in the middle of it is its
/// own. A character that no face, no fallback and no stand-in has is left out,
/// which is what the DVI path does with the same character.
fn drawn(
    text: &str,
    covers: &dyn Fn(char) -> bool,
    outside: &dyn Fn(char) -> Option<(usize, u16)>,
) -> Vec<Piece> {
    let mut pieces: Vec<Piece> = Vec::new();
    for ch in printing_chars(text) {
        let Some(glyph) = glyph_for(ch, covers, outside) else {
            continue;
        };
        let (from, codes, source) = match glyph {
            Glyph::Own(code) => (Source::Face, (code as char).to_string(), ch.to_string()),
            Glyph::Fallback(code) => (Source::Symbol, (code as char).to_string(), ch.to_string()),
            // A glyph id is a two-byte code, written high byte first the way
            // `/Identity-H` reads it, and held as two `char`s under 256 so the
            // content stream escapes each of them as the one byte it is.
            Glyph::Outside(face, glyph) => (
                Source::Outside(face),
                [(glyph >> 8) as u8 as char, (glyph & 0xFF) as u8 as char]
                    .iter()
                    .collect(),
                ch.to_string(),
            ),
            // A stand-in is measured as what it SETS and not as what it stands
            // for: `Cmd` takes three letters' room wherever it lands.
            Glyph::StandIn(text) => (Source::Face, text.to_string(), text.to_string()),
        };
        match pieces.last_mut() {
            Some(last) if last.from == from => {
                last.codes.push_str(&codes);
                last.source.push_str(&source);
            }
            _ => pieces.push(Piece {
                codes,
                source,
                from,
            }),
        }
    }
    pieces
}

/// Which characters a face can draw, out of the font file's own `cmap`.
///
/// `None` for one of the fourteen: it has no file to read, and carrying all of
/// WinAnsi is what being one of them means.
fn face_coverage(font: &crate::pdf::Font) -> Option<std::collections::BTreeSet<u32>> {
    let crate::pdf::Font::TrueType { bytes, .. } = font else {
        return None;
    };
    let sfnt = crate::sfnt::Sfnt::parse(bytes.clone()).ok()?;
    Some(sfnt.cmap().ok()?.into_keys().collect())
}

/// Break lines with a caller-supplied measurer.
///
/// The measurer is asked for a width IN A FACE, and the face is state the text
/// carries: a `\ttfamily` holds until its group closes, so the stack has to
/// live across words, lines and paragraphs here exactly as it does where the
/// page is drawn. Measuring a monospace word in the prose font is how a line
/// of code came out narrower than it sets.
///
/// That carried state -- the style stacks, the centring flag and the list
/// depth -- is ALL one paragraph hands the next. So on a pool of more than one
/// thread a cheap serial pass (`paragraph_starts`) records it at each
/// paragraph's start, the paragraphs are broken independently and collected in
/// document order, and the `\parskip` between two is decided on the collected
/// lines as the serial walk decided it. One thread, or a document of few
/// paragraphs, walks the paragraphs in turn with no prescan.
fn break_lines_measured(
    text: &str,
    layout: &Layout,
    width_of: &(dyn Fn(&str, Face, f64) -> f64 + Sync),
) -> Vec<String> {
    break_lines_from(text, layout, width_of, None)
}

/// [`break_lines_measured`], carrying on from the paragraphs a [`Pipeline`]
/// broke -- when the text they were read from opens `text`, and so its
/// paragraphs are the first of `text`'s, split at the same separators.
fn break_lines_from(
    text: &str,
    layout: &Layout,
    width_of: &(dyn Fn(&str, Face, f64) -> f64 + Sync),
    ahead: Option<BrokenAhead>,
) -> Vec<String> {
    let (mut broken, mut carried, rest) = match ahead {
        Some(a) if text.starts_with(&a.read) => (a.paragraphs, a.carried, &text[a.read.len()..]),
        _ => (Vec::new(), ParagraphStart::first(layout), text),
    };
    let paras: Vec<&str> = rest.split("\n\n").collect();
    broken.extend(break_paragraphs(&paras, layout, &mut carried, width_of));
    let mut lines = Vec::new();
    for (sets_text, own) in broken {
        // `\parskip`: the space LaTeX leaves BETWEEN two paragraphs, which
        // texrs left out entirely -- and which is the largest reason it set a
        // book short. See `PARAGRAPH_SPACE`. It goes in only between two
        // paragraphs that both set text, so a heading's own space is not added
        // to, and nothing is left at the head of the document.
        let after_text = lines
            .last()
            .is_some_and(|line: &String| !is_space_line(line) && !is_break_line(line));
        if after_text && sets_text {
            lines.push(VERTICAL_SPACE.to_string());
        }
        lines.extend(own);
    }
    lines
}

/// Each of `paras` broken, in order, from the state `carried` holds, which is
/// left as the last of them leaves it.
fn break_paragraphs(
    paras: &[&str],
    layout: &Layout,
    carried: &mut ParagraphStart,
    width_of: &(dyn Fn(&str, Face, f64) -> f64 + Sync),
) -> Vec<(bool, Vec<String>)> {
    match paras.len() >= PARALLEL_PARAGRAPHS && rayon::current_num_threads() > 1 {
        true => {
            use rayon::prelude::*;
            let starts = paragraph_starts(paras, layout, carried.clone());
            if let (Some(last), Some(start)) = (paras.last(), starts.last()) {
                *carried = start.clone();
                advance_paragraph(last, layout, carried);
            }
            paras
                .par_iter()
                .zip(starts)
                .map(|(para, mut start)| break_measured(para, layout, &mut start, width_of))
                .collect()
        }
        false => paras
            .iter()
            .map(|para| break_measured(para, layout, carried, width_of))
            .collect(),
    }
}

/// Fewer paragraphs than this are broken on the calling thread: fanning out
/// costs more than a short document's breaking is worth.
const PARALLEL_PARAGRAPHS: usize = 64;

/// Breaking paragraphs while the rest of the document is still being lowered.
///
/// The lowerer is serial, token to token, but a paragraph it has finished is
/// finished: what breaking it needs is its own text, the state the paragraphs
/// before it left (`ParagraphStart`, read off their text), the layout and the
/// faces. So the lowerer hands its text on as it goes (a [`Feed`]), a job on
/// the pool breaks each run of finished paragraphs as it arrives, and the page
/// builder takes what was broken ([`Ahead`]) and breaks only the rest.
///
/// Nothing here is ASSUMED to be what the page builder would have made. The
/// text is what the lowerer's commands say when nothing but fixed text is in
/// them -- the run writes the document's text, and a conditional it decides
/// stops the feed -- and [`to_pdf_ahead`] uses the broken paragraphs only
/// when that text opens the text the run produced, after the references are
/// resolved, and the families and the layout are the ones they were measured
/// with. A document that switches its font or its page geometry halfway is
/// broken whole, after lowering, exactly as before.
pub struct Pipeline {
    done: std::sync::mpsc::Receiver<std::thread::Result<Option<Ahead>>>,
}

/// What the lowerer hands the breaking job.
enum Fed {
    /// The families and layout in force when the first text was handed on,
    /// which the paragraphs are measured with.
    Start {
        families: Box<Families>,
        layout: Layout,
    },
    /// More of the text, in order, slots and all.
    Text(String),
    /// A batch of formula settings, by the index of its first formula.
    Settings(usize, crate::math::Settings),
}

/// The lowerer's end of a [`Pipeline`].
pub struct Feed {
    tx: std::sync::mpsc::Sender<Fed>,
    /// How many of the document level's commands have been read for text.
    scanned: usize,
    /// How much of the command after those, a run of text still open, has.
    taken: usize,
    /// Text read and not yet handed on.
    pending: String,
    started: bool,
    /// Set once something was met whose text only the run knows, or the
    /// breaking job has stopped listening: nothing more is handed on.
    stopped: bool,
}

/// How much text the lowerer gathers before handing it on.
const FEED_BYTES: usize = 32 * 1024;

/// How much an open run of text grows by before it is searched for a
/// paragraph break to hand on up to.
const TAIL_STEP: usize = 4 * 1024;

impl Pipeline {
    /// Start the breaking job on the pool. `near` is the directory the
    /// document was read from, which is where the faces are looked for.
    pub fn start(near: Option<&std::path::Path>) -> (Feed, Pipeline) {
        let (tx, rx) = std::sync::mpsc::channel();
        let (done_tx, done) = std::sync::mpsc::channel();
        let near = near.map(std::path::Path::to_path_buf);
        rayon::spawn(move || {
            let broken = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                break_fed(&rx, near.as_deref())
            }));
            let _ = done_tx.send(broken);
        });
        let feed = Feed {
            tx,
            scanned: 0,
            taken: 0,
            pending: String::new(),
            started: false,
            stopped: false,
        };
        (feed, Pipeline { done })
    }

    /// What the job broke, once the feed is closed and the job has finished
    /// the run of paragraphs it was on.
    pub fn finish(self) -> Option<Ahead> {
        crate::math::receive(&self.done).unwrap_or_else(|p| std::panic::resume_unwind(p))
    }
}

impl Feed {
    /// Where the lowerer's formula settings are told to, so the job can fill
    /// the slots in the text it is handed as the join will.
    pub fn tap(&self) -> crate::math::Tap {
        let tx = self.tx.clone();
        std::sync::Arc::new(move |first, settings| {
            let _ = tx.send(Fed::Settings(first, settings));
        })
    }

    /// Read the document level's commands as far as they can no longer change
    /// the text they write, and hand it on once there is enough of it.
    ///
    /// The last command that is not a line directive is still open. When it is
    /// a run of text, the next characters are appended to it and a ligature
    /// takes its last character back out -- a character that begins a
    /// ligature, never a paragraph break -- so it is final up to its last
    /// paragraph break. Everything before it is final.
    pub fn offer(&mut self, out: &[Cmd], families: &Families, layout: &Layout) {
        if self.stopped {
            return;
        }
        let mut end = out.len();
        while end > 0 && matches!(out[end - 1], Cmd::Line(_)) {
            end -= 1;
        }
        let Some(open) = end.checked_sub(1) else {
            return;
        };
        while self.scanned < open {
            let cmd = &out[self.scanned];
            let fixed = match (self.taken, cmd) {
                (0, _) => fixed_text(cmd, &mut self.pending),
                (taken, Cmd::Text(t)) => {
                    self.pending.push_str(&t[taken..]);
                    true
                }
                _ => false,
            };
            if !fixed {
                self.stopped = true;
                return;
            }
            self.taken = 0;
            self.scanned += 1;
        }
        // Looked into only once it has grown by a step, so a run of text is
        // searched about once and not once per character added to it.
        if let Cmd::Text(t) = &out[open] {
            if t.len() - self.taken >= TAIL_STEP {
                if let Some(at) = t[self.taken..].rfind("\n\n") {
                    let upto = self.taken + at + 2;
                    self.pending.push_str(&t[self.taken..upto]);
                    self.taken = upto;
                }
            }
        }
        if self.pending.len() < FEED_BYTES {
            return;
        }
        if !self.started {
            self.started = true;
            let start = Fed::Start {
                families: Box::new(families.clone()),
                layout: layout.clone(),
            };
            self.stopped = self.tx.send(start).is_err();
        }
        let text = std::mem::take(&mut self.pending);
        self.stopped |= self.tx.send(Fed::Text(text)).is_err();
    }
}

/// Append the text `cmd` writes when the run comes to it, if that is fixed
/// already: `false` when the run decides it (a conditional or a loop), or it
/// is text this does not write the way the run does (a colour's markers).
fn fixed_text(cmd: &Cmd, into: &mut String) -> bool {
    match cmd {
        Cmd::Text(t) => {
            into.push_str(t);
            true
        }
        Cmd::Group { body, .. } => body.iter().all(|cmd| fixed_text(cmd, into)),
        Cmd::Color { .. }
        | Cmd::IfNum { .. }
        | Cmd::IfOdd { .. }
        | Cmd::Loop { .. }
        | Cmd::RustCompile(_) => false,
        _ => true,
    }
}

/// The breaking job: take the text as it comes, fill its formula slots as
/// their settings come back, and break each run of finished paragraphs.
///
/// Once the feed closes, whatever it handed on that can be settled is broken
/// too. The page builder would break it next in any case, and this way how
/// much was broken here depends on the text alone and not on how the job and
/// the lowerer happened to race.
fn break_fed(rx: &std::sync::mpsc::Receiver<Fed>, near: Option<&std::path::Path>) -> Option<Ahead> {
    use std::sync::mpsc::TryRecvError;
    let mut start: Option<(Families, Layout)> = None;
    let mut breaker: Option<Ahead> = None;
    let mut settings = crate::math::SettingsTable::default();
    // Text handed on whose slots are not all settled yet, and settled text
    // not yet broken.
    let mut unsettled = String::new();
    let mut settled = String::new();
    let (mut fresh, mut closed) = (false, false);
    loop {
        let fed = match rx.try_recv() {
            Ok(fed) => Some(fed),
            Err(TryRecvError::Empty) => None,
            Err(TryRecvError::Disconnected) => {
                closed = true;
                None
            }
        };
        let fed = match fed {
            Some(fed) => fed,
            // Everything queued is in: settle it, and break the paragraphs it
            // finished once there are enough of them to fan out, or once
            // nothing more is coming.
            None if fresh => {
                fresh = false;
                let spec = |index: usize, row: usize| settings.get(index, row);
                let upto =
                    crate::math::first_unsettled(&unsettled, &spec).unwrap_or(unsettled.len());
                settled.push_str(&crate::math::filled(&unsettled[..upto], &spec));
                unsettled.drain(..upto);
                let (paras, used) = finished_paragraphs(&settled);
                if paras.len() >= PARALLEL_PARAGRAPHS || (closed && !paras.is_empty()) {
                    let (families, layout) = start.as_ref()?;
                    breaker
                        .get_or_insert_with(|| Ahead::new(families, layout, near))
                        .break_next(&paras);
                    settled.drain(..used);
                }
                continue;
            }
            None if closed => break,
            // Idle: run another job rather than hold the thread, and block
            // only when there is none.
            None => match rayon::yield_now() {
                Some(rayon::Yield::Executed) => continue,
                _ => match rx.recv() {
                    Ok(fed) => fed,
                    Err(_) => {
                        closed = true;
                        continue;
                    }
                },
            },
        };
        match fed {
            // Borrowed glyphs are reserved off the whole text, which no
            // stretch of it can stand in for.
            Fed::Start { families, .. } if !families.fallbacks.is_empty() => return None,
            Fed::Start { families, layout } => start = Some((*families, layout)),
            Fed::Text(text) => unsettled.push_str(&text),
            Fed::Settings(first, batch) => settings.insert(first, batch),
        }
        fresh = true;
    }
    breaker
}

/// The paragraphs `text` has finished -- each followed by its separator --
/// split exactly as `str::split` splits the whole text, and how much of it
/// they take up with their separators.
fn finished_paragraphs(text: &str) -> (Vec<&str>, usize) {
    let mut paras = Vec::new();
    let mut from = 0;
    while let Some(at) = text[from..].find("\n\n") {
        paras.push(&text[from..from + at]);
        from += at + 2;
    }
    (paras, from)
}

/// Paragraphs broken ahead, the text they were read from, and the state the
/// last of them left.
struct BrokenAhead {
    /// Each paragraph followed by its separator.
    read: String,
    paragraphs: Vec<(bool, Vec<String>)>,
    carried: ParagraphStart,
}

/// What a [`Pipeline`] broke, for [`to_pdf_ahead`]: the breaking job's own
/// state, handed over whole when it finishes.
pub struct Ahead {
    faces: Faces,
    families: Families,
    layout: Layout,
    broken: BrokenAhead,
}

impl Ahead {
    fn new(families: &Families, layout: &Layout, near: Option<&std::path::Path>) -> Self {
        Ahead {
            // With no fallback family the faces do not depend on the text.
            faces: Faces::new(families, near, ""),
            families: families.clone(),
            layout: layout.clone(),
            broken: BrokenAhead {
                read: String::new(),
                paragraphs: Vec::new(),
                carried: ParagraphStart::first(layout),
            },
        }
    }

    /// Break the next paragraphs of the document.
    fn break_next(&mut self, paras: &[&str]) {
        let faces = &self.faces;
        let width_of = |word: &str, face: Face, size: f64| faces.width_of(word, face, size);
        let broken = &mut self.broken;
        let lines = break_paragraphs(paras, &self.layout, &mut broken.carried, &width_of);
        broken.paragraphs.extend(lines);
        for para in paras {
            broken.read.push_str(para);
            broken.read.push_str("\n\n");
        }
    }

    /// Whether the paragraphs were measured in what `families` and `layout`
    /// set the document in.
    fn measured_as(&self, families: &Families, layout: &Layout) -> bool {
        let layout_then = Layout {
            paging: layout.paging,
            ..self.layout.clone()
        };
        families.fallbacks.is_empty() && self.families == *families && layout_then == *layout
    }
}

/// What breaking one paragraph needs to know that the paragraphs before it
/// left behind.
#[derive(Clone, Debug, PartialEq)]
struct ParagraphStart {
    colours: Vec<Spec>,
    faces: Vec<Face>,
    sizes: Vec<TypeSize>,
    /// Centring is a REGION and outlives the paragraph its marker landed in:
    /// a title page is one `\begin{center}` holding half a dozen
    /// `\par`-separated pieces.
    centred: bool,
    /// And so is the list depth: a `\begin{itemize}` opens a region that runs
    /// to its `\end`, and an item's own body is regularly several paragraphs.
    /// 0 is "not in a list".
    depth: usize,
}

impl ParagraphStart {
    /// What the first paragraph of a document begins with.
    fn first(layout: &Layout) -> Self {
        ParagraphStart {
            // The breaker cares about the face and not about the colour, but
            // the two markers are interleaved in one stream, so the same
            // splitter reads both and the colour half goes on a stack nothing
            // here looks at.
            colours: Vec::new(),
            faces: vec![Face::MAIN],
            // Seeded with the document's own size, which is the entry never
            // popped: an unbalanced size marker leaves the body size in force.
            sizes: vec![TypeSize {
                size: layout.size,
                leading: layout.leading,
            }],
            centred: false,
            depth: 0,
        }
    }
}

/// The state each paragraph begins with, advanced from `carried` in document
/// order exactly as `paragraph_starts_serial` advances it.
///
/// Reading a paragraph's markers is the cost, and a paragraph's markers do the
/// same thing to the state whatever state they meet: a stack pops some number
/// of entries it did not push and then leaves what it pushed, and the centring
/// flag and the depth are each SET or left alone. So every paragraph's effect
/// is read in parallel against stacks not yet known (`ParagraphEffect`); a
/// serial walk applies the effects in order, which for the common paragraph
/// that touches nothing is three flag tests, and records the state at the head
/// of each chunk of paragraphs; and the chunks then fill in their own
/// paragraphs' states in parallel.
fn paragraph_starts(
    paras: &[&str],
    layout: &Layout,
    carried: ParagraphStart,
) -> Vec<ParagraphStart> {
    use rayon::prelude::*;
    let effects: Vec<ParagraphEffect> = paras
        .par_iter()
        .map(|para| ParagraphEffect::of(para, layout))
        .collect();
    let size = paras
        .len()
        .div_ceil(rayon::current_num_threads() * 4)
        .max(1);
    let mut state = carried;
    let mut heads = Vec::with_capacity(paras.len().div_ceil(size));
    for (at, (para, effect)) in paras.iter().zip(&effects).enumerate() {
        if at % size == 0 {
            heads.push(state.clone());
        }
        effect.advance(para, layout, &mut state);
    }
    let chunks: Vec<Vec<ParagraphStart>> = paras
        .par_chunks(size)
        .zip(effects.par_chunks(size))
        .zip(heads)
        .map(|((paras, effects), mut state)| {
            paras
                .iter()
                .zip(effects)
                .map(|(para, effect)| {
                    let start = state.clone();
                    effect.advance(para, layout, &mut state);
                    start
                })
                .collect()
        })
        .collect();
    chunks.concat()
}

/// The state each paragraph begins with, one paragraph after another: what
/// `paragraph_starts` must reproduce.
#[cfg(test)]
fn paragraph_starts_serial(
    paras: &[&str],
    layout: &Layout,
    mut carried: ParagraphStart,
) -> Vec<ParagraphStart> {
    let mut starts = Vec::with_capacity(paras.len());
    for para in paras {
        starts.push(carried.clone());
        advance_paragraph(para, layout, &mut carried);
    }
    starts
}

/// Move `state` over one paragraph, without measuring or breaking anything.
fn advance_paragraph(para: &str, layout: &Layout, state: &mut ParagraphStart) {
    let ParagraphStart {
        colours,
        faces,
        sizes,
        centred,
        depth,
    } = state;
    let (now_centred, now_depth) = walk_paragraph(
        para,
        layout,
        &mut Live {
            colours,
            faces,
            sizes,
        },
    );
    *centred = now_centred.unwrap_or(*centred);
    *depth = now_depth.unwrap_or(*depth);
}

/// Read one paragraph's markers into `styles` by the same routing
/// `break_measured` breaks with, and say what it last SET the centring flag
/// and the list depth to, if anything.
///
/// Pictures, listings and tables leave every piece of the state where they
/// found it (a table READS the stacks; see `table_lines`). In prose the region
/// markers set the centring flag and the depth, and the stacks move only in a
/// word `word_width` splits into styled runs -- one holding a colour or face
/// marker -- so only those words are walked, split exactly as `fill` splits
/// them.
fn walk_paragraph(
    para: &str,
    layout: &Layout,
    styles: &mut impl StyleStacks,
) -> (Option<bool>, Option<usize>) {
    let (mut centred, mut depth) = (None, None);
    let (_, para) = paragraph_params(para, &layout.breaking);
    let para: &str = &para;
    if is_block_para(para) || listing_lines(para).is_some() || para.contains(TABLE_ROW) {
        return (centred, depth);
    }
    for part in para.split([PAGE_BREAK, VERTICAL_SPACE]) {
        let mut rest = part;
        loop {
            let (stretch, marker) = next_stretch(rest);
            if stretch.contains(STACK_MARKERS) {
                for word in words_carrying_refs(stretch) {
                    if word.contains(STACK_MARKERS) {
                        walk_styles(&word, styles);
                    }
                }
            }
            let Some(marker) = marker else { break };
            // `cross_region` SETS what it moves, whatever it was before.
            let (mut now_centred, mut now_depth) = (false, 0);
            rest = cross_region(rest, stretch, marker, &mut now_centred, &mut now_depth);
            match marker {
                LIST_INDENT => depth = Some(now_depth),
                _ => centred = Some(now_centred),
            }
        }
    }
    (centred, depth)
}

/// What one paragraph does to the state the paragraph before it left, read
/// without knowing that state.
struct ParagraphEffect {
    styles: StyleEffect,
    centred: Option<bool>,
    depth: Option<usize>,
}

impl ParagraphEffect {
    fn of(para: &str, layout: &Layout) -> Self {
        let mut styles = StyleEffect::default();
        let (centred, depth) = walk_paragraph(para, layout, &mut styles);
        ParagraphEffect {
            styles,
            centred,
            depth,
        }
    }

    /// Move `state` over the paragraph this was read from. A stack the
    /// paragraph moves that is EMPTY has no floor for its pops to stop at --
    /// only the breaker's colour stack starts that way, until its first push
    /// -- so that paragraph is walked again against the state itself.
    fn advance(&self, para: &str, layout: &Layout, state: &mut ParagraphStart) {
        if !self
            .styles
            .apply(&mut state.colours, &mut state.faces, &mut state.sizes)
        {
            advance_paragraph(para, layout, state);
            return;
        }
        state.centred = self.centred.unwrap_or(state.centred);
        state.depth = self.depth.unwrap_or(state.depth);
    }
}

/// One paragraph's lines, from the state the paragraphs before it left, which
/// it advances; and whether it sets text, which is what decides the
/// `\parskip` before it.
fn break_measured(
    para: &str,
    layout: &Layout,
    state: &mut ParagraphStart,
    width_of: &dyn Fn(&str, Face, f64) -> f64,
) -> (bool, Vec<String>) {
    let ParagraphStart {
        colours,
        faces,
        sizes,
        centred,
        depth,
    } = state;
    let mut lines = Vec::new();
    // The parameters this paragraph ended under (see `BREAK_PARAMS`), which
    // `fill` reads off the layout it is handed.
    let (params, para) = paragraph_params(para, &layout.breaking);
    let para: &str = &para;
    let sets = sets_text(para);
    let with_params;
    let layout = match params == layout.breaking {
        true => layout,
        false => {
            with_params = Layout {
                breaking: params,
                ..layout.clone()
            };
            &with_params
        }
    };
    // A picture is one line of its own, whatever it measures: it is drawn
    // rather than set, so there is nothing in it to fill to a measure and
    // nothing a break may fall inside. `line_height` reads the room it takes
    // off the marker, and the drawing loop below draws it there.
    if is_block_para(para) {
        // `\begin{center}\begin{tikzpicture}` is how most documents put a
        // drawing on a page, and the centring is a REGION that outlives the
        // paragraph its marker landed in -- so the flag `fill` is carrying is
        // what says whether this picture is centred, and it goes on the line
        // the way it goes on a line of text.
        lines.push(match *centred {
            true => format!("{CENTRE}{}", para.trim()),
            false => para.trim().to_string(),
        });
        return (sets, lines);
    }
    // A code listing is already broken, by the author -- see
    // `listing_lines`, which the DVI breaker reads the same way.
    if let Some(code) = listing_lines(para) {
        lines.extend(code.map(str::to_string));
        return (sets, lines);
    }
    // A table is set as a table -- rows on their own lines, columns as wide
    // as their content -- rather than filled into prose. A row end is what
    // says a paragraph is one, the way a listing break says a paragraph is a
    // listing.
    if para.contains(TABLE_ROW) {
        table_lines(para, layout, colours, faces, sizes, width_of, &mut lines);
        return (sets, lines);
    }
    // A forced break is its own line, so the paginator can see one. It has to
    // come out here because `split_whitespace` below counts a form feed as
    // whitespace and would silently drop it.
    for (part_number, part) in para.split(PAGE_BREAK).enumerate() {
        if part_number > 0 {
            lines.push(PAGE_BREAK.to_string());
        }
        // Vertical space is its own line for the same reason: a vertical tab
        // is whitespace to Rust, so the space a heading asked for would vanish
        // into the gap between two words.
        for (space_number, part) in part.split(VERTICAL_SPACE).enumerate() {
            if space_number > 0 {
                lines.push(VERTICAL_SPACE.to_string());
            }
            fill(
                part, centred, depth, layout, colours, faces, sizes, width_of, &mut lines,
            );
        }
    }
    (sets, lines)
}

/// The markers `word_width` splits a word into styled runs at, which are the
/// only places the breaker moves the colour, face and size stacks.
const STACK_MARKERS: [char; 4] = ['\u{1}', '\u{3}', FACE_PUSH, FACE_POP];

/// The text `fill` sets in one alignment: up to the next region marker, and
/// that marker.
fn next_stretch(rest: &str) -> (&str, Option<char>) {
    match rest.find([CENTRE, CENTRE_END, LIST_INDENT]) {
        Some(at) => (&rest[..at], rest[at..].chars().next()),
        None => (rest, None),
    }
}

/// Step over the region marker that ends `stretch`, applying it, and return
/// the text after it.
///
/// The depth marker carries the new depth as one digit, so a nested list
/// opening and the outer list resuming after it are the same instruction with
/// different arguments -- and nothing has to track a stack on this side.
fn cross_region<'a>(
    rest: &'a str,
    stretch: &str,
    marker: char,
    centred: &mut bool,
    depth: &mut usize,
) -> &'a str {
    match marker {
        LIST_INDENT => {
            let (deeper, after) = strip_indent(&rest[stretch.len()..]);
            *depth = deeper;
            after
        }
        m => {
            *centred = m == CENTRE;
            &rest[stretch.len() + m.len_utf8()..]
        }
    }
}

/// Fill one stretch of text into lines at the measure, total-fit, marking each
/// line the centring markers put it inside.
///
/// The markers are cut out BEFORE words are counted because a region opens
/// against the text it centres -- `\centering` is followed straight by the
/// title -- so a word carrying one would be measured with it and set with it.
/// Cutting there also ends the line in hand, which is what a change of
/// alignment means: LaTeX's own `\centering` applies to whole paragraphs.
#[allow(clippy::too_many_arguments)]
fn fill(
    text: &str,
    centred: &mut bool,
    depth: &mut usize,
    layout: &Layout,
    colours: &mut Vec<Spec>,
    faces: &mut Vec<Face>,
    sizes: &mut Vec<TypeSize>,
    width_of: &dyn Fn(&str, Face, f64) -> f64,
    lines: &mut Vec<String>,
) {
    use crate::linebreak::After;
    let mut rest = text;
    loop {
        let (stretch, marker) = next_stretch(rest);
        // A list narrows the measure by exactly what it moves the text in, so
        // a long item wraps INSIDE the list rather than running back out to
        // the right margin. A centred line is not moved in -- see `start` --
        // so it is not narrowed either.
        let indent = match *centred {
            true => 0.0,
            false => list_indent(*depth, layout),
        };
        let measure = layout.measure - indent;
        // A centred line says so in its first character, so the page can
        // position it by what it measures. The alternative -- a parallel list
        // of which lines are centred -- would have to survive pagination, and
        // the form feed a forced break travels as is the pattern already here.
        //
        // Centring is asked FIRST and the indent second, because the two are
        // not independent: a `\begin{center}` inside a list is still centred,
        // over the whole measure. An earlier revision of this put the indent
        // arm ahead of the centring one, so a centred line at any list depth
        // lost its centring marker and set flush at the list indent instead of
        // by its own width. A line can carry one prefix, and centring is the
        // one that wins;
        // `centring_inside_a_list_still_centres_over_the_whole_measure` in
        // tests/typeset.rs is what holds the order.
        let start = |centred: bool, depth: usize| match (centred, depth) {
            (true, _) => CENTRE.to_string(),
            (_, 0) => String::new(),
            (_, deep) => indent_mark(deep),
        };
        // Every word is measured ONCE, here, and the sequence is handed to the
        // total-fit breaker. Measuring here rather than inside the breaker is
        // what keeps the colour and face stacks walked exactly once and in
        // document order, which is the only order they mean anything in.
        let mut pieces: Vec<crate::linebreak::Piece> = Vec::new();
        for word in words_carrying_refs(stretch) {
            // The space between two words is set in the face in force where it
            // falls, which is the one the word BEFORE it left; and the word
            // itself costs what it costs in the faces its own markers select.
            // Measuring a monospace word in the prose font is how a line of
            // code came out narrower than it sets.
            if let Some(previous) = pieces.last_mut() {
                previous.after = crate::linebreak::After::Glue(width_of(
                    " ",
                    current_face(faces),
                    current_size(sizes).size,
                ));
            }
            measure_word(&word, colours, faces, sizes, width_of, &mut pieces);
        }
        // tex.web §813: the set of breakpoints that costs the WHOLE paragraph
        // least, rather than the ones a left-to-right fill happens to reach.
        let breaks = crate::linebreak::break_paragraph(&pieces, measure, &layout.breaking);
        let mut from = 0usize;
        for (number, end) in breaks.iter().enumerate() {
            let mut line = start(*centred, *depth);
            for (offset, piece) in pieces[from..*end].iter().enumerate() {
                // The pieces of one word run together; two words are joined by
                // the space that stood between them.
                if offset > 0 && matches!(pieces[from + offset - 1].after, After::Glue(_)) {
                    line.push(' ');
                }
                line.push_str(&piece.text);
            }
            // A line ending inside a word carries the hyphen the word did not
            // write. One ending after a hyphen the AUTHOR wrote already has it.
            if matches!(pieces[*end - 1].after, After::Discretionary(_)) {
                line.push('-');
            }
            from = *end;
            // Every line but the paragraph's last is a FULL line and is the one
            // set to the measure. The last stays ragged, which is what TeX's
            // `\parfillskip` makes of it, and a centred line is positioned by
            // its own width so it is left alone.
            let last = number + 1 == breaks.len();
            lines.push(match *centred || last {
                true => line,
                false => format!("{JUSTIFY}{line}"),
            });
        }
        match marker {
            Some(marker) => rest = cross_region(rest, stretch, marker, centred, depth),
            None => return,
        }
    }
}

/// Measure one word into the pieces a line may end between.
///
/// A word carrying a marker is ONE piece: `word_width` walks the colour and
/// face stacks to measure it, and a fragment of it would be measured in a face
/// its own markers had not selected yet. Only a plain word is offered to the
/// hyphenator, which is also the only kind Liang's patterns were stated for.
fn measure_word(
    word: &str,
    colours: &mut Vec<Spec>,
    faces: &mut Vec<Face>,
    sizes: &mut Vec<TypeSize>,
    width_of: &dyn Fn(&str, Face, f64) -> f64,
    out: &mut Vec<crate::linebreak::Piece>,
) {
    use crate::linebreak::{After, Piece};
    let face = current_face(faces);
    let size = current_size(sizes).size;
    let whole = |text: &str, width: f64| Piece {
        text: text.to_string(),
        width,
        after: After::Nothing,
    };
    // A cross-reference span is one piece for a stronger reason than the face
    // and colour markers are: it is DELIMITED by its markers, so a word broken
    // between them -- and a pandoc label key is full of the hyphens the
    // breakpoint scan below cuts at -- would leave a fragment with no opening
    // marker on it, and the label key would be measured and drawn as text.
    if word.contains(['\u{1}', '\u{3}', FACE_PUSH, FACE_POP, REF]) {
        let width = word_width(word, colours, faces, sizes, width_of);
        out.push(whole(word, width));
        return;
    }
    // A hyphen the author wrote is a breakpoint of its own (tex.web §869), and
    // TeX does not go looking for more inside a word that already has one.
    if word.contains('-') {
        let parts: Vec<&str> = word.split_inclusive('-').collect();
        for (number, part) in parts.iter().enumerate() {
            out.push(Piece {
                text: part.to_string(),
                width: width_of(part, face, size),
                after: match number + 1 < parts.len() {
                    true => After::Explicit,
                    false => After::Nothing,
                },
            });
        }
        return;
    }
    // A word is regularly wrapped in punctuation -- an opening quote, a full
    // stop -- and the patterns are stated for LETTERS. The letters in the
    // middle are what is offered; the punctuation stays welded to the fragment
    // it sits against.
    let letter = |c: char| c.is_ascii_alphabetic();
    let head = word.len() - word.trim_start_matches(|c| !letter(c)).len();
    let tail = word.len() - word.trim_end_matches(|c| !letter(c)).len();
    let points: Vec<usize> = match head + tail <= word.len() {
        true => crate::linebreak::hyphenator()
            .points(&word[head..word.len() - tail])
            .iter()
            .map(|at| at + head)
            .collect(),
        false => Vec::new(),
    };
    if points.is_empty() {
        out.push(whole(word, width_of(word, face, size)));
        return;
    }
    let dash = width_of("-", face, size);
    let mut from = 0usize;
    for at in points.iter().copied().chain(std::iter::once(word.len())) {
        out.push(Piece {
            text: word[from..at].to_string(),
            width: width_of(&word[from..at], face, size),
            after: match at == word.len() {
                true => After::Nothing,
                false => After::Discretionary(dash),
            },
        });
        from = at;
    }
}

/// How far in from the margin a list at `depth` sets, in points.
///
/// LaTeX's `\leftmargini` is 2.5em at the type size (`article.cls`), and each
/// level in moves by the same again, so a nested item is visibly inside the one
/// holding it rather than a hair off it.
fn list_indent(depth: usize, layout: &Layout) -> f64 {
    depth as f64 * 2.5 * layout.size
}

/// The marker that puts what follows it at `depth`, which is what the lowerer
/// writes at every list boundary and what the breaker reads back.
///
/// The depth is ONE character, because that is what the marker registry
/// declares and what every reader of these markers skips. Nine levels is far
/// past anything a document nests -- LaTeX itself refuses past four -- and
/// deeper lists set at the ninth level rather than being read as a depth of
/// nothing. Depth 0 is the marker that ENDS a list: back at the margin.
pub fn indent_mark(depth: usize) -> String {
    let digit = char::from_digit(depth.min(9) as u32, 10).unwrap_or('0');
    format!("{LIST_INDENT}{digit}")
}

/// The depth a marked line carries, and the line without the marker.
///
/// Both the breaker and the page ask this, so the pair is split in one place
/// rather than in two that could disagree about how wide one level is.
fn strip_indent(line: &str) -> (usize, &str) {
    let Some(rest) = line.strip_prefix(LIST_INDENT) else {
        return (0, line);
    };
    let mut chars = rest.chars();
    let depth = chars.next().and_then(|c| c.to_digit(10)).unwrap_or(0) as usize;
    (depth, chars.as_str())
}

/// How far below the text block the page number sits, LaTeX's `\footskip`.
///
/// 30pt in every class the corpus uses. Measured against lualatex's own output
/// for a default article: it draws the folio at y=89.365 on a 792pt page, which
/// is the text block's bottom edge less this.
const FOOTSKIP: f64 = 30.0;

/// `\parskip`, as a fraction of the leading.
///
/// Every book in the corpus loads pandoc's preamble, which loads `parskip.sty`
/// and so sets `\parskip` to half a line. Measured, in the lualatex-built
/// scifi2/docs/book.pdf: consecutive baselines inside a paragraph are 13.549bp
/// apart and consecutive baselines ACROSS a paragraph boundary are 20.324bp
/// apart, and 20.324 - 13.549 = 6.775 = 13.549/2, on all 2,613 of that book's
/// paragraph boundaries.
const PARAGRAPH_SPACE: f64 = 0.5;

/// Whether the page holding these lines is the one after which numbering
/// starts again.
///
/// `\end{titlepage}` resets LaTeX's page counter (extreport.cls:514-518), so a
/// cover sheet is not page one and everything after it is a page lower than the
/// sheet it sits on. `heading_pages` reads the same mark for the contents; both
/// have to agree or a contents entry names a number no page carries.
fn restarts_here(lines: &[&str]) -> bool {
    lines.iter().any(|line| {
        let mut chars = line.chars();
        while let Some(ch) = chars.next() {
            if ch == TOC && chars.next() == Some(TOC_PAGE_ONE) {
                return true;
            }
        }
        false
    })
}

/// Whether a broken line is vertical space rather than text.
fn is_space_line(line: &str) -> bool {
    !line.is_empty() && line.chars().all(|c| c == VERTICAL_SPACE)
}

/// Whether a broken line is a forced page break rather than text.
fn is_break_line(line: &str) -> bool {
    !line.is_empty() && line.chars().all(|c| c == PAGE_BREAK)
}

/// What one broken line takes down the page.
///
/// A line of text takes a leading. A line of vertical space takes ONE unit of
/// `\parskip`, which is half of one: that is the smallest space the page
/// spends, so it is the unit the rest are counted in -- a heading asks for its
/// space as that many of them (`lower::push_heading`).
/// What each broken line is led on, in order, once for the whole document.
///
/// A line does not carry its own size the way a picture carries its own
/// height: a heading long enough to wrap sets its marker on the FIRST line
/// only, and the lines after it are inside a size that opened before them. So
/// the stack has to be walked in order across every line, which is what this
/// does once, rather than asked of a line on its own -- the fitter considers a
/// line many times and would get a different answer each way round.
///
/// A line is led on the LARGEST size standing anywhere on it, which is what
/// keeps a body line holding one `\large` word from being set into the line
/// above it.
///
/// Only a line holding a size marker moves the stack, and one without any is
/// led on whatever stands at its head -- `leading_on` with nothing to read. So
/// which lines hold one is asked of every line on its own, in parallel, and
/// the walk in order reads only those.
fn line_leadings(lines: &[String], layout: &Layout) -> Vec<f64> {
    // Both markers are ASCII, and no byte of a longer UTF-8 sequence is.
    let marked = per_line(lines.len(), |i| {
        lines[i]
            .bytes()
            .any(|b| b == SIZE_PUSH as u8 || b == SIZE_POP as u8)
    });
    let mut sizes: Vec<TypeSize> = vec![TypeSize {
        size: layout.size,
        leading: layout.leading,
    }];
    lines
        .iter()
        .zip(marked)
        .map(|(line, marked)| match marked {
            true => leading_on(line, &mut sizes),
            false => current_size(&sizes).leading,
        })
        .collect()
}

/// Fewer lines or page starts than this are read on the calling thread: the
/// question asked of each is a scan of one line or one page, and fanning out
/// costs more than a short document's worth of them.
const PARALLEL_LINES: usize = 2048;

/// `read` of every index below `count`, in index order: on the pool for a
/// long run, on the calling thread for a short one or a pool of one. What
/// `read` answers must depend on its index alone, which is what makes the two
/// the same vector.
fn per_line<T: Send>(count: usize, read: impl Fn(usize) -> T + Sync + Send) -> Vec<T> {
    use rayon::prelude::*;
    match count >= PARALLEL_LINES && rayon::current_num_threads() > 1 {
        true => (0..count).into_par_iter().map(read).collect(),
        false => (0..count).map(read).collect(),
    }
}

/// The leading one line is set on, advancing `sizes` by the markers it holds.
///
/// The fitter and the drawing pass MUST take their vertical step from this
/// same function: the fitter charges what it returns and the page advances by
/// it, and two spellings of the same rule are two chances for the page to
/// drift from what was fitted for it. The drawing pass asks on a copy of the
/// stack, because `styled_runs` walks the real one for the same line.
fn leading_on(line: &str, sizes: &mut Vec<TypeSize>) -> f64 {
    // What is in force as the line OPENS counts: a wrapped heading's second
    // line carries no marker of its own.
    let mut most = current_size(sizes).leading;
    let mut chars = line.chars();
    while let Some(ch) = chars.next() {
        match ch {
            SIZE_PUSH => {
                let mut spec = String::new();
                for c in chars.by_ref() {
                    if c == SIZE_PUSH {
                        break;
                    }
                    spec.push(c);
                }
                let pushed = match size_spec(&spec) {
                    Some((size, leading)) => TypeSize { size, leading },
                    None => current_size(sizes),
                };
                sizes.push(pushed);
                most = most.max(pushed.leading);
            }
            // The bottom entry is the document's own size and is never popped,
            // so an unbalanced close leaves the body size in force.
            SIZE_POP if sizes.len() > 1 => {
                sizes.pop();
            }
            _ => {}
        }
    }
    most
}

fn line_height(line: &str, leading: f64) -> f64 {
    // A picture takes its bounding box, and a leading under it before the next
    // line's baseline -- so its slot is the height of the drawing plus one
    // ordinary line. The number is read off the marker rather than measured
    // here, because measuring means parsing the picture and this is asked once
    // per line per page the fitter considers. See `PICTURE`.
    // An image takes the room it was remeasured to, and a leading under it
    // before the next baseline -- the same slot a picture gets.
    if let Some((_, height, _)) = image_parts(line) {
        if let Ok(height) = height.parse::<f64>() {
            return height + leading;
        }
    }
    if let Some((height, _, _)) = picture_parts(line) {
        return height + leading;
    }
    match is_space_line(line) {
        true => leading * PARAGRAPH_SPACE,
        false => leading,
    }
}

/// Whether a paragraph of the text stream will set any text at all.
///
/// A heading is written as its own paragraphs with paragraphs of vertical
/// space either side of it, and the space between two paragraphs goes in only
/// where there are two paragraphs of TEXT: adding it around a heading would
/// pay for the heading's own space twice. Every marker and every kind of
/// whitespace -- the vertical tab a listing breaks its lines on, the form feed
/// a forced break travels as -- answers false here.
fn sets_text(para: &str) -> bool {
    // A picture sets no CHARACTERS and is still something on the page, so the
    // space between two paragraphs goes in either side of it: without this a
    // drawing was welded to the prose above it, since every character of a
    // picture span is an instruction and none of them prints.
    is_block_para(para) || printing_chars(para).any(|c| !c.is_whitespace())
}

/// Fewer pages than this are drawn on the calling thread: fanning out costs
/// more than a handful of pages are worth.
const PARALLEL_PAGES: usize = 8;

/// Fewer pictures and images than this are remeasured on the calling thread,
/// for the same reason.
const PARALLEL_BLOCKS: usize = 8;

/// What drawing one page needs to know that a serial walk over the pages
/// before it would have left behind.
#[derive(Clone, Debug, PartialEq)]
struct PageStart {
    colours: Vec<Spec>,
    faces: Vec<Face>,
    sizes: Vec<TypeSize>,
    /// The printed page number.
    folio: usize,
}

/// The style stacks and folio each page begins with.
///
/// A `\color`, `\ttfamily` or size change holds until its group closes, which
/// may be pages later, so the stacks cross page boundaries; the folio counts
/// from one and starts again after a title page.
///
/// Reading a page's lines is the cost, and what they do to the stacks does not
/// depend on the stacks they meet (see `StyleEffect`). So on a pool of more
/// than one thread each page's effect, and whether it restarts the folio, is
/// read in parallel, and a serial walk applies them in page order -- one
/// truncate and one short extend per page that moves a stack. A handful of
/// pages, or one thread, walks the lines in turn (`page_starts_serial`), which
/// is what this reproduces.
fn page_starts(
    chunks: &[Vec<&str>],
    mut colours: Vec<Spec>,
    mut faces: Vec<Face>,
    mut sizes: Vec<TypeSize>,
) -> Vec<PageStart> {
    use rayon::prelude::*;
    if chunks.len() < PARALLEL_PAGES || rayon::current_num_threads() == 1 {
        return page_starts_serial(chunks, colours, faces, sizes);
    }
    let effects: Vec<(bool, StyleEffect)> = chunks
        .par_iter()
        .map(|chunk| {
            let mut effect = StyleEffect::default();
            walk_page(chunk, &mut effect);
            (restarts_here(chunk), effect)
        })
        .collect();
    let mut folio = 1;
    let mut starts = Vec::with_capacity(chunks.len());
    for (chunk, (restarts, effect)) in chunks.iter().zip(&effects) {
        if *restarts {
            folio = 1;
        }
        starts.push(PageStart {
            colours: colours.clone(),
            faces: faces.clone(),
            sizes: sizes.clone(),
            folio,
        });
        folio += 1;
        // Only an empty stack defeats the effect, and every stack here is
        // seeded; walking the page again keeps that an assumption checked.
        if !effect.apply(&mut colours, &mut faces, &mut sizes) {
            walk_page(
                chunk,
                &mut Live {
                    colours: &mut colours,
                    faces: &mut faces,
                    sizes: &mut sizes,
                },
            );
        }
    }
    starts
}

/// The style stacks and folio each page begins with, one page after another.
fn page_starts_serial(
    chunks: &[Vec<&str>],
    mut colours: Vec<Spec>,
    mut faces: Vec<Face>,
    mut sizes: Vec<TypeSize>,
) -> Vec<PageStart> {
    let mut folio = 1;
    let mut starts = Vec::with_capacity(chunks.len());
    for chunk in chunks {
        if restarts_here(chunk) {
            folio = 1;
        }
        starts.push(PageStart {
            colours: colours.clone(),
            faces: faces.clone(),
            sizes: sizes.clone(),
            folio,
        });
        folio += 1;
        walk_page(
            chunk,
            &mut Live {
                colours: &mut colours,
                faces: &mut faces,
                sizes: &mut sizes,
            },
        );
    }
    starts
}

/// Read one page's style markers into `styles` by the same line routing
/// `to_pdf` draws with: lines that are space, images, pictures or table rules
/// never reach the style splitter, and the rest walk the stacks exactly once.
fn walk_page(chunk: &[&str], styles: &mut impl StyleStacks) {
    for &line in chunk {
        let line = without_longtable(line);
        if is_space_line(line)
            || image_parts(line).is_some()
            || picture_parts(line).is_some()
            || line.starts_with(TABLE_MARK)
        {
            continue;
        }
        let line = line.strip_prefix(CENTRE).unwrap_or(line);
        let line = line.strip_prefix(JUSTIFY).unwrap_or(line);
        let (_, line) = strip_indent(line);
        walk_styles(line, styles);
    }
}

/// Split broken lines into pages: at a forced break, and otherwise wherever
/// LaTeX's penalties say a page costs least to end, carrying a longtable's
/// head and foot onto every page it runs onto.
///
/// Two questions, and they are answered in two places. `page_items` says what
/// the page HOLDS -- the lines that go together and the ones held back to be
/// repeated -- and `plan_pages` says where each page ENDS. Splitting them is
/// what lets the second be answered by cost over the whole document rather
/// than by the first break that does not fit; the third piece, `page_stops`,
/// is the fitting, and it is what the two share.
///
/// `chunks` alone cannot do this: it fills every page to the brim, so a
/// `\newpage` has nowhere to say anything and a chapter starts wherever the
/// previous one happened to end. Nor can it now be a count of lines at all,
/// since a line of vertical space is half the height of a line of text.
///
/// Nor can a table be filled that way. A table is not a run of lines a break
/// may fall anywhere in:
///
///   * a row whose cell wrapped is several lines and one thing, and a break
///     between them tears the row in half;
///   * the head belongs above the rows, on EVERY page they run onto, and a
///     continuation page whose first row has no head over it is a page of
///     unlabelled numbers;
///   * the foot belongs under the rows on every page the table runs PAST, and
///     under the end of the table on the last -- so room for it has to be kept
///     back before the page is full, not found after it is.
///
/// So the lines say what they are (`LONGTABLE`), and this reads them: the
/// repeating head and foot are lines of the stream that are held back rather
/// than set where they stand, and a break inside a table sets the foot, ends
/// the page and opens the next one with the head. The head and foot are lines
/// of `lines` like any other, so repeating one costs nothing -- the page holds
/// the same `&str` again.
fn paginate<'a>(lines: &'a [String], layout: &Layout) -> Vec<Vec<&'a str>> {
    let leadings = line_leadings(lines, layout);
    let items = page_items(lines, layout, &leadings);
    let mut pages: Vec<Vec<&str>> = Vec::new();
    for Planned { from, upto, foot } in plan_pages(&items, lines, layout, &leadings) {
        let mut page: Vec<&str> = Vec::new();
        // The head of a table this page opens in the middle of.
        if items[from].repeat_head {
            let (at, end) = items[from].head;
            page.extend(lines[at..end].iter().map(String::as_str));
        }
        for item in &items[from..upto] {
            if !matches!(item.kind, Kind::Set(_)) {
                continue;
            }
            page.extend(
                lines[item.at..item.at + item.len]
                    .iter()
                    .map(String::as_str),
            );
        }
        // And the foot of a table that runs past it.
        if let Some((at, end)) = foot {
            page.extend(lines[at..end].iter().map(String::as_str));
        }
        if !page.is_empty() {
            pages.push(page);
        }
    }
    pages
}

/// What one item of the page stream is.
enum Kind {
    /// A forced break: `\newpage`, which ends the page wherever it falls.
    Break,
    /// Lines the page sets nothing of, because they are a longtable's
    /// repeating head or its foot: held back to be put where they belong.
    Held,
    /// Lines to set, of this height, that no page break may fall inside --
    /// one ordinary line, or the several a table row wrapped onto.
    Set(f64),
}

/// One thing the paginator moves: the unit a page holds a whole number of.
///
/// `paginate` used to walk the lines and decide as it went, which is why the
/// two questions it answers -- WHAT a page holds and WHERE it ends -- were one
/// loop and only the second of them could be reconsidered. Splitting the first
/// out here is what lets the second be answered by cost over the whole
/// document rather than by the first break that fits.
///
/// The item stream does not depend on where the pages end, and that is what
/// makes this sound: the head a page repeats, the foot it holds back, and the
/// number of lines a too-tall group is cut into -- `room` below, which is
/// measured against the head and not against what the page has already used --
/// are all fixed by the lines alone.
struct Item {
    /// Where in `lines` this item starts, and how many lines it is.
    at: usize,
    len: usize,
    kind: Kind,
    /// The head a page beginning with this item repeats above it.
    head: (usize, usize),
    repeat_head: bool,
    /// The foot a page ending BEFORE this item carries below it, because the
    /// table runs past that page.
    foot: (usize, usize),
}

/// The height a run of lines takes.
fn run_height(lines: &[String], run: (usize, usize), leadings: &[f64]) -> f64 {
    lines[run.0..run.1]
        .iter()
        .enumerate()
        .map(|(i, l)| line_height(l, leadings[run.0 + i]))
        .sum()
}

/// Read the broken lines as the stream of items a page is filled with.
///
/// This is the walk `paginate` did, with the fitting taken out of it: every
/// decision left here is about what the lines ARE.
fn page_items(lines: &[String], layout: &Layout, leadings: &[f64]) -> Vec<Item> {
    const EMPTY: (usize, usize) = (0, 0);
    // A run of lines held back, extended one line at a time. They are written
    // consecutively (`table_lines`), so the run is a range; a line that does
    // not continue the run starts a new one rather than swallowing the gap.
    let extend = |run: (usize, usize), at: usize| match run.0 != run.1 && run.1 == at {
        true => (run.0, at + 1),
        false => (at, at + 1),
    };
    let mut head = EMPTY;
    let mut foot = EMPTY;
    let mut in_table = false;
    let mut items = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        let line = lines[i].as_str();
        if is_break_line(line) {
            // A forced break cannot fall inside a table: a table is one
            // paragraph and is recognised as one before the break character is
            // split out of it, so the break stays inside a cell. It can stand
            // BETWEEN two of them, and the second must not inherit the first
            // one's head.
            in_table = false;
            head = EMPTY;
            foot = EMPTY;
            items.push(Item {
                at: i,
                len: 1,
                kind: Kind::Break,
                head,
                repeat_head: false,
                foot,
            });
            i += 1;
            continue;
        }
        let Some(code) = longtable_code(line) else {
            // Out of the table again: the next one brings its own head, and
            // this one's must not be carried into the prose after it.
            in_table = false;
            head = EMPTY;
            foot = EMPTY;
            items.push(Item {
                at: i,
                len: 1,
                kind: Kind::Set(line_height(line, leadings[i])),
                head,
                repeat_head: false,
                foot,
            });
            i += 1;
            continue;
        };
        if !in_table {
            in_table = true;
            head = EMPTY;
            foot = EMPTY;
        }
        // What is only repeated is not set here.
        if code == LT_REPEAT || code == LT_FOOT {
            match code == LT_REPEAT {
                true => head = extend(head, i),
                false => foot = extend(foot, i),
            }
            items.push(Item {
                at: i,
                len: 1,
                kind: Kind::Held,
                head,
                repeat_head: false,
                foot,
            });
            i += 1;
            continue;
        }
        // What must not be broken into: the rest of this head, or the lines
        // this row wrapped onto.
        let continues = match code {
            LT_HEAD => LT_HEAD,
            _ => LT_CONT,
        };
        let mut group = 1;
        while lines
            .get(i + group)
            .is_some_and(|next| longtable_code(next) == Some(continues))
        {
            group += 1;
        }
        if code == LT_HEAD {
            head = (i, i + group);
        }
        // A group taller than the page it would be repeated on cannot be kept
        // whole; it is set where it falls rather than pushing every page after
        // it out of shape.
        // A table's lines are all lines of text, so the room a page under the
        // head has for them is what is left of it divided by the leading.
        let room = ((layout.height - run_height(lines, head, leadings)) / layout.leading)
            .floor()
            .max(1.0) as usize;
        let step = group.min(room);
        items.push(Item {
            at: i,
            len: step,
            kind: Kind::Set(step as f64 * layout.leading),
            head,
            // A page opening with the head is where the table STARTS on it,
            // and the head is what is about to be set anyway.
            repeat_head: code != LT_HEAD,
            foot,
        });
        i += step;
    }
    items
}

/// One page of the plan: the items it holds, and the foot that goes under it
/// because a table runs past it.
struct Planned {
    from: usize,
    upto: usize,
    foot: Option<(usize, usize)>,
}

/// A place a page may end: the item the NEXT page starts at, the height this
/// page comes to when it ends here, and the foot that goes under it.
#[derive(Clone, Copy)]
struct Stop {
    next: usize,
    used: f64,
    foot: Option<(usize, usize)>,
    /// The document, or a `\newpage`, ended the page rather than the fitting:
    /// the room left over is not this break's fault and is not charged for.
    forced: bool,
}

/// Every place a page filled from `from` may end, in order, put at the end of
/// `stops`.
///
/// The last of them is where the old paginator broke -- the first break that
/// did not fit -- and the ones before it are what it never offered.
fn page_stops(
    items: &[Item],
    lines: &[String],
    layout: &Layout,
    leadings: &[f64],
    from: usize,
    stops: &mut Vec<Stop>,
) {
    // Float slack, so a page that comes to exactly its height is not one line
    // short of it.
    const SLACK: f64 = 1e-6;
    let mut used = match items[from].repeat_head {
        true => run_height(lines, items[from].head, leadings),
        false => 0.0,
    };
    let mut set = 0usize;
    let mut j = from;
    while j < items.len() {
        let item = &items[j];
        match item.kind {
            // Consecutive breaks do not make blank pages: \clearpage after
            // \newpage is one break, which is what both mean together.
            Kind::Break if set == 0 => j += 1,
            Kind::Break => {
                stops.push(Stop {
                    next: j + 1,
                    used,
                    foot: None,
                    forced: true,
                });
                return;
            }
            Kind::Held => j += 1,
            Kind::Set(tall) => {
                if set > 0 {
                    // Room for the group AND for the foot under it: longtable
                    // keeps the foot's height back on every page for the same
                    // reason.
                    let foot = (item.foot.0 != item.foot.1).then_some(item.foot);
                    let below = foot.map_or(0.0, |f| run_height(lines, f, leadings));
                    stops.push(Stop {
                        next: j,
                        used: used + below,
                        foot,
                        forced: false,
                    });
                    // Nothing further down the page can fit either.
                    if used + below > layout.height + SLACK {
                        return;
                    }
                }
                used += tall;
                set += 1;
                j += 1;
            }
        }
    }
    stops.push(Stop {
        next: items.len(),
        used,
        foot: None,
        forced: true,
    });
}

/// The three penalties the page builder charges between the lines of a
/// paragraph (tex.web §890), read from the document by the lowerer.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PageParams {
    /// `\clubpenalty`: what leaving a paragraph's first line alone at the foot
    /// of a page costs.
    pub club: f64,
    /// `\widowpenalty`: what leaving its last line alone at the top of the
    /// next page costs.
    pub widow: f64,
    /// `\brokenpenalty`: charged for ending a page on a line that broke
    /// inside a word.
    pub broken: f64,
}

impl Default for PageParams {
    /// plain.tex's values, which latex.ltx:500-503 of the 2026 release sets
    /// identically: 150, 150 and 100.
    fn default() -> Self {
        Self {
            club: 150.0,
            widow: 150.0,
            broken: 100.0,
        }
    }
}

impl PageParams {
    /// The penalties as a document left them when it was lowered, and
    /// plain.tex's for any it never assigned -- texrs loads no format, and
    /// INITEX's zeros are not what a document is set with.
    pub fn from_intpars(p: &crate::intpar::IntPars) -> Self {
        let d = Self::default();
        let read = |name: &str, fallback: f64| {
            crate::intpar::index(name)
                .and_then(|i| p.assigned(i))
                .map_or(fallback, |v| v as f64)
        };
        Self {
            club: read("clubpenalty", d.club),
            widow: read("widowpenalty", d.widow),
            broken: read("brokenpenalty", d.broken),
        }
    }
}

/// `\@secpenalty` (latex.ltx:17229), which `\@startsection` adds BEFORE the
/// space above a heading (latex.ltx:17242): a page would rather end there than
/// anywhere else nearby, which is what keeps a heading off the foot of a page.
const SEC_PENALTY: f64 = -300.0;

/// `\@M`. tex.web §157: a penalty this large or larger forbids the break.
const FORBID_PENALTY: f64 = 10000.0;

/// What a page pays for each leading of room it leaves empty.
///
/// The reference is set `\raggedbottom` -- report.cls:731-733 turns it on for
/// every one-sided document and no book in the corpus is two-sided -- so the
/// badness lualatex adds to a page's penalty is zero however short the page
/// is, and its output routine takes the cheapest penalty on the page whatever
/// that costs in white space. Priced that way, the least-cost plan for a WHOLE
/// document is degenerate: every page could end after one line for nothing. So
/// the room a page leaves is charged for, at a rate that says what the two are
/// worth against each other -- a widow is worth a line and a half of white
/// space, and a page is worth about thirty of them, so a page is added only
/// where the penalties really have piled up.
const SLACK_COST: f64 = 100.0;

/// What ending a page immediately before each line costs.
///
/// The penalties are the ones LaTeX states and TeX adds up between the lines
/// of a paragraph (tex.web §890): `\clubpenalty` after a paragraph's first
/// line, `\widowpenalty` before its last, `\brokenpenalty` after a line that
/// broke inside a word, and `\@M` -- no break at all -- inside a heading,
/// between a heading and the text it introduces, and after the first line of
/// that text. Two of them can fall in the same place and TeX charges both: the
/// one break in a two-line paragraph is a club AND a widow.
///
/// A paragraph is a run of consecutive lines of text here, which is what one
/// is on this side: the breaker puts a line of vertical space between two of
/// them, and a table's lines say they are a table's. A code listing is such a
/// run too and is treated as a paragraph -- leaving one line of a program
/// alone at the top of a page is the same fault as leaving one line of prose
/// there.
///
/// What each line IS -- space, text, a heading, a line that broke inside a
/// word -- is a question of that line alone, so it is asked of every line in
/// parallel, and the walk in order over paragraphs reads the answers.
fn break_penalties(lines: &[String], params: &PageParams) -> Vec<f64> {
    let n = lines.len();
    let mut cost = vec![0.0f64; n + 1];
    let is_text =
        |line: &str| !is_space_line(line) && !is_break_line(line) && longtable_code(line).is_none();
    // Heading is only ever read of a text line, and hyphen of a text line with
    // another under it in the same paragraph, so only those are scanned for
    // them: a line's own scan is the cost here, and the walk below asked it of
    // exactly those lines.
    let class = per_line(n, |i| {
        let line = lines[i].as_str();
        let space = is_space_line(line);
        let text = is_text(line);
        let continued = text && lines.get(i + 1).is_some_and(|next| is_text(next));
        (
            space,
            text,
            text && heading_line(line),
            continued && printing_chars(line).last() == Some('-'),
        )
    });
    let space = |k: usize| class[k].0;
    let text = |k: usize| class[k].1;
    let heading = |k: usize| class[k].2;
    let hyphen = |k: usize| class[k].3;
    let mut i = 0;
    while i < n {
        if !text(i) {
            i += 1;
            continue;
        }
        let from = i;
        let mut upto = i;
        while upto < n && text(upto) {
            upto += 1;
        }
        i = upto;
        if (from..upto).any(heading) {
            // `\@xsect`: `\par \nobreak` after the title (latex.ltx:17282) and
            // `\clubpenalty\@M` on the paragraph under it (latex.ltx:17322), so
            // the heading, the space below it and the first two lines of that
            // paragraph are one block. `\interlinepenalty\@M` (latex.ltx:17259)
            // is what forbids a break inside a title that took two lines.
            let mut below = upto;
            while below < n && space(below) {
                below += 1;
            }
            let held = match below < n && text(below) {
                true => below + 1,
                false => below,
            };
            cost[from + 1..=held.min(n)].fill(FORBID_PENALTY);
            // `\addpenalty\@secpenalty\addvspace` (latex.ltx:17242): the
            // penalty goes before the space above the heading, and that space
            // is ONE `\vskip` -- so it is one breakpoint, at its head, and not
            // one per line of it.
            let mut above = from;
            while above > 0 && space(above - 1) {
                above -= 1;
            }
            // `.min(from)` because a heading with NO space above it -- one at
            // the very head of the stream -- has no `\vskip` to forbid a break
            // inside, and an empty range is what that has to come to. No
            // document in the corpus reaches it, because `push_heading` always
            // writes the space; the guard is here so that one which did would
            // not index backwards.
            cost[(above + 1).min(from)..from].fill(FORBID_PENALTY);
            // Two headings running together: the space between them is the
            // space below the first, which no break may fall in.
            if cost[above] != FORBID_PENALTY {
                cost[above] = SEC_PENALTY;
            }
            continue;
        }
        for (e, c) in cost.iter_mut().enumerate().take(upto).skip(from + 1) {
            if e == from + 1 {
                *c += params.club;
            }
            if e == upto - 1 {
                *c += params.widow;
            }
            if hyphen(e - 1) {
                *c += params.broken;
            }
        }
    }
    cost
}

/// Whether this line is a heading the contents lists.
///
/// The lowerer writes the mark and the code naming the level
/// (`toc_entry_mark`) at the head of the title, and it survives the breaker:
/// `heading_pages` reads the same mark off the pages to number the contents.
fn heading_line(line: &str) -> bool {
    let mut chars = line.chars();
    while let Some(ch) = chars.next() {
        if ch == TOC && chars.next().is_some_and(|code| toc_level(code).is_some()) {
            return true;
        }
    }
    false
}

/// What a run of consecutive page starts offers: every place a page from each
/// may end, one start after another; the ones it may be CHOSEN to end at, with
/// what each costs on its own -- the room it leaves, charged unless the end was
/// forced, and the penalty of the break; and per start, where its share of
/// those ends and the stop it falls back on when none of them is open.
#[derive(Default)]
struct Offers {
    stops: Vec<Stop>,
    eligible: Vec<Eligible>,
    starts: Vec<Start>,
}

impl Offers {
    fn clear(&mut self) {
        self.stops.clear();
        self.eligible.clear();
        self.starts.clear();
    }
}

/// One start of an [`Offers`] run.
struct Start {
    /// Where this start's offers end in `eligible`; the start before it ends
    /// where they begin.
    eligible: usize,
    /// Which of `stops` the page ends at when nothing eligible is, and the
    /// room it leaves as `empty` charges it.
    fallback: (usize, f64),
}

/// A stop that fits and that no penalty forbids, as the choice reads it.
struct Eligible {
    /// Which of the run's `stops` this is.
    index: usize,
    next: usize,
    empty: f64,
    broken: f64,
}

/// How many page starts have their offers gathered at once, and how many of
/// them one task gathers. A start offers about a page of lines, so the block
/// bounds what is held at a time to a few megabytes however long the document
/// is; the run keeps a task's buffers its own, so the threads do not allocate
/// per start.
const PLAN_BLOCK: usize = 2048;
const PLAN_RUN: usize = 16;

/// Where the pages end: the plan that costs the document least.
///
/// The first break that fits is what `paginate` used to take, and a page
/// filled that way has no way of knowing that the line it is about to keep is
/// the last of its paragraph, or that the heading it ends on introduces text
/// that is now overleaf. So the breaks are chosen the way
/// `linebreak::break_paragraph` chooses a paragraph's: every place a page MAY
/// end is offered, each costs what it leaves empty plus what LaTeX's penalties
/// say about the break itself, and the plan taken is the one whose total over
/// the whole document is least. `best[k]` is what setting `items[k..]` costs
/// with a page starting at `k`, so the answer is `best[0]` and it is built
/// backwards from the end of the document.
///
/// Returns each page as the items it holds and the foot that goes under it.
fn plan_pages(items: &[Item], lines: &[String], layout: &Layout, leadings: &[f64]) -> Vec<Planned> {
    // Float slack, so a page that comes to exactly its height is not one line
    // short of it.
    const SLACK: f64 = 1e-6;
    let penalty = break_penalties(lines, &layout.paging);
    let count = items.len();
    let mut best = vec![f64::INFINITY; count + 1];
    let mut chosen: Vec<Option<Stop>> = vec![None; count + 1];
    best[count] = 0.0;
    // Where a page started at `from` may end, and what each end costs before
    // what follows it is added, depend on `from` alone; only the choice reads
    // `best`. So with more than one thread the offers are gathered for a block
    // of starts at a time, in parallel runs of consecutive starts, and the
    // choice walks back through the block in order; with one, each start's
    // offers are gathered into the same buffer just before they are chosen
    // from. Either way the choice makes the same sums in the same order.
    let gather = |run: &mut Offers, starts: std::ops::Range<usize>| {
        for from in starts {
            let first = run.stops.len();
            page_stops(items, lines, layout, leadings, from, &mut run.stops);
            // A page has to hold something and the document has to have a
            // plan, so where every break is forbidden or none of them fits,
            // the fullest is taken anyway -- which is what the old paginator
            // did with all of them: the last stop that fits, or the first.
            let mut fallback: Option<(usize, f64)> = None;
            for (index, stop) in run.stops.iter().enumerate().skip(first) {
                let room = layout.height - stop.used;
                let fits = room >= -SLACK;
                let empty = match stop.forced {
                    true => 0.0,
                    false => SLACK_COST * room.max(0.0) / layout.leading,
                };
                if fits || fallback.is_none() {
                    fallback = Some((index, empty));
                }
                let broken = match stop.forced {
                    true => 0.0,
                    false => penalty[items[stop.next].at],
                };
                if fits && broken < FORBID_PENALTY {
                    run.eligible.push(Eligible {
                        index,
                        next: stop.next,
                        empty,
                        broken,
                    });
                }
            }
            run.starts.push(Start {
                eligible: run.eligible.len(),
                fallback: fallback.expect("a page start has at least one stop"),
            });
        }
    };
    // The run's starts are `base..`, chosen from last to first: the cheapest
    // eligible stop, the first of them on a tie, or the fallback when there
    // is none.
    let choose = |run: &Offers, base: usize, best: &mut [f64], chosen: &mut [Option<Stop>]| {
        for (at, start) in run.starts.iter().enumerate().rev() {
            let first = match at {
                0 => 0,
                _ => run.starts[at - 1].eligible,
            };
            let mut least = f64::INFINITY;
            let mut pick = None;
            for offer in &run.eligible[first..start.eligible] {
                let cost = best[offer.next] + offer.empty + offer.broken;
                if cost < least {
                    least = cost;
                    pick = Some(offer.index);
                }
            }
            let index = pick.unwrap_or_else(|| {
                let (index, empty) = start.fallback;
                least = best[run.stops[index].next] + empty;
                index
            });
            best[base + at] = least;
            chosen[base + at] = Some(run.stops[index]);
        }
    };
    match count >= PARALLEL_LINES && rayon::current_num_threads() > 1 {
        true => {
            use rayon::prelude::*;
            // The blocks, from the end of the document back to its start.
            let blocks: Vec<std::ops::Range<usize>> = (0..count.div_ceil(PLAN_BLOCK))
                .rev()
                .map(|b| b * PLAN_BLOCK..((b + 1) * PLAN_BLOCK).min(count))
                .collect();
            let fill = |runs: &mut [Offers], block: &std::ops::Range<usize>| {
                runs.par_iter_mut().enumerate().for_each(|(k, run)| {
                    run.clear();
                    let start = block.start + k * PLAN_RUN;
                    if start < block.end {
                        gather(run, start..(start + PLAN_RUN).min(block.end));
                    }
                });
            };
            // Two sets of buffers, kept from block to block so that no thread
            // allocates after the first two: while one block is chosen from
            // on this thread, the pool gathers the next one into the other.
            let fresh = || -> Vec<Offers> {
                (0..PLAN_BLOCK / PLAN_RUN)
                    .map(|_| Offers::default())
                    .collect()
            };
            let (mut here, mut next) = (fresh(), fresh());
            fill(&mut here, &blocks[0]);
            for (b, block) in blocks.iter().enumerate() {
                rayon::join(
                    || {
                        for (k, run) in here.iter().enumerate().rev() {
                            choose(run, block.start + k * PLAN_RUN, &mut best, &mut chosen);
                        }
                    },
                    || {
                        if let Some(after) = blocks.get(b + 1) {
                            fill(&mut next, after);
                        }
                    },
                );
                std::mem::swap(&mut here, &mut next);
            }
        }
        false => {
            let mut run = Offers::default();
            for from in (0..count).rev() {
                run.clear();
                gather(&mut run, from..from + 1);
                choose(&run, from, &mut best, &mut chosen);
            }
        }
    }
    let mut plan = Vec::new();
    let mut at = 0usize;
    while at < count {
        let Some(stop) = chosen[at] else {
            break;
        };
        plan.push(Planned {
            from: at,
            upto: stop.next.min(count),
            foot: stop.foot,
        });
        at = stop.next;
    }
    plan
}

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

    /// A planned page as `(from, upto, foot)`, the fields of [`Planned`].
    type PagePlan = (usize, usize, Option<(usize, usize)>);

    /// xorshift64*, so the documents are the same on every run.
    struct Rng(u64);

    impl Rng {
        fn below(&mut self, n: usize) -> usize {
            self.0 ^= self.0 >> 12;
            self.0 ^= self.0 << 25;
            self.0 ^= self.0 >> 27;
            (self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) as usize % n
        }
    }

    /// Broken lines of every kind the paginator reads: prose that sometimes
    /// broke inside a word, vertical space, forced breaks, headings, size
    /// changes, longtables with heads, repeated heads, feet and wrapped rows.
    fn document(seed: u64, count: usize) -> Vec<String> {
        let mut rng = Rng(seed);
        let mut lines = Vec::new();
        while lines.len() < count {
            match rng.below(40) {
                0 => lines.push(PAGE_BREAK.to_string()),
                1..=3 => {
                    lines.push(VERTICAL_SPACE.to_string().repeat(1 + rng.below(3)));
                    lines.push(format!("{TOC}{TOC_SECTION}Heading"));
                    lines.push(VERTICAL_SPACE.to_string());
                }
                4 => lines.push(size_span(14.4, 18.0, "Larger")),
                5 => {
                    let code = |c: char, text: &str| format!("{LONGTABLE}{c}{text}");
                    lines.push(code(LT_HEAD, "head"));
                    lines.push(code(LT_REPEAT, "head again"));
                    lines.push(code(LT_FOOT, "foot"));
                    for _ in 0..rng.below(120) {
                        lines.push(code(LT_ROW, "row"));
                        for _ in 0..rng.below(3) {
                            lines.push(code(LT_CONT, "row, wrapped"));
                        }
                    }
                }
                _ => {
                    for _ in 0..1 + rng.below(9) {
                        lines.push(match rng.below(6) {
                            0 => "a line that broke inside a hyph-".to_string(),
                            _ => "an ordinary line of prose".to_string(),
                        });
                    }
                    lines.push(VERTICAL_SPACE.to_string());
                }
            }
        }
        lines
    }

    /// `plan_pages` before its offers were gathered apart from the choice:
    /// one walk back over the starts, asking each for its stops as it goes.
    fn reference(
        items: &[Item],
        lines: &[String],
        layout: &Layout,
        leadings: &[f64],
    ) -> Vec<PagePlan> {
        const SLACK: f64 = 1e-6;
        let penalty = break_penalties(lines, &layout.paging);
        let count = items.len();
        let mut best = vec![f64::INFINITY; count + 1];
        let mut chosen: Vec<Option<Stop>> = vec![None; count + 1];
        best[count] = 0.0;
        for from in (0..count).rev() {
            let mut fallback: Option<(Stop, f64)> = None;
            let mut stops = Vec::new();
            page_stops(items, lines, layout, leadings, from, &mut stops);
            for stop in stops {
                let room = layout.height - stop.used;
                let fits = room >= -SLACK;
                let empty = match stop.forced {
                    true => 0.0,
                    false => SLACK_COST * room.max(0.0) / layout.leading,
                };
                let rest = best[stop.next] + empty;
                if fits || fallback.is_none() {
                    fallback = Some((stop, rest));
                }
                let broken = match stop.forced {
                    true => 0.0,
                    false => penalty[items[stop.next].at],
                };
                if !fits || broken >= FORBID_PENALTY {
                    continue;
                }
                if rest + broken < best[from] {
                    best[from] = rest + broken;
                    chosen[from] = Some(stop);
                }
            }
            if chosen[from].is_none() {
                if let Some((stop, cost)) = fallback {
                    best[from] = cost;
                    chosen[from] = Some(stop);
                }
            }
        }
        let mut plan = Vec::new();
        let mut at = 0;
        while let Some(stop) = chosen.get(at).copied().flatten() {
            plan.push((at, stop.next.min(count), stop.foot));
            at = stop.next;
        }
        plan
    }

    fn in_pool<T: Send>(threads: usize, run: impl FnOnce() -> T + Send) -> T {
        rayon::ThreadPoolBuilder::new()
            .num_threads(threads)
            .build()
            .expect("pool")
            .install(run)
    }

    #[test]
    fn pages_planned_on_many_threads_are_the_plan_one_walk_makes() {
        let layout = Layout::default();
        for seed in [1, 7, 0x5eed] {
            // Several blocks of starts, so the pipelined gather crosses from
            // one block into the next, and the last block is a partial one.
            let lines = document(seed, PLAN_BLOCK * 3 + 517);
            let plan = |threads| {
                in_pool(threads, || {
                    let leadings = line_leadings(&lines, &layout);
                    let items = page_items(&lines, &layout, &leadings);
                    let plan: Vec<_> = plan_pages(&items, &lines, &layout, &leadings)
                        .into_iter()
                        .map(|p| (p.from, p.upto, p.foot))
                        .collect();
                    (leadings, break_penalties(&lines, &layout.paging), plan)
                })
            };
            let (leadings, penalties, serial) = plan(1);
            let items = page_items(&lines, &layout, &leadings);
            assert_eq!(
                serial,
                reference(&items, &lines, &layout, &leadings),
                "seed {seed}"
            );
            assert!(
                serial.len() > 50,
                "seed {seed}: too few pages to say anything"
            );
            assert!(
                serial.iter().any(|p| p.2.is_some()),
                "seed {seed}: no page ran a table past its foot"
            );
            let mut sizes = vec![TypeSize {
                size: layout.size,
                leading: layout.leading,
            }];
            let walked: Vec<f64> = lines.iter().map(|l| leading_on(l, &mut sizes)).collect();
            assert_eq!(leadings, walked, "seed {seed}");
            for threads in [2, 8] {
                assert!(
                    plan(threads) == (leadings.clone(), penalties.clone(), serial.clone()),
                    "seed {seed}: {threads} threads"
                );
            }
        }
    }
}

/// A table of contents: where one belongs, which headings feed it, and where
/// the document's own page numbering starts.
///
/// `\tableofcontents` is 123 occurrences across the corpus -- every book opens
/// with a contents page -- and the prelude answered it with nothing, so none
/// of them was set: a missing feature, and pages the reference has that this
/// does not.
///
/// A contents cannot be built in one pass. An entry says which page its
/// chapter starts on, that page is not known until the document has been
/// broken and paginated, and the contents itself then moves every page after
/// it -- it is pages of its own. TeX answers this with the `.aux` file and a
/// second run. There is no `.aux` here and no multi-pass driver, so the two
/// passes are run INSIDE the typesetter, in `contents_set`: the text is broken
/// and paginated with the contents in place, the page each heading landed on
/// is read back off the pages, and the contents is rebuilt with those numbers
/// until the numbers stop moving. That is the fixed point `latexmk` reaches by
/// running latex twice, and it is reached in two passes here for the same
/// reason -- an entry is one line whatever its page number reads, so only the
/// digits change the second time.
///
/// Recording the page as the page is BUILT was the alternative, and it cannot
/// answer this: the contents is set before the chapters it lists, so at the
/// moment its own page is built not one of the numbers on it exists yet.
///
/// The one character after the marker says what it is:
///
///   * a DIGIT -- the contents belongs here, listing headings down to that
///     level. It is `tocdepth`, which every book in the corpus sets to 0:
///     chapters only;
///   * `TOC_CHAPTER`, `TOC_SECTION`, `TOC_SUBSECTION` -- the heading this
///     marks is an entry of that level;
///   * `TOC_PAGE_ONE` -- the page after the one this falls on is page 1.
///
/// U+0015 is the next free control character after U+0014 (LIST_INDENT); the
/// `MARKERS` registry says what the rest are spent on.
pub const TOC: char = '\u{15}';

/// A `\chapter` heading, which is level 0 -- `tocdepth` 0 lists these alone.
pub const TOC_CHAPTER: char = 'c';

/// A `\section` heading: level 1.
pub const TOC_SECTION: char = 's';

/// A `\subsection` heading: level 2.
pub const TOC_SUBSECTION: char = 'u';

/// The page after the one this marker is set on is page 1.
///
/// The `titlepage` environment closes with `\newpage` and then, unless the
/// class is two-sided, `\setcounter{page}\@ne` -- extreport.cls:514-518, which
/// is the class every book in the corpus loads and no document in it says
/// `twoside`. So the cover sheet is not one of the document's numbered pages,
/// and every folio a contents entry prints is one less than the sheet it
/// stands on: lualatex's own contents for `rubyrs/docs/book.tex` reads 1 for a
/// chapter on sheet 2 and 6 for one on sheet 7, and this reads the same.
pub const TOC_PAGE_ONE: char = 'p';

/// What a contents page is headed: `\contentsname` in book.cls and report.cls.
const CONTENTS_NAME: &str = "Contents";

/// How many times the contents is rebuilt before its numbers are taken as
/// settled. Two passes is what a document needs; the second is the one that
/// finds them unchanged, and the rest are only ever reached by a document
/// whose entries wrap differently each time.
const CONTENTS_PASSES: usize = 4;

/// The heading level a TOC code names, or `None` when the code is not an entry.
fn toc_level(code: char) -> Option<usize> {
    match code {
        TOC_CHAPTER => Some(0),
        TOC_SECTION => Some(1),
        TOC_SUBSECTION => Some(2),
        _ => None,
    }
}

/// The mark naming a heading of this level, for the lowerer to write.
///
/// Empty past a subsection: `\subsubsection` is a heading the contents does
/// not list here, and there is no code for it to carry.
pub fn toc_entry_mark(level: usize) -> String {
    match level {
        0 => format!("{TOC}{TOC_CHAPTER}"),
        1 => format!("{TOC}{TOC_SECTION}"),
        2 => format!("{TOC}{TOC_SUBSECTION}"),
        _ => String::new(),
    }
}

/// The mark asking for a contents listing headings down to `depth`.
pub fn toc_request_mark(depth: usize) -> String {
    let digit = char::from_digit(depth.min(9) as u32, 10).unwrap_or('0');
    format!("{TOC}{digit}")
}

/// The mark saying the page after this one is the document's page 1.
pub fn toc_page_one_mark() -> String {
    format!("{TOC}{TOC_PAGE_ONE}")
}

/// How deep a contents this text asks for, or `None` when it asks for none.
///
/// The digit is what tells a request from an entry: an entry's code is a
/// letter, so the scan walks past every heading in the document without
/// mistaking one for the `\tableofcontents` that lists it.
fn contents_depth(text: &str) -> Option<usize> {
    let mut rest = text;
    while let Some(at) = rest.find(TOC) {
        let after = &rest[at + TOC.len_utf8()..];
        let code = after.chars().next()?;
        if let Some(depth) = code.to_digit(10) {
            return Some(depth as usize);
        }
        rest = &after[code.len_utf8()..];
    }
    None
}

/// Every heading the contents lists, in the order the document sets them.
///
/// The title is taken through `printing_chars`, so a heading's own colour and
/// face markers do not travel into the contents line: they are balanced where
/// the heading stands, but the colour and face stacks carry from line to line
/// across the whole document, and a marker copied into a second place is a
/// marker pushed twice.
fn contents_entries(text: &str, depth: usize) -> Vec<(usize, String)> {
    let mut entries = Vec::new();
    let mut rest = text;
    while let Some(at) = rest.find(TOC) {
        let after = &rest[at + TOC.len_utf8()..];
        let Some(code) = after.chars().next() else {
            break;
        };
        rest = &after[code.len_utf8()..];
        let Some(level) = toc_level(code) else {
            continue;
        };
        if level > depth {
            continue;
        }
        // The heading owns its paragraph: the lowerer writes the mark, the
        // title, and the paragraph break that ends it. A title broken across
        // source lines is one line here, so the words are rejoined.
        let title = rest.split("\n\n").next().unwrap_or("");
        let plain: String = printing_chars(title).collect();
        entries.push((
            level,
            plain.split_whitespace().collect::<Vec<_>>().join(" "),
        ));
    }
    entries
}

/// Which page of the document each heading landed on, in the document's own
/// page numbering.
///
/// Read off the PAGES rather than off the lines, because that is the question
/// an entry asks -- and only the paginator knows where a page ends.
fn heading_pages(lines: &[String], layout: &Layout, depth: usize) -> Vec<usize> {
    let mut found = Vec::new();
    for (folio, page) in folio_pages(lines, layout) {
        for line in page {
            let mut chars = line.chars();
            while let Some(ch) = chars.next() {
                if ch != TOC {
                    continue;
                }
                let Some(code) = chars.next() else {
                    break;
                };
                if matches!(toc_level(code), Some(level) if level <= depth) {
                    found.push(folio);
                }
            }
        }
    }
    found
}

/// Whether this line carries the mark saying the page after it is page 1.
///
/// The code character belongs to the mark whatever it is, so the scan steps
/// over it: a contents mark reading `TOC` `TOC_CHAPTER` followed by a `p` the
/// document wrote is not this.
fn carries_page_one(line: &str) -> bool {
    let mut chars = line.chars();
    while let Some(ch) = chars.next() {
        if ch == TOC && chars.next() == Some(TOC_PAGE_ONE) {
            return true;
        }
    }
    false
}

/// Every page of the document paired with the folio it prints, in the
/// document's own page numbering.
///
/// The folio restarts at 1 on the page AFTER the one carrying `TOC_PAGE_ONE`,
/// because that mark stands on a cover sheet the class does not number -- see
/// `toc_page_one_mark`.
///
/// The contents and the cross-references ask the same question of the pages --
/// which page did this mark land on -- so they ask it in one place rather than
/// keeping two copies of the folio arithmetic that could drift apart.
fn folio_pages<'a>(lines: &'a [String], layout: &Layout) -> Vec<(usize, Vec<&'a str>)> {
    let mut folio = 1usize;
    let mut pages = Vec::new();
    for page in paginate(lines, layout) {
        // Read off the page the mark stands on and applied to the NEXT one:
        // the mark says the page after it is page 1.
        let restart = page.iter().any(|line| carries_page_one(line));
        pages.push((folio, page));
        folio = match restart {
            true => 1,
            false => folio + 1,
        };
    }
    pages
}

/// One entry of the contents: its title, the leaders, and the page it starts
/// on set against the right margin.
///
/// A title too long for one line is filled to what the number and a space
/// either side of the leaders leave of the measure, and the number goes on the
/// last of its lines -- which is where LaTeX's own `\@dottedtocline` puts it.
fn entry_lines(
    level: usize,
    title: &str,
    page: usize,
    layout: &Layout,
    width_of: &dyn Fn(&str, Face, f64) -> f64,
) -> Vec<String> {
    let face = Face::MAIN;
    let number = page.to_string();
    let indent = list_indent(level, layout);
    let space = width_of(" ", face, layout.size);
    // A face whose full stop measures nothing would divide by zero; one dot is
    // then the whole leader, which is honest about knowing no better.
    let dot = width_of(".", face, layout.size).max(f64::EPSILON);
    let room = layout.measure - indent - width_of(&number, face, layout.size) - 2.0 * space;
    let mut lines: Vec<String> = Vec::new();
    let mut current = String::new();
    for word in title.split_whitespace() {
        let wider = match current.is_empty() {
            true => word.to_string(),
            false => format!("{current} {word}"),
        };
        match !current.is_empty() && width_of(&wider, face, layout.size) > room {
            true => lines.push(std::mem::replace(&mut current, word.to_string())),
            false => current = wider,
        }
    }
    let dots = ((room - width_of(&current, face, layout.size)) / dot)
        .floor()
        .max(0.0) as usize;
    lines.push(format!("{current} {} {number}", ".".repeat(dots)));
    // Level 0 sets at the margin and carries no mark at all; a deeper entry
    // carries the indent marker a list item does, so the page positions it the
    // one way it knows.
    let mark = match level {
        0 => String::new(),
        deep => indent_mark(deep),
    };
    lines.into_iter().map(|l| format!("{mark}{l}")).collect()
}

/// The contents itself: the heading, and the entries under it.
///
/// The entry lines are handed to the breaker the way a code listing's are --
/// each already broken, terminated by `LISTING_BREAK` -- because a contents
/// line is set as it is written. Filled into a paragraph instead, the leaders
/// of one entry would run the next entry onto the end of it.
fn contents_block(
    entries: &[(usize, String)],
    pages: &[usize],
    layout: &Layout,
    width_of: &dyn Fn(&str, Face, f64) -> f64,
) -> String {
    let mut listing = String::new();
    for (at, (level, title)) in entries.iter().enumerate() {
        // A heading whose page has not been read yet -- the first pass, before
        // anything has been paginated -- still takes the one line it will take
        // when it has one, so the pass measures the contents at its real
        // height.
        let page = pages.get(at).copied().unwrap_or(0);
        // A chapter entry is set clear of the one above it: report.cls spends
        // `\vskip 1.0em` above every `\l@chapter` and nothing above an
        // `\l@section`. A line is the unit this page has, and the difference
        // it makes is whole pages -- lualatex sets rubyrs's ninety-six chapter
        // entries in four pages where this set them in two.
        if *level == 0 {
            listing.push(VERTICAL_SPACE);
            listing.push(LISTING_BREAK);
        }
        for line in entry_lines(*level, title, page, layout, width_of) {
            listing.push_str(&line);
            listing.push(LISTING_BREAK);
        }
    }
    // A contents starts a page, as `\chapter*{\contentsname}` does in
    // report.cls, and the chapter after it starts one of its own.
    format!(
        "\n\n{PAGE_BREAK}\n\n{VERTICAL_SPACE}\n\n{CONTENTS_NAME}\n\n{VERTICAL_SPACE}\n\n{listing}\n\n"
    )
}

/// The text with every contents request replaced by the contents itself.
fn with_contents(
    text: &str,
    entries: &[(usize, String)],
    pages: &[usize],
    layout: &Layout,
    width_of: &dyn Fn(&str, Face, f64) -> f64,
) -> String {
    let block = contents_block(entries, pages, layout, width_of);
    let mut out = String::with_capacity(text.len() + block.len());
    let mut rest = text;
    while let Some(at) = rest.find(TOC) {
        let after = &rest[at + TOC.len_utf8()..];
        let Some(code) = after.chars().next() else {
            break;
        };
        out.push_str(&rest[..at]);
        match code.is_ascii_digit() {
            true => out.push_str(&block),
            // An entry mark stays where it is: the pass that follows reads the
            // page it lands on back out of it.
            false => {
                out.push(TOC);
                out.push(code);
            }
        }
        rest = &after[code.len_utf8()..];
    }
    out.push_str(rest);
    out
}

/// The document's text with its contents set into it, page numbers and all.
///
/// Returns the text untouched -- and does no extra work at all -- for a
/// document that asked for no contents, which is every document that is not
/// one of the books.
fn contents_set<'a>(
    text: &'a str,
    layout: &Layout,
    width_of: &(dyn Fn(&str, Face, f64) -> f64 + Sync),
) -> std::borrow::Cow<'a, str> {
    let Some(depth) = contents_depth(text) else {
        return std::borrow::Cow::Borrowed(text);
    };
    let entries = contents_entries(text, depth);
    let mut pages: Vec<usize> = vec![0; entries.len()];
    for _ in 0..CONTENTS_PASSES {
        let staged = with_contents(text, &entries, &pages, layout, width_of);
        let lines = break_lines_measured(&staged, layout, width_of);
        let found = heading_pages(&lines, layout, depth);
        // The numbers stopped moving, and the text they were read out of is
        // the text that carries them: that is what a second run leaves behind.
        if found == pages {
            return std::borrow::Cow::Owned(staged);
        }
        pages = found;
    }
    std::borrow::Cow::Owned(with_contents(text, &entries, &pages, layout, width_of))
}

/// A cross-reference: `\ref` and `\pageref`, and the `\label` they name.
///
/// `\label` is 88,341 occurrences across the corpus and the prelude answered
/// all three of these with nothing, so `See chapter \ref{ch:one} on page
/// \pageref{ch:one}.` set as `See chapter  on page .` -- a book full of "see
/// chapter" with no number after it, which reads as broken prose rather than
/// as a missing feature.
///
/// A reference cannot be answered where it is written, for the same reason a
/// contents entry cannot: the number belongs to a unit that may not have been
/// read yet, and the page belongs to a pagination that has not happened. So
/// what goes into the text is the QUESTION -- this marker, one character
/// saying which of the three it is, the label key, and the marker again to
/// close it -- and the typesetter answers it, in the two places either side of
/// where the contents is built:
///
///   * `refs_numbered` gives a `\ref` the number of the sectioning unit its
///     label stands in. That needs no page broken, so it runs BEFORE the
///     contents is built and its digits are on the lines the contents counts;
///   * `refs_paged` gives a `\pageref` the page its label fell on, which is
///     only known AFTER the contents is in place -- the contents is pages of
///     its own and moves every page after it.
///
/// U+0017 is the next free control character after U+0016; the `MARKERS`
/// registry says what the rest are spent on.
pub const REF: char = '\u{17}';

/// A `\label`: the key it declares, standing where the document put it.
pub const REF_LABEL: char = 'l';

/// A `\ref`: the number of the unit holding this key.
pub const REF_NUMBER: char = 'n';

/// A `\pageref`: the page this key fell on.
pub const REF_PAGE: char = 'p';

/// latex.ltx's `\@currentlabel`, as a `\refstepcounter` leaves it: the span holds
/// the number itself -- a section's `2`, an equation's `2.1`, a `\tag`'s `A` --
/// and every `\label` after it names that number until the next one.
/// `src/math.rs` writes one for each numbered heading, caption and display place.
pub const REF_VALUE: char = 'v';

/// The start and end of a group that a `REF_VALUE` inside it does not outlive:
/// a float or a display environment, which `\begin` opens with `\begingroup`.
/// The spans carry no key.
pub const REF_OPEN: char = '(';
pub const REF_CLOSE: char = ')';

/// What LaTeX sets for a reference whose label it has not got: `??`, from
/// latex.ltx's `\@setref`, which sets that and warns.
///
/// Setting nothing was what this did, and a gap in a sentence is a fault the
/// author cannot see. Two question marks are one they can.
const UNRESOLVED: &str = "??";

/// How many times the page references are resolved before their numbers are
/// taken as settled, for the reason `CONTENTS_PASSES` gives: a `\pageref` that
/// resolves from nothing to `12` is two characters wider than it was, and a
/// line that then does not fit moves the page the next label falls on.
const REF_PASSES: usize = 4;

/// The mark naming one cross-reference, for the lowerer to write.
///
/// The key is stripped of whitespace and of control characters: the span is
/// delimited by the marker, and a line is split into words on spaces, so a key
/// holding either could not be read back whole. A LaTeX label key holds
/// neither.
pub fn ref_mark(code: char, key: &str) -> String {
    let key: String = key
        .chars()
        .filter(|c| !c.is_whitespace() && !c.is_control())
        .collect();
    format!("{REF}{code}{key}{REF}")
}

/// One cross-reference span in the text.
struct RefSpan<'a> {
    /// Where the opening marker is.
    at: usize,
    /// One past the closing marker.
    end: usize,
    /// Which of the three this is: a label, a `\ref` or a `\pageref`.
    code: char,
    /// The label key between them.
    key: &'a str,
}

/// The next cross-reference span at or after `from`, or `None`.
///
/// A marker with no closing marker after it is not a span. The lowerer writes
/// both or neither, so this is only reached by a document that wrote the
/// character itself -- and half a span read as a whole one would swallow the
/// rest of the book.
fn next_ref(text: &str, from: usize) -> Option<RefSpan<'_>> {
    let at = from + text[from..].find(REF)?;
    let after = at + REF.len_utf8();
    let code = text[after..].chars().next()?;
    let key_at = after + code.len_utf8();
    let close = key_at + text[key_at..].find(REF)?;
    Some(RefSpan {
        at,
        end: close + REF.len_utf8(),
        code,
        key: &text[key_at..close],
    })
}

/// Whether this word is nothing but cross-reference spans.
///
/// Pandoc writes `\label` straight after the heading it names, so the label
/// opens the paragraph under it and stands between the paragraph break and the
/// first word -- a word of its own, once the text is split on whitespace. It
/// prints nothing, so measured as a word it would pay for the space beside it:
/// a space the document did not write, at 88,341 places in the corpus, at the
/// head of the paragraph under every heading in every book.
/// `words_carrying_refs` puts it onto the word that follows instead, where it
/// measures nothing and marks the same place.
fn is_ref_only(word: &str) -> bool {
    let mut at = 0;
    while let Some(span) = next_ref(word, at) {
        if span.at != at {
            return false;
        }
        at = span.end;
    }
    at > 0 && at == word.len()
}

/// The words of `text`, with every span that is nothing but a cross-reference
/// carried onto the word after it.
///
/// Both breakers split a stretch into words here rather than each calling
/// `split_whitespace` and deciding for itself what to do with a label, because
/// a label measured as a word on one path and not on the other is two
/// different books.
fn words_carrying_refs(text: &str) -> Vec<std::borrow::Cow<'_, str>> {
    let mut words: Vec<std::borrow::Cow<str>> = Vec::new();
    let mut carried = String::new();
    for word in text.split_whitespace() {
        if is_ref_only(word) {
            carried.push_str(word);
            continue;
        }
        words.push(match carried.is_empty() {
            true => std::borrow::Cow::Borrowed(word),
            false => std::borrow::Cow::Owned(format!("{}{word}", std::mem::take(&mut carried))),
        });
    }
    // A span the text ENDED on has no word to be carried onto and goes onto
    // the word before it, so that the page it fell on can still be read back
    // off the line. Text that is nothing but spans has no word either way; the
    // label is then dropped, and a `\pageref` to it sets `??` -- which is the
    // honest answer, since there is no line for it to have landed on.
    if !carried.is_empty() {
        if let Some(last) = words.last_mut() {
            last.to_mut().push_str(&carried);
        }
    }
    words
}

/// Whether the text holds a cross-reference of this kind.
///
/// Both resolving passes ask this first and hand the text straight back when
/// the answer is no, so a document that writes no reference -- which is every
/// document in the corpus, and every test that is not about this -- is not
/// walked twice or rewritten at all.
fn has_ref(text: &str, code: char) -> bool {
    let mut at = 0;
    while let Some(span) = next_ref(text, at) {
        if span.code == code {
            return true;
        }
        at = span.end;
    }
    false
}

/// The number each label names: latex.ltx's `\@currentlabel` where the
/// `\label` stands.
///
/// `\@currentlabel` is set by `\refstepcounter` and by nothing else, and every
/// one the typesetting run follows -- a numbered heading's, a caption's, a
/// display's -- reaches the text as a `REF_VALUE` span carrying the number the
/// class's `\the<counter>` writes (`math::number::Numbering`). So a label names
/// the last span before it, as it does under LaTeX: a `\section*` steps
/// nothing and leaves the previous number standing, and a label before any
/// step names `\@currentlabel`'s initial empty value. A `REF_OPEN` ..
/// `REF_CLOSE` pair is a group: the value inside it is the outer one again
/// once it closes, so a label after a figure names the section around it.
///
/// Counting the contents marks instead -- which this did -- numbered every
/// class as report: an article's first section came back as `0.1`, its
/// appendix as `0.2`, and a figure as the subsection it stood in.
fn unit_numbers(text: &str) -> std::collections::HashMap<String, String> {
    let mut current = String::new();
    let mut saved = Vec::new();
    let mut numbers = std::collections::HashMap::new();
    let mut at = 0;
    while let Some(span) = next_ref(text, at) {
        match span.code {
            REF_VALUE => current = span.key.to_string(),
            REF_OPEN => saved.push(current.clone()),
            REF_CLOSE => current = saved.pop().unwrap_or(current),
            // The last definition of a key wins, which is what a rerun over
            // LaTeX's own `.aux` does with a duplicated label.
            REF_LABEL => {
                numbers.insert(span.key.to_string(), current.clone());
            }
            _ => {}
        }
        at = span.end;
    }
    numbers
}

/// The text with every `\ref` replaced by the number its label names,
/// and `??` where there is no such label.
///
/// Public because `--text` resolves them too: a document read as text has no
/// pages, but it has its own structure, and "see chapter 2" is what the
/// sentence says.
pub fn refs_numbered(text: &str) -> std::borrow::Cow<'_, str> {
    if !has_ref(text, REF_NUMBER) {
        return std::borrow::Cow::Borrowed(text);
    }
    let numbers = unit_numbers(text);
    let mut out = String::with_capacity(text.len());
    let mut at = 0;
    while let Some(span) = next_ref(text, at) {
        out.push_str(&text[at..span.at]);
        match span.code == REF_NUMBER {
            true => out.push_str(numbers.get(span.key).map_or(UNRESOLVED, String::as_str)),
            // A label stays where it is: the pass that follows reads the page
            // it lands on back out of it, exactly as a contents entry mark is
            // left for `heading_pages`.
            false => out.push_str(&text[span.at..span.end]),
        }
        at = span.end;
    }
    out.push_str(&text[at..]);
    std::borrow::Cow::Owned(out)
}

/// Which page of the document each label fell on, in the document's own page
/// numbering.
///
/// The question `heading_pages` asks, asked at the labels instead and answered
/// off the same pages.
fn label_pages(lines: &[String], layout: &Layout) -> std::collections::HashMap<String, usize> {
    let mut found = std::collections::HashMap::new();
    for (folio, page) in folio_pages(lines, layout) {
        for line in page {
            let mut at = 0;
            while let Some(span) = next_ref(line, at) {
                if span.code == REF_LABEL {
                    found.insert(span.key.to_string(), folio);
                }
                at = span.end;
            }
        }
    }
    found
}

/// The text with every `\pageref` replaced by the page its label fell on, and
/// `??` where no page carries that label.
fn with_pagerefs(text: &str, pages: &std::collections::HashMap<String, usize>) -> String {
    let mut out = String::with_capacity(text.len());
    let mut at = 0;
    while let Some(span) = next_ref(text, at) {
        out.push_str(&text[at..span.at]);
        match span.code == REF_PAGE {
            true => match pages.get(span.key) {
                Some(page) => out.push_str(&page.to_string()),
                None => out.push_str(UNRESOLVED),
            },
            false => out.push_str(&text[span.at..span.end]),
        }
        at = span.end;
    }
    out.push_str(&text[at..]);
    out
}

/// The document's text with its page references resolved.
///
/// Run AFTER the contents is set, because the contents is pages of its own and
/// moves every page after it: a number read before it was built would name the
/// sheet the label stood on without it.
///
/// The fixed point is `contents_set`'s, for the same reason and to the same
/// depth -- the number a reference sets is text on a line, so resolving one
/// can move the page the next one names. Returns the text untouched, and does
/// no work at all, for a document that wrote no `\pageref`.
fn refs_paged<'a>(
    text: &'a str,
    layout: &Layout,
    width_of: &(dyn Fn(&str, Face, f64) -> f64 + Sync),
) -> std::borrow::Cow<'a, str> {
    if !has_ref(text, REF_PAGE) {
        return std::borrow::Cow::Borrowed(text);
    }
    let mut pages = std::collections::HashMap::new();
    for _ in 0..REF_PASSES {
        let staged = with_pagerefs(text, &pages);
        let lines = break_lines_measured(&staged, layout, width_of);
        let found = label_pages(&lines, layout);
        // The numbers stopped moving, and the text they were read out of is
        // the text that carries them.
        if found == pages {
            return std::borrow::Cow::Owned(staged);
        }
        pages = found;
    }
    std::borrow::Cow::Owned(with_pagerefs(text, &pages))
}

/// The left edge of a list item's lines, carried through the text the way
/// centring is, with the nesting depth as the one character after it.
///
/// `\item` is 8,683 occurrences across the corpus and set inline: an itemize
/// with two items read back as "first item second item" on one line, with no
/// bullet and no break, because the prelude answered `\begin{itemize}` with
/// nothing and `\item` with its optional argument. What a list needs from the
/// page is a left edge and a narrower measure, and both follow from one number
/// -- so the marker carries the depth and the page turns it into a position
/// (`list_indent`).
///
/// U+0014 is the next free control character after U+0013 (JUSTIFY); the
/// `MARKERS` registry below says what the rest are spent on.
pub const LIST_INDENT: char = '\u{14}';

/// A forced page break, carried through the text the way colour is.
///
/// `\newpage` and `\clearpage` were defined by the prelude to expand to
/// nothing, so a book's title page, copyright page and first chapter ran
/// together into one stream of prose and the page count came out at half what
/// the document asks for. A form feed is what the character means, it survives
/// the run because it is not a word, and it is split out of the text BEFORE
/// words are, since Rust counts it as whitespace and would otherwise drop it.
pub const PAGE_BREAK: char = '\u{c}';

/// A `tikzpicture`, carried whole through the text the way a page break is.
///
/// A picture is not text and cannot be expanded into any: its body is TikZ,
/// full of backslashes that are not control sequences and semicolons that end
/// commands, and the prelude used to answer `\draw#1;` with nothing -- so
/// every picture in every document was read, discarded, and drawn nowhere.
/// The body reaches the page instead, as ONE marker span holding the whole
/// picture, because a line is all that survives breaking and pagination.
///
/// The span is `PICTURE`, the height the picture reserves, `;`, the option
/// list and the body base64-encoded with a `:` between them, and `PICTURE`
/// again. Encoded because a picture body holds newlines, spaces and every
/// punctuation mark there is, and a paragraph splitter would tear it apart;
/// base64 is one word of `A-Za-z0-9+/=`, which nothing in the pipeline splits.
///
/// The height is carried rather than recomputed because `line_height` -- which
/// every page-fitting decision goes through -- has no fonts and no palette to
/// parse a picture with, and because parsing one per fitting decision would be
/// paid for over and over. `to_pdf` restates it once, against the document's
/// own metrics, so the room reserved is the room the picture is drawn in.
///
/// U+0018 is the next free control character after U+0017 (REF); the `MARKERS`
/// registry below says what the rest are spent on.
pub const PICTURE: char = '\u{18}';

/// An `\includegraphics` marker, bracketing its own spec at both ends.
///
/// U+0018 is `PICTURE` and U+0019/U+001A are the size pair; this is the next
/// free control character. See `MARKERS`.
pub const IMAGE: char = '\u{1b}';

/// One image span: the width and height asked for, and the file.
///
/// The two lengths are carried as the document WROTE them and resolved later:
/// `width=0.8\textwidth` is a fraction of a measure the lowerer does not know,
/// and the natural size is a fact about a file it has not opened. `f0.8` is
/// that fraction, a bare number is absolute PDF points, and an empty field is
/// "not asked for". `image_remeasured` turns all three into points once the
/// layout and the file are both in hand -- the same two-step `PICTURE` uses,
/// and for the same reason.
pub fn image_span(width: &str, height: &str, path: &str) -> String {
    format!("{IMAGE}{width};{height};{}{IMAGE}", base64(path.as_bytes()))
}

/// One `\includegraphics` length, as the spec [`image_span`] carries.
///
/// `\textwidth` and its two synonyms are the measure, which is a number this
/// side of the engine does not have -- so a length stated in them is carried
/// as the fraction it is and resolved where the layout is known. Every other
/// length is a dimension and becomes points here.
///
/// A bare `\textwidth` is the whole measure: the factor LaTeX reads in front
/// of a length defaults to one.
pub fn image_length(value: &str) -> String {
    let value = value.trim();
    let relative = ["textwidth", "linewidth", "columnwidth", "textheight"]
        .iter()
        .find_map(|name| value.split_once(&format!("\\{name}")));
    if let Some((factor, _)) = relative {
        let factor = factor.trim();
        let factor: f64 = match factor.is_empty() {
            true => 1.0,
            false => match factor.parse() {
                Ok(f) => f,
                Err(_) => return String::new(),
            },
        };
        return format!("f{factor}");
    }
    match dimen_bp(value) {
        Some(points) => points.to_string(),
        None => String::new(),
    }
}

/// The `width=` and `height=` an `\includegraphics` was given, as specs.
///
/// Every other key -- `scale`, `angle`, `keepaspectratio`, `trim`, `clip` --
/// is dropped rather than guessed at. A figure at the wrong size is a figure
/// a reader can still see; there is nothing to be gained by inventing what
/// `angle=90` would have done to the page.
pub fn image_options(options: &str) -> (String, String) {
    let mut width = String::new();
    let mut height = String::new();
    for option in options.split(',') {
        let Some((key, value)) = option.split_once('=') else {
            continue;
        };
        match key.trim() {
            "width" => width = image_length(value),
            "height" => height = image_length(value),
            _ => {}
        }
    }
    (width, height)
}

/// An image as its own paragraph, the way a picture is one.
pub fn image_mark(width: &str, height: &str, path: &str) -> String {
    format!("\n\n{}\n\n", image_span(width, height, path))
}

/// What an image line says: its width spec, its height spec, and its file.
///
/// `None` for every line that is not one, which is nearly all of them.
pub fn image_parts(line: &str) -> Option<(String, String, String)> {
    let inner = line.trim();
    // Centring is a prefix on the line rather than part of the span, so that
    // everything reading one reads it the same way centred or not -- as for a
    // picture, and `\begin{center}` around a figure is how most documents put
    // an image on a page.
    let inner = inner.strip_prefix(CENTRE).unwrap_or(inner);
    let inner = inner.strip_prefix(IMAGE)?.strip_suffix(IMAGE)?;
    let (width, rest) = inner.split_once(';')?;
    let (height, path) = rest.split_once(';')?;
    Some((
        width.to_string(),
        height.to_string(),
        String::from_utf8(unbase64(path)?).ok()?,
    ))
}

/// The room an image line takes, in PDF points, with its spec resolved.
///
/// A length is `f0.8` for a fraction of the measure, a bare number for points,
/// or empty for "take it from the file". A file that cannot be read reserves
/// nothing and draws nothing: a missing figure must cost a document its
/// picture, never its remaining pages.
///
/// With one length given the other follows the file's own proportions, which
/// is what `\includegraphics[width=\textwidth]` means and what every book in
/// the corpus writes. `image` is what reading the file gave, if it read.
fn image_size(
    width: &str,
    height: &str,
    image: Option<&crate::image::Image>,
    layout: &Layout,
) -> Option<(f64, f64)> {
    let resolve = |spec: &str| -> Option<f64> {
        match spec.strip_prefix('f') {
            Some(fraction) => fraction.parse::<f64>().ok().map(|f| f * layout.measure),
            None => spec.parse().ok(),
        }
    };
    match (resolve(width), resolve(height)) {
        (Some(w), Some(h)) => Some((w, h)),
        (w, h) => {
            // A pixel is a big point unless the document says otherwise, which
            // is graphicx's rule for a file stating no resolution -- and
            // neither PNG's `pHYs` nor JPEG's density is read here.
            let image = image?;
            let (nw, nh) = (f64::from(image.width), f64::from(image.height));
            if nw <= 0.0 || nh <= 0.0 {
                return None;
            }
            match (w, h) {
                (Some(w), None) => Some((w, w * nh / nw)),
                (None, Some(h)) => Some((h * nw / nh, h)),
                // Neither stated: the file's own size, brought down to the
                // page if it does not fit. A diagram exported at 1600 pixels
                // is 1600 big points wide, three times the measure and taller
                // than the sheet, and would take a page to itself and overrun
                // it -- `inventions` came out at 333 pages against a 240
                // reference that way, having been 203 with the figures gone.
                //
                // This is what pandoc's `\pandocbounded` wrapper is FOR: its
                // own comment reads "scales image to fit in text
                // height/width", and every figure in the corpus is inside
                // one. Scaling DOWN only, never up, which is what that
                // wrapper does -- it compares against 1 and leaves a small
                // image alone.
                _ => {
                    let fit = (layout.measure / nw)
                        .min(layout.height / nh)
                        .clamp(f64::MIN_POSITIVE, 1.0);
                    Some((nw * fit, nh * fit))
                }
            }
        }
    }
}

/// A face's x-height as a fraction of its em, which is the unit
/// `Scale=MatchLowercase` compares.
fn relative_x_height(file: &std::path::Path) -> Option<f64> {
    let sfnt = crate::sfnt::Sfnt::parse(std::fs::read(file).ok()?).ok()?;
    let x = f64::from(sfnt.x_height()?);
    let em = f64::from(sfnt.head().ok()?.units_per_em.max(1));
    (x > 0.0).then_some(x / em)
}

/// What fontspec's `Scale=` asks a family to be set at.
///
/// A number is that number. `MatchLowercase` is the ratio of the MAIN face's
/// x-height to this one's, which is what a document writes so a display family
/// sits beside its text family without looming over it -- Orbitron's x-height
/// is large against Arimo's, so an unscaled `\Huge` heading comes out visibly
/// bigger than the document asked for.
///
/// 1.0 wherever the answer cannot be had: a `Scale=` naming something else, a
/// file that cannot be read, or a face whose `OS/2` predates `sxHeight`.
/// Scaling by a guess would be worse than not scaling.
fn face_scale(
    spec: Option<&str>,
    file: Option<&std::path::Path>,
    main: Option<&std::path::Path>,
) -> f64 {
    let Some(spec) = spec else { return 1.0 };
    if let Ok(factor) = spec.parse::<f64>() {
        return match factor > 0.0 {
            true => factor,
            false => 1.0,
        };
    }
    if !spec.eq_ignore_ascii_case("MatchLowercase") {
        return 1.0;
    }
    let (Some(file), Some(main)) = (file, main) else {
        return 1.0;
    };
    match (relative_x_height(main), relative_x_height(file)) {
        (Some(want), Some(have)) if have > 0.0 => want / have,
        _ => 1.0,
    }
}

/// The file an `\includegraphics` names, beside the document that named it.
///
/// A book writes `\includegraphics{figures/plot.png}` and is built from
/// another directory; the path is the document's, not the caller's. An
/// absolute path is taken as it stands.
fn image_file(path: &str, near: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
    let named = std::path::Path::new(path);
    let found = |candidate: std::path::PathBuf| candidate.is_file().then_some(candidate);
    let resolve = |candidate: &std::path::Path| -> Option<std::path::PathBuf> {
        if candidate.is_absolute() {
            return found(candidate.to_path_buf());
        }
        near.and_then(|dir| found(dir.join(candidate)))
            .or_else(|| found(candidate.to_path_buf()))
    };
    // The file the document named, if this engine can read it. A PDF, an EPS
    // or an SVG is a legal thing for `\includegraphics` to name and lualatex
    // reads all three; `image::read` reads PNG and JPEG, and nothing here can
    // rasterise the others.
    let readable = |candidate: &std::path::Path| {
        matches!(
            candidate
                .extension()
                .and_then(|e| e.to_str())
                .map(str::to_ascii_lowercase)
                .as_deref(),
            Some("png" | "jpg" | "jpeg")
        )
    };
    if readable(named) {
        if let Some(file) = resolve(named) {
            return Some(file);
        }
    }
    // Otherwise the same picture in a format that can be read, beside the one
    // that cannot. graphicx resolves an extensionless name against a
    // preference list of its own (`\DeclareGraphicsExtensions`), so trying the
    // siblings of a name is its convention rather than an invention here --
    // and a pipeline that emits a diagram as PDF generally emits the PNG
    // next to it. Dropping the figure instead would lose every one of them.
    for extension in ["png", "jpg", "jpeg"] {
        if let Some(file) = resolve(&named.with_extension(extension)) {
            return Some(file);
        }
    }
    resolve(named)
}

/// What one path an `\includegraphics` named came to.
struct ImageRead {
    /// Whether [`image_file`] found a file for it.
    found: bool,
    /// The picture that file holds, if it read. Shared by every line naming
    /// the path, so the writer finds two uses to be one XObject by address
    /// rather than by comparing their pixels.
    image: Option<std::sync::Arc<crate::image::Image>>,
}

/// Every path the image lines name, by the path as the line spells it.
type Images = std::collections::HashMap<String, ImageRead>;

/// Find and read every file the image lines name, each once.
///
/// A document that repeats its figures names the same file hundreds of times,
/// and finding and reading it per use -- once to measure, once more to draw --
/// held a copy of the pixels for every use until the file was written: four
/// hundred uses of ten photographs was gigabytes. A file's reading depends on
/// the file and nothing else, so with enough image lines to pay for it the
/// distinct files are read on the rayon pool; the table is the same whatever
/// the thread count.
fn images_read(lines: &[String], near: Option<&std::path::Path>) -> Images {
    let mut uses = 0usize;
    let mut seen = std::collections::HashSet::new();
    let mut paths: Vec<String> = Vec::new();
    for line in lines {
        // The marker's opening character first, as for counting blocks: most
        // lines are prose, and `image_parts` decodes the path it finds.
        let inner = line.trim_start();
        let inner = inner.strip_prefix(CENTRE).unwrap_or(inner);
        if !inner.starts_with(IMAGE) {
            continue;
        }
        let Some((_, _, path)) = image_parts(line) else {
            continue;
        };
        uses += 1;
        if seen.insert(path.clone()) {
            paths.push(path);
        }
    }
    let read = |path: &String| {
        let file = image_file(path, near);
        let image = file
            .as_ref()
            .and_then(|file| crate::image::open(file).ok())
            .map(std::sync::Arc::new);
        let found = file.is_some();
        (path.clone(), ImageRead { found, image })
    };
    match uses >= PARALLEL_BLOCKS && paths.len() > 1 {
        true => {
            use rayon::prelude::*;
            paths.par_iter().map(read).collect()
        }
        false => paths.iter().map(read).collect(),
    }
}

/// An image line with its lengths resolved to points against the layout and
/// the file, so the fitter and the drawing pass read one number rather than
/// each working it out. A file that cannot be read leaves the line empty: it
/// reserves nothing and draws nothing.
fn image_remeasured(line: String, layout: &Layout, images: &Images) -> String {
    let Some((width, height, path)) = image_parts(&line) else {
        return line;
    };
    let centred = is_centred(&line);
    let Some(read) = images.get(&path).filter(|read| read.found) else {
        return String::new();
    };
    let Some((w, h)) = image_size(&width, &height, read.image.as_deref(), layout) else {
        return String::new();
    };
    let span = image_span(&w.to_string(), &h.to_string(), &path);
    match centred {
        true => format!("{CENTRE}{span}"),
        false => span,
    }
}

/// The marker span for a picture, as its own paragraph.
///
/// The paragraph breaks are part of it: a picture is a block on the page and
/// not a word in a line, so it owns its own lines rather than running into the
/// prose either side of it -- exactly as a heading does (`lower::push_heading`).
///
/// The height is measured with [`crate::tikz::parse_document`] against no
/// font at all, because the lowerer has none to size node text by. `to_pdf`
/// measures it again through the document's own face and rewrites this
/// number before the page is fitted; the contents and `\pageref` passes,
/// which fit pages earlier, read it as written here.
pub fn picture_mark(options: &str, body: &str) -> String {
    picture_paragraph(&picture_spec(options, body))
}

/// A picture paragraph whose span holds `spec`: what [`picture_spec`] makes,
/// or the slot the lowerer writes while the picture is measured on the pool
/// (`math::Formulas::picture`), which comes to the same text once filled.
pub fn picture_paragraph(spec: &str) -> String {
    format!("\n\n{PICTURE}{spec}{PICTURE}\n\n")
}

/// What a picture span holds between its two [`PICTURE`]s: the height
/// measured against no font, and the source. See [`picture_mark`].
pub fn picture_spec(options: &str, body: &str) -> String {
    let picture = crate::tikz::parse_document(
        options,
        body,
        crate::colour::Colours::predefined(),
        &crate::tikz::Estimate,
    );
    let (_, height) = picture.extent();
    picture_contents(height, options, body)
}

/// One picture span: the height it reserves and the source it was read from.
fn picture_span(height: f64, options: &str, body: &str) -> String {
    format!(
        "{PICTURE}{}{PICTURE}",
        picture_contents(height, options, body)
    )
}

fn picture_contents(height: f64, options: &str, body: &str) -> String {
    format!(
        "{height};{}:{}",
        base64(options.as_bytes()),
        base64(body.as_bytes())
    )
}

/// What a picture line says: the height it reserves, its options and its body.
///
/// `None` for every line that is not one, which is all but a handful of them.
fn picture_parts(line: &str) -> Option<(f64, String, String)> {
    let inner = line.trim();
    // A centred picture carries the same prefix a centred line of text does,
    // and it is a prefix rather than part of the span so that everything which
    // reads one -- `line_height`, the page fitter, the drawing loop -- reads it
    // the same way whether the picture is centred or not.
    let inner = inner.strip_prefix(CENTRE).unwrap_or(inner);
    let inner = inner.strip_prefix(PICTURE)?.strip_suffix(PICTURE)?;
    let (height, source) = inner.split_once(';')?;
    let (options, body) = source.split_once(':')?;
    Some((
        height.parse().ok()?,
        String::from_utf8(unbase64(options)?).ok()?,
        String::from_utf8(unbase64(body)?).ok()?,
    ))
}

/// Whether a paragraph of the text stream is a picture and nothing else.
fn is_image_para(para: &str) -> bool {
    image_parts(para).is_some()
}

/// Whether a paragraph is a picture, or an image, which the breaker and the
/// fitter treat alike: one line, drawn rather than set.
fn is_block_para(para: &str) -> bool {
    is_picture_para(para) || is_image_para(para)
}

fn is_picture_para(para: &str) -> bool {
    picture_parts(para).is_some()
}

/// Whether a line -- of text or of picture -- is set by its own width.
fn is_centred(line: &str) -> bool {
    line.trim_start().starts_with(CENTRE)
}

/// The picture line with the height it really reserves, measured through the
/// document's own font.
///
/// The number `picture_mark` wrote was measured with no font at all, because
/// the lowerer has none: a node's text was charged half an em a character.
/// This is the same picture read again through the face the page is set in,
/// and it is what every fitting decision below then uses -- so the room a page
/// keeps for a picture is the room the picture is drawn in.
fn picture_remeasured(line: String, metrics: &dyn crate::tikz::Metrics) -> String {
    let Some((_, options, body)) = picture_parts(&line) else {
        return line;
    };
    let picture = crate::tikz::parse_document(
        &options,
        &body,
        crate::colour::Colours::predefined(),
        metrics,
    );
    let (_, height) = picture.extent();
    let span = picture_span(height, &options, &body);
    match is_centred(&line) {
        true => format!("{CENTRE}{span}"),
        false => span,
    }
}

/// The base64 alphabet, RFC 4648 §4.
const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// The alphabet inverted: a character's six bits, or 64 for one outside it.
///
/// A picture line is read back several times per page the fitter considers --
/// `line_height`, `paginate`, the breaker's block test -- and searching the
/// alphabet once per character made that decoding a quarter of a drawing-heavy
/// document's serial time.
const UNBASE64: [u8; 128] = {
    let mut table = [64u8; 128];
    let mut at = 0;
    while at < 64 {
        table[BASE64[at] as usize] = at as u8;
        at += 1;
    }
    table
};

/// `bytes` as base64: one word, with nothing in it a text pipeline splits on.
fn base64(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for group in bytes.chunks(3) {
        let packed = group
            .iter()
            .enumerate()
            .fold(0u32, |acc, (at, b)| acc | (*b as u32) << (16 - 8 * at));
        for at in 0..4 {
            out.push(match at <= group.len() {
                true => BASE64[(packed >> (18 - 6 * at)) as usize & 0x3f] as char,
                false => '=',
            });
        }
    }
    out
}

/// The bytes back, or `None` for anything that is not base64.
fn unbase64(text: &str) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(text.len() / 4 * 3);
    let mut packed = 0u32;
    let mut held = 0u32;
    for ch in text.chars() {
        if ch == '=' {
            break;
        }
        let six = match UNBASE64.get(ch as usize) {
            Some(&six) if six < 64 => u32::from(six),
            _ => return None,
        };
        packed = packed << 6 | six;
        held += 6;
        if held >= 8 {
            held -= 8;
            out.push((packed >> held) as u8);
        }
    }
    Some(out)
}

/// Every character the typesetting path reads as an INSTRUCTION rather than as
/// text, and whether one character of argument follows it.
///
/// A marker says where a line sits, what face it is in, what colour it takes --
/// none of which the document wrote. So none may ever reach a reader, and
/// `without_marks` in lib.rs is the one place that decides what a reader gets.
///
/// The list exists because forgetting that place is the mistake this port keeps
/// making. Three separate parallel implementations added a marker, taught
/// `to_pdf` and the line breaker about it, and left `without_marks` alone: one
/// of them put 122 raw control characters into a book's `--text` output, and
/// the file's own comment already recorded the same fault as fixed once before.
/// `every_marker_is_stripped_from_the_text_a_reader_gets` walks this list, so a
/// constant added without an entry here fails a test rather than shipping.
pub const MARKERS: &[(char, bool)] = &[
    // The colour trio: a spec opens, runs to its close, and a pop ends the run.
    ('\u{1}', false),
    ('\u{2}', false),
    ('\u{3}', false),
    (LISTING_BREAK, false),
    (PAGE_BREAK, false),
    (CENTRE, false),
    (CENTRE_END, false),
    (VERTICAL_SPACE, false),
    (JUSTIFY, false),
    // The one that carries an argument: the character naming the face.
    (FACE_PUSH, true),
    (FACE_POP, false),
    // The size pair. `SIZE_PUSH` brackets its own spec -- it appears twice,
    // once at each end -- so it swallows no single character the way a face
    // code does; the walk toggles on it instead, as it does for `PICTURE`.
    (SIZE_PUSH, false),
    (SIZE_POP, false),
    // The breaker's parameters for a paragraph, a spec spanned the same way.
    (BREAK_PARAMS, false),
    // The image span, bracketed by its own marker the way a picture is.
    (IMAGE, false),
    (TABLE_CELL, false),
    (TABLE_ROW, false),
    // The list indent carries an argument too: the digit saying how deep the
    // list holding this line is nested.
    (LIST_INDENT, true),
    // The other one that carries an argument: the character saying which rule,
    // or which of longtable's section boundaries, this mark is.
    (TABLE_MARK, true),
    // And the one saying which part of a longtable a line is, whose argument
    // is the code naming that part.
    (LONGTABLE, true),
    // The contents marker, whose argument says which of the three things it
    // is: a request, a heading it lists, or where page 1 begins.
    (TOC, true),
    // The cross-reference marker. Its argument says which of the three it is
    // -- a label, a `\ref` or a `\pageref` -- and the label key follows, up to
    // a second marker that closes the span.
    (REF, true),
    // The picture marker, span-shaped like the cross-reference one: everything
    // from it to the second one is the encoded picture, and a reader asking for
    // the document's TEXT gets none of it -- a picture has no words.
    (PICTURE, true),
];

/// The end of a line INSIDE a code listing, carried through the text the way a
/// page break is.
///
/// Pandoc wraps every code block in `Highlighting`, and that body is real TeX --
/// `\NormalTok{…}` and its siblings have to expand -- so it cannot be read as
/// verbatim and its newlines reached the breaker as ordinary spaces.
/// `split_whitespace` then reflowed the program into the prose around it.
/// Measured: rubyrs/docs/book.tex set a nine-line `dup_value` as three, one of
/// them `... => v.clone(), Some(obj) => { let copy = obj.clone();
/// self.alloc(copy) } None =>`, and the book came out in 208 pages where
/// lualatex sets it in 332. A vertical tab is a line separator by definition,
/// it survives the run because it is not a word, and like the page break it is
/// split out BEFORE words are.
pub const LISTING_BREAK: char = '\u{b}';

/// The lines of a code listing, or `None` when the paragraph is prose.
///
/// A listing arrives as `LISTING_BREAK`-TERMINATED lines, so an empty segment
/// is an empty code line and is kept: a blank line in a program is part of the
/// program, and a paragraph break -- which is what the lexer would have made of
/// it -- is not. Prose holds no break and is broken to the measure as before.
///
/// Both breakers ask this, so a listing is recognised the same way on the DVI
/// and PDF paths rather than in two places that could drift apart.
fn listing_lines(para: &str) -> Option<impl Iterator<Item = &str>> {
    para.contains(LISTING_BREAK)
        .then(|| para.split_terminator(LISTING_BREAK))
}

/// A cell boundary inside a table row: the `&` the document wrote, where a
/// table is being SET rather than flattened.
///
/// ASCII's own unit separator, which is what a field boundary means.
pub const TABLE_CELL: char = '\u{1f}';

/// The end of a table row: the `\\` the document wrote inside a table. ASCII's
/// record separator, for the same reason.
///
/// A paragraph holding one of these is a table, the way a paragraph holding a
/// `LISTING_BREAK` is a listing -- so the region needs no marker of its own.
pub const TABLE_ROW: char = '\u{1e}';

/// A table mark that is not text: one of booktabs' three rules, or the end of
/// one of longtable's sections. The character AFTER it says which.
pub const TABLE_MARK: char = '\u{1d}';

/// The part of a table a line belongs to: the character AFTER it is one of the
/// `LT_` codes below.
///
/// A longtable repeats its head at the top of every page it runs onto and sets
/// its foot at the bottom of every page it runs past. The only thing that
/// knows where a page ends is `paginate`, and all it sees is lines -- so the
/// line has to say what part of which table it is. That is what this carries.
///
/// It also says where a row STARTS, because a row is not a line: a cell that
/// wrapped makes a row several lines tall, and a page break inside those lines
/// tears the row in half.
///
/// U+0016 is the next free control character after U+0015; the `MARKERS`
/// registry above says what the rest are spent on.
pub const LONGTABLE: char = '\u{16}';

/// The codes `LONGTABLE` carries.
///
/// `LT_HEAD` is a head that is set where it stands AND repeated above every
/// continuation page. `LT_REPEAT` is the repeating head of a table that gave a
/// DIFFERENT first head, so it is set only above the pages after the first.
/// `LT_FOOT` is never set where it stands: it belongs at the bottom of a page
/// the table runs past, and `paginate` puts it there. `LT_ROW` opens a line
/// that is set where it stands, and `LT_CONT` continues it -- the two together
/// are what says a row and the lines its cells wrapped onto are one thing.
const LT_HEAD: char = 'h';
const LT_REPEAT: char = 'H';
const LT_FOOT: char = 'f';
const LT_ROW: char = 'r';
const LT_CONT: char = 'c';

/// Which part of a table this line is, or `None` when it is not a table line.
fn longtable_code(line: &str) -> Option<char> {
    line.strip_prefix(LONGTABLE)?.chars().next()
}

/// The line without the part it says it is: what the page draws.
fn without_longtable(line: &str) -> &str {
    let Some(rest) = line.strip_prefix(LONGTABLE) else {
        return line;
    };
    let mut chars = rest.chars();
    chars.next();
    chars.as_str()
}

/// The codes `TABLE_MARK` carries. The three rules, then the boundaries that
/// say where longtable's head and foot end.
///
/// Public because `lower.rs` writes them and this reads them, and one spelling
/// in one place is what keeps the two agreeing.
pub const RULE_TOP: char = 't';
pub const RULE_MID: char = 'm';
pub const RULE_BOTTOM: char = 'b';
pub const HEAD_END: char = 'h';
pub const FIRST_HEAD_END: char = 'H';
pub const FOOT_END: char = 'f';
/// `\endlastfoot`, which is not `\endfoot`: one is set at the bottom of every
/// page the table runs past and the other once, under the end of the table.
/// They shared `FOOT_END` and a table writing both put its last foot into its
/// body.
pub const LAST_FOOT_END: char = 'F';

/// One entry of a table: a rule across it, or a row of cells.
///
/// Cloneable because a section can be set twice: a table that gave no
/// `\endlastfoot` sets its repeating foot under the end of the table as well
/// as at the bottom of every page before it.
#[derive(Clone)]
enum Entry {
    Rule(char),
    Row(Vec<String>),
}

/// A longtable's sections: what each of its four boundaries closes, and the
/// body that follows the last of them.
///
/// longtable states its head and its foot BEFORE its body -- `\endhead` closes
/// the head, `\endlastfoot` the foot -- so nothing can be set in the order a
/// reader gets it until the sections are told apart. Keeping them apart is
/// also what lets the head be set AGAIN at the top of the next page, which is
/// the whole of what a longtable is for.
#[derive(Default)]
struct Sections {
    /// What `\endfirsthead` closes: set at the top of the FIRST page only.
    first_head: Vec<Entry>,
    /// What `\endhead` closes: set again at the top of every page the table
    /// runs onto.
    head: Vec<Entry>,
    /// What `\endfoot` closes: set at the bottom of every page the table runs
    /// PAST, and so on no page at all when it fits on one.
    foot: Vec<Entry>,
    /// What `\endlastfoot` closes: set once, under the end of the table.
    last_foot: Vec<Entry>,
    /// Everything after the last boundary: the rows. A `tabular` names no
    /// boundary and is all body, which leaves its entries in the order it
    /// wrote them.
    body: Vec<Entry>,
}

impl Sections {
    /// The head the FIRST page gets: the first head where one is given, and
    /// the repeating head otherwise -- longtable.sty defaults `\endfirsthead`
    /// to `\endhead`.
    fn opening_head(&self) -> &[Entry] {
        match self.first_head.is_empty() {
            true => &self.head,
            false => &self.first_head,
        }
    }

    /// The foot under the END of the table: the last foot where one is given,
    /// and the repeating foot otherwise -- `\endlastfoot` defaults to
    /// `\endfoot` the same way.
    fn closing_foot(&self) -> &[Entry] {
        match self.last_foot.is_empty() {
            true => &self.foot,
            false => &self.last_foot,
        }
    }
}

/// Split a table paragraph into its sections, each holding its rules and rows
/// in the order they were written.
///
/// A boundary closes the material written since the last one: whatever stands
/// before `\endhead` IS the head. Reading it that way, rather than switching a
/// destination on each boundary, is what tells `\endfoot` from `\endlastfoot`;
/// before this the two shared one code and a table writing both put its last
/// foot into its body.
///
/// A row whose cells are all blank is dropped: the newline between the last
/// `\\` and `\end{longtable}` is one, and a blank line in the middle of a
/// table is not something the document asked for.
fn table_sections(para: &str) -> Sections {
    let mut sections = Sections::default();
    // The entries written since the last boundary. Which section they belong
    // to is decided by the boundary that closes them, which has not been read
    // yet -- so they wait here until one is.
    let mut pending: Vec<Entry> = Vec::new();
    let mut row: Vec<String> = Vec::new();
    let mut cell = String::new();
    // A cell is measured and wrapped as one line, so the line ends the source
    // wrote inside it are spaces like any other.
    let finish = |cell: &mut String| -> String {
        let taken = std::mem::take(cell);
        taken.split_whitespace().collect::<Vec<&str>>().join(" ")
    };
    let mut chars = para.chars();
    while let Some(ch) = chars.next() {
        match ch {
            TABLE_MARK => {
                let code = chars.next().unwrap_or(RULE_MID);
                let section = match code {
                    FIRST_HEAD_END => &mut sections.first_head,
                    HEAD_END => &mut sections.head,
                    FOOT_END => &mut sections.foot,
                    LAST_FOOT_END => &mut sections.last_foot,
                    rule => {
                        pending.push(Entry::Rule(rule));
                        continue;
                    }
                };
                // A boundary written twice keeps what the first one closed:
                // taking `pending` again would empty the section rather than
                // add to it.
                if section.is_empty() {
                    *section = std::mem::take(&mut pending);
                }
            }
            TABLE_CELL => row.push(finish(&mut cell)),
            TABLE_ROW => {
                row.push(finish(&mut cell));
                if row.iter().any(|c| !c.is_empty()) {
                    pending.push(Entry::Row(std::mem::take(&mut row)));
                }
                row.clear();
            }
            c => cell.push(c),
        }
    }
    sections.body = pending;
    sections
}

/// The entries of a table in the order they are SET, for a path with no page
/// to repeat anything on.
///
/// That is not the order longtable WRITES them: the bottom rule is written
/// before the first row of data, and setting the stream in arrival order would
/// draw it under the head. Every markdown table pandoc emits has this shape.
fn table_entries(para: &str) -> Vec<Entry> {
    let sections = table_sections(para);
    sections
        .opening_head()
        .iter()
        .chain(&sections.body)
        .chain(sections.closing_foot())
        .cloned()
        .collect()
}

/// Set a table: each row on its own line, each column as wide as its content,
/// and each booktabs rule as a line the page draws a rule for.
///
/// Before this a table was one paragraph of prose -- "Name Value alpha 1 beta 2",
/// running into the sentence after it -- because `&` was lowered to a space and
/// `\\` to a newline. The corpus leans on tables heavily: pandoc emits a
/// longtable for every markdown table, 132 of them in groovyrs/docs/book.tex.
///
/// The ambient colour and face stacks are READ and not advanced. Every line
/// this produces balances its own markers (see `wrap_cell`), so the stacks
/// `to_pdf` walks down the page are exactly where the table found them.
fn table_lines(
    para: &str,
    layout: &Layout,
    colours: &[Spec],
    faces: &[Face],
    sizes: &[TypeSize],
    width_of: &dyn Fn(&str, Face, f64) -> f64,
    out: &mut Vec<String>,
) {
    let sections = table_sections(para);
    // Every section is measured against every other: the head repeated at the
    // top of page four stands over the rows set under it, so how wide its
    // cells are is part of how wide the columns are.
    let entries: Vec<&Entry> = sections
        .first_head
        .iter()
        .chain(&sections.head)
        .chain(&sections.foot)
        .chain(&sections.last_foot)
        .chain(&sections.body)
        .collect();
    let cols = entries
        .iter()
        .filter_map(|e| match e {
            Entry::Row(cells) => Some(cells.len()),
            Entry::Rule(_) => None,
        })
        .max()
        .unwrap_or(0);
    if cols == 0 {
        return;
    }
    // Padding is written in spaces, so the space is the unit every width here
    // is counted in. booktabs leaves a `\tabcolsep` either side of a column;
    // two spaces is that gap in this unit.
    let space = width_of(" ", current_face(faces), current_size(sizes).size).max(f64::MIN_POSITIVE);
    let gutter = 2.0 * space;
    // What a cell costs, in the faces its own markers select, measured on
    // copies of the stacks so measuring never moves them.
    let measure = |text: &str| -> f64 {
        let (mut c, mut f, mut s) = (colours.to_vec(), faces.to_vec(), sizes.to_vec());
        styled_runs(text, &mut c, &mut f, &mut s)
            .iter()
            .map(|(plain, _, face, ts)| width_of(plain, *face, ts.size))
            .sum()
    };

    // Each column asks for what its widest cell needs.
    let mut natural = vec![0.0f64; cols];
    for entry in &entries {
        if let Entry::Row(cells) = *entry {
            for (j, cell) in cells.iter().enumerate() {
                natural[j] = natural[j].max(measure(cell));
            }
        }
    }
    // If they do not all fit, the columns that are under their fair share keep
    // what they asked for and the ones over it share what is left, in
    // proportion to what they asked for. That is what makes a table of one
    // long prose column and two short ones readable rather than three equal
    // columns of wrapped fragments.
    let room = (layout.measure - gutter * (cols - 1) as f64).max(space);
    let asked: f64 = natural.iter().sum();
    let fair = room / cols as f64;
    let over: f64 = natural.iter().filter(|w| **w > fair).sum();
    let under: f64 = natural.iter().filter(|w| **w <= fair).sum();
    let widths: Vec<f64> = match asked <= room || over <= 0.0 {
        true => natural.clone(),
        false => natural
            .iter()
            .map(|w| match *w > fair {
                // Never below four spaces: a column narrower than a short word
                // wraps every cell to one letter a line.
                true => ((room - under) * w / over).max(4.0 * space),
                false => *w,
            })
            .collect(),
    };
    // Where each column starts, and how far the rules run.
    let mut starts = vec![0.0f64; cols];
    for j in 1..cols {
        starts[j] = starts[j - 1] + widths[j - 1] + gutter;
    }
    let span = starts[cols - 1] + widths[cols - 1];

    // One entry, set: a rule is the line the page draws a rule from, a row is
    // its cells wrapped to their columns -- which is one line, or several when
    // a cell wrapped.
    let set = |entry: &Entry| -> Vec<String> {
        let cells = match entry {
            Entry::Rule(kind) => return vec![rule_line(*kind, span, space)],
            Entry::Row(cells) => cells,
        };
        let wrapped: Vec<Vec<String>> = cells
            .iter()
            .enumerate()
            .map(|(j, cell)| wrap_cell(cell, widths[j], colours, faces, sizes, width_of))
            .collect();
        let height = wrapped.iter().map(Vec::len).max().unwrap_or(0);
        let mut lines = Vec::with_capacity(height);
        for k in 0..height {
            let mut line = String::new();
            let mut at = 0.0f64;
            for (j, fragments) in wrapped.iter().enumerate() {
                let Some(fragment) = fragments.get(k).filter(|f| !f.is_empty()) else {
                    continue;
                };
                // Pad to the column, in the unit the padding is written in.
                // The nearest whole space rather than the last one that fits,
                // so a column stands within HALF a space of where it was
                // measured to be and not within a whole one; and never fewer
                // than one space, so two cells cannot touch even where the
                // first overran the width it was given.
                let want = ((starts[j] - at) / space).round() as i64;
                for _ in 0..want.max(i64::from(j > 0)) {
                    line.push(' ');
                    at += space;
                }
                line.push_str(fragment);
                at += measure(fragment);
            }
            lines.push(line);
        }
        lines
    };

    // A section, with every line saying which part of the table it is. That is
    // what `paginate` reads to repeat the head and to hold the foot back.
    //
    // `rows` says whether the section's entries are separate things: a body
    // row is one, so the lines a cell wrapped onto are marked as continuing it
    // and no page break can fall between them. A head or a foot is set whole
    // or not at all, so every one of its lines carries the section's own code
    // and the whole block is one thing.
    let mut emit = |entries: &[Entry], code: char, rows: bool| {
        for entry in entries {
            for (n, line) in set(entry).into_iter().enumerate() {
                let mut marked = String::from(LONGTABLE);
                marked.push(match rows && n > 0 {
                    true => LT_CONT,
                    false => code,
                });
                marked.push_str(&line);
                out.push(marked);
            }
        }
    };
    // The repeating head of a table that gave a different first head, and the
    // repeating foot: neither is set where it stands. They are written into
    // the stream all the same, because the lines `paginate` repeats have to be
    // lines it can point at.
    if !sections.first_head.is_empty() {
        emit(&sections.head, LT_REPEAT, false);
    }
    emit(&sections.foot, LT_FOOT, false);
    // The head of the first page, which is also the head that repeats unless a
    // first head was given -- and says which of the two it is.
    let opening = match sections.first_head.is_empty() {
        true => LT_HEAD,
        false => LT_ROW,
    };
    emit(sections.opening_head(), opening, opening == LT_ROW);
    emit(&sections.body, LT_ROW, true);
    // And the foot under the end of the table. A table that gave no
    // `\endlastfoot` sets its repeating foot here as well, which is what
    // longtable does with it.
    emit(sections.closing_foot(), LT_ROW, true);
}

/// The line a rule is set from: the mark, the code saying which rule, and the
/// spaces that MEASURE how far it runs.
///
/// The span has to reach `to_pdf` somehow, and a line is all that survives
/// pagination. Spaces carry it because the page already measures text and so
/// needs nothing new to read this. They are added by the breaker and never
/// reach `--text`, which sees the mark and its code in the text stream and
/// strips both.
fn rule_line(kind: char, span: f64, space: f64) -> String {
    let mut line = String::from(TABLE_MARK);
    line.push(kind);
    let mut at = 0.0;
    while at + space <= span {
        line.push(' ');
        at += space;
    }
    line
}

/// Break one cell into fragments no wider than its column, each of which
/// balances its own markers.
///
/// This is the defect a previous attempt at tables shipped. A row taller than
/// one line is set by putting the nth fragment of every column on the nth
/// line, while `to_pdf` walks ONE colour stack and ONE face stack down the
/// page. A fragment that opened `\texttt` and left it open therefore handed
/// that face to the cell BESIDE it, because the next thing drawn is the next
/// column's fragment and not the rest of this cell. So a fragment closes what
/// it opened, and the next one writes those markers again at its head; the
/// markers are not measured, so re-opening them costs the column nothing.
fn wrap_cell(
    cell: &str,
    width: f64,
    colours: &[Spec],
    faces: &[Face],
    sizes: &[TypeSize],
    width_of: &dyn Fn(&str, Face, f64) -> f64,
) -> Vec<String> {
    let (mut c, mut f, mut s) = (colours.to_vec(), faces.to_vec(), sizes.to_vec());
    let space = width_of(" ", current_face(&f), current_size(&s).size);
    // What this cell has opened and not closed, as the text that opens it and
    // the character that closes it.
    let mut open: Vec<(String, char)> = Vec::new();
    let mut fragments = Vec::new();
    let mut line = String::new();
    let mut at = 0.0f64;
    for word in cell.split(' ').filter(|w| !w.is_empty()) {
        // Measuring advances the stacks, which is what keeps the word after a
        // `\texttt` measured in the face that `\texttt` left in force.
        let cost: f64 = styled_runs(word, &mut c, &mut f, &mut s)
            .iter()
            .map(|(plain, _, face, ts)| width_of(plain, *face, ts.size))
            .sum();
        let need = match line.is_empty() {
            true => cost,
            false => at + space + cost,
        };
        if !line.is_empty() && need > width {
            for (_, close) in open.iter().rev() {
                line.push(*close);
            }
            fragments.push(std::mem::take(&mut line));
            for (opener, _) in &open {
                line.push_str(opener);
            }
            at = cost;
        } else {
            if !line.is_empty() {
                line.push(' ');
            }
            at = need;
        }
        line.push_str(word);
        absorb(word, &mut open);
    }
    if !line.is_empty() {
        for (_, close) in open.iter().rev() {
            line.push(*close);
        }
        fragments.push(line);
    }
    fragments
}

/// Record which markers a word leaves OPEN, as the text that opens each and the
/// character that closes it.
///
/// Colour and face are separate stacks -- they nest inside each other, and a
/// `\texttt` closing does not close the `\color` under it -- so a close pops
/// the topmost entry of its OWN kind rather than whatever is on top.
fn absorb(word: &str, open: &mut Vec<(String, char)>) {
    fn close(open: &mut Vec<(String, char)>, kind: char) {
        if let Some(at) = open.iter().rposition(|(_, c)| *c == kind) {
            open.remove(at);
        }
    }
    let mut chars = word.chars();
    while let Some(ch) = chars.next() {
        match ch {
            '\u{1}' => {
                let mut spec = String::from('\u{1}');
                for c in chars.by_ref() {
                    spec.push(c);
                    if c == '\u{2}' {
                        break;
                    }
                }
                open.push((spec, '\u{3}'));
            }
            '\u{3}' => close(open, '\u{3}'),
            FACE_PUSH => {
                let code = chars.next().unwrap_or_else(|| Face::MAIN.code());
                open.push((format!("{FACE_PUSH}{code}"), FACE_POP));
            }
            FACE_POP => close(open, FACE_POP),
            _ => {}
        }
    }
}

/// The start of a centred region, and, on a broken line, that the line is
/// centred.
///
/// `\begin{center}` and `\centering` were defined by the prelude to expand to
/// nothing, so "centred line" and "left line" came out as one flowing line and
/// a title page -- which is built entirely out of centred pieces -- collapsed
/// into the prose after it. Centring is carried the way a forced break is,
/// in the text itself: a region marker the breaker consumes, and then one
/// character at the head of each line it produced, which is what survives
/// pagination without a second structure beside the lines saying which of them
/// were centred.
pub const CENTRE: char = '\u{e}';

/// The end of a centred region, back to the margin.
pub const CENTRE_END: char = '\u{f}';

/// That a broken line is FULL, and so is set to the measure rather than at the
/// width its glyphs come to.
///
/// Justification is a property of the line and not of the text, so it cannot be
/// worked out again where the page is drawn: by then the paragraphs have been
/// flattened into one list of lines and nothing says which of them the author
/// ended and which the breaker did. The breaker knows -- it pushed the line
/// because the next word did not fit -- and says so at the head of the line,
/// the way a centred line is marked, which is what survives pagination without
/// a second structure beside the lines.
///
/// A device control character rather than a letter, for the same reason the
/// others are: it is not a character any document writes.
pub const JUSTIFY: char = '\u{13}';

/// A line's worth of vertical space with nothing drawn on it.
///
/// `\chapter` and `\section` set their heading hard against the paragraph
/// after it, so a heading was indistinguishable from the text it introduces
/// and the page held lines that lualatex spends on white space. A vertical tab
/// is what the character means; like the form feed it is split out of the text
/// before words are, because Rust counts it as whitespace too.
pub const VERTICAL_SPACE: char = '\u{10}';

/// The r, g and b a marker carried, kept verbatim as written rather than
/// parsed, because they are handed straight back to PDF's `rg` operator.
type Spec = (String, String, String);

/// A stretch of a line, the colour it is drawn in and the face it is set in.
///
/// Always a colour, never "none": the stack it comes off is seeded with the
/// document's default, so every run says what it is drawn in. The face is the
/// same -- the bottom of its stack is the main face.
type StyledRun = (String, Spec, Face, TypeSize);

/// The colour every LaTeX document starts in, as PDF wants it written.
///
/// A document that wants another says `\color`, which arrives here as a marker
/// and pushes on top of this one.
const DEFAULT_COLOUR: (&str, &str, &str) = ("0", "0", "0");

/// The markers the runtime writes turn colour on and off part way along a line,
/// so a line is not one string in one colour: `let x` may be black and `= 1`
/// blue. Each run is emitted with its own colour and its own position, which is
/// why the caller advances x by the width of what it just drew.
///
/// Colour is a STACK, not one current colour, because the markers nest:
/// `\color{textPrim}` at the top of a book is still in force inside the
/// `\texttt` that pushes neonCyan for one word and pops again. Popping to "no
/// colour" -- what this did -- meant that after the first closing marker
/// everything was drawn in black, on a page `\pagecolor` had painted #05050A:
/// 573,723 of the 715,546 drawn characters of `rubyrs/docs/book.tex`, a whole
/// book black on black. The DVI path has had this right all along, as `color
/// push rgb` / `color pop` at typeset.rs:117-137; this is the same thing.
///
/// The stack belongs to the CALLER and carries from line to line, because a
/// `\color` set once above the whole document is in force on every line under
/// it, not just the one the marker landed on. Its bottom entry is the
/// document's default and is never popped, so an unbalanced closing marker
/// leaves that in force rather than nothing at all.
///
/// The face markers are read in the SAME pass and split the line the same way,
/// because the two nest inside each other: a book's `\texttt` is a mono face
/// wrapped around a `\color`, and two passes would have to agree about where
/// the other one's markers were.
fn styled_runs(
    line: &str,
    stack: &mut Vec<Spec>,
    faces: &mut Vec<Face>,
    sizes: &mut Vec<TypeSize>,
) -> Vec<StyledRun> {
    let mut drawn = Drawn {
        stacks: Live {
            colours: stack,
            faces,
            sizes,
        },
        runs: Vec::new(),
        text: String::new(),
    };
    walk_styles(line, &mut drawn);
    drawn.flush();
    drawn.runs
}

/// What the style markers of a line DO, one call per marker, to whatever is
/// keeping the stacks: the live stacks a page is drawn from (`Live`, and
/// `Drawn` around it, which also cuts the line into runs), or the record of a
/// stretch's effect on stacks not yet known (`StyleEffect`).
///
/// One reader of the markers for all of them, so the parallel prescans cannot
/// read a marker differently from the page that draws it.
trait StyleStacks {
    /// A character that prints.
    fn text(&mut self, _ch: char) {}
    /// A formula's setting, which is a run of its own.
    fn math(&mut self, _spec: &str) {}
    /// A colour opens; `None` is a spec that is not three components, which
    /// pushes the colour already in force.
    fn push_colour(&mut self, spec: Option<Spec>);
    fn pop_colour(&mut self);
    /// A face opens, as a code applied to the face in force.
    fn push_face(&mut self, code: char);
    fn pop_face(&mut self);
    /// A size opens; `None` is a spec that cannot be read, which pushes the
    /// size already in force.
    fn push_size(&mut self, size: Option<TypeSize>);
    fn pop_size(&mut self);
}

/// Read one line's style markers into `stacks`.
fn walk_styles(line: &str, stacks: &mut impl StyleStacks) {
    let mut chars = line.chars();
    while let Some(ch) = chars.next() {
        match ch {
            FACE_PUSH => {
                // The code character belongs to the marker whatever it is: a
                // marker read as one character would set the other as a glyph.
                let code = chars.next().unwrap_or_else(|| Face::MAIN.code());
                stacks.push_face(code);
            }
            FACE_POP => stacks.pop_face(),
            SIZE_PUSH => {
                // The spec runs to the marker that closes it, which is the
                // same character: read to it whatever is between, so a
                // damaged spec costs its own heading and not the rest of the
                // document.
                let mut spec = String::new();
                for c in chars.by_ref() {
                    if c == SIZE_PUSH {
                        break;
                    }
                    spec.push(c);
                }
                // A spec that cannot be read still pushes, because the
                // `SIZE_POP` that closes it is coming either way and has to
                // pop what this pushed rather than the entry underneath.
                stacks
                    .push_size(size_spec(&spec).map(|(size, leading)| TypeSize { size, leading }));
            }
            SIZE_POP => stacks.pop_size(),
            '\u{1}' => {
                let mut spec = String::new();
                for c in chars.by_ref() {
                    if c == '\u{2}' {
                        break;
                    }
                    spec.push(c);
                }
                // A formula's marker has the same shape and carries its
                // SETTING rather than a colour: where every glyph of it goes,
                // decided by `mlist_to_hlist`. The text between the marker and
                // its close is the formula spelled out for a reader, which the
                // page does not draw -- it draws the setting -- so it is
                // skipped here along with the `\u{3}` that ends it.
                if crate::math::is_setting(&spec) {
                    for c in chars.by_ref() {
                        if c == '\u{3}' {
                            break;
                        }
                    }
                    stacks.math(&spec);
                    continue;
                }
                let p: Vec<&str> = spec.split(',').collect();
                // A spec that is not three components still pushes -- the
                // colour it inherits -- because the `\u{3}` that closes it is
                // coming either way and has to pop what this pushed, not the
                // entry underneath.
                stacks.push_colour(match p.len() == 3 {
                    true => Some((p[0].to_string(), p[1].to_string(), p[2].to_string())),
                    false => None,
                });
            }
            '\u{3}' => stacks.pop_colour(),
            c => stacks.text(c),
        }
    }
}

/// The colour in force, which is the document's default when nothing has
/// pushed.
fn current_colour(colours: &[Spec]) -> Spec {
    colours.last().cloned().unwrap_or_else(|| {
        (
            DEFAULT_COLOUR.0.to_string(),
            DEFAULT_COLOUR.1.to_string(),
            DEFAULT_COLOUR.2.to_string(),
        )
    })
}

/// The stacks themselves, moved by the markers.
struct Live<'a> {
    colours: &'a mut Vec<Spec>,
    faces: &'a mut Vec<Face>,
    sizes: &'a mut Vec<TypeSize>,
}

impl StyleStacks for Live<'_> {
    fn push_colour(&mut self, spec: Option<Spec>) {
        let pushed = spec.unwrap_or_else(|| current_colour(self.colours));
        self.colours.push(pushed);
    }
    fn pop_colour(&mut self) {
        // The bottom entry is the document's default and is never popped.
        if self.colours.len() > 1 {
            self.colours.pop();
        }
    }
    fn push_face(&mut self, code: char) {
        // Applied to the face already in force, so `\textbf` inside a
        // `\sffamily` group reaches the page as the sans BOLD face rather
        // than replacing the family.
        self.faces
            .push(Face::from_code(code, current_face(self.faces)));
    }
    fn pop_face(&mut self) {
        // The bottom entry is the main face and is never popped, so an
        // unbalanced close leaves the document in its own face.
        if self.faces.len() > 1 {
            self.faces.pop();
        }
    }
    fn push_size(&mut self, size: Option<TypeSize>) {
        let pushed = size.unwrap_or_else(|| current_size(self.sizes));
        self.sizes.push(pushed);
    }
    fn pop_size(&mut self) {
        // The bottom entry is the document's own size and is never popped:
        // an unbalanced close leaves the body size in force rather than
        // nothing at all.
        if self.sizes.len() > 1 {
            self.sizes.pop();
        }
    }
}

/// The live stacks, and the line cut into runs at every marker: each run is
/// the text between two markers in the style in force over it.
struct Drawn<'a> {
    stacks: Live<'a>,
    runs: Vec<StyledRun>,
    text: String,
}

impl Drawn<'_> {
    /// End the run in hand, in the style it was set in.
    fn flush(&mut self) {
        if !self.text.is_empty() {
            let text = std::mem::take(&mut self.text);
            let run = self.styled(text);
            self.runs.push(run);
        }
    }
    fn styled(&self, text: String) -> StyledRun {
        (
            text,
            current_colour(self.stacks.colours),
            current_face(self.stacks.faces),
            current_size(self.stacks.sizes),
        )
    }
}

impl StyleStacks for Drawn<'_> {
    fn text(&mut self, ch: char) {
        self.text.push(ch);
    }
    fn math(&mut self, spec: &str) {
        self.flush();
        let run = self.styled(crate::math::run(spec));
        self.runs.push(run);
    }
    fn push_colour(&mut self, spec: Option<Spec>) {
        self.flush();
        self.stacks.push_colour(spec);
    }
    fn pop_colour(&mut self) {
        self.flush();
        self.stacks.pop_colour();
    }
    fn push_face(&mut self, code: char) {
        self.flush();
        self.stacks.push_face(code);
    }
    fn pop_face(&mut self) {
        self.flush();
        self.stacks.pop_face();
    }
    fn push_size(&mut self, size: Option<TypeSize>) {
        self.flush();
        self.stacks.push_size(size);
    }
    fn pop_size(&mut self) {
        self.flush();
        self.stacks.pop_size();
    }
}

/// What a stretch of markers does to one stack, read without knowing what is
/// on it.
///
/// Every stack here has a floor -- its bottom entry is never popped -- and a
/// pop of an entry the stretch pushed itself always succeeds, since the floor
/// is under it. So any sequence of pushes and pops comes to `pops` pops of
/// entries that were there before (stopping at the floor) followed by
/// `pushes`. A push that copies or modifies the entry in force can only meet,
/// when the stretch's own pushes are all gone, the entry that the final
/// `pops` leave on top: each entry says how it is made from that one.
struct StackEffect<E> {
    pops: usize,
    pushes: Vec<E>,
    /// Whether any marker moved this stack at all, which is what an EMPTY
    /// stack -- one without a floor -- cannot be answered without.
    moved: bool,
}

impl<E> Default for StackEffect<E> {
    fn default() -> Self {
        StackEffect {
            pops: 0,
            pushes: Vec::new(),
            moved: false,
        }
    }
}

impl<E> StackEffect<E> {
    fn push(&mut self, entry: E) {
        self.moved = true;
        self.pushes.push(entry);
    }

    fn pop(&mut self) {
        self.moved = true;
        if self.pushes.pop().is_none() {
            self.pops += 1;
        }
    }

    /// Apply this to a stack with a floor, making each pushed entry from the
    /// entry the pops leave on top.
    fn apply<T>(&self, stack: &mut Vec<T>, make: impl Fn(&E, &T) -> T) {
        if !self.moved {
            return;
        }
        stack.truncate(stack.len().saturating_sub(self.pops).max(1));
        let Some(below) = stack.last() else { return };
        let pushed: Vec<T> = self.pushes.iter().map(|entry| make(entry, below)).collect();
        stack.extend(pushed);
    }

    /// Whether `apply` can answer for `stack`: it can for any stack with its
    /// floor in place, and for any stack this does not move.
    fn applies_to<T>(&self, stack: &[T]) -> bool {
        !self.moved || !stack.is_empty()
    }
}

/// A pushed colour or size: one the marker named, or a copy of the one in
/// force where it was pushed.
#[derive(Clone)]
enum Pushed<T> {
    Named(T),
    InForce,
}

impl<T: Clone> Pushed<T> {
    fn make(&self, below: &T) -> T {
        match self {
            Pushed::Named(value) => value.clone(),
            Pushed::InForce => below.clone(),
        }
    }
}

/// A pushed face, as what it makes of each face it could be pushed onto. A
/// face code modifies the face in force (`Face::from_code`), and there are
/// only twelve faces, so a chain of codes is a table of twelve.
#[derive(Clone, Copy)]
struct FaceMap([u8; 12]);

impl FaceMap {
    const IDENTITY: FaceMap = FaceMap([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);

    /// This, and then `code` applied to what it made.
    fn then(self, code: char) -> FaceMap {
        FaceMap(
            self.0
                .map(|at| Face::from_code(code, Face::ALL[at as usize]).index() as u8),
        )
    }

    fn of(self, face: Face) -> Face {
        Face::ALL[self.0[face.index()] as usize]
    }
}

/// What a stretch of markers does to the colour, face and size stacks, read
/// by the same `walk_styles` that moves the stacks themselves.
#[derive(Default)]
struct StyleEffect {
    colours: StackEffect<Pushed<Spec>>,
    faces: StackEffect<FaceMap>,
    sizes: StackEffect<Pushed<TypeSize>>,
}

impl StyleEffect {
    /// Apply this to the three stacks, or leave them as they are and say so
    /// when a stack it moves is empty.
    fn apply(
        &self,
        colours: &mut Vec<Spec>,
        faces: &mut Vec<Face>,
        sizes: &mut Vec<TypeSize>,
    ) -> bool {
        if !(self.colours.applies_to(colours)
            && self.faces.applies_to(faces)
            && self.sizes.applies_to(sizes))
        {
            return false;
        }
        self.colours.apply(colours, Pushed::make);
        self.faces.apply(faces, |map, below| map.of(*below));
        self.sizes.apply(sizes, Pushed::make);
        true
    }
}

impl StyleStacks for StyleEffect {
    fn push_colour(&mut self, spec: Option<Spec>) {
        let pushed = match spec {
            Some(spec) => Pushed::Named(spec),
            None => self
                .colours
                .pushes
                .last()
                .cloned()
                .unwrap_or(Pushed::InForce),
        };
        self.colours.push(pushed);
    }
    fn pop_colour(&mut self) {
        self.colours.pop();
    }
    fn push_face(&mut self, code: char) {
        let under = self
            .faces
            .pushes
            .last()
            .copied()
            .unwrap_or(FaceMap::IDENTITY);
        self.faces.push(under.then(code));
    }
    fn pop_face(&mut self) {
        self.faces.pop();
    }
    fn push_size(&mut self, size: Option<TypeSize>) {
        let pushed = match size {
            Some(size) => Pushed::Named(size),
            None => self.sizes.pushes.last().cloned().unwrap_or(Pushed::InForce),
        };
        self.sizes.push(pushed);
    }
    fn pop_size(&mut self) {
        self.sizes.pop();
    }
}

/// The face in force, which is the main one when nothing has pushed.
fn current_face(faces: &[Face]) -> Face {
    faces.last().copied().unwrap_or_default()
}

/// What one word costs, in the faces it is set in.
///
/// A word can carry markers -- `\texttt{x}` is a marker, a letter and a marker
/// -- so it is not necessarily one width in one face. The plain case is the
/// one that runs a million times a book, so it is answered without splitting
/// anything.
fn word_width(
    word: &str,
    colours: &mut Vec<Spec>,
    faces: &mut Vec<Face>,
    sizes: &mut Vec<TypeSize>,
    width_of: &dyn Fn(&str, Face, f64) -> f64,
) -> f64 {
    if !word.contains(STACK_MARKERS) {
        return width_of(word, current_face(faces), current_size(sizes).size);
    }
    styled_runs(word, colours, faces, sizes)
        .iter()
        .map(|(text, _, face, ts)| width_of(text, *face, ts.size))
        .sum()
}

/// Find the file for a font family the document named.
///
/// `\setmainfont{Arimo}` names a FAMILY, not a path, and resolving one is what
/// fontconfig exists for. `fc-match` is asked first because it answers the way
/// every other program on the machine would; the directory walk is the fallback
/// for a machine without it. A family nothing matches returns `None` and the
/// caller falls back to naming one of the fourteen, which gets the widths right
/// and the shapes wrong -- better than refusing to typeset.
pub fn find_family(family: &str) -> Option<std::path::PathBuf> {
    // Memoised for the same reason `find_font` is: this spawns fc-match and,
    // when that answers with something else, reads every font file in the
    // system directories to check its name. Neither answer changes during a
    // run.
    static SEEN: std::sync::OnceLock<
        std::sync::Mutex<std::collections::HashMap<String, Option<std::path::PathBuf>>>,
    > = std::sync::OnceLock::new();
    let seen = SEEN.get_or_init(Default::default);
    if let Some(hit) = seen.lock().ok().and_then(|m| m.get(family).cloned()) {
        return hit;
    }
    let found = find_family_uncached(family);
    if let Ok(mut m) = seen.lock() {
        m.insert(family.to_string(), found.clone());
    }
    found
}

fn find_family_uncached(family: &str) -> Option<std::path::PathBuf> {
    if let Ok(out) = std::process::Command::new("fc-match")
        .args(["-f", "%{file}", family])
        .output()
    {
        if out.status.success() {
            let p = String::from_utf8_lossy(&out.stdout).trim().to_string();
            let path = std::path::Path::new(&p);
            // fc-match ALWAYS answers, with a default when it has no match, so
            // the answer is only useful if it looks like the family asked for.
            if path.exists() && file_matches(path, family) {
                return Some(path.to_path_buf());
            }
        }
    }
    let wanted = normalise(family);
    for dir in [
        "/System/Library/Fonts",
        "/System/Library/Fonts/Supplemental",
        "/Library/Fonts",
        "/usr/share/fonts",
        "/usr/local/share/fonts",
    ] {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let ext = path
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("")
                .to_ascii_lowercase();
            if ext != "ttf" && ext != "otf" {
                continue;
            }
            if normalise(&path.file_stem()?.to_string_lossy()).starts_with(&wanted) {
                return Some(path);
            }
        }
    }
    None
}

/// A font file's stem, compared the way a family name should be: case and
/// spacing are not part of the identity.
fn file_matches(path: &std::path::Path, family: &str) -> bool {
    path.file_stem()
        .map(|s| normalise(&s.to_string_lossy()).starts_with(&normalise(family)))
        .unwrap_or(false)
}

fn normalise(name: &str) -> String {
    name.chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .collect::<String>()
        .to_ascii_lowercase()
}

/// Load a family as an embeddable PDF font: its outlines, and its own widths.
///
/// This is the difference between a page set in Arimo's METRICS and one set in
/// Arimo. The widths come from the font's `hmtx` through its `cmap`, so a line
/// is measured in the face it will be printed in rather than in Computer
/// Modern's.
pub fn embed_family(family: &str) -> Option<crate::pdf::Font> {
    embed_file(&find_family(family)?)
}

/// Embed the font FILE a document supplied itself.
///
/// fontspec `Path=` names a directory of `.ttf` files that ship WITH the
/// document, which is how a book uses a face nobody has installed. Looking
/// such a name up among the installed families finds nothing, and fc-match
/// answers with a default -- so the book was set in whatever that default was.
pub fn embed_file(path: &std::path::Path) -> Option<crate::pdf::Font> {
    let bytes = std::fs::read(path).ok()?;
    let sfnt = crate::sfnt::Sfnt::parse(bytes.clone()).ok()?;
    // A CFF-flavoured OpenType carries PostScript outlines, which a
    // /FontFile2 must not: that entry means a TrueType font program.
    if sfnt.is_cff() {
        return None;
    }
    let head = sfnt.head().ok()?;
    let hhea = sfnt.hhea().ok()?;
    let cmap = sfnt.cmap().ok()?;
    let advances = sfnt.advance_widths().ok()?;
    let upem = f64::from(head.units_per_em.max(1));
    let scale = |v: f64| (v * 1000.0 / upem).round() as i64;

    // PDF wants a width for every code in the range, in 1/1000 em, so a code
    // the font has no glyph for still needs an entry.
    //
    // A code is a WinAnsi code -- that is the encoding the font is written with
    // -- and a `cmap` is indexed by Unicode, so the two are joined by what the
    // code MEANS. They agree from 0xA0 up, where WinAnsi is Latin-1, and part
    // company between 0x80 and 0x9F: reading code 0x97 as U+0097 finds nothing
    // and writes `.notdef`'s width where the em dash's belongs.
    let mut widths = Vec::with_capacity(224);
    for code in 32u32..=255 {
        let character = u8::try_from(code).ok().and_then(winansi_unicode);
        let gid = character
            .and_then(|c| cmap.get(&(c as u32)))
            .copied()
            .unwrap_or(0) as usize;
        let adv = advances
            .get(gid)
            .or_else(|| advances.last())
            .copied()
            .unwrap_or(0);
        widths.push(scale(f64::from(adv)));
    }
    Some(crate::pdf::Font::TrueType {
        name: path.file_stem()?.to_string_lossy().replace(' ', ""),
        bytes,
        widths,
        bbox: [
            scale(f64::from(head.x_min)),
            scale(f64::from(head.y_min)),
            scale(f64::from(head.x_max)),
            scale(f64::from(head.y_max)),
        ],
        ascent: scale(f64::from(hhea.ascender)),
        descent: scale(f64::from(hhea.descender)),
    })
}

#[cfg(test)]
mod font_file_tests {
    use super::FontFile;

    /// The options a real book writes, verbatim.
    const REAL: &str = "\n    Path=/private/tmp/build/scifi2/docs/.fonts/,\n    Extension=.ttf,\n    RawFeature={fallback=symfb},\n    UprightFont=Arimo-VF,\n    UprightFeatures={RawFeature={axis={wght=400}}},\n    BoldFont=Arimo-VF,\n    BoldFeatures={RawFeature={axis={wght=700}}},\n";

    #[test]
    fn the_options_a_document_ships_its_font_with() {
        let spec = FontFile::parse(REAL);
        assert_eq!(spec.upright.as_deref(), Some("Arimo-VF"));
        assert_eq!(spec.extension.as_deref(), Some(".ttf"));
        assert_eq!(
            spec.path.as_deref(),
            Some("/private/tmp/build/scifi2/docs/.fonts/")
        );
    }

    #[test]
    fn the_face_files_are_read_from_the_same_options() {
        // `BoldFont=` and `ItalicFont=` sit in the option list `UprightFont=`
        // does, and reading past them is why `\textbf` and `\emph` were set in
        // the upright face. The corpus's bold IS the upright file at another
        // weight, which is honest to report as such: what is asserted is that
        // the key was READ, not that the file differs.
        let spec = FontFile::parse(REAL);
        assert_eq!(spec.bold.as_deref(), Some("Arimo-VF"));
        assert_eq!(spec.italic.as_deref(), None, "this book names no italic");
        let both = FontFile::parse("Extension=.ttf,UprightFont=A,ItalicFont=A-Italic");
        assert_eq!(both.italic.as_deref(), Some("A-Italic"));
        // A face the document named no file for resolves to nothing, whatever
        // is beside the document, so the caller falls back to the main face
        // rather than setting the italic in some file that happens to be there.
        assert_eq!(
            both.resolve_face(
                super::Face {
                    bold: true,
                    ..super::Face::MAIN
                },
                None
            ),
            None
        );
    }

    #[test]
    fn a_value_holding_commas_does_not_tear_the_keys_after_it() {
        // `UprightFeatures={RawFeature={axis={wght=400}}}` sits BEFORE the keys
        // that matter in some documents. Splitting on every comma leaves
        // `wght=400}}}` as a key and loses everything past it.
        let spec = FontFile::parse("Extension=.ttf,Numbers={Proportional,Lining},UprightFont=X-VF");
        assert_eq!(spec.upright.as_deref(), Some("X-VF"));
        assert_eq!(spec.extension.as_deref(), Some(".ttf"));
    }

    #[test]
    fn a_stale_path_is_retried_beside_the_document() {
        // `Path=` is written when the document is BUILT and regularly points
        // into a scratch directory that is gone by the time it is read. The
        // fonts ship with the document, so the last component is tried there.
        let dir = std::env::temp_dir().join(format!("texrs_ff_{}", std::process::id()));
        let fonts = dir.join(".fonts");
        std::fs::create_dir_all(&fonts).expect("mkdir");
        let file = fonts.join("Arimo-VF.ttf");
        std::fs::write(&file, b"not really a font").expect("write");

        let spec =
            FontFile::parse("Path=/gone/for/good/.fonts/,Extension=.ttf,UprightFont=Arimo-VF");
        assert_eq!(spec.resolve(Some(&dir)), Some(file.clone()));
        // With nowhere to look, it resolves to nothing rather than to a guess.
        assert_eq!(spec.resolve(None), None);

        // A path that IS there wins outright.
        let direct = format!(
            "Path={}/,Extension=.ttf,UprightFont=Arimo-VF",
            fonts.display()
        );
        assert_eq!(FontFile::parse(&direct).resolve(None), Some(file));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_mandatory_argument_ending_in_a_font_extension_names_the_file_itself() {
        // `\setmainfont{Arimo-VF.ttf}[Path=...]` is the spelling lualatex
        // honours and this read as a family name, which named nothing
        // installed: `upright` stayed empty, `resolve_face` returned at its
        // first `?`, and no path was ever built.
        let mut spec = FontFile::parse("Path=/somewhere/.fonts/");
        spec.absorb_filename("Arimo-VF.ttf");
        assert_eq!(spec.upright.as_deref(), Some("Arimo-VF"));
        assert_eq!(spec.extension.as_deref(), Some(".ttf"));
        assert_eq!(spec.path.as_deref(), Some("/somewhere/.fonts/"));
        // The extension is kept as the document wrote it, since that is the
        // name to open on a filesystem that tells the cases apart.
        let mut upper = FontFile::default();
        upper.absorb_filename("Arimo-VF.TTF");
        assert_eq!(upper.upright.as_deref(), Some("Arimo-VF"));
        assert_eq!(upper.extension.as_deref(), Some(".TTF"));
        for spelt in ["A.otf", "A.OTF", "A.ttc", "A.otc"] {
            let mut one = FontFile::default();
            one.absorb_filename(spelt);
            assert_eq!(one.upright.as_deref(), Some("A"), "{spelt} is a filename");
        }
    }

    #[test]
    fn a_family_name_is_not_read_as_a_file_and_explicit_options_win() {
        // The other spelling must be untouched: `\setmainfont{Arimo}` names a
        // family, and a family with a dot in it -- `Dr. Sugiyama` is one --
        // is still not a filename.
        for family in ["Arimo", "NoSuchFontExistsAnywhere", "Dr. Sugiyama", ".ttf"] {
            assert_eq!(super::split_font_filename(family), None, "{family}");
            assert_eq!(super::font_family_name(family), family);
            let mut spec = FontFile::default();
            spec.absorb_filename(family);
            assert_eq!(spec.upright, None, "{family} named no file");
            assert_eq!(spec.extension, None, "{family} named no extension");
        }
        // A document that writes both said the keys last and meant them: the
        // filename fills what the options left empty and overrides nothing.
        let mut both = FontFile::parse("Path=/f/,Extension=.otf,UprightFont=Arimo-Regular");
        both.absorb_filename("Arimo-VF.ttf");
        assert_eq!(both.upright.as_deref(), Some("Arimo-Regular"));
        assert_eq!(both.extension.as_deref(), Some(".otf"));
        assert_eq!(super::font_family_name("Arimo-VF.ttf"), "Arimo-VF");
    }

    #[test]
    fn the_filename_spelling_resolves_to_the_file_beside_the_document() {
        // The whole point: a path is built, and it is the file the document
        // ships. A file that is NOT there resolves to nothing so the caller
        // still falls back rather than failing the run.
        let dir = std::env::temp_dir().join(format!("texrs_ffn_{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("mkdir");
        let file = dir.join("Arimo-VF.ttf");
        std::fs::write(&file, b"not really a font").expect("write");

        let mut spec = FontFile::parse(&format!("Path={}/", dir.display()));
        spec.absorb_filename("Arimo-VF.ttf");
        assert_eq!(spec.resolve(None), Some(file));

        let mut missing = FontFile::parse(&format!("Path={}/", dir.display()));
        missing.absorb_filename("NotThere-VF.ttf");
        assert_eq!(missing.resolve(None), None, "a missing file falls back");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn options_that_name_no_file_resolve_to_nothing() {
        // `\setmainfont{Georgia}` with no options at all must fall through to
        // the installed families rather than resolving to some file nearby.
        assert_eq!(
            FontFile::parse("").resolve(Some(std::path::Path::new("/tmp"))),
            None
        );
    }
}

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

    /// xorshift64*, so the documents are the same on every run.
    struct Rng(u64);

    impl Rng {
        fn below(&mut self, n: usize) -> usize {
            self.0 ^= self.0 >> 12;
            self.0 ^= self.0 << 25;
            self.0 ^= self.0 >> 27;
            (self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) as usize % n
        }
    }

    /// A word of text glued to style markers, unbalanced as often as not:
    /// named and damaged colours, every face code and a damaged one, named
    /// and damaged sizes, and the region markers.
    fn piece(rng: &mut Rng) -> String {
        match rng.below(16) {
            0 => format!("\u{1}{},0,{}\u{2}", rng.below(3), rng.below(3)),
            1 => "\u{1}bad\u{2}".to_string(),
            2 | 3 => "\u{3}".to_string(),
            4 | 5 => {
                let codes = [
                    'r', 's', 'm', 'b', 'i', 'n', 'B', 'j', 'S', 'J', 'k', 'M', 'K', '?',
                ];
                format!("{FACE_PUSH}{}", codes[rng.below(codes.len())])
            }
            6 | 7 => FACE_POP.to_string(),
            8 => format!(
                "{SIZE_PUSH}{};{}{SIZE_PUSH}",
                8 + rng.below(10),
                10 + rng.below(10)
            ),
            9 => format!("{SIZE_PUSH}junk{SIZE_PUSH}"),
            10 => SIZE_POP.to_string(),
            11 => CENTRE.to_string(),
            12 => CENTRE_END.to_string(),
            13 => format!("{LIST_INDENT}{}", rng.below(4)),
            _ => ["word", "x", "abc"][rng.below(3)].to_string(),
        }
    }

    fn document(seed: u64, paragraphs: usize) -> Vec<String> {
        let mut rng = Rng(seed);
        (0..paragraphs)
            .map(|_| {
                let mut para = String::new();
                for _ in 0..rng.below(24) {
                    para.push_str(&piece(&mut rng));
                    match rng.below(5) {
                        0 => para.push(' '),
                        1 if rng.below(8) == 0 => para.push(PAGE_BREAK),
                        _ => {}
                    }
                }
                para
            })
            .collect()
    }

    fn seeded(colours: Vec<Spec>, layout: &Layout) -> ParagraphStart {
        ParagraphStart {
            colours,
            faces: vec![Face::MAIN],
            sizes: vec![TypeSize {
                size: layout.size,
                leading: layout.leading,
            }],
            centred: false,
            depth: 0,
        }
    }

    /// The parallel paragraph prescan records what the serial one does, on
    /// the breaker's empty colour stack and on a seeded one.
    #[test]
    fn paragraph_starts_match_the_serial_walk() {
        let layout = Layout::default();
        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(4)
            .build()
            .unwrap();
        for seed in 1..=40u64 {
            let doc = document(seed, 50 + seed as usize * 7);
            let paras: Vec<&str> = doc.iter().map(String::as_str).collect();
            for colours in [Vec::new(), vec![current_colour(&[])]] {
                let start = seeded(colours, &layout);
                let serial = paragraph_starts_serial(&paras, &layout, start.clone());
                let parallel = pool.install(|| paragraph_starts(&paras, &layout, start));
                assert_eq!(parallel, serial, "seed {seed}");
            }
        }
    }

    /// The parallel page prescan records what the serial one does, the folio
    /// included.
    #[test]
    fn page_starts_match_the_serial_walk() {
        let layout = Layout::default();
        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(4)
            .build()
            .unwrap();
        for seed in 1..=40u64 {
            let doc = document(seed, 200);
            let mut rng = Rng(seed ^ 0x9E37_79B9);
            let mut chunks: Vec<Vec<&str>> = Vec::new();
            let mut lines = doc.iter().map(String::as_str);
            while let Some(first) = lines.next() {
                let mut page = vec![first];
                page.extend(lines.by_ref().take(rng.below(12)));
                chunks.push(page);
            }
            let start = seeded(vec![current_colour(&[])], &layout);
            let serial = page_starts_serial(
                &chunks,
                start.colours.clone(),
                start.faces.clone(),
                start.sizes.clone(),
            );
            let parallel =
                pool.install(|| page_starts(&chunks, start.colours, start.faces, start.sizes));
            assert!(chunks.len() >= PARALLEL_PAGES);
            assert_eq!(parallel, serial, "seed {seed}");
        }
    }

    /// A face pushed under a chain of codes is the chain applied to the face
    /// in force, for every face it could meet.
    #[test]
    fn face_map_is_the_codes_applied_in_turn() {
        let codes = ['s', 'b', '?', 'n', 'i', 'M', 'r'];
        for below in Face::ALL {
            let mut map = FaceMap::IDENTITY;
            let mut face = below;
            for code in codes {
                map = map.then(code);
                face = Face::from_code(code, face);
                assert_eq!(map.of(below), face);
            }
        }
    }
}