f-office-docx 0.3.0

DOCX model and Word's layout rules.
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
//! Breaking a paragraph into lines.

use f_office_units::scale::THOUSANDTHS;
use f_office_units::{Length, count_factor};

use crate::character_class::CharacterClass;
use crate::kinsoku::{Kinsoku, breaks_between};
use crate::props::EastAsianLanguage;

use crate::props::{TabKind, TabStop};
use crate::tabs::Tabs;
use crate::text::{AUTOMATIC_HYPHEN, FaceIndex, Glyph, LINE_END_HYPHEN, SOFT_HYPHEN, SpaceKind};

pub(crate) mod joints;

use joints::JointCounts;

/// The no-break space, U+00A0, which joins the words on both of its sides.
const NO_BREAK_SPACE: char = '\u{a0}';

/// One unit of paragraph content after measuring.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Piece {
    /// A glyph.
    Glyph(Glyph),
    /// A tab, with the face of its run.
    Tab(Option<FaceIndex>),
    /// A positional tab, with the face of its run and the stop that it goes to.
    PositionTab(Option<FaceIndex>, TabStop),
    /// A line break inside the paragraph, with the face of its run.
    LineBreak(Option<FaceIndex>),
    /// A page break.
    PageBreak,
    /// A column break.
    ColumnBreak,
    /// A mark without width for the footnote with this number, whose reference is on the line.
    Note(NoteNumber),
    /// A mark without width right after an auto-numbered endnote reference (`w:endnoteReference`)
    /// with this many glyphs on the line.
    Endnote(u16),
    /// A mark without width right after a footnote's own mark (`w:footnoteRef`) in the
    /// footnote's text.
    NoteMarkEnd,
    /// A mark without width right after an endnote's own mark (`w:endnoteRef`) with this many
    /// glyphs in the endnote's text.
    EndnoteMarkEnd(u16),
    /// A mark without width for the anchor of the comment with this index, whose balloon goes
    /// beside the line.
    Comment(CommentIndex),
    /// A mark without width for the anchor of the paragraph's floating drawing with this index,
    /// in the order of the paragraph's content, which is placed down from the line that holds
    /// the mark. [`break_lines`] takes the marks out before it breaks the other pieces, so that
    /// they change no line, and gives each to its line's [`Line::anchors`].
    Anchor(usize),
    /// A mark without width that draws nothing and sizes its line with this face, such as the
    /// reference mark in a comment's text.
    Strut(FaceIndex),
    /// A mark without width at the start of a line after a clearing line break: the line
    /// goes below the floating objects.
    Clear,
    /// The rule of a note separator (`w:separator`), drawn at the strikeout position of the
    /// run's face.
    Rule {
        /// The face of its run.
        face: FaceIndex,
        /// Its length.
        width: Length,
    },
    /// The square of a check box form field, as wide as the single line of its run's face.
    CheckBox {
        /// The face of its run, at the size of the box.
        face: FaceIndex,
        /// Its advance: the single line height of the face.
        width: Length,
    },
    /// A move of the pieces after it by a length, back when negative, which draws nothing and
    /// keeps the line from breaking there: the places of the parts of a stacked fraction.
    Shift(Length),
    /// The move of an `ADVANCE` field: as [`Piece::Shift`], a move of the pieces after it,
    /// back when negative, which draws nothing. It belongs to the word before it, and the
    /// word ends after it, so the line can break after it but not before it.
    Advance(Length),
    /// The bar of a stacked fraction, which takes no room and runs from its place over its
    /// width, at the axis of its face's size.
    Bar {
        /// The face of the fraction's run.
        face: FaceIndex,
        /// Its length: the width of the wider part.
        width: Length,
    },
    /// A bar over or under an expression of an equation: the bar of a radical over its element,
    /// or the bar of a bar structure over or under its base. It has no advance and runs from
    /// its place over its width, with its top `top` above the baseline of its face and
    /// `thickness` thick, and its line has room for it and for `beyond` above and below it.
    Vinculum {
        /// The face of the root sign as drawn, or of the bar structure's marks.
        face: FaceIndex,
        /// Its length: the width of the element or the base.
        width: Length,
        /// The height of its top above the baseline of its face, on a dot.
        top: Length,
        /// Its thickness.
        thickness: Length,
        /// The room of its line above its top and below its bottom.
        beyond: (Length, Length),
        /// The white space above its top that the box of its structure holds: a radical's
        /// `RadicalExtraAscender`, an overbar's `OverbarExtraAscender`; none for an underbar.
        clear: Length,
    },
    /// A diagonal strike across a border box (`m:borderBox`): zero advance, connecting the box's
    /// corners from `x` to `x + width` between `bottom` and `top` above the face's baseline.
    Diagonal {
        /// The face of the border box's marks.
        face: FaceIndex,
        /// The horizontal span of the strike.
        width: Length,
        /// The lower edge above the face's baseline.
        bottom: Length,
        /// The upper edge above the face's baseline.
        top: Length,
        /// The stroke thickness.
        thickness: Length,
        /// Whether the strike rises from bottom-left to top-right (`strikeBLTR`); false for
        /// top-left to bottom-right (`strikeTLBR`).
        rising: bool,
    },
    /// An inline object that sits on the baseline, raised or lowered with its run.
    Object {
        /// Its advance.
        width: Length,
        /// Its height, which stands above its bottom.
        height: Length,
        /// How far its run raises its bottom above the baseline (`w:position`), or lowers it
        /// below the baseline when negative.
        raised: Length,
        /// The index of its picture in the layout's pictures, if it shows one.
        picture: Option<usize>,
        /// The index of its shape in the layout's inline drawings, if it shows one.
        drawing: Option<DrawingIndex>,
        /// Whether its run draws an underline, which stands below the object and needs room
        /// below the baseline when the object is alone on its line and taller than its font
        /// line (`UnderlinedObjectRoom`).
        underlined: bool,
        /// Its run's own unshifted face. On a target that sizes inline object lines by the
        /// objects' runs (`ObjectLineMultiple::ObjectRun`, compatibility mode 15 and later), this
        /// face sets the single line of an object-alone line in place of the paragraph mark or
        /// line break, scales multiple spacing below a tall object alone, and expands a text line
        /// when its single line exceeds the text's. `None` where the run has no face, as for a
        /// label's legacy spacer or picture bullet.
        run_face: Option<FaceIndex>,
        /// Whether the object attaches to the word before it with no break opportunity before
        /// the object, while still allowing a break after it: true for single inline VML vector
        /// shapes (`w:pict` without `v:imagedata`, `v:group`, or `o:hr="t"`) and false for inline
        /// pictures, OLE objects, VML groups, horizontal rules, DrawingML (`wp:inline`) shapes,
        /// and list label spacers.
        joins_before: bool,
    },
}

/// The index of an inline drawing among the drawings of a layout's pass output, which the
/// layout makes when it measures the drawing, and reads when it sizes and draws its line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DrawingIndex(usize);

impl DrawingIndex {
    /// The drawing at `index` in the pass output's list.
    pub(crate) const fn new(index: usize) -> Self {
        Self(index)
    }

    /// Its place in the pass output's list.
    pub(crate) const fn get(self) -> usize {
        self.0
    }
}

/// The index of a comment among the comments in the order of their first references, which
/// the layout makes at a comment's first reference.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct CommentIndex(usize);

impl CommentIndex {
    /// The comment at `index` in the order of references.
    pub(crate) const fn new(index: usize) -> Self {
        Self(index)
    }

    /// Its place in the order of references.
    pub(crate) const fn get(self) -> usize {
        self.0
    }
}

/// The number of a footnote: the place of its ID in the order of the first references of the
/// footnotes, from 0, which a footnote's reference piece names. Its reference and its mark show
/// its label, which the section's numbering of footnotes gives it at its first reference.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NoteNumber(usize);

impl NoteNumber {
    /// The number of the footnote whose ID has the place `index`, from 0, in the order of the
    /// first references.
    pub(crate) const fn of_index(index: usize) -> Self {
        Self(index)
    }

    /// The place of the footnote's ID in the order of the first references, from 0.
    pub(crate) const fn index(self) -> usize {
        self.0
    }
}

/// A piece placed on a line, at an offset from the line start.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Placed {
    /// The piece.
    pub piece: Piece,
    /// Its offset from the line start.
    pub x: Length,
    /// Its advance.
    pub advance: Length,
    /// For a tab, the character that fills its space.
    pub leader: Option<char>,
    /// For a tab, the kind of the stop that it goes to.
    pub tab: Option<TabKind>,
}

/// How a line ends.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineEnd {
    /// Where the next word does not fit, or at the end of the paragraph.
    #[default]
    Wrap,
    /// Inside a word that does not fit on a line of its own.
    Split,
    /// At a line break (`w:br`), with the face of its run.
    Break(Option<FaceIndex>),
    /// At a page break, which follows the line.
    PageBreak,
    /// At a column break, which follows the line.
    ColumnBreak,
}

/// A line of a paragraph.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Line {
    /// The pieces in order.
    pub placed: Vec<Placed>,
    /// How the line ends.
    pub end: LineEnd,
    /// The decision that kept the line's last word on it.
    pub kept: Option<Fit>,
    /// For a line that ends before a word that does not fit, the decision that moved it to
    /// the next line.
    pub wrapped: Option<Fit>,
    /// Whether the word that did not fit ends with a punctuation mark that Word lets stand
    /// past the end of this line, and fits without it: Word keeps the word on this line and
    /// hangs the mark, where F-Office, which hangs no mark, moves the word.
    pub would_hang: bool,
    /// Whether this line keeps its final word with a trailing punctuation mark hanging past the
    /// right margin (`w:overflowPunct`), so the line justifies its text before the hanging mark
    /// to the right edge and ends immediately after the mark.
    pub hung: bool,
    /// The anchor marks on the line ([`Piece::Anchor`]), in their order, beside its placed
    /// pieces, which they do not change.
    pub anchors: Vec<LineAnchor>,
    /// The hyphen that the line shows at its end where a word breaks, which the text does not
    /// hold: its last glyph.
    pub hyphen: Option<EndHyphen>,
    /// How many of the spaces at the line's end, from the first, count as its written text:
    /// those that keep the right-to-left level of their runs in a left-to-right paragraph.
    /// Layout sets it when it places the line; 0 for every other line.
    pub written_end_spaces: usize,
}

/// A hyphen that a line shows at its end where a word breaks, which the text does not hold.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EndHyphen {
    /// At an automatic hyphenation point.
    Automatic,
    /// At a soft hyphen, which shows nothing inside a line.
    Soft,
}

/// An anchor mark on a line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineAnchor {
    /// How many of the line's placed pieces come before the mark.
    pub at: usize,
    /// The index of the mark's drawing, in the order of the paragraph's content.
    pub drawing: usize,
}

/// What lies on a line before one of its drawn glyphs, in the order of drawing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Step {
    /// Nothing, or only spaces or an inline object: the glyph starts the line.
    Start,
    /// Nothing, and the glyph is the first of a list label.
    Label,
    /// A list label: the glyph is the first of the text after it.
    AfterLabel,
    /// A tab to a left stop, also a default stop or a positional tab that aligns at the left,
    /// also when the tab starts the line.
    Tab,
    /// A tab to a center, right or decimal stop, an aligned tab: the text after it centers on
    /// the stop, ends at it or puts its decimal separator at it.
    AlignedTab,
    /// Spaces that stretch or shrink on a justified line.
    Stretched,
    /// Spaces at their own width.
    Space,
    /// An inline object.
    Object,
    /// A tab before it, whose leader the glyph is a character of: it sits on the leader's grid.
    Leader,
    /// Only the glyph before it.
    Glyph,
}

/// The numbers of one decision whether a word fits on its line, from the start of the line, by
/// which a caller can replay the decision with another rule.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Fit {
    /// The width of the line.
    pub width: Length,
    /// Where the word ends on the line, without the spaces after it.
    pub end: Length,
    /// The width of the word, without the spaces after it.
    pub word: Length,
    /// The width of the spaces on the line before the word, in all.
    pub spaces: Length,
    /// The width of the spaces right before the word.
    pub space: Length,
    /// How many spaces the line holds before the word, in all.
    pub space_count: usize,
    /// How many of them lie right before the word.
    pub last_space_count: usize,
    /// How far past its width a tab stop past the end lets the line run.
    pub room: Length,
    /// How far past its width the line may run for the word: the room, and on a justified
    /// line the shrinking of its spaces.
    pub over: Length,
    /// Whether the spaces of the line may shrink.
    pub shrinks: bool,
}

impl Line {
    /// The pieces of `lines` in order, with the breaks that ended them, so that they can be
    /// broken into lines again.
    #[must_use]
    pub fn pieces(lines: &[Self]) -> Vec<Piece> {
        let mut pieces = Vec::new();
        for line in lines {
            let mut marks = line.anchors.iter().peekable();
            for (index, placed) in line.placed.iter().enumerate() {
                while let Some(mark) = marks.next_if(|mark| mark.at <= index) {
                    pieces.push(Piece::Anchor(mark.drawing));
                }
                pieces.push(placed.piece);
            }
            pieces.extend(marks.map(|mark| Piece::Anchor(mark.drawing)));
            match line.end {
                LineEnd::PageBreak => pieces.push(Piece::PageBreak),
                LineEnd::ColumnBreak => pieces.push(Piece::ColumnBreak),
                LineEnd::Break(face) => pieces.push(Piece::LineBreak(face)),
                LineEnd::Wrap | LineEnd::Split => {}
            }
        }
        pieces
    }

    /// Whether the line is the first of several of its paragraph and holds only a page break,
    /// so that the paragraph starts with a page break and goes on after it.
    #[must_use]
    pub fn starts_with_page_break(&self, index: usize, last: bool) -> bool {
        index == 0 && !last && self.holds_only_page_break()
    }

    /// Whether the line holds nothing and ends at a page break.
    #[must_use]
    pub fn holds_only_page_break(&self) -> bool {
        self.placed.is_empty() && self.end == LineEnd::PageBreak
    }

    /// The index of the first line of a paragraph broken into `lines`: 0, or, when the
    /// paragraph holds more than page breaks, the count of the leading page breaks that
    /// `breaks` puts before its first line: the first of them or all of them.
    #[must_use]
    pub fn first_index(lines: &[Self], breaks: LeadingBreaks) -> usize {
        let leading = lines
            .iter()
            .take_while(|line| line.holds_only_page_break())
            .count();
        if leading == lines.len() {
            return 0;
        }
        breaks.before_first_line(leading)
    }

    /// Whether a page or column break follows the line.
    #[must_use]
    pub const fn breaks_page_or_column(&self) -> bool {
        matches!(self.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
    }
}

impl Line {
    /// The width up to the end of the last glyph that is not a trailing space.
    #[must_use]
    pub fn width(&self) -> Length {
        self.end_of(self.written())
    }

    /// The width that the fit test needs for the line: its width ([`Self::width`]) with what the
    /// test counts beside the advances of its written pieces ([`counted`]).
    #[must_use]
    pub fn fit_width(&self) -> Length {
        let written = self.placed.get(..self.written()).unwrap_or_default();
        self.width() + written.iter().map(|p| counted(&p.piece)).sum()
    }

    /// The number of pieces before the line's trailing spaces: the pieces of its written
    /// text.
    #[must_use]
    pub fn written(&self) -> usize {
        self.last_visible().map_or(0, |last| last + 1)
    }

    /// Where the first `pieces` pieces of the line end, from the line's start.
    #[must_use]
    pub fn end_of(&self, pieces: usize) -> Length {
        pieces
            .checked_sub(1)
            .and_then(|last| self.placed.get(last))
            .map_or(Length::ZERO, |p| p.x + p.advance)
    }

    /// Whether the line holds text of a run without `w:rtl`: a glyph of such a run that is
    /// not a space.
    #[must_use]
    pub fn holds_left_to_right_text(&self) -> bool {
        self.placed
            .iter()
            .any(|p| !is_space(&p.piece) && run_rtl(&p.piece) == Some(false))
    }

    /// Whether the line holds text of a run with `w:rtl`: a glyph of such a run that is
    /// not a space.
    #[must_use]
    pub(crate) fn holds_right_to_left_text(&self) -> bool {
        self.placed
            .iter()
            .any(|p| !is_space(&p.piece) && run_rtl(&p.piece) == Some(true))
    }

    /// The index of the last piece that is not a trailing space, of text or of an operator
    /// where an equation breaks, or of the last space at the line's end that counts as its
    /// written text ([`Self::written_end_spaces`]).
    #[must_use]
    pub fn last_visible(&self) -> Option<usize> {
        let last = self
            .placed
            .iter()
            .rposition(|p| !is_space(&p.piece) && !is_operator_space(&p.piece))?;
        let spaces = self.placed.len() - 1 - last;
        Some(last + self.written_end_spaces.min(spaces))
    }

    /// The index of the first piece whose spaces a justified line may stretch: the first piece
    /// that is not a space, so that spaces at the start of the line keep their width.
    #[must_use]
    pub fn first_stretched(&self) -> usize {
        let after_tab = self
            .placed
            .iter()
            .rposition(|p| matches!(p.piece, Piece::Tab(_) | Piece::PositionTab(..)))
            .map_or(0, |i| i + 1);
        let rest = self.placed.get(after_tab..).unwrap_or(&[]);
        after_tab
            + rest
                .iter()
                .position(|p| !is_space(&p.piece))
                .unwrap_or(rest.len())
    }
}

/// Where the line breaker has met Thai text on the line that it fills.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ThaiText {
    /// Neither on the line nor in the word that it tests.
    None,
    /// In the word that the line tests only.
    InWord,
    /// On the line.
    OnLine,
}

/// Whether `piece` is a glyph of the Thai block.
fn is_thai(piece: &Piece) -> bool {
    matches!(piece, Piece::Glyph(glyph) if CharacterClass::Thai.contains(glyph.ch))
}

/// The widths and tab settings that line breaking needs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Frame {
    /// The width of the first line.
    pub first_width: Length,
    /// The width of the other lines.
    pub width: Length,
    /// The width of the text area of the column or cell, from the column edge: where the
    /// lines would end without a right indent.
    pub area_width: Length,
    /// The distance from the column edge to the start of the first line.
    pub first_start: Length,
    /// The distance from the column edge to the start of the other lines.
    pub start: Length,
    /// The tab stops.
    pub tabs: Tabs,
    /// How much each space on a justified line may shrink so that one more word fits.
    pub shrink: Shrink,
    /// Whether a line that holds a Thai character, with the word that it tests, keeps its
    /// spaces from shrinking ([`Frame::shrink`]).
    pub thai_keeps_spaces: bool,
    /// Which spaces at the end of a word count in the word's fit ([`Breaker::fitted_end_spaces`]).
    pub end_space_fit: EndSpaceFit,
    /// The characters that may not start or end a line of East Asian text, or `None` for text
    /// without an East Asian language, which breaks only where Latin text does.
    pub kinsoku: Option<Kinsoku>,
    /// Whether a joined space run, a run of white space that holds a no-break space, keeps the
    /// words on both of its sides on one line, as from compatibility mode
    /// [`JOINED_SPACE_MODE`](crate::params::JOINED_SPACE_MODE).
    pub joined_spaces: bool,
    /// What the target's line breaking does with tabs and footnote references.
    pub breaking: LineBreaking,
    /// Whether the limit of [`LineBreaking::ends_aligned_text`] also holds for a stop at or past
    /// the line's end; where it does not, the text after such a stop keeps its place at the stop and the
    /// line runs on to where it ends.
    pub limits_past_end: bool,
    /// How far the blank halves of the punctuation on a justified line of East Asian text may
    /// shrink so that more text fits, or `None` where punctuation keeps its width.
    pub punctuation: Option<Compression>,
    /// How a line may end at an automatic hyphenation point ([`AUTOMATIC_HYPHEN`]), or `None`
    /// where the paragraph's words have none.
    pub hyphenation: Option<Hyphenation>,
    /// What line breaking does when a trailing mark of [`Kinsoku::hangs`] overflows a line whose
    /// preceding pieces fit (`w:overflowPunct`).
    pub overflow_punct: OverflowPunct,
}

/// What line breaking does when a trailing mark of [`Kinsoku::hangs`] overflows a line whose
/// preceding pieces fit (`w:overflowPunct`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OverflowPunct {
    /// Disabled (`w:overflowPunct w:val="0"`): neither hang nor warn.
    Off,
    /// Wrap the word and record [`Line::would_hang`] so layout can warn.
    #[default]
    Warn,
    /// Keep the word on the line with its trailing mark hanging past the right margin
    /// ([`Line::hung`]).
    Hang,
}

/// Which spaces at the end of a word count in the word's fit on a line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum EndSpaceFit {
    /// None: a word fits without the spaces at its end, which hang past the line's width.
    #[default]
    WithoutSpaces,
    /// On a line that already holds text of a run without `w:rtl`, the right-to-left spaces at
    /// the word's end, from the first: the spaces of runs with `w:rtl`, and, on a line that
    /// already holds a left-to-right letter, after a word that ends with a right-to-left letter
    /// before a word that starts with one, the spaces between them, whether or not their runs
    /// have `w:rtl`. The spaces of runs with `w:rtl` keep their runs' right-to-left level when
    /// the line ends after them, and the line holds them as written text. A justified line
    /// counts all of them as its spaces ([`Breaker::shrink_over`]).
    WithRightToLeftSpaces,
}

impl EndSpaceFit {
    /// Whether the fit counts the spaces between right-to-left letters on `line`: where it
    /// counts right-to-left spaces, on a line that already holds a left-to-right letter.
    fn between_letters(self, line: &Line) -> bool {
        self == Self::WithRightToLeftSpaces
            && line
                .placed
                .iter()
                .filter_map(|p| run_glyph(&p.piece))
                .any(|glyph| left_to_right(glyph.ch))
    }
}

/// The spaces at the end of a word that count in its fit ([`EndSpaceFit`]): their width, how
/// many there are, and how far they may shrink in all.
#[derive(Clone, Copy, Debug, Default)]
struct EndSpaces {
    width: Length,
    count: usize,
    shrink: Length,
    /// Whether the word starts with a right-to-left letter.
    starts_right_to_left: bool,
}

/// How a paragraph's lines may end at the automatic hyphenation points of its words. A word
/// that does not fit breaks at its last point whose part, with the hyphen, fits.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Hyphenation {
    /// The hyphenation zone where it holds: a word is hyphenated only when the room that the
    /// line leaves for it is wider than the zone. `None` where the zone does not hold.
    pub zone: Option<Length>,
    /// The most lines in a row that may end at an automatic point, or `None` for no limit.
    pub limit: Option<std::num::NonZeroUsize>,
}

/// What the target's line breaking does with the text after a tab, with a footnote reference's
/// mark and with a paragraph's leading page breaks, which a frame carries.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LineBreaking {
    /// Whether the text after a tab to a right, center or decimal stop that would end past its
    /// limit ends there instead; otherwise it runs past.
    pub ends_aligned_text: bool,
    /// Whether a footnote reference's mark is text of its word, so that a line breaks after it
    /// only where its last glyph and the next piece allow a break.
    pub note_reference_in_word: bool,
    /// Whether a tab whose next stop is a custom left stop past the line's end goes to the
    /// line's end; otherwise it goes to its stop.
    pub left_stops_to_line_end: bool,
    /// Which of a paragraph's leading page breaks come before its first line, which takes the
    /// first line's start and width; the lines before it take those of the other lines.
    pub leading_breaks: LeadingBreaks,
}

/// Which of the page breaks that start a paragraph come before its first line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LeadingBreaks {
    /// None: the first line is the first break's line.
    #[default]
    None,
    /// The first: the line after it is the first line, also when it holds the next break.
    First,
    /// All: the first line is the first line that does not hold only a page break.
    All,
}

impl LeadingBreaks {
    /// How many of a paragraph's `leading` page breaks come before its first line.
    #[must_use]
    pub fn before_first_line(self, leading: usize) -> usize {
        match self {
            Self::None => 0,
            Self::First => leading.min(1),
            Self::All => leading,
        }
    }
}

impl Frame {
    /// The start and the width of the first line or of another line in a column `column`
    /// wide, from the column's left edge. The frame's starts lie at the side where the lines
    /// start, which is the right side of a right-to-left paragraph, so there they mirror across
    /// the column, and the indents swap sides on the page.
    #[must_use]
    pub fn on_page(&self, first: bool, column: Length, right_to_left: bool) -> (Length, Length) {
        let (start, width) = if first {
            (self.first_start, self.first_width)
        } else {
            (self.start, self.width)
        };
        if right_to_left {
            (column - start - width, width)
        } else {
            (start, width)
        }
    }
}

/// Which trailing full-width closing punctuation marks may trim their blank right half
/// (`0.5 em`) to fit at the end of a line under `compressPunctuation` before
/// `TRAILING_PUNCTUATION_TRIM_MODE`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TrailingTrim {
    /// No trailing closing-mark blank-half trim.
    #[default]
    None,
    /// Any full-width closing mark ([`closing_mark`]) trims its trailing blank right half.
    Closing,
    /// Full-width closing marks except those centered in Japanese ([`japanese_centered_mark`]).
    NonJapaneseCentered,
    /// Full-width closing marks except those centered in Traditional Chinese ([`centered_mark`]).
    NonTraditionalCentered,
}

impl TrailingTrim {
    /// Whether `ch` carries an unsplit trailing blank right half that trims at line end.
    #[must_use]
    pub fn trims(self, ch: char) -> bool {
        match self {
            Self::None => false,
            Self::Closing => closing_mark(ch),
            Self::NonJapaneseCentered => closing_mark(ch) && !japanese_centered_mark(ch),
            Self::NonTraditionalCentered => closing_mark(ch) && !centered_mark(ch),
        }
    }
}

/// How a line with compressed punctuation chooses between shrinking the blank halves of its
/// punctuation marks so that the next word fits and stretching its gaps without the word: it
/// shrinks when the shrink per blank half is at most `ratio` times the stretch per gap of the line
/// without the word (`0` on non-justified lines). Before `TRAILING_PUNCTUATION_TRIM_MODE`, a
/// trailing closing mark matched by `trailing_trim` also gives up its own blank right half
/// directly at line end.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Compression {
    /// How many times the stretch per gap each blank half may shrink on a justified line: a whole
    /// multiple, or `0` on non-justified lines.
    pub ratio: i64,
    /// Whether the Japanese middle dot (`・`, U+30FB) also carries a blank half.
    pub middle_dot: bool,
    /// Which trailing closing marks trim their blank right half at line end.
    pub trailing_trim: TrailingTrim,
}

/// The blank halves of the punctuation marks of some pieces: how many, and the advance of the
/// widest mark. The blank half of a closing mark is its right half, that of an opening mark its
/// left half, and in Japanese that of a middle dot its two blank quarters.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Halves {
    /// How many blank halves there are.
    pub count: usize,
    /// The advance of the widest of their marks.
    pub em: Length,
}

impl Halves {
    /// The blank halves among `pieces`.
    fn of(pieces: &[Piece], include_middle_dot: bool) -> Self {
        pieces
            .iter()
            .fold(Self::default(), |halves, piece| match piece {
                Piece::Glyph(g)
                    if !g.label
                        && g.punctuation_half.is_open()
                        && (closing_mark(g.ch)
                            || opening_mark(g.ch)
                            || (include_middle_dot && middle_dot(g.ch))) =>
                {
                    Self {
                        count: halves.count + 1,
                        em: halves.em.max(g.punctuation_half.full_em(g.advance)),
                    }
                }
                _ => halves,
            })
    }

    /// These blank halves and `other`.
    fn and(self, other: Self) -> Self {
        Self {
            count: self.count + other.count,
            em: self.em.max(other.em),
        }
    }
}

impl Compression {
    /// How far a line may run past its width for the next word, when the line with the word has
    /// the blank halves `halves`, a closing mark at its end among them, and the line without it
    /// leaves `room` to stretch over `gaps` gaps. No half shrinks by more than its own width.
    #[must_use]
    pub fn over(self, halves: Halves, (room, gaps): (Length, i64)) -> Length {
        if halves.count == 0 || gaps <= 0 || room <= Length::ZERO {
            return Length::ZERO;
        }
        let count = count_factor(halves.count);
        (room * (self.ratio * count))
            .div_toward_zero(gaps)
            .min((halves.em * count).div_toward_zero(2))
    }
}

/// How many gaps each letter joint of a justified line counts as beside its spaces, in the
/// stretch per gap that the line would need without one more word: a line whose letter joints
/// take kashidas spreads that stretch over its joints too.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct JointGaps {
    /// The gaps of a letter joint after a seen, sheen, sad or dad.
    pub seen: i64,
    /// The gaps of each other letter joint.
    pub other: i64,
}

impl JointGaps {
    /// The gaps that the letter joints `joints` count as.
    #[must_use]
    pub fn of(self, joints: JointCounts) -> i64 {
        self.seen * count_factor(joints.seen) + self.other * count_factor(joints.other)
    }
}

/// The limits on shrinking the spaces of a justified line: each space by a share of its width,
/// and, to take one more word, each by a share of the stretch per gap that the line would need
/// without that word.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Shrink {
    /// The share of the space width, in thousandths.
    pub permille: i64,
    /// The most that each space of the line may shrink to take one more word, as a share of
    /// the stretch per gap that the line would need without that word, in thousandths. 0 sets
    /// no such limit.
    pub stretch_permille: i64,
    /// How far the line may run past its width to take a word, as a share of its natural width
    /// up to the word's end: a part and a whole. A whole of 0 sets no such limit.
    pub natural: (i64, i64),
    /// The gaps that the line's letter joints count as in the stretch per gap without the word;
    /// zero where the joints count as none.
    pub joints: JointGaps,
}

impl Shrink {
    /// How far a line whose natural width up to a word's end is `end` may run past its width
    /// to take the word, or `None` where the line has no limit of a share of its natural width.
    /// The line takes the word while its width is at least the rest of the natural width, to
    /// the nearest twip.
    #[must_use]
    pub fn of_natural(self, end: Length) -> Option<Length> {
        let (part, whole) = self.natural;
        (whole > 0).then(|| {
            end - (end * (whole - part))
                .div_round(whole)
                .nearest_whole(Length::UNITS_PER_TWIP)
        })
    }

    /// How much a space of this advance may shrink.
    #[must_use]
    pub fn of(self, advance: Length) -> Length {
        (advance * self.permille).div_toward_zero(THOUSANDTHS)
    }

    /// How far a line may run over the column to take a word of `word` after spaces of
    /// `space`, when its spaces may shrink by `spaces` in all, and it holds `count` spaces
    /// before the word, `last` of them right before it, and the letter joints `joints`.
    ///
    /// When the line runs over by `over`, each of its `count` spaces shrinks by
    /// `over / count`. Without the word, the line leaves `space + word - over` to stretch over
    /// its `count - last` gaps and the gaps that its joints count as ([`JointGaps`]), `j`. The
    /// word fits when the shrink is at most the share `stretch_permille` of that stretch:
    /// `over * (count - last + j) * 1000 <= stretch_permille * count * (space + word - over)`.
    #[must_use]
    pub fn over(
        self,
        spaces: Length,
        (space, word): (Length, Length),
        (count, last): (usize, usize),
        joints: JointCounts,
    ) -> Length {
        if self.stretch_permille == 0 || count == 0 {
            return spaces;
        }
        let (count, last) = (count_factor(count), count_factor(last));
        let gaps = count - last + self.joints.of(joints);
        let share = self.stretch_permille * count;
        spaces.min(((space + word) * share).div_toward_zero(THOUSANDTHS * gaps + share))
    }
}

/// Breaks pieces into lines. A paragraph always has at least one line. The anchor marks of the
/// pieces ([`Piece::Anchor`]) take no part in the breaks: each goes to the line that holds the
/// piece after it, or to the last line.
#[must_use]
pub fn break_lines(pieces: &[Piece], frame: &Frame) -> Vec<Line> {
    if !pieces.iter().any(|piece| matches!(piece, Piece::Anchor(_))) {
        return break_pieces(pieces, frame);
    }
    let mut marks = Vec::new();
    let mut rest = Vec::with_capacity(pieces.len());
    for piece in pieces {
        match piece {
            Piece::Anchor(drawing) => marks.push((rest.len(), *drawing)),
            other => rest.push(*other),
        }
    }
    let mut lines = break_pieces(&rest, frame);
    give_marks(&mut lines, &rest, &marks);
    lines
}

/// Gives each anchor mark of `marks`, the index in `pieces` of the piece that it stands before
/// and the index of its drawing, to the line of `lines`, broken from `pieces`, that holds that
/// piece. A line holds its placed pieces, the soft hyphens that it drops between them and the
/// break that ends it; a mark after every piece goes to the last line.
fn give_marks(lines: &mut [Line], pieces: &[Piece], marks: &[(usize, usize)]) {
    let mut next = 0;
    // For each line, the index in `pieces` of each placed piece and the index after its end.
    let mut spans: Vec<(Vec<usize>, usize)> = Vec::with_capacity(lines.len());
    for line in lines.iter() {
        let mut find = |found: &dyn Fn(&Piece) -> bool| {
            while pieces.get(next).is_some_and(|piece| !found(piece)) {
                next += 1;
            }
            next += 1;
            next - 1
        };
        let placed = line
            .placed
            .iter()
            .map(|placed| find(&|piece| same_piece(piece, &placed.piece)))
            .collect();
        if line.end != LineEnd::Wrap && line.end != LineEnd::Split {
            find(&|piece| {
                matches!(
                    piece,
                    Piece::LineBreak(_) | Piece::PageBreak | Piece::ColumnBreak
                )
            });
        }
        spans.push((placed, next));
    }
    for &(before, drawing) in marks {
        let index = spans
            .iter()
            .position(|(_, end)| *end > before)
            .unwrap_or(spans.len().saturating_sub(1));
        let at = spans.get(index).map_or(0, |(placed, _)| {
            placed.iter().filter(|&&at| at < before).count()
        });
        if let Some(line) = lines.get_mut(index) {
            line.anchors.push(LineAnchor { at, drawing });
        }
    }
}

/// Whether a placed piece is the piece `piece` of the pieces that were broken: a soft hyphen
/// or an automatic hyphenation point at the end of a wrapped line shows as a hyphen-minus.
fn same_piece(piece: &Piece, placed: &Piece) -> bool {
    match (piece, placed) {
        (Piece::Glyph(glyph), Piece::Glyph(shown)) if is_hyphen_point(glyph.ch) => {
            Glyph {
                ch: shown.ch,
                ..*glyph
            } == *shown
        }
        _ => piece == placed,
    }
}

/// Breaks pieces without anchor marks into lines.
fn break_pieces(pieces: &[Piece], frame: &Frame) -> Vec<Line> {
    let mut breaker = Breaker {
        frame,
        thai: ThaiText::None,
        lines: Vec::new(),
        line: Line::default(),
        x: Length::ZERO,
        shrink: Length::ZERO,
        spaces: Length::ZERO,
        space_count: 0,
        stretching: false,
        counted: Length::ZERO,
        room: Length::ZERO,
        blank: Halves::default(),
        hyphen_lines: 0,
        ends_at_point: false,
    };
    let mut i = 0;
    while i < pieces.len() {
        i = breaker.step(pieces, i);
    }
    // A paragraph that ends with a page break has no empty line after it. After a column
    // break at its end, the paragraph has an empty line at the top of the next column.
    let after_page_break = breaker
        .lines
        .last()
        .is_some_and(|line| line.end == LineEnd::PageBreak);
    if !(after_page_break && breaker.line.placed.is_empty()) {
        settle_soft_hyphens(&mut breaker.line, false);
        strip_trailing_auto_space(&mut breaker.line);
        breaker.lines.push(breaker.line);
    }
    breaker.lines
}

struct Breaker<'a> {
    frame: &'a Frame,
    /// Whether the line, or the word that it tests, holds a Thai character.
    thai: ThaiText,
    lines: Vec<Line>,
    line: Line,
    x: Length,
    /// How far the spaces placed on the line may shrink in all.
    shrink: Length,
    /// The width of the spaces placed on the line that a justified line stretches: those after
    /// its last tab and after the first piece that follows it and is not a space.
    spaces: Length,
    /// How many such spaces are placed on the line.
    space_count: usize,
    /// Whether a piece that is not a space lies on the line after its last tab, or after its
    /// start, so that the spaces placed next stretch.
    stretching: bool,
    /// What the fit test counts beside the advances of the pieces placed on the line since its
    /// last tab or its start ([`counted`]).
    counted: Length,
    /// How far an aligned tab stop past the line end lets the line run on.
    room: Length,
    /// The blank halves of the punctuation marks placed on the line.
    blank: Halves,
    /// How many lines in a row before this one end at an automatic hyphenation point.
    hyphen_lines: usize,
    /// Whether the line ends at an automatic hyphenation point.
    ends_at_point: bool,
}

impl Breaker<'_> {
    fn step(&mut self, pieces: &[Piece], i: usize) -> usize {
        match pieces.get(i) {
            Some(Piece::LineBreak(face)) => {
                self.finish(LineEnd::Break(*face));
                i + 1
            }
            Some(Piece::PageBreak) => {
                self.finish(LineEnd::PageBreak);
                i + 1
            }
            Some(Piece::ColumnBreak) => {
                self.finish(LineEnd::ColumnBreak);
                i + 1
            }
            Some(piece @ (Piece::Tab(_) | Piece::PositionTab(..))) => {
                if matches!(piece, Piece::Tab(_)) && self.stop_past_end() {
                    self.finish(LineEnd::Wrap);
                }
                self.place_tab(*piece, pieces.get(i + 1..).unwrap_or(&[]));
                i + 1
            }
            Some(
                piece @ (Piece::Note(_)
                | Piece::Endnote(_)
                | Piece::NoteMarkEnd
                | Piece::EndnoteMarkEnd(_)
                | Piece::Comment(_)
                | Piece::Strut(_)
                | Piece::Clear),
            ) => {
                self.push(*piece, Length::ZERO);
                i + 1
            }
            Some(
                Piece::Glyph(_)
                | Piece::Shift(_)
                | Piece::Advance(_)
                | Piece::Bar { .. }
                | Piece::Vinculum { .. }
                | Piece::Diagonal { .. }
                | Piece::Object { .. }
                | Piece::Rule { .. }
                | Piece::CheckBox { .. },
            ) => self.place_word(pieces, i),
            // `break_lines` has taken the anchor marks out.
            Some(Piece::Anchor(_)) | None => i + 1,
        }
    }

    fn finish(&mut self, end: LineEnd) {
        let mut line = std::mem::take(&mut self.line);
        settle_soft_hyphens(&mut line, false);
        strip_trailing_auto_space(&mut line);
        line.end = end;
        self.lines.push(line);
        self.x = Length::ZERO;
        self.thai = ThaiText::None;
        self.shrink = Length::ZERO;
        self.spaces = Length::ZERO;
        self.space_count = 0;
        self.stretching = false;
        self.counted = Length::ZERO;
        self.room = Length::ZERO;
        self.blank = Halves::default();
        self.hyphen_lines = if std::mem::take(&mut self.ends_at_point) {
            self.hyphen_lines + 1
        } else {
            0
        };
    }

    fn width(&self) -> Length {
        if self.on_first_line() {
            self.frame.first_width
        } else {
            self.frame.width
        }
    }

    fn start(&self) -> Length {
        if self.on_first_line() {
            self.frame.first_start
        } else {
            self.frame.start
        }
    }

    /// Whether the line that the breaker fills is the paragraph's first: the first line of all,
    /// or, where the frame starts the first line after leading page breaks
    /// ([`LineBreaking::leading_breaks`]), the line after the first of them or after all of
    /// them.
    fn on_first_line(&self) -> bool {
        let before = self
            .frame
            .breaking
            .leading_breaks
            .before_first_line(self.lines.len());
        self.lines.len() == before && self.lines.iter().all(Line::holds_only_page_break)
    }

    /// Whether a tab here would move from inside the line to a stop past its end, on a line
    /// that holds something: a default stop, or a custom left stop, not the hanging indent,
    /// where the frame's [`LineBreaking::left_stops_to_line_end`] says so. Such a tab starts the next line, and so does a tab after
    /// spaces that have run past the end. A line that already runs past its end, after a custom
    /// stop there, keeps its tabs.
    fn stop_past_end(&self) -> bool {
        let absolute = self.start() + self.x;
        let end = self.start() + self.width();
        let (stop, default) = self.frame.tabs.next_stop(absolute);
        let past = if absolute <= end {
            stop.position > end
        } else {
            self.room == Length::ZERO
        };
        let moves = default || self.left_stop_to_line_end(stop);
        moves && !self.line.placed.is_empty() && past
    }

    /// The stop that a tab goes to: `stop`, or, for a tab to a custom left stop past the line's
    /// end that the frame's [`LineBreaking::left_stops_to_line_end`] sends to the line's end, a stop of the same kind
    /// and leader at the line's end.
    fn stop_or_line_end(&self, piece: &Piece, stop: TabStop, end: Length) -> TabStop {
        if matches!(piece, Piece::Tab(_)) && stop.position > end && self.left_stop_to_line_end(stop)
        {
            TabStop {
                position: end,
                ..stop
            }
        } else {
            stop
        }
    }

    /// Whether `stop` is a custom left stop, not the hanging indent, that the frame's
    /// [`LineBreaking::left_stops_to_line_end`] sends to the line's end when it lies past it.
    fn left_stop_to_line_end(&self, stop: TabStop) -> bool {
        // quirk: LeftStopPastEnd (src/quirks.rs)
        stop.kind == TabKind::Left
            && self.frame.tabs.is_custom(stop)
            && self.frame.breaking.left_stops_to_line_end
    }

    fn place_tab(&mut self, piece: Piece, after: &[Piece]) {
        let absolute = self.start() + self.x;
        // A positional tab goes to its own stop, whatever the tab stops of the paragraph.
        let stop = match piece {
            Piece::PositionTab(_, stop) => stop,
            _ => self.frame.tabs.next(absolute),
        };
        let end = self.start() + self.width();
        let stop = self.stop_or_line_end(&piece, stop, end);
        let gap = stop.position - absolute;
        // The line may run on up to a stop that lies past its end, which lets the text after a
        // right, center or decimal stop line up there.
        self.room = self.room.max(stop.position - end);
        let at_stop = match stop.kind {
            TabKind::Right => gap - following_width(after, None),
            TabKind::Center => gap - following_width(after, None).div_toward_zero(2),
            TabKind::Decimal => gap - following_width(after, Some('.')),
            TabKind::Left => gap,
        };
        // quirk: AlignedTabOverrun (src/quirks.rs)
        let advance = match stop.kind {
            TabKind::Right | TabKind::Center | TabKind::Decimal
                if self.frame.breaking.ends_aligned_text =>
            {
                // Text that would end past its limit from its stop, wherever the stop lies,
                // ends there instead, but never starts left of the tab. The limit is the end
                // of the text area for a stop past the line's end and inside the area, which
                // a right indent leaves between the two, and the line's end otherwise; the
                // line runs on to where the text ends, and never past the limit.
                let width = following_width(after, None);
                if stop.position >= end && !self.frame.limits_past_end {
                    let advance = at_stop.max(Length::ZERO);
                    self.room = self.room.max(absolute + advance + width - end);
                    advance
                } else {
                    let limit = if stop.position > end && stop.position <= self.frame.area_width {
                        self.frame.area_width
                    } else {
                        end
                    };
                    let advance = at_stop.min(limit - absolute - width).max(Length::ZERO);
                    self.room = self.room.max((absolute + advance + width).min(limit) - end);
                    advance
                }
            }
            _ => at_stop,
        };
        self.push(piece, advance.max(Length::ZERO));
        if let Some(placed) = self.line.placed.last_mut() {
            placed.leader = stop.leader;
            placed.tab = Some(stop.kind);
        }
    }

    fn place_word(&mut self, pieces: &[Piece], i: usize) -> usize {
        let end = word_end(pieces, i, self.frame);
        let word = pieces.get(i..end).unwrap_or(&[]);
        let (_, visible) = widths(word);
        let ends = self.fitted_end_spaces(word, pieces.get(end));
        let visible = visible + ends.width;
        if self.thai != ThaiText::OnLine {
            self.thai = if word.iter().any(is_thai) {
                ThaiText::InWord
            } else {
                ThaiText::None
            };
        }
        let fit = self.fit_ending(visible, self.punctuation_over(word), ends);
        // Spaces that follow a word stay on its line, even one that runs past its width
        // because its spaces shrink, so that no wrapped line starts with them.
        let room = self
            .shrink
            .max(self.frame.shrink.of_natural(self.x).unwrap_or(Length::ZERO));
        let spaces = !self.line.hung && word.iter().all(is_space) && self.x <= self.width() + room;
        let overflows = self.line.hung || fit.end > fit.width + fit.over;
        if overflows && !spaces && self.place_hanging_word(word, visible) {
            return end;
        }
        if overflows
            && !spaces
            && !self.line.hung
            && let Some(point) = self.hyphen_point(word)
        {
            return i + self.place_to_point(word, point, fit);
        }
        if overflows && !self.line.placed.is_empty() && !spaces {
            // The tab immediately before a word that does not fit goes to the next line with it,
            // leaving earlier pieces (including earlier tabs) on this line.
            let tab = self.take_trailing_tab();
            settle_soft_hyphens(&mut self.line, tab.is_none());
            self.line.wrapped = Some(fit);
            // A word after a tab that goes to the next line with it is left out: the line's end
            // is no longer the word's start.
            self.line.would_hang = !self.line.hung && tab.is_none() && self.fits_before_hang(word);
            self.finish(LineEnd::Wrap);
            if let Some(tab) = tab {
                self.place_tab(tab, pieces.get(i..).unwrap_or(&[]));
            }
        }
        if self.x + visible > self.width() + self.trailing_trim_over(word)
            && self.line.placed.is_empty()
        {
            return i + self.place_split(word);
        }
        self.line.kept = Some(self.fit(visible));
        for piece in word {
            self.push(*piece, advance(piece));
        }
        end
    }

    /// The spaces at the end of `word` that count in its fit ([`Frame::end_space_fit`]).
    fn fitted_end_spaces(&self, word: &[Piece], next: Option<&Piece>) -> EndSpaces {
        if self.frame.end_space_fit == EndSpaceFit::WithoutSpaces
            || !self.line.holds_left_to_right_text()
        {
            return EndSpaces::default();
        }
        let Some(last) = word.iter().rposition(|piece| !is_space(piece)) else {
            return EndSpaces::default();
        };
        let letter = |piece: Option<&Piece>| {
            piece
                .and_then(run_glyph)
                .is_some_and(|glyph| right_to_left(glyph.ch))
        };
        let between = self.frame.end_space_fit.between_letters(&self.line)
            && letter(word.get(last))
            && letter(next);
        let start = EndSpaces {
            starts_right_to_left: letter(word.first()),
            ..EndSpaces::default()
        };
        word.iter()
            .skip(last + 1)
            .take_while(|piece| is_space(piece) && (between || run_rtl(piece) == Some(true)))
            .fold(start, |ends, piece| EndSpaces {
                width: ends.width + advance(piece) + counted(piece),
                count: ends.count + 1,
                shrink: ends.shrink + self.frame.shrink.of(advance(piece)),
                ..ends
            })
    }

    /// The index in `word`, which does not fit, of its last automatic hyphenation point whose
    /// part, with the hyphen, fits on the line, where the line may end at a point: after fewer
    /// lines in a row that end at a point than the limit, and where the zone holds, when the
    /// room that the line leaves for the word is wider than the zone.
    fn hyphen_point(&self, word: &[Piece]) -> Option<usize> {
        let rules = self.frame.hyphenation?;
        if rules
            .limit
            .is_some_and(|limit| self.hyphen_lines >= limit.get())
        {
            return None;
        }
        if rules.zone.is_some_and(|zone| self.width() - self.x <= zone) {
            return None;
        }
        (0..word.len()).rev().find(|&k| {
            let Some(part) = word.get(..=k).filter(
                |part| matches!(part.last(), Some(Piece::Glyph(g)) if g.ch == AUTOMATIC_HYPHEN),
            ) else {
                return false;
            };
            let (_, visible) = widths(part);
            let fit = self.fit_with(visible, self.punctuation_over(part));
            fit.end <= fit.width + fit.over
        })
    }

    /// Places the part of `word` up to its automatic hyphenation point at `point`, which shows
    /// a hyphen, and ends the line there. Returns the count of pieces placed. `wrapped` is the
    /// decision that the whole word did not fit.
    fn place_to_point(&mut self, word: &[Piece], point: usize, wrapped: Fit) -> usize {
        let part = word.get(..=point).unwrap_or(&[]);
        let (_, visible) = widths(part);
        self.line.kept = Some(self.fit_with(visible, self.punctuation_over(part)));
        for piece in part {
            self.push(*piece, advance(piece));
        }
        settle_soft_hyphens(&mut self.line, true);
        self.line.wrapped = Some(wrapped);
        self.ends_at_point = true;
        self.finish(LineEnd::Wrap);
        part.len()
    }

    /// Keeps `word` on the current line with its trailing mark hanging past the right margin when
    /// hanging punctuation is enabled (`OverflowPunct::Hang`), the line is not already hung, no
    /// trailing tab sits right before `word`, and the pieces before the mark fit without shrinking
    /// spaces.
    fn place_hanging_word(&mut self, word: &[Piece], visible: Length) -> bool {
        if self.frame.overflow_punct != OverflowPunct::Hang
            || self.line.hung
            || self.has_trailing_tab()
            || !self.fits_before_hang(word)
        {
            return false;
        }
        self.line.kept = Some(self.fit(visible));
        for piece in word {
            self.push(*piece, advance(piece));
        }
        self.line.hung = true;
        true
    }

    /// The pieces of `word` before a trailing mark matched by `Kinsoku::hangs`, or `None`.
    /// Checks the mark glyph's own run `w:lang w:eastAsia` when present (so an explicit
    /// non-East-Asian run language disables hanging, and an explicit East Asian run language
    /// activates its script's hanging set under `OverflowPunct::Hang`).
    fn hanging_prefix<'w>(&self, word: &'w [Piece]) -> Option<&'w [Piece]> {
        if self.frame.overflow_punct == OverflowPunct::Off {
            return None;
        }
        let last = word.iter().rposition(|piece| !is_space(piece))?;
        let (Some(Piece::Glyph(mark)), Some(rest)) = (word.get(last), word.get(..last)) else {
            return None;
        };
        let hangs = match (self.frame.overflow_punct, mark.east_asian_language) {
            (_, Some(EastAsianLanguage::NonEastAsian)) => false,
            (OverflowPunct::Hang, Some(EastAsianLanguage::Script(script))) => {
                Kinsoku::of(script).hangs(mark.ch)
            }
            _ => self.frame.kinsoku.is_some_and(|k| k.hangs(mark.ch)),
        };
        hangs.then_some(rest)
    }

    /// Whether `word` ends with a hanging punctuation mark and its preceding pieces fit within
    /// the line's width, tab room, space shrink, and punctuation compression.
    fn fits_before_hang(&self, word: &[Piece]) -> bool {
        let Some(rest) = self.hanging_prefix(word) else {
            return false;
        };
        let (_, visible) = widths(rest);
        let fit = self.fit_with(visible, self.punctuation_over(rest));
        fit.end <= fit.width + fit.over
    }

    /// Whether a trailing tab sits at the end of the line after at least one earlier piece.
    fn has_trailing_tab(&self) -> bool {
        self.line.placed.len() >= 2
            && matches!(
                self.line.placed.last().map(|p| &p.piece),
                Some(Piece::Tab(_) | Piece::PositionTab(..))
            )
    }

    /// The numbers of the decision whether a word of visible width `word` fits after the
    /// pieces placed so far.
    fn fit(&self, word: Length) -> Fit {
        self.fit_with(word, Length::ZERO)
    }

    /// How far the line may run past its width for `word` because a trailing full-width closing
    /// mark gives up its blank right half at line end.
    fn trailing_trim_over(&self, word: &[Piece]) -> Length {
        self.frame
            .punctuation
            .and_then(|c| trailing_closing_half(word, c.trailing_trim))
            .map_or(Length::ZERO, |(_, half)| half)
    }

    /// How far the line may run past its width for `word` because its punctuation, `word`'s
    /// own included, shrinks.
    fn punctuation_over(&self, word: &[Piece]) -> Length {
        let Some(compression) = self.frame.punctuation else {
            return Length::ZERO;
        };
        let (rest, trimmed) = match trailing_closing_half(word, compression.trailing_trim) {
            Some((last, half)) => (word.get(..last).unwrap_or(&[]), half),
            None => (word, Length::ZERO),
        };
        let inner = compression.over(
            self.blank.and(Halves::of(rest, compression.middle_dot)),
            self.stretch(),
        );
        trimmed + inner
    }

    /// The room that the line leaves when it ends here, and the gaps that it stretches over:
    /// its spaces after the last tab, or the full-width-adjacent glyph gaps after the last tab
    /// when it has no spaces.
    fn stretch(&self) -> (Length, i64) {
        let first = self.line.first_stretched();
        let placed = self.line.placed.get(first..).unwrap_or(&[]);
        let spaces =
            i64::try_from(placed.iter().filter(|p| is_space(&p.piece)).count()).unwrap_or(0);
        let gaps = if spaces > 0 {
            spaces
        } else {
            let full_width = |p: &Placed| matches!(p.piece, Piece::Glyph(g) if CharacterClass::FullWidthCell.contains(g.ch));
            let labeled = |p: &Placed| matches!(p.piece, Piece::Glyph(g) if g.label);
            i64::try_from(
                placed
                    .windows(2)
                    .filter(|pair| {
                        let (Some(a), Some(b)) = (pair.first(), pair.get(1)) else {
                            return false;
                        };
                        !labeled(a) && !labeled(b) && (full_width(a) || full_width(b))
                    })
                    .count(),
            )
            .unwrap_or(0)
        };
        let end_gap = match self.line.placed.last().map(|p| &p.piece) {
            Some(Piece::Glyph(g)) => g.trailing_auto_space,
            _ => Length::ZERO,
        };
        (self.width() - (self.x - end_gap), gaps)
    }

    /// [`Breaker::fit`] for a word whose line may run `punctuation` past its width because
    /// its punctuation shrinks.
    fn fit_with(&self, word: Length, punctuation: Length) -> Fit {
        self.fit_ending(word, punctuation, EndSpaces::default())
    }

    /// [`Breaker::fit_with`] for a word whose fit counts the spaces `ends` at its end.
    fn fit_ending(&self, word: Length, punctuation: Length, ends: EndSpaces) -> Fit {
        // A word holds no space before its end, so only the spaces placed so far may shrink,
        // and the spaces right before it only when they stretch. The space of an operator
        // right before a term of an equation hangs where the line would end without the term,
        // so it counts in the room that the line leaves then, but as no space of the line.
        let last: Vec<&Placed> = self
            .line
            .placed
            .iter()
            .rev()
            .take_while(|p| self.stretching && (is_space(&p.piece) || is_operator_space(&p.piece)))
            .collect();
        let space: Length = last.iter().map(|p| p.advance).sum();
        let last_space_count = last.iter().filter(|p| is_space(&p.piece)).count();
        let end = self.x + self.counted + word;
        let kept = self.frame.thai_keeps_spaces && self.thai != ThaiText::None;
        let over = if kept {
            Length::ZERO
        } else {
            self.frame
                .shrink
                .of_natural(end)
                .unwrap_or_else(|| self.shrink_over(&last, (space, word), last_space_count, ends))
        };
        Fit {
            width: self.width(),
            end,
            word,
            spaces: self.spaces,
            space,
            space_count: self.space_count,
            last_space_count,
            room: self.room,
            over: over + self.room + punctuation,
            shrinks: !kept && (self.frame.shrink.permille > 0 || self.frame.shrink.natural.1 > 0),
        }
    }

    /// How far the line may run past its width because its spaces shrink ([`Shrink::over`]),
    /// for `word` after the spaces `last`, `last_count` of them spaces of width `space`, with
    /// the spaces `ends` at its end that count in its fit. Where the line counts right-to-left
    /// spaces beside text of a run without `w:rtl` ([`EndSpaceFit::WithRightToLeftSpaces`]),
    /// they are spaces of the line: those at the word's end shrink as its other spaces, and
    /// those right before the word, of runs with `w:rtl` or between right-to-left letters, stay
    /// written text of the line without the word, so that they leave it no room and are among
    /// its gaps.
    fn shrink_over(
        &self,
        last: &[&Placed],
        (space, word): (Length, Length),
        last_count: usize,
        ends: EndSpaces,
    ) -> Length {
        let rtl_before = last.iter().all(|p| run_rtl(&p.piece) == Some(true));
        let letters_before = self.frame.end_space_fit.between_letters(&self.line)
            && ends.starts_right_to_left
            && self
                .line
                .placed
                .iter()
                .rev()
                .find(|p| !is_space(&p.piece))
                .and_then(|p| run_glyph(&p.piece))
                .is_some_and(|glyph| right_to_left(glyph.ch));
        let kept_before = self.frame.end_space_fit != EndSpaceFit::WithoutSpaces
            && (rtl_before || letters_before)
            && !last.is_empty()
            && self.line.holds_left_to_right_text();
        let (space, hanging) = if kept_before {
            (Length::ZERO, 0)
        } else {
            (space, last_count)
        };
        let joints = if self.frame.shrink.joints == JointGaps::default() {
            JointCounts::default()
        } else {
            joints::joint_counts(&self.line.placed)
        };
        self.frame.shrink.over(
            self.shrink + ends.shrink,
            (space, word),
            (self.space_count + ends.count, hanging + ends.count),
            joints,
        )
    }

    /// Removes the last tab at the end of the line when at least one piece stays before it.
    fn take_trailing_tab(&mut self) -> Option<Piece> {
        if self.line.placed.len() >= 2
            && matches!(
                self.line.placed.last().map(|p| &p.piece),
                Some(Piece::Tab(_) | Piece::PositionTab(..))
            )
        {
            let tab = self.line.placed.pop()?;
            self.x = tab.x;
            Some(tab.piece)
        } else {
            None
        }
    }

    /// Places as many glyphs of an overlong word as fit, and at least one. The line ends when
    /// the rest of the word goes to the next line. A word that is placed whole, such as one
    /// inline picture wider than the line, keeps the line open, so that a paragraph that ends
    /// there gets no empty line after it.
    fn place_split(&mut self, word: &[Piece]) -> usize {
        let mut placed = 0;
        for piece in word {
            let a = advance(piece);
            let end_gap = match piece {
                Piece::Glyph(g) => g.trailing_auto_space,
                _ => Length::ZERO,
            };
            if placed > 0 && self.x + self.counted + a - end_gap + counted(piece) > self.width() {
                break;
            }
            self.push(*piece, a);
            placed += 1;
        }
        if placed < word.len() {
            self.finish(LineEnd::Split);
        }
        placed
    }

    fn push(&mut self, piece: Piece, advance: Length) {
        self.line.placed.push(Placed {
            piece,
            x: self.x,
            advance,
            leader: None,
            tab: None,
        });
        self.x += advance;
        if is_thai(&piece) {
            self.thai = ThaiText::OnLine;
        }
        // Only the spaces and punctuation that a justified line stretches may shrink: a tab starts
        // the count again, and spaces count from the first piece after it that is not a space.
        if matches!(piece, Piece::Tab(_) | Piece::PositionTab(..)) {
            self.shrink = Length::ZERO;
            self.spaces = Length::ZERO;
            self.space_count = 0;
            self.stretching = false;
            self.counted = Length::ZERO;
            self.blank = Halves::default();
        } else if !is_space(&piece) {
            self.stretching = true;
        } else if self.stretching {
            self.shrink += self.frame.shrink.of(advance);
            self.spaces += advance;
            self.space_count += 1;
        }
        self.counted += counted(&piece);
        let include_middle_dot = self.frame.punctuation.is_some_and(|c| c.middle_dot);
        self.blank = self.blank.and(Halves::of(&[piece], include_middle_dot));
    }
}

/// The end of the word that starts at `i`: its other glyphs, then the spaces after it. A word
/// also ends after a hyphen-minus, U+2010 HYPHEN, an en dash or an em dash, and after the space
/// of an operator where an equation may break ([`SpaceKind::Operator`]), when no more of that
/// space follows.
fn word_end(pieces: &[Piece], i: usize, frame: &Frame) -> usize {
    let mut j = i;
    loop {
        match pieces.get(j) {
            Some(Piece::Glyph(g))
                if g.ch != ' ' || matches!(g.space, SpaceKind::Equation | SpaceKind::Assembly) =>
            {
                j += 1;
                if (g.space == SpaceKind::Operator && !pieces.get(j).is_some_and(is_operator_space))
                    || ends_word_after(g, pieces.get(j), frame.kinsoku)
                {
                    return j;
                }
            }
            // The parts of a stacked fraction stay on one line, and a note's own mark with the
            // text after it.
            Some(
                Piece::Shift(_)
                | Piece::Bar { .. }
                | Piece::Vinculum { .. }
                | Piece::Diagonal { .. }
                | Piece::Endnote(_)
                | Piece::NoteMarkEnd
                | Piece::EndnoteMarkEnd(_),
            ) => j += 1,
            // A single inline VML vector shape attaches to the word before it and allows a break
            // after it.
            Some(
                Piece::Object {
                    joins_before: true, ..
                }
                | Piece::Advance(_),
            ) => return j + 1,
            // A footnote reference's mark is text of its word, where the quirk says so: the
            // word goes on after it unless its last glyph and the next piece allow a break.
            // quirk: NoteReferenceBreak (src/quirks.rs)
            Some(Piece::Note(_)) if frame.breaking.note_reference_in_word => {
                j += 1;
                let before = j.checked_sub(2).and_then(|k| pieces.get(k));
                if let Some(Piece::Glyph(g)) = before
                    && ends_word_after(g, pieces.get(j), frame.kinsoku)
                {
                    return j;
                }
            }
            // A joined space run keeps the word after it on the line of this one.
            Some(_) if frame.joined_spaces && joins(pieces, (i, j)) => j = spaces_end(pieces, j),
            _ => break,
        }
    }
    spaces_end(pieces, j).max(i + 1)
}

/// The width of the widest word of `pieces` without its trailing spaces, with the words that
/// the line breaks of `frame` find: the narrowest line that holds each word whole.
#[must_use]
pub(crate) fn widest_word(pieces: &[Piece], frame: &Frame) -> Length {
    let mut widest = Length::ZERO;
    let mut start = 0;
    while start < pieces.len() {
        let end = word_end(pieces, start, frame);
        widest = widest.max(widths(pieces.get(start..end).unwrap_or_default()).1);
        start = end;
    }
    widest
}

/// The end of the spaces that start at `j`.
fn spaces_end(pieces: &[Piece], mut j: usize) -> usize {
    while matches!(pieces.get(j), Some(p) if is_space(p)) {
        j += 1;
    }
    j
}

/// Whether the spaces at `j`, of the word that starts at `i`, belong to a joined space run:
/// the glyph of the word before them or the first glyph after them is a no-break space.
fn joins(pieces: &[Piece], (i, j): (usize, usize)) -> bool {
    let no_break =
        |piece: Option<&Piece>| matches!(piece, Some(Piece::Glyph(g)) if g.ch == NO_BREAK_SPACE);
    let before = j > i && no_break(j.checked_sub(1).and_then(|k| pieces.get(k)));
    pieces.get(j).is_some_and(is_space) && (before || no_break(pieces.get(spaces_end(pieces, j))))
}

/// Whether a word ends after a glyph: after a hyphen or a dash, or where East Asian text
/// may break before the next piece.
fn ends_word_after(before: &Glyph, next: Option<&Piece>, kinsoku: Option<Kinsoku>) -> bool {
    if matches!(
        before.ch,
        '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | SOFT_HYPHEN
    ) {
        return true;
    }
    let Some(Piece::Glyph(next)) = next else {
        return false;
    };
    if next.ch == ' ' {
        return false;
    }
    let kinsoku = kinsoku.map(|k| k.for_pair(before.east_asian_language, next.east_asian_language));
    breaks_between(before.ch, next.ch, kinsoku)
}

/// Whether a character is a place where a word may break with a hyphen that shows only at the
/// end of a line: a soft hyphen or an automatic hyphenation point.
const fn is_hyphen_point(ch: char) -> bool {
    matches!(ch, SOFT_HYPHEN | AUTOMATIC_HYPHEN)
}

/// The full width and the width without trailing spaces, each with what the fit test counts
/// beside the advances ([`counted`]). The space of an operator where an equation may break
/// trails as a space does. A word that ends with a soft hyphen or an automatic
/// hyphenation point needs the hyphen's width as well, for the line may end there.
fn widths(word: &[Piece]) -> (Length, Length) {
    let total: Length = word.iter().map(|p| advance(p) + counted(p)).sum();
    let trailing: Length = word
        .iter()
        .rev()
        .take_while(|p| is_space(p) || is_operator_space(p))
        .map(|p| advance(p) + counted(p))
        .sum();
    let last_auto_space = match word.last() {
        Some(Piece::Glyph(g)) => g.trailing_auto_space,
        _ => Length::ZERO,
    };
    let hyphen = match word.last() {
        Some(Piece::Glyph(g)) if is_hyphen_point(g.ch) => g.advance,
        _ => Length::ZERO,
    };
    (total, total - trailing - last_auto_space + hyphen)
}

/// Drops any East Asian / Latin or digit auto-space (`w:autoSpaceDE` / `w:autoSpaceDN`) from the
/// last placed glyph of a finished line, since the following character moved to the next line.
fn strip_trailing_auto_space(line: &mut Line) {
    if let Some(last) = line.placed.last_mut()
        && let Piece::Glyph(g) = &mut last.piece
        && g.trailing_auto_space > Length::ZERO
    {
        let gap = g.trailing_auto_space;
        g.advance -= gap;
        last.advance -= gap;
        if g.auto_space > Length::ZERO {
            g.auto_space = (g.auto_space - gap).max(Length::ZERO);
        }
        g.trailing_auto_space = Length::ZERO;
    }
}

/// Shows a soft hyphen at the end of a line as a hyphen-minus with its width, and an automatic
/// hyphenation point there as [`LINE_END_HYPHEN`], and records which the line shows; and drops
/// those inside the line, which show nothing.
fn settle_soft_hyphens(line: &mut Line, wrapped: bool) {
    if wrapped
        && let Some(last) = line.placed.last_mut()
        && let Piece::Glyph(g) = &mut last.piece
        && is_hyphen_point(g.ch)
    {
        let hyphen = if g.ch == AUTOMATIC_HYPHEN {
            g.ch = LINE_END_HYPHEN;
            EndHyphen::Automatic
        } else {
            g.ch = '-';
            EndHyphen::Soft
        };
        last.advance = g.advance;
        line.hyphen = Some(hyphen);
    }
    line.placed
        .retain(|p| !matches!(p.piece, Piece::Glyph(g) if is_hyphen_point(g.ch)));
}

/// The width of the text and inline objects after a tab, up to the next tab or break and without
/// trailing spaces, with what the fit test counts beside the advances ([`counted`]). With a
/// decimal character, the width stops before its first occurrence.
pub(crate) fn following_width(after: &[Piece], decimal: Option<char>) -> Length {
    let mut total = Length::ZERO;
    let mut visible = Length::ZERO;
    for piece in after {
        match piece {
            Piece::Glyph(glyph) => {
                if Some(glyph.ch) == decimal {
                    return total;
                }
                total += glyph.advance + glyph.counted;
                if glyph.ch != ' ' {
                    visible = total;
                }
            }
            Piece::Object { width, .. } => {
                total += *width;
                visible = total;
            }
            _ => break,
        }
    }
    if decimal.is_some() { total } else { visible }
}

/// What the fit test counts beside the advance of `piece`: a glyph's [`Glyph::counted`], and
/// nothing for a hyphenation point or another piece.
const fn counted(piece: &Piece) -> Length {
    match piece {
        Piece::Glyph(g) if !is_hyphen_point(g.ch) => g.counted,
        _ => Length::ZERO,
    }
}

pub(crate) const fn advance(piece: &Piece) -> Length {
    match piece {
        Piece::Glyph(g) if is_hyphen_point(g.ch) => Length::ZERO,
        Piece::Glyph(g) => g.advance,
        Piece::Shift(length) | Piece::Advance(length) => *length,
        Piece::Object { width, .. } | Piece::Rule { width, .. } | Piece::CheckBox { width, .. } => {
            *width
        }
        Piece::Bar { .. }
        | Piece::Vinculum { .. }
        | Piece::Diagonal { .. }
        | Piece::Tab(_)
        | Piece::PositionTab(..)
        | Piece::LineBreak(_)
        | Piece::PageBreak
        | Piece::ColumnBreak
        | Piece::Note(_)
        | Piece::Endnote(_)
        | Piece::NoteMarkEnd
        | Piece::EndnoteMarkEnd(_)
        | Piece::Comment(_)
        | Piece::Anchor(_)
        | Piece::Strut(_)
        | Piece::Clear => Length::ZERO,
    }
}

/// If `word`'s last non-space piece is a full-width closing mark matched by `trim`, returns its
/// index in `word` and its blank right half (`advance / 2`).
fn trailing_closing_half(word: &[Piece], trim: TrailingTrim) -> Option<(usize, Length)> {
    if trim == TrailingTrim::None {
        return None;
    }
    let last = word.iter().rposition(|piece| !is_space(piece))?;
    match word.get(last) {
        Some(Piece::Glyph(mark)) if mark.punctuation_half.is_open() && trim.trims(mark.ch) => {
            Some((
                last,
                mark.punctuation_half
                    .full_em(mark.advance)
                    .div_toward_zero(2),
            ))
        }
        _ => None,
    }
}

/// Whether a character is a full-width punctuation mark whose right half is blank, such as a
/// closing bracket or an ideographic comma.
#[must_use]
pub fn closing_mark(ch: char) -> bool {
    matches!(
        ch,
        '\u{3001}'
            | '\u{3002}'
            | '\u{FF0C}'
            | '\u{FF0E}'
            | '\u{FF1A}'
            | '\u{FF1B}'
            | '\u{FF01}'
            | '\u{300D}'
            | '\u{300F}'
            | '\u{FF09}'
            | '\u{3011}'
            | '\u{3015}'
            | '\u{3009}'
            | '\u{300B}'
            | '\u{FF5D}'
            | '\u{FF3D}'
    )
}

/// Whether a character is a full-width punctuation mark that Traditional Chinese places in the
/// middle of its em, with a blank quarter on each side: the comma, the enumeration comma, the
/// full stop, the semicolon and the colon. Other scripts place them at the left of the em.
#[must_use]
pub const fn centered_mark(ch: char) -> bool {
    matches!(
        ch,
        '\u{FF0C}' | '\u{3001}' | '\u{3002}' | '\u{FF1B}' | '\u{FF1A}'
    )
}

/// Whether a character is a full-width punctuation mark that Japanese places in the middle of its
/// em, with a blank quarter on each side: the colon, the semicolon and the middle dot.
#[must_use]
pub const fn japanese_centered_mark(ch: char) -> bool {
    matches!(ch, '\u{FF1A}' | '\u{FF1B}' | '\u{30FB}')
}

/// Whether a character is the Katakana middle dot (`・`), which carries a compressible blank half
/// (two blank quarters) in Japanese.
#[must_use]
pub const fn middle_dot(ch: char) -> bool {
    ch == '\u{30FB}'
}

/// Whether a character is a full-width punctuation mark whose left half is blank, such as an
/// opening bracket.
#[must_use]
pub fn opening_mark(ch: char) -> bool {
    matches!(
        ch,
        '\u{300C}'
            | '\u{300E}'
            | '\u{FF08}'
            | '\u{3010}'
            | '\u{3014}'
            | '\u{3008}'
            | '\u{300A}'
            | '\u{FF5B}'
            | '\u{FF3B}'
    )
}

/// Which mark of a kerned East Asian punctuation pair gave up its blank half.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum KernedMark {
    /// The first mark had a blank right half and gave it up (`」,`, `),`, `」「`, `)(`, `,「`).
    Left,
    /// The second mark was an opening bracket and gave up its blank left half (`「「`, `,「` in
    /// Traditional Chinese).
    Right,
}

/// Which mark of the pair `(left, right)` gives up its blank half when a kerned run closes up
/// the pair of East Asian punctuation marks by half an em under the run's East Asian `script`
/// (`w:lang w:eastAsia`), or `None` when the pair does not kern: `left` has a blank right half or
/// `right` is an opening bracket, and both are marks for that script.
///
/// - Opening and closing brackets always qualify, even when `script` is `None`.
/// - Stops (`,`, `。`, `、`, `.`) have a blank right half in Simplified Chinese and Japanese,
///   stand in the middle in Traditional Chinese, and do not close up without an East Asian
///   script.
/// - Colon and semicolon (`:`, `;`) have a blank right half in Simplified Chinese and stand in
///   the middle in Japanese and Traditional Chinese.
/// - Exclamation (`!`) has a blank right half in Simplified Chinese only.
/// - Middle dot (`・`) stands in the middle in Japanese only.
/// - Question mark (`?`) never closes up.
#[must_use]
pub(crate) fn kerned_pair(
    left: char,
    right: char,
    script: Option<crate::props::EastAsianScript>,
) -> Option<KernedMark> {
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum Kind {
        Opening,
        Closing,
        Middle,
    }
    let kind = |ch: char| -> Option<Kind> {
        use crate::props::EastAsianScript::{Japanese, Simplified, Traditional};
        if opening_mark(ch) {
            return Some(Kind::Opening);
        }
        if matches!(
            ch,
            '\u{300D}'
                | '\u{300F}'
                | '\u{FF09}'
                | '\u{3011}'
                | '\u{3015}'
                | '\u{3009}'
                | '\u{300B}'
                | '\u{FF5D}'
                | '\u{FF3D}'
        ) {
            return Some(Kind::Closing);
        }
        match (ch, script) {
            ('\u{3001}' | '\u{3002}' | '\u{FF0C}' | '\u{FF0E}', Some(Simplified | Japanese))
            | ('\u{FF01}' | '\u{FF1A}' | '\u{FF1B}', Some(Simplified)) => Some(Kind::Closing),
            ('\u{3001}' | '\u{3002}' | '\u{FF0C}' | '\u{FF0E}', Some(Traditional))
            | ('\u{FF1A}' | '\u{FF1B}', Some(Japanese | Traditional))
            | ('\u{30FB}', Some(Japanese)) => Some(Kind::Middle),
            _ => None,
        }
    };
    match (kind(left), kind(right)) {
        (Some(Kind::Closing), Some(_)) => Some(KernedMark::Left),
        (Some(_), Some(Kind::Opening)) => Some(KernedMark::Right),
        _ => None,
    }
}

/// Whether a piece is a space glyph that a line may break at and stretch: not an equation
/// space ([`SpaceKind::Equation`]).
#[must_use]
pub fn is_space(piece: &Piece) -> bool {
    matches!(piece, Piece::Glyph(g) if g.ch == ' ' && g.space == SpaceKind::Free)
}

/// Whether a piece is a space that a justified line stretches or shrinks: a space of
/// [`is_space`], or a no-break space that takes a plain space's share ([`SpaceKind::NoBreak`]).
#[must_use]
pub fn stretches(piece: &Piece) -> bool {
    is_space(piece) || matches!(piece, Piece::Glyph(g) if g.space == SpaceKind::NoBreak)
}

/// Whether a piece is the space of an operator where an equation may break
/// ([`SpaceKind::Operator`]).
fn is_operator_space(piece: &Piece) -> bool {
    matches!(piece, Piece::Glyph(g) if g.space == SpaceKind::Operator)
}

/// The glyph of a piece that is text of a run; none for a list label, which is not a run of
/// the text and keeps its UAX 9 classes, and for a piece that is no glyph.
pub(crate) const fn run_glyph(piece: &Piece) -> Option<&Glyph> {
    match piece {
        Piece::Glyph(glyph) if !glyph.label => Some(glyph),
        _ => None,
    }
}

/// Whether a piece is text of a run with `w:rtl`; none for a piece that is no text of a run.
pub(crate) fn run_rtl(piece: &Piece) -> Option<bool> {
    run_glyph(piece).map(|glyph| glyph.direction.class().is_some())
}

/// Whether a character is written from right to left, such as Hebrew or Arabic.
pub(crate) fn right_to_left(ch: char) -> bool {
    matches!(
        unicode_bidi::bidi_class(ch),
        unicode_bidi::BidiClass::R | unicode_bidi::BidiClass::AL
    )
}

/// Whether a character is a left-to-right letter, such as a Latin one.
fn left_to_right(ch: char) -> bool {
    unicode_bidi::bidi_class(ch) == unicode_bidi::BidiClass::L
}

#[cfg(test)]
mod tests {
    use super::{
        EndHyphen, EndSpaceFit, Frame, Hyphenation, JointCounts, JointGaps, LeadingBreaks, Line,
        LineBreaking, LineEnd, NoteNumber, Piece, Shrink, break_lines, following_width, is_space,
    };
    use crate::props::{TabKind, TabStop};
    use crate::quirks::{AlignedTabOverrun, LeftStopPastEnd, NoteReferenceBreak};
    use crate::tabs::Tabs;
    use crate::text::AUTOMATIC_HYPHEN;
    use crate::text::{FaceIndex, Glyph, SpaceKind};
    use f_office_units::Length;

    #[test]
    fn keeps_a_footnote_s_place_from_zero() {
        assert_eq!(NoteNumber::of_index(4).index(), 4);
    }

    fn glyphs(text: &str) -> Vec<Piece> {
        text.chars()
            .map(|ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch)))
            .collect()
    }

    /// The pieces of `text`, of 10 units each, whose glyphs from the `first` on belong to a
    /// run with `w:rtl`.
    fn marked_from(text: &str, first: usize) -> Vec<Piece> {
        let mut pieces = glyphs(text);
        for piece in pieces.iter_mut().skip(first) {
            if let Piece::Glyph(glyph) = piece {
                glyph.direction = crate::text::RunDirection::of(true, None);
            }
        }
        pieces
    }

    #[test]
    fn fits_a_word_with_its_rtl_end_spaces_beside_left_to_right_text() {
        // "ab" in a run without `w:rtl`, then Hebrew words in a run with `w:rtl`. The third
        // word ends at 80 units and its space at 90: it fits a line of 85 only without it.
        let mixed = marked_from("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}", 3);
        let fitted = |width| Frame {
            end_space_fit: EndSpaceFit::WithRightToLeftSpaces,
            ..frame(width)
        };
        assert_eq!(
            texts(&break_lines(&mixed, &frame(85))),
            ["ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "\u{5d4}\u{5d5}"]
        );
        assert_eq!(
            texts(&break_lines(&mixed, &fitted(85))),
            ["ab \u{5d0}\u{5d1} ", "\u{5d2}\u{5d3} \u{5d4}\u{5d5}"]
        );
        // The spaces between right-to-left letters count in the same way in runs without
        // `w:rtl`; a space before a Latin word does not.
        let plain = glyphs("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
        assert_eq!(
            texts(&break_lines(&plain, &fitted(85))),
            ["ab \u{5d0}\u{5d1} ", "\u{5d2}\u{5d3} \u{5d4}\u{5d5}"]
        );
        let latin_after = glyphs("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} cd");
        assert_eq!(
            texts(&break_lines(&latin_after, &fitted(85))),
            ["ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "cd"]
        );
        // A line of right-to-left text only fits its words without their spaces.
        let pure = marked_from("\u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}", 0);
        assert_eq!(
            texts(&break_lines(&pure, &fitted(55))),
            texts(&break_lines(&pure, &frame(55)))
        );
        // So does one without `w:rtl`, which holds no left-to-right letter: the second word ends
        // at 50 and the space after it at 60.
        let plain_only = glyphs("\u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
        assert_eq!(
            texts(&break_lines(&plain_only, &fitted(55))),
            ["\u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "\u{5d4}\u{5d5}"]
        );
    }

    #[test]
    fn counts_kept_rtl_spaces_as_spaces_of_a_justified_line() {
        // Four Latin words, then Hebrew words in a run with `w:rtl`, each piece 10 units; each
        // space may shrink by 2. The third Hebrew word ends at 180 with its space.
        let mixed = marked_from(
            "ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}",
            12,
        );
        let justified = |width| Frame {
            shrink: Shrink {
                permille: 250,
                stretch_permille: 500,
                natural: (0, 0),
                joints: JointGaps::default(),
            },
            end_space_fit: EndSpaceFit::WithRightToLeftSpaces,
            ..frame(width)
        };
        let fitted = [
            "ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} ",
            "\u{5d4}\u{5d5}",
        ];
        let wrapped = [
            "ab cd ef gh \u{5d0}\u{5d1} ",
            "\u{5d2}\u{5d3} \u{5d4}\u{5d5}",
        ];
        // Its end space shrinks too: 6 spaces may shrink by 11 units, as half the stretch per
        // gap allows; without it, the 5 spaces before the word only by 10.
        assert_eq!(texts(&break_lines(&mixed, &justified(169))), fitted);
        // The space before the word is a gap of the line without it, and leaves it no room: by
        // the stretch, the spaces may not shrink by 12, as they could if it hung.
        assert_eq!(texts(&break_lines(&mixed, &justified(168))), wrapped);
        // The same holds for the spaces between right-to-left letters in runs without `w:rtl`.
        let plain = glyphs("ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
        assert_eq!(texts(&break_lines(&plain, &justified(169))), fitted);
        assert_eq!(texts(&break_lines(&plain, &justified(168))), wrapped);
        // On a line of right-to-left text only without `w:rtl`, which holds no left-to-right
        // letter, the spaces between its letters count in neither part.
        let only = glyphs(
            "\u{5e9}\u{5ea} \u{5e7}\u{5e8} \u{5e6}\u{5e4} \u{5e2}\u{5e1} \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}",
        );
        for width in 160..180 {
            let hanging = Frame {
                end_space_fit: EndSpaceFit::WithoutSpaces,
                ..justified(width)
            };
            assert_eq!(
                texts(&break_lines(&only, &justified(width))),
                texts(&break_lines(&only, &hanging)),
                "{width}"
            );
        }
    }

    fn frame(width: i64) -> Frame {
        Frame {
            first_width: Length::from_units(width),
            width: Length::from_units(width),
            area_width: Length::from_units(width),
            first_start: Length::ZERO,
            start: Length::ZERO,
            tabs: Tabs::new([], Length::from_units(25), None),
            shrink: Shrink::default(),
            thai_keeps_spaces: false,
            end_space_fit: EndSpaceFit::WithoutSpaces,
            kinsoku: None,
            joined_spaces: false,
            breaking: LineBreaking::default(),
            limits_past_end: true,
            punctuation: None,
            hyphenation: None,
            overflow_punct: super::OverflowPunct::Warn,
        }
    }

    fn texts(lines: &[Line]) -> Vec<String> {
        lines
            .iter()
            .map(|line| {
                line.placed
                    .iter()
                    .map(|p| match p.piece {
                        Piece::Glyph(g) => g.ch,
                        _ => '|',
                    })
                    .collect()
            })
            .collect()
    }

    #[test]
    fn anchor_marks_change_no_line_and_go_to_the_line_of_the_piece_after_them() {
        let text = glyphs("ab cd ef");
        // Marks before "a", inside "cd", before "ef" and after the last piece.
        let mut marked = text.clone();
        for (at, drawing) in [(8, 3), (6, 2), (4, 1), (0, 0)] {
            marked.insert(at, Piece::Anchor(drawing));
        }
        for width in [25, 45, 55, 100] {
            assert_eq!(
                texts(&break_lines(&marked, &frame(width))),
                texts(&break_lines(&text, &frame(width))),
                "{width}"
            );
        }
        let anchors = |lines: &[Line]| -> Vec<Vec<(usize, usize)>> {
            lines
                .iter()
                .map(|line| line.anchors.iter().map(|a| (a.at, a.drawing)).collect())
                .collect()
        };
        let lines = break_lines(&marked, &frame(55));
        assert_eq!(texts(&lines), ["ab cd ", "ef"]);
        assert_eq!(
            anchors(&lines),
            [vec![(0, 0), (4, 1)], vec![(0, 2), (2, 3)]]
        );
        // Lines broken again from their pieces keep their marks in their places.
        let again = break_lines(&Line::pieces(&lines), &frame(100));
        assert_eq!(anchors(&again), [vec![(0, 0), (4, 1), (6, 2), (8, 3)]]);
    }

    #[test]
    fn a_footnote_reference_as_text_keeps_the_closing_parenthesis_after_it_on_its_line() {
        let with = |note_reference_break| Frame {
            breaking: LineBreaking {
                note_reference_in_word: note_reference_break == NoteReferenceBreak::AsText,
                ..LineBreaking::default()
            },
            ..frame(65)
        };
        let mut pieces = glyphs("ab (c1");
        pieces.push(Piece::Note(NoteNumber::of_index(0)));
        pieces.extend(glyphs(") d"));
        assert_eq!(
            texts(&break_lines(&pieces, &with(NoteReferenceBreak::After))),
            ["ab (c1|", ") d"]
        );
        assert_eq!(
            texts(&break_lines(&pieces, &with(NoteReferenceBreak::AsText))),
            ["ab ", "(c1|) d"]
        );
        // A space after the mark still ends the word.
        let mut spaced = glyphs("ab c1");
        spaced.push(Piece::Note(NoteNumber::of_index(0)));
        spaced.extend(glyphs(" de"));
        assert_eq!(
            texts(&break_lines(&spaced, &with(NoteReferenceBreak::AsText))),
            ["ab c1| ", "de"]
        );
    }

    #[test]
    fn a_joined_space_run_keeps_the_words_on_both_of_its_sides_on_one_line() {
        let with = |joined_spaces| Frame {
            joined_spaces,
            ..frame(70)
        };
        // A no-break space then a space, a space then a no-break space, and both around one;
        // then plain spaces and a no-break space alone, which no mode changes.
        for (text, apart, together) in [
            (
                "aa bb\u{a0} cc",
                ["aa bb\u{a0} ", "cc"],
                ["aa ", "bb\u{a0} cc"],
            ),
            (
                "aa bb \u{a0}cc",
                ["aa bb ", "\u{a0}cc"],
                ["aa ", "bb \u{a0}cc"],
            ),
            (
                "aa b \u{a0} cc",
                ["aa b \u{a0} ", "cc"],
                ["aa ", "b \u{a0} cc"],
            ),
            ("aa bb  cc", ["aa bb  ", "cc"], ["aa bb  ", "cc"]),
            (
                "aa bb\u{a0}cc",
                ["aa ", "bb\u{a0}cc"],
                ["aa ", "bb\u{a0}cc"],
            ),
        ] {
            assert_eq!(texts(&break_lines(&glyphs(text), &with(false))), apart);
            assert_eq!(texts(&break_lines(&glyphs(text), &with(true))), together);
        }
    }

    #[test]
    fn breaks_east_asian_text_between_characters_with_kinsoku() {
        use crate::kinsoku::Kinsoku;
        use crate::props::EastAsianScript;
        let with = |kinsoku: Option<Kinsoku>| Frame {
            kinsoku,
            ..frame(40)
        };
        let text = glyphs("ab 日本語、文字");
        // Without an East Asian language, the run of East Asian characters is one word, which
        // goes to the next line whole and splits there.
        let latin = break_lines(&text, &with(None));
        assert_eq!(texts(&latin), vec!["ab ", "日本語、", "文字"]);
        // With one, a line breaks between characters.
        let japanese = Some(Kinsoku::of(EastAsianScript::Japanese));
        let lines = break_lines(&text, &with(japanese));
        assert_eq!(texts(&lines), vec!["ab 日", "本語、文", "字"]);
        // "、" may not start a line, so "文" goes to the next line with it. With kinsoku off,
        // "、" starts the line.
        let mark = glyphs("日本語文、字");
        let kept = break_lines(&mark, &with(japanese));
        assert_eq!(texts(&kept), vec!["日本語", "文、字"]);
        let free = break_lines(&mark, &with(Some(Kinsoku::FREE)));
        assert_eq!(texts(&free), vec!["日本語文", "、字"]);
    }

    #[test]
    fn marks_a_line_before_a_word_that_fits_without_its_hanging_mark() {
        use crate::kinsoku::Kinsoku;
        use crate::props::EastAsianScript;
        let simplified = Kinsoku::of(EastAsianScript::Simplified);
        let with = |kinsoku: Kinsoku| Frame {
            kinsoku: Some(kinsoku),
            ..frame(40)
        };
        let hangs = |text: &str, kinsoku: Kinsoku| {
            let lines = break_lines(&glyphs(text), &with(kinsoku));
            (
                texts(&lines),
                lines.iter().map(|l| l.would_hang).collect::<Vec<_>>(),
            )
        };
        // Four glyphs of 10 units fill the line, and "," may not start the next: "四" goes
        // with it, where Word keeps "四" and hangs the mark. A Latin word in parentheses keeps
        // its closing parenthesis, which Word hangs too.
        let lines = |a: &[&str]| a.iter().map(|t| (*t).to_owned()).collect::<Vec<_>>();
        assert_eq!(
            hangs("一二三四,五", simplified),
            (lines(&["一二三", "四,五"]), vec![true, false])
        );
        assert_eq!(
            hangs("一(ab)", simplified),
            (lines(&["一", "(ab)"]), vec![true, false])
        );
        // No hang: with `w:overflowPunct` off; before a mark that cannot start a line but is
        // not of the list, "…"; where the character before the mark does not fit either; and
        // with kinsoku off, where the mark starts the next line.
        let no = |text: &str, kinsoku: Kinsoku| {
            let (_, hung) = hangs(text, kinsoku);
            assert!(hung.iter().all(|hang| !hang), "{text}");
        };
        no("一二三四,五", simplified.without_hanging());
        no("一二三四…五", simplified);
        no("一二三四五,", simplified);
        no("一二三四,五", Kinsoku::FREE);
    }

    #[test]
    fn breaks_after_spaces_and_hyphens() {
        let lines = break_lines(&glyphs("aa bb-cc dd"), &frame(60));
        assert_eq!(texts(&lines), vec!["aa bb-", "cc dd"]);
        let narrow = break_lines(&glyphs("aa bb-cc dd"), &frame(50));
        assert_eq!(texts(&narrow), vec!["aa ", "bb-cc ", "dd"]);
        assert_eq!(lines[0].width(), Length::from_units(60));
        assert_eq!(lines[1].last_visible(), Some(4));
    }

    #[test]
    fn breaks_an_equation_after_the_space_of_an_operator_which_hangs() {
        let pieces: Vec<Piece> = glyphs("a+\u{a0}b+\u{a0}cd")
            .into_iter()
            .map(|piece| match piece {
                Piece::Glyph(mut g) if g.ch == '\u{a0}' => {
                    g.space = SpaceKind::Operator;
                    Piece::Glyph(g)
                }
                other => other,
            })
            .collect();
        let lines = break_lines(&pieces, &frame(50));
        assert_eq!(texts(&lines), vec!["a+\u{a0}b+\u{a0}", "cd"]);
        assert_eq!(lines[0].last_visible(), Some(4));
        assert!(!is_space(&pieces[2]));
    }

    #[test]
    fn a_justified_line_counts_the_operator_space_before_a_term_in_its_room() {
        let pieces: Vec<Piece> = glyphs("a b c d+\u{a0}e+\u{a0}f")
            .into_iter()
            .map(|piece| match piece {
                Piece::Glyph(mut g) if g.ch == '\u{a0}' => {
                    g.space = SpaceKind::Operator;
                    Piece::Glyph(g)
                }
                other => other,
            })
            .collect();
        let mut f = frame(101);
        f.shrink = Shrink {
            permille: 500,
            stretch_permille: 500,
            natural: (0, 0),
            joints: JointGaps::default(),
        };
        // "a b c d+ e+" is 110 wide, 9 over a frame of 101. Without "e+", the line would leave
        // the 20 of the term and the 10 of the operator space before it to stretch over its 3
        // gaps, so it may run over by 30 * 1500 / (3000 + 1500) = 10.
        assert_eq!(
            texts(&break_lines(&pieces, &f)),
            vec!["a b c d+\u{a0}e+\u{a0}", "f"]
        );
        f.width = Length::from_units(99);
        f.first_width = f.width;
        assert_eq!(
            texts(&break_lines(&pieces, &f)),
            vec!["a b c d+\u{a0}", "e+\u{a0}f"]
        );
    }

    #[test]
    fn hangs_the_whole_space_after_a_relation() {
        let pieces: Vec<Piece> = glyphs("a=\u{200a}\u{a0}b=\u{200a}\u{a0}cd")
            .into_iter()
            .map(|piece| match piece {
                Piece::Glyph(mut g) if matches!(g.ch, '\u{200a}' | '\u{a0}') => {
                    g.space = SpaceKind::Operator;
                    Piece::Glyph(g)
                }
                other => other,
            })
            .collect();
        let lines = break_lines(&pieces, &frame(60));
        assert_eq!(
            texts(&lines),
            vec!["a=\u{200a}\u{a0}b=\u{200a}\u{a0}", "cd"]
        );
        assert_eq!(lines[0].last_visible(), Some(5));
    }

    #[test]
    fn keeps_the_numbers_of_its_decisions() {
        let lines = break_lines(&glyphs("aa bb cc"), &frame(50));
        assert_eq!(texts(&lines), vec!["aa bb ", "cc"]);
        // "bb" fit after "aa " and one space, and "cc" would have ended at 80 after two.
        let u = Length::from_units;
        let kept = lines[0].kept.unwrap();
        assert_eq!(
            (kept.end, kept.word, kept.spaces, kept.space),
            (u(50), u(20), u(10), u(10))
        );
        let wrapped = lines[0].wrapped.unwrap();
        assert_eq!(
            (wrapped.width, wrapped.end, wrapped.spaces),
            (u(50), u(80), u(20))
        );
        assert_eq!((wrapped.over, wrapped.shrinks), (Length::ZERO, false));
        // The last line ends its paragraph, not before a word.
        assert_eq!(lines[1].kept.unwrap().end, u(20));
        assert_eq!(lines[1].wrapped, None);
    }

    #[test]
    fn shows_a_soft_hyphen_only_where_a_line_ends() {
        // Each glyph is 10 units wide. "bbcc" fits with "aa " in 70 units, so its soft hyphen
        // shows nothing and takes no width.
        let text = "aa bb\u{E0AD}cc dd";
        let wide = break_lines(&glyphs(text), &frame(70));
        assert_eq!(texts(&wide), vec!["aa bbcc ", "dd"]);
        assert_eq!(wide[0].placed[5].x, Length::from_units(50));
        // In 60 units the line ends at the soft hyphen, which shows a hyphen-minus.
        let narrow = break_lines(&glyphs(text), &frame(60));
        assert_eq!(texts(&narrow), vec!["aa bb-", "cc dd"]);
        assert_eq!(narrow[0].width(), Length::from_units(60));
        // The hyphen needs room as well: in 50 units "bb-" goes to the next line, where
        // "bbcc" fits whole.
        let tight = break_lines(&glyphs(text), &frame(50));
        assert_eq!(texts(&tight), vec!["aa ", "bbcc ", "dd"]);
        // A soft hyphen at the end of the paragraph shows nothing.
        let end = break_lines(&glyphs("aa\u{E0AD}"), &frame(60));
        assert_eq!(texts(&end), vec!["aa"]);
        // A U+00AD in the text is an ordinary character.
        let literal = break_lines(&glyphs("aa bb\u{AD}cc dd"), &frame(70));
        assert_eq!(texts(&literal), vec!["aa ", "bb\u{AD}cc ", "dd"]);
    }

    #[test]
    fn marks_the_line_that_ends_at_a_soft_hyphen() {
        // Each glyph is 10 units wide, as in the test above.
        let hyphens = |text: &str, width| {
            let lines = break_lines(&glyphs(text), &frame(width));
            lines.iter().map(|line| line.hyphen).collect::<Vec<_>>()
        };
        assert_eq!(hyphens("aa bb\u{E0AD}cc dd", 70), [None, None]);
        assert_eq!(
            hyphens("aa bb\u{E0AD}cc dd", 60),
            [Some(EndHyphen::Soft), None]
        );
        assert_eq!(hyphens("aa\u{E0AD}", 60), [None]);
    }

    #[test]
    fn breaks_after_the_move_of_an_advance_field_but_not_before_it() {
        // Each glyph is 10 units wide. The move of 30 belongs to "aa", and "bb" after it
        // starts a word: "aa" and the move take 50, and "bb" goes to the next line.
        let moved = |before: &str, after: &str| {
            let mut pieces = glyphs(before);
            pieces.push(Piece::Advance(Length::from_units(30)));
            pieces.extend(glyphs(after));
            pieces
        };
        let lines = break_lines(&moved("aa", "bb cc"), &frame(60));
        assert_eq!(texts(&lines), vec!["aa|", "bb cc"]);
        // In 50 units "aa" and its move (`|`) leave the line of "a " together.
        let lines = break_lines(&moved("a aa", "bb"), &frame(50));
        assert_eq!(texts(&lines), vec!["a ", "aa|", "bb"]);
    }

    /// The pieces of `text`, with an automatic hyphenation point at each `=`.
    fn with_points(text: &str) -> Vec<Piece> {
        glyphs(&text.replace('=', &AUTOMATIC_HYPHEN.to_string()))
    }

    /// The texts of `lines`, with the hyphen of an automatic point at a line end as `-`.
    fn hyphenated_texts(lines: &[Line]) -> Vec<String> {
        texts(lines)
            .into_iter()
            .map(|text| text.replace(super::LINE_END_HYPHEN, "-"))
            .collect()
    }

    #[test]
    fn ends_a_line_at_the_last_automatic_point_that_fits() {
        // Each glyph advances 10; the hyphen takes room only at the end of a line, so on a line
        // of 120 `hyphen-` fits after `aaaa ` and `hyphena-` does not.
        let hyphenated = |rules| Frame {
            hyphenation: Some(rules),
            ..frame(120)
        };
        let pieces = with_points("aaaa hy=phen=ation");
        let lines = break_lines(&pieces, &hyphenated(Hyphenation::default()));
        assert_eq!(hyphenated_texts(&lines), ["aaaa hyphen-", "ation"]);
        assert_eq!(lines[0].hyphen, Some(EndHyphen::Automatic));
        // Without hyphenation the word goes down whole, and no point shows.
        assert_eq!(
            hyphenated_texts(&break_lines(&pieces, &frame(120))),
            ["aaaa ", "hyphenation"]
        );
        // A zone as wide as the room of 70 keeps the word whole; a narrower one does not.
        let zone = |units| Hyphenation {
            zone: Some(Length::from_units(units)),
            limit: None,
        };
        assert_eq!(
            hyphenated_texts(&break_lines(&pieces, &hyphenated(zone(70)))),
            ["aaaa ", "hyphenation"]
        );
        assert_eq!(
            hyphenated_texts(&break_lines(&pieces, &hyphenated(zone(69)))),
            ["aaaa hyphen-", "ation"]
        );
    }

    #[test]
    fn ends_no_more_lines_in_a_row_at_a_point_than_the_limit() {
        let pieces = with_points("aaaa=aaaa=aaaa=aaaa=aaaa=aaaa");
        let limited = |limit| Frame {
            hyphenation: Some(Hyphenation {
                zone: None,
                limit: std::num::NonZeroUsize::new(limit),
            }),
            ..frame(60)
        };
        assert_eq!(
            hyphenated_texts(&break_lines(&pieces, &limited(0))),
            ["aaaa-", "aaaa-", "aaaa-", "aaaa-", "aaaa-", "aaaa"]
        );
        // The third line may not end at a point, so the word is split there as a word that fits
        // no line is, and the count starts again.
        assert_eq!(
            hyphenated_texts(&break_lines(&pieces, &limited(2))),
            ["aaaa-", "aaaa-", "aaaaaa", "aa-", "aaaa-", "aaaa"]
        );
    }

    #[test]
    fn breaks_after_en_and_em_dashes() {
        let en = break_lines(&glyphs("aa bb\u{2013}cc dd"), &frame(60));
        assert_eq!(texts(&en), vec!["aa bb\u{2013}", "cc dd"]);
        let em = break_lines(&glyphs("aa bb\u{2014}cc dd"), &frame(60));
        assert_eq!(texts(&em), vec!["aa bb\u{2014}", "cc dd"]);
    }

    #[test]
    fn breaks_after_a_unicode_hyphen() {
        let lines = break_lines(&glyphs("aa bb\u{2010}cc dd"), &frame(60));
        assert_eq!(texts(&lines), vec!["aa bb\u{2010}", "cc dd"]);
    }

    #[test]
    fn thai_text_keeps_the_spaces_of_its_line() {
        let mut f = frame(72);
        f.shrink = Shrink {
            permille: 400,
            stretch_permille: 0,
            natural: (0, 0),
            joints: JointGaps::default(),
        };
        f.thai_keeps_spaces = true;
        // As in the test below, "aa bb cc" fits only because its spaces shrink. A Thai word on
        // the line, or as the word that it tests, keeps them; a line of Latin words shrinks.
        assert_eq!(
            texts(&break_lines(&glyphs("aa bb cc"), &f)),
            vec!["aa bb cc"]
        );
        assert_eq!(
            texts(&break_lines(&glyphs("aa bb กข"), &f)),
            vec!["aa bb ", "กข"]
        );
        assert_eq!(
            texts(&break_lines(&glyphs("กข bb cc"), &f)),
            vec!["กข bb ", "cc"]
        );
        f.thai_keeps_spaces = false;
        assert_eq!(
            texts(&break_lines(&glyphs("กข bb cc"), &f)),
            vec!["กข bb cc"]
        );
    }

    #[test]
    fn justified_lines_may_shrink_their_spaces() {
        let mut f = frame(50);
        f.shrink = Shrink {
            permille: 400,
            stretch_permille: 0,
            natural: (0, 0),
            joints: JointGaps::default(),
        };
        // "aa bb cc" is 80 wide with two inner spaces of 10; each may shrink by 40% of it, 4,
        // so the line may be 8 wider than the frame.
        assert_eq!(
            texts(&break_lines(&glyphs("aa bb c"), &f)),
            vec!["aa bb ", "c"]
        );
        f.width = Length::from_units(72);
        f.first_width = f.width;
        assert_eq!(
            texts(&break_lines(&glyphs("aa bb cc"), &f)),
            vec!["aa bb cc"]
        );
        let u = Length::from_units;
        assert_eq!(f.shrink.of(u(10)), u(4));
        assert_eq!(
            Shrink {
                permille: 100,
                stretch_permille: 0,
                natural: (0, 0),
                joints: JointGaps::default(),
            }
            .of(u(10)),
            u(1)
        );
    }

    #[test]
    fn a_share_of_the_natural_width_limits_the_overrun_to_the_nearest_twip() {
        let twips = |t| Length::from_twips(t).unwrap();
        let shrink = Shrink {
            natural: (3, 80),
            ..Shrink::default()
        };
        // A natural width of 8,000 twips needs a width of 7,700; one of 8,001 needs 7,700.96,
        // 7,701 to the nearest twip.
        assert_eq!(shrink.of_natural(twips(8_000)), Some(twips(300)));
        assert_eq!(shrink.of_natural(twips(8_001)), Some(twips(300)));
        assert_eq!(shrink.of_natural(twips(8_010)), Some(twips(300)));
        assert_eq!(shrink.of_natural(twips(8_020)), Some(twips(301)));
        assert_eq!(Shrink::default().of_natural(twips(8_000)), None);
    }

    #[test]
    fn keeps_the_spaces_after_a_word_that_shrinks_its_line() {
        let mut f = frame(72);
        f.shrink = Shrink {
            permille: 400,
            stretch_permille: 0,
            natural: (0, 0),
            joints: JointGaps::default(),
        };
        // "aa bb c-" is 80 wide and fits by shrinking its two spaces. The space after the dash
        // stays on the line instead of starting the next one.
        let dashed = break_lines(&glyphs("aa bb c\u{2013} dd"), &f);
        assert_eq!(texts(&dashed), vec!["aa bb c\u{2013} ", "dd"]);
    }

    #[test]
    fn a_justified_line_takes_a_word_only_when_its_spaces_shrink_by_at_most_half_the_stretch() {
        let mut f = frame(82);
        f.shrink = Shrink {
            permille: 500,
            stretch_permille: 500,
            natural: (0, 0),
            joints: JointGaps::default(),
        };
        // "a b c d e" is 90 wide with 4 spaces before "e", 8 over a frame of 82, and the spaces
        // could take 20. Without "e", the line would stretch 20 over its 3 gaps. With it, each
        // of the 4 spaces shrinks by 8 / 4 = 2, which is not more than half of 20 / 3. The line
        // may run over by 4 * 20 / (3 * 2 + 4) = 8, so that E(3k - 2) <= k(g + s).
        assert_eq!(
            texts(&break_lines(&glyphs("a b c d e"), &f)),
            vec!["a b c d e"]
        );
        f.width = Length::from_units(81);
        f.first_width = f.width;
        assert_eq!(
            texts(&break_lines(&glyphs("a b c d e"), &f)),
            vec!["a b c d ", "e"]
        );
        // Without the share, the spaces alone take the 9.
        f.shrink.stretch_permille = 0;
        assert_eq!(
            texts(&break_lines(&glyphs("a b c d e"), &f)),
            vec!["a b c d e"]
        );
        f.shrink.stretch_permille = 500;
        let u = Length::from_units;
        assert_eq!(
            f.shrink
                .over(u(20), (u(10), u(10)), (4, 1), JointCounts::default()),
            u(8)
        );
        // The limit of each space still holds.
        assert_eq!(
            f.shrink
                .over(u(5), (u(10), u(10)), (4, 1), JointCounts::default()),
            u(5)
        );
        // A line with no gap without the word: only the limit of each space holds.
        assert_eq!(
            f.shrink
                .over(u(5), (u(10), u(10)), (1, 1), JointCounts::default()),
            u(5)
        );
        assert_eq!(
            Shrink::default().over(u(10), (u(10), u(20)), (2, 1), JointCounts::default()),
            u(10)
        );
    }

    #[test]
    fn a_justified_line_takes_a_word_less_often_when_its_letter_joints_count_as_gaps() {
        let mut shrink = Shrink {
            permille: 500,
            stretch_permille: 500,
            natural: (0, 0),
            joints: JointGaps { seen: 9, other: 3 },
        };
        let u = Length::from_units;
        // As in the test above, the line holds 4 spaces before the word, one of them right
        // before it. Letter joints that count as gaps spread the stretch without the word over
        // more gaps, so the line may run over less: with one other joint of 3 gaps, by
        // 4 * 20 / (2 * (3 + 3) + 4) = 5, and with one joint after a seen of 9 gaps instead, by
        // 4 * 14 / (2 * (3 + 9) + 4) = 2.
        let other = JointCounts { seen: 0, other: 1 };
        assert_eq!(shrink.over(u(20), (u(10), u(10)), (4, 1), other), u(5));
        let seen = JointCounts { seen: 1, other: 0 };
        assert_eq!(shrink.over(u(20), (u(7), u(7)), (4, 1), seen), u(2));
        // Joints of no weight leave the limit of the spaces alone.
        shrink.joints = JointGaps::default();
        assert_eq!(shrink.over(u(20), (u(10), u(10)), (4, 1), other), u(8));
    }

    #[test]
    fn trailing_spaces_do_not_force_a_break() {
        let lines = break_lines(&glyphs("aaaa    b"), &frame(40));
        assert_eq!(texts(&lines), vec!["aaaa    ", "b"]);
        assert_eq!(lines[0].width(), Length::from_units(40));
    }

    #[test]
    fn places_an_object_as_a_word_of_its_own() {
        let object = Piece::Object {
            width: Length::from_units(50),
            height: Length::from_units(200),
            raised: Length::ZERO,
            picture: None,
            drawing: None,
            underlined: false,
            run_face: None,
            joins_before: false,
        };
        let mut pieces = glyphs("ab ");
        pieces.push(object);
        pieces.extend(glyphs(" cd"));
        let lines = break_lines(&pieces, &frame(100));
        assert_eq!(texts(&lines), vec!["ab | ", "cd"]);
        assert_eq!(lines[0].placed[3].advance, Length::from_units(50));
        assert_eq!(lines[0].width(), Length::from_units(80));
        let narrow = break_lines(&pieces, &frame(70));
        assert_eq!(texts(&narrow), vec!["ab ", "| ", "cd"]);
    }

    #[test]
    fn attaches_a_joining_object_to_its_preceding_word_only() {
        let obj = |width: i64, joins_before: bool| Piece::Object {
            width: Length::from_units(width),
            height: Length::from_units(100),
            raised: Length::ZERO,
            picture: None,
            drawing: None,
            underlined: false,
            run_face: None,
            joins_before,
        };
        let mut pieces = glyphs("ab cd");
        pieces.push(obj(60, true));
        assert_eq!(texts(&break_lines(&pieces, &frame(85))), vec!["ab ", "cd|"]);
        let mut non_joining = glyphs("ab cd");
        non_joining.push(obj(60, false));
        assert_eq!(
            texts(&break_lines(&non_joining, &frame(85))),
            vec!["ab cd", "|"]
        );
        let mut after_text = glyphs("ab ");
        after_text.push(obj(50, true));
        after_text.extend(glyphs("ef"));
        assert_eq!(
            texts(&break_lines(&after_text, &frame(85))),
            vec!["ab |", "ef"]
        );
        let mut two_objs = glyphs("ab ");
        two_objs.push(obj(50, true));
        two_objs.push(obj(50, true));
        assert_eq!(
            texts(&break_lines(&two_objs, &frame(85))),
            vec!["ab |", "|"]
        );
        let mut hyphen = glyphs("ab cd-");
        hyphen.push(obj(60, true));
        assert_eq!(
            texts(&break_lines(&hyphen, &frame(85))),
            vec!["ab cd-", "|"]
        );
        let mut overlong = glyphs("ab cd");
        overlong.push(obj(75, true));
        assert_eq!(
            texts(&break_lines(&overlong, &frame(85))),
            vec!["ab ", "cd", "|"]
        );
    }

    #[test]
    fn measures_an_object_after_a_tab_as_text_with_its_width() {
        let object = Piece::Object {
            width: Length::from_units(50),
            height: Length::from_units(200),
            raised: Length::ZERO,
            picture: None,
            drawing: None,
            underlined: false,
            run_face: None,
            joins_before: false,
        };
        let mut after = vec![object];
        after.extend(glyphs("ab  "));
        assert_eq!(following_width(&after, None), Length::from_units(70));
        let mut spaced = vec![object];
        spaced.extend(glyphs("   "));
        assert_eq!(following_width(&spaced, None), Length::from_units(50));
    }

    #[test]
    fn splits_a_word_that_is_too_long() {
        let lines = break_lines(&glyphs("abcdefg"), &frame(30));
        assert_eq!(texts(&lines), vec!["abc", "def", "g"]);
        // The lines that end inside the word say so.
        let ends: Vec<LineEnd> = lines.iter().map(|l| l.end).collect();
        assert_eq!(ends, vec![LineEnd::Split, LineEnd::Split, LineEnd::Wrap]);
        assert_eq!(
            break_lines(&glyphs("ab cd"), &frame(30))[0].end,
            LineEnd::Wrap
        );
    }

    #[test]
    fn honors_breaks_and_tabs() {
        let mut pieces = glyphs("a");
        pieces.push(Piece::Tab(None));
        pieces.extend(glyphs("b"));
        pieces.push(Piece::LineBreak(Some(FaceIndex::nth(3))));
        pieces.extend(glyphs("c"));
        pieces.push(Piece::PageBreak);
        let lines = break_lines(&pieces, &frame(100));
        assert_eq!(texts(&lines), vec!["a|b", "c"]);
        assert_eq!(lines[0].placed[1].advance, Length::from_units(15));
        assert_eq!(lines[0].placed[2].x, Length::from_units(25));
        assert_eq!(lines[1].end, LineEnd::PageBreak);
        assert_eq!(lines[0].end, LineEnd::Break(Some(FaceIndex::nth(3))));
        pieces.extend(glyphs("d"));
        assert_eq!(
            texts(&break_lines(&pieces, &frame(100))),
            vec!["a|b", "c", "d"]
        );
        assert_eq!(break_lines(&[], &frame(100)).len(), 1);
    }

    /// A frame whose first line is 50 units wide and the others 100, which puts `leading`
    /// page breaks before the first line: two words of 40 units with a space between them fit
    /// on another line but not on the first.
    fn narrow_first(leading: LeadingBreaks) -> Frame {
        let mut f = frame(100);
        f.first_width = Length::from_units(50);
        f.breaking.leading_breaks = leading;
        f
    }

    #[test]
    fn starts_the_first_line_after_leading_page_breaks_where_the_frame_says_so() {
        let (none, first, all) = (
            LeadingBreaks::None,
            LeadingBreaks::First,
            LeadingBreaks::All,
        );
        // (page breaks, leading breaks) and (lines, index of the first line). After the first
        // break only, the second break's line is the narrow first line, and the text takes the
        // other lines' width.
        let cases = [
            ((1, none), (2, 0)),
            ((1, first), (3, 1)),
            ((1, all), (3, 1)),
            ((2, none), (3, 0)),
            ((2, first), (3, 1)),
            ((3, first), (4, 1)),
            ((2, all), (4, 2)),
            ((0, all), (2, 0)),
            ((0, first), (2, 0)),
        ];
        for ((breaks, leading), expected) in cases {
            let mut pieces = vec![Piece::PageBreak; breaks];
            pieces.extend(glyphs("aaaa bbbb"));
            let lines = break_lines(&pieces, &narrow_first(leading));
            let found = (lines.len(), Line::first_index(&lines, leading));
            assert_eq!(found, expected, "{breaks} breaks, {leading:?}");
        }
    }

    #[test]
    fn keeps_the_first_line_at_the_start_after_text_or_without_text() {
        // A page break after text ends a line of the paragraph's first; the text after it
        // takes the other lines' width.
        let mut pieces = glyphs("c");
        pieces.push(Piece::PageBreak);
        pieces.extend(glyphs("aaaa bbbb"));
        let lines = break_lines(&pieces, &narrow_first(LeadingBreaks::All));
        assert_eq!(lines.len(), 2);
        assert_eq!(Line::first_index(&lines, LeadingBreaks::All), 0);
        // A paragraph of page breaks alone keeps its first line at the start.
        let only = [Piece::PageBreak, Piece::PageBreak];
        for leading in [LeadingBreaks::First, LeadingBreaks::All] {
            let lines = break_lines(&only, &narrow_first(leading));
            assert_eq!(Line::first_index(&lines, leading), 0);
        }
    }

    #[test]
    fn keeps_an_empty_line_after_a_column_break_that_ends_the_pieces() {
        let mut pieces = glyphs("a");
        pieces.push(Piece::ColumnBreak);
        let lines = break_lines(&pieces, &frame(100));
        assert_eq!(texts(&lines), vec!["a", ""]);
        assert_eq!(lines[0].end, LineEnd::ColumnBreak);
        // A page break at the end leaves no empty line.
        let mut pieces = glyphs("a");
        pieces.push(Piece::PageBreak);
        assert_eq!(break_lines(&pieces, &frame(100)).len(), 1);
    }

    #[test]
    fn gives_back_the_pieces_of_lines_with_their_breaks() {
        let mut pieces = glyphs("aaa bbb");
        pieces.push(Piece::LineBreak(Some(FaceIndex::nth(1))));
        pieces.extend(glyphs("ccc"));
        pieces.push(Piece::PageBreak);
        pieces.extend(glyphs("ddd"));
        let lines = break_lines(&pieces, &frame(100));
        assert_eq!(lines[0].end, LineEnd::Break(Some(FaceIndex::nth(1))));
        assert_eq!(lines[1].end, LineEnd::PageBreak);
        let again = Line::pieces(&lines);
        assert_eq!(again, pieces);
        // Broken again in a narrower frame, the explicit breaks stay.
        let narrow = break_lines(&again, &frame(40));
        assert_eq!(texts(&narrow), vec!["aaa ", "bbb", "ccc", "ddd"]);
        assert_eq!(narrow[1].end, LineEnd::Break(Some(FaceIndex::nth(1))));
        assert_eq!(narrow[2].end, LineEnd::PageBreak);
    }

    #[test]
    fn stretches_only_spaces_after_the_last_tab_and_the_first_glyph() {
        let line = |pieces: &[Piece]| break_lines(pieces, &frame(1000)).remove(0);
        assert_eq!(line(&glyphs("  a b")).first_stretched(), 2);
        assert_eq!(line(&glyphs("a b")).first_stretched(), 0);
        let mut pieces = glyphs("a b");
        pieces.push(Piece::Tab(None));
        pieces.extend(glyphs(" c d"));
        // "a b", the tab and the space after it keep their widths.
        assert_eq!(line(&pieces).first_stretched(), 5);
    }

    #[test]
    fn moves_a_tab_down_with_the_word_after_it() {
        let mut pieces = glyphs("aaaa");
        pieces.push(Piece::Tab(None));
        pieces.extend(glyphs("bbbbbb"));
        let lines = break_lines(&pieces, &frame(100));
        assert_eq!(texts(&lines), vec!["aaaa", "|bbbbbb"]);
        assert_eq!(lines[1].placed[0].advance, Length::from_units(25));
        assert_eq!(lines[1].placed[1].x, Length::from_units(25));
        // A tab alone on its line stays there.
        let mut alone = vec![Piece::Tab(None)];
        alone.extend(glyphs(&"c".repeat(12)));
        let lines = break_lines(&alone, &frame(100));
        assert_eq!(texts(&lines)[0], "|");
    }

    #[test]
    fn starts_a_new_line_with_a_tab_whose_default_stop_lies_past_the_end() {
        // Default stops every 25 units in a line of 60: after "aa" the tabs go to 25 and 50,
        // and the third one, whose stop at 75 lies past the end, starts the next line. The
        // space after it follows it there.
        let mut pieces = glyphs("aa");
        pieces.extend([Piece::Tab(None); 3]);
        pieces.extend(glyphs(" bb"));
        let lines = break_lines(&pieces, &frame(60));
        assert_eq!(texts(&lines), vec!["aa||", "| bb"]);
        assert_eq!(lines[1].placed[2].x, Length::from_units(35));
        // A stop at the end itself still holds the tab.
        let mut pieces = glyphs("a");
        pieces.extend([Piece::Tab(None); 2]);
        let lines = break_lines(&pieces, &frame(50));
        assert_eq!(texts(&lines), vec!["a||"]);
        // Spaces may run past the end, but a tab after them starts the next line.
        let mut pieces = glyphs("aaaa      ");
        pieces.push(Piece::Tab(None));
        let lines = break_lines(&pieces, &frame(60));
        assert_eq!(texts(&lines), vec!["aaaa      ", "|"]);
    }

    #[test]
    fn aligns_text_at_right_center_and_decimal_stops() {
        let stop = |position, kind| TabStop {
            position: Length::from_units(position),
            kind,
            leader: Some('.'),
        };
        let mut f = frame(500);
        let mut run = |kind, text: &str| {
            f.tabs = Tabs::new([stop(200, kind)], Length::from_units(25), None);
            let mut pieces = glyphs("a");
            pieces.push(Piece::Tab(None));
            pieces.extend(glyphs(text));
            let lines = break_lines(&pieces, &f);
            (
                lines[0].placed[1].advance.units(),
                lines[0].placed[1].leader,
            )
        };
        assert_eq!(run(TabKind::Right, "bcd "), (160, Some('.')));
        assert_eq!(run(TabKind::Center, "bcd"), (175, Some('.')));
        assert_eq!(run(TabKind::Decimal, "12.5"), (170, Some('.')));
        assert_eq!(run(TabKind::Decimal, "125"), (160, Some('.')));
        assert_eq!(run(TabKind::Right, &"x".repeat(30)), (0, Some('.')));
    }

    #[test]
    fn ends_text_after_a_center_or_decimal_stop_at_the_line_end_where_the_quirk_says() {
        let (past, ends) = (
            AlignedTabOverrun::RunsPast,
            AlignedTabOverrun::EndsAtAreaEnd,
        );
        // Centered on the stop, the text would end at 105, past the line's end at 100.
        assert!(aligned_tab(TabKind::Center, 80, "bcdef", past, 0).0 > 1);
        assert_eq!(
            aligned_tab(TabKind::Center, 80, "bcdef", ends, 0),
            (1, Some(40))
        );
        // With its point at the stop, the text would end at 120.
        assert!(aligned_tab(TabKind::Decimal, 80, "12.345", past, 0).0 > 1);
        assert_eq!(
            aligned_tab(TabKind::Decimal, 80, "12.345", ends, 0),
            (1, Some(30))
        );
        // Text that ends inside the line keeps its place at the stop.
        assert_eq!(
            aligned_tab(TabKind::Center, 80, "bc", ends, 0),
            (1, Some(60))
        );
    }

    #[test]
    fn ends_text_after_a_stop_past_the_line_end_at_the_line_end_where_the_quirk_says() {
        let ends = AlignedTabOverrun::EndsAtAreaEnd;
        assert_eq!(
            aligned_tab(TabKind::Center, 120, "bc", ends, 0),
            (1, Some(70))
        );
        assert_eq!(
            aligned_tab(TabKind::Right, 120, "bc", ends, 0),
            (1, Some(70))
        );
    }

    #[test]
    fn wraps_only_the_last_trailing_tab_with_a_word_that_does_not_fit() {
        let stop = |position, kind| TabStop {
            position: Length::from_units(position),
            kind,
            leader: None,
        };
        // Line width 100, default stops every 50, center stop at 40 and right stop at 80.
        let mut f = frame(100);
        f.tabs = Tabs::new(
            [stop(40, TabKind::Center), stop(80, TabKind::Right)],
            Length::from_units(50),
            None,
        );
        // Tabs-only line: Tab1(40), Tab2(80), Tab3(100=end) before "ab" -> only Tab3 wraps to
        // line 2, centering "ab" (width 20) on 40 so "ab" starts at 30.
        let mut pieces = vec![Piece::Tab(None), Piece::Tab(None), Piece::Tab(None)];
        pieces.extend(glyphs("ab"));
        let lines = break_lines(&pieces, &f);
        assert_eq!(
            (lines.len(), lines[0].placed.len(), lines[1].placed[1].x),
            (2, 2, Length::from_units(30)),
        );

        // Mixed line with two left stops (80, then default 100=end): "a" + Tab1(80) + Tab2(100)
        // before "bc" -> only Tab2 wraps, placing "bc" at 80 (not 100).
        let mut f2 = frame(100);
        f2.tabs = Tabs::new([stop(80, TabKind::Left)], Length::from_units(20), None);
        let mut pieces2 = glyphs("a");
        pieces2.push(Piece::Tab(None));
        pieces2.push(Piece::Tab(None));
        pieces2.extend(glyphs("bc"));
        let lines2 = break_lines(&pieces2, &f2);
        assert_eq!(
            (lines2.len(), lines2[0].placed.len(), lines2[1].placed[1].x),
            (2, 2, Length::from_units(80)),
        );

        // Single tab alone on a line stays on line 1 so line 1 is not emptied.
        let mut f3 = frame(100);
        f3.tabs = Tabs::new([stop(100, TabKind::Left)], Length::from_units(50), None);
        let mut pieces3 = vec![Piece::Tab(None)];
        pieces3.extend(glyphs("ab"));
        let lines3 = break_lines(&pieces3, &f3);
        assert_eq!(
            (lines3.len(), lines3[0].placed.len(), lines3[1].placed[0].x),
            (2, 1, Length::ZERO),
        );
    }

    #[test]
    fn takes_the_text_area_end_as_the_limit_of_a_stop_beside_a_right_indent() {
        let ends = AlignedTabOverrun::EndsAtAreaEnd;
        // Beside a right indent of 20, the limit after a stop before the line's end at 80 is
        // that end; after a stop between it and the text area's end at 100, it is the area's
        // end; and after a stop past the area, it is the line's end again.
        assert_eq!(
            aligned_tab(TabKind::Center, 70, "bcd", ends, 20),
            (1, Some(40))
        );
        assert_eq!(
            aligned_tab(TabKind::Center, 90, "bcd", ends, 20),
            (1, Some(60))
        );
        assert_eq!(
            aligned_tab(TabKind::Center, 90, "bcdefgh", ends, 20),
            (1, Some(20))
        );
        assert_eq!(
            aligned_tab(TabKind::Center, 120, "bc", ends, 20),
            (1, Some(50))
        );
        // Text wider than the area after the tab's start goes to the next line with the tab.
        assert!(aligned_tab(TabKind::Center, 90, "bcdefghijk", ends, 20).0 > 1);
    }

    #[test]
    fn keeps_text_after_a_stop_past_the_line_end_at_the_stop_where_the_mode_says() {
        let older = (AlignedTabOverrun::EndsAtAreaEnd, false);
        // A center stop past the line's end keeps its text centered on the stop, on the line.
        assert_eq!(
            aligned_tab_in(TabKind::Center, 120, "bcde", older, 0),
            (1, Some(90))
        );
        // So does a stop exactly at the line's end, and a right stop past it.
        assert_eq!(
            aligned_tab_in(TabKind::Center, 100, "bcdefg", older, 0),
            (1, Some(60))
        );
        assert_eq!(
            aligned_tab_in(TabKind::Right, 130, "bc", older, 0),
            (1, Some(100))
        );
        // A stop before the line's end still ends its text at the line's end.
        assert_eq!(
            aligned_tab_in(TabKind::Center, 80, "bcdef", older, 0),
            (1, Some(40))
        );
    }

    /// The number of lines of a line of 100 less `indent` in a text area of 100 that holds `a`,
    /// a tab to one stop of `kind` at `position` and `text`, and the tab's advance.
    fn aligned_tab(
        kind: TabKind,
        position: i64,
        text: &str,
        overrun: AlignedTabOverrun,
        indent: i64,
    ) -> (usize, Option<i64>) {
        aligned_tab_in(kind, position, text, (overrun, true), indent)
    }

    /// As [`aligned_tab`], with the frame's `limits_past_end` beside the quirk.
    fn aligned_tab_in(
        kind: TabKind,
        position: i64,
        text: &str,
        (overrun, limits_past_end): (AlignedTabOverrun, bool),
        indent: i64,
    ) -> (usize, Option<i64>) {
        let mut f = frame(100 - indent);
        f.area_width = Length::from_units(100);
        f.breaking.ends_aligned_text = overrun == AlignedTabOverrun::EndsAtAreaEnd;
        f.limits_past_end = limits_past_end;
        let stop = TabStop {
            position: Length::from_units(position),
            kind,
            leader: None,
        };
        f.tabs = Tabs::new([stop], Length::from_units(25), None);
        let mut pieces = glyphs("a");
        pieces.push(Piece::Tab(None));
        pieces.extend(glyphs(text));
        let lines = break_lines(&pieces, &f);
        let tab = lines
            .first()
            .and_then(|line| line.placed.get(1))
            .map(|placed| placed.advance.units());
        (lines.len(), tab)
    }

    #[test]
    fn runs_on_to_a_right_stop_past_the_line_end() {
        let stop = |kind| TabStop {
            position: Length::from_units(120),
            kind,
            leader: None,
        };
        let line = |kind, after: &str| {
            // The text starts 10 after the column edge, so the line ends at 110.
            let mut f = frame(100);
            f.first_start = Length::from_units(10);
            f.tabs = Tabs::new([stop(kind)], Length::from_units(25), None);
            let mut pieces = glyphs("aaaa");
            pieces.push(Piece::Tab(None));
            pieces.extend(glyphs(after));
            texts(&break_lines(&pieces, &f))
        };
        assert_eq!(line(TabKind::Right, "bb"), ["aaaa|bb"]);
        // The room ends at the stop.
        assert_eq!(
            line(TabKind::Right, "bb cccccccc"),
            ["aaaa|bb ", "cccccccc"]
        );
        // Text after a left stop starts at the stop, so it cannot fit before it.
        assert_ne!(line(TabKind::Left, "bb"), ["aaaa|bb"]);
    }

    #[test]
    fn empty_paragraph_has_one_line() {
        let lines = break_lines(&[], &frame(100));
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].width(), Length::ZERO);
        assert!(!is_space(&Piece::LineBreak(None)));
    }

    #[test]
    fn an_object_wider_than_the_line_ends_its_paragraph_on_that_line() {
        let wide = Piece::Object {
            width: Length::from_units(150),
            height: Length::from_units(50),
            raised: Length::ZERO,
            picture: None,
            drawing: None,
            underlined: false,
            run_face: None,
            joins_before: false,
        };
        assert_eq!(texts(&break_lines(&[wide], &frame(100))), ["|"]);
        // Text after it goes to the next line, and an overlong word still breaks inside.
        let mut pieces = vec![wide];
        pieces.extend(glyphs("aa"));
        assert_eq!(texts(&break_lines(&pieces, &frame(100))), ["|", "aa"]);
        assert_eq!(
            texts(&break_lines(&glyphs("abcdefghijkl"), &frame(100))),
            ["abcdefghij", "kl"]
        );
    }

    #[test]
    fn punctuation_shrinks_up_to_r_times_the_stretch_per_gap_of_the_shorter_line() {
        let compression = super::Compression {
            ratio: 32,
            middle_dot: false,
            trailing_trim: super::TrailingTrim::None,
        };
        let u = Length::from_units;
        let halves = |count| super::Halves {
            count,
            em: u(1_000),
        };
        // A line of 21 characters with 10 blank halves that ends with an ideograph: at 0.940 em
        // the shorter line leaves 0.060 em over 19 gaps, and the line may run 1.010 em past;
        // at 0.945 em only 0.926 em.
        assert_eq!(compression.over(halves(10), (u(60), 19)), u(1_010));
        assert_eq!(compression.over(halves(10), (u(55), 19)), u(926));
        // With a closing mark at the end, its blank half counts as an eleventh: 0.1 em of room
        // gives 1.852 em.
        assert_eq!(compression.over(halves(11), (u(100), 19)), u(1_852));
        // A half shrinks by its own width at most.
        assert_eq!(compression.over(halves(1), (u(900), 2)), u(500));
        assert_eq!(compression.over(halves(10), (u(60), 0)), Length::ZERO);
    }

    #[test]
    fn a_justified_line_takes_one_more_character_when_its_halves_may_shrink() {
        let pieces = glyphs("永、永、永、永永永");
        let frame = |width, compressing: bool| Frame {
            kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
            punctuation: compressing.then_some(super::Compression {
                ratio: 32,
                middle_dot: false,
                trailing_trim: super::TrailingTrim::None,
            }),
            ..frame(width)
        };
        // The eighth character needs 9, and the three blank halves may give up their 15,
        // because the shorter line would stretch its 6 gaps by 1 in all. With no room, the
        // line takes nothing.
        assert_eq!(
            texts(&break_lines(&pieces, &frame(71, true))),
            ["永、永、永、永永", "永"]
        );
        assert_eq!(
            texts(&break_lines(&pieces, &frame(70, true))),
            ["永、永、永、永", "永永"]
        );
        assert_eq!(
            texts(&break_lines(&pieces, &frame(71, false))),
            ["永、永、永、永", "永永"]
        );
    }

    #[test]
    fn japanese_middle_dot_carries_a_blank_half_only_when_middle_dot_is_enabled() {
        let pieces = glyphs("所属・役職");
        let make = |middle_dot| Frame {
            kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
            punctuation: Some(super::Compression {
                ratio: 32,
                middle_dot,
                trailing_trim: super::TrailingTrim::None,
            }),
            ..frame(46)
        };
        assert_eq!(texts(&break_lines(&pieces, &make(true))), ["所属・役職"]);
        assert_eq!(
            texts(&break_lines(&pieces, &make(false))),
            ["所属・役", "職"]
        );
    }

    #[test]
    fn punctuation_compression_ignores_marks_before_tab() {
        let u = Length::from_units;
        let mut before_tab = glyphs("一、");
        before_tab.push(Piece::Tab(None));
        before_tab.extend(glyphs("甲乙丙"));
        let compressed = Frame {
            kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
            punctuation: Some(super::Compression {
                ratio: 32,
                middle_dot: false,
                trailing_trim: super::TrailingTrim::None,
            }),
            tabs: crate::tabs::Tabs::new([], u(40), None),
            ..frame(66)
        };
        assert_eq!(
            texts(&break_lines(&before_tab, &compressed)),
            ["一、|甲乙", "丙"]
        );

        // Punctuation inside a list label without a tab (`g.label == true`) also carries no
        // compressible blank half.
        let mut labeled = glyphs("一、甲乙丙");
        for i in 0..2 {
            if let Some(Piece::Glyph(g)) = labeled.get_mut(i) {
                g.label = true;
            }
        }
        assert_eq!(
            texts(&break_lines(
                &labeled,
                &Frame {
                    tabs: crate::tabs::Tabs::new([], u(40), None),
                    ..Frame {
                        width: u(46),
                        first_width: u(46),
                        ..compressed
                    }
                }
            )),
            ["一、甲乙", "丙"]
        );
    }

    #[test]
    fn trailing_auto_space_is_dropped_at_line_end_but_kept_inside_line() {
        let u = Length::from_units;
        // 3 glyphs of advance 10, with glyph[1] carrying trailing_auto_space = 3 (advance 13).
        let mut pieces = glyphs("甲8壬");
        if let Some(Piece::Glyph(g)) = pieces.get_mut(1) {
            g.advance = u(13);
            g.auto_space = u(3);
            g.trailing_auto_space = u(3);
        }
        // Width 20 fits "甲8" once trailing auto-space (3) is dropped at line end, and strips
        // the trailing gap from the placed glyph so line.width() == 20.
        let wrapped = break_lines(&pieces, &frame(20));
        assert_eq!(texts(&wrapped), ["甲8", "壬"]);
        assert_eq!(wrapped[0].width(), u(20));
        if let Some(Piece::Glyph(g)) = wrapped[0].placed.get(1).map(|p| p.piece) {
            assert_eq!(
                (g.advance, g.auto_space, g.trailing_auto_space),
                (u(10), u(0), u(0))
            );
        }
        // Width 33 keeps all 3 glyphs on one line and retains the 3-unit auto-space inside.
        let single = break_lines(&pieces, &frame(33));
        assert_eq!(texts(&single), ["甲8壬"]);
        assert_eq!(single[0].width(), u(33));
    }

    #[test]
    fn punctuation_compression_ignores_closed_kerned_halves() {
        let u = Length::from_units;
        let pair_frame = |width| Frame {
            kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
            punctuation: Some(super::Compression {
                ratio: 32,
                middle_dot: false,
                trailing_trim: super::TrailingTrim::None,
            }),
            ..frame(width)
        };
        let mut pair = glyphs("甲」,乙");
        if let Some(Piece::Glyph(close)) = pair.get_mut(1) {
            close.advance = u(5);
            close.punctuation_half = crate::text::PunctuationHalf::Closed;
        }
        assert_eq!(texts(&break_lines(&pair, &pair_frame(30))), ["甲」,乙"]);
        assert_eq!(
            texts(&break_lines(&pair, &pair_frame(28))),
            ["甲」,", "乙"]
        );

        let mut opens = glyphs("甲「「乙");
        if let Some(Piece::Glyph(first)) = opens.get_mut(1) {
            first.advance = u(5);
            first.punctuation_half = crate::text::PunctuationHalf::OpenShortened(u(5));
        }
        if let Some(Piece::Glyph(second)) = opens.get_mut(2) {
            second.punctuation_half = crate::text::PunctuationHalf::Closed;
        }
        assert_eq!(texts(&break_lines(&opens, &pair_frame(30))), ["甲「「乙"]);
        assert_eq!(
            texts(&break_lines(&opens, &pair_frame(28))),
            ["甲「「", "乙"]
        );
    }

    #[test]
    fn trailing_closing_trim_fits_half_em_overrun_by_script() {
        let make = |width, trailing_trim| Frame {
            kinsoku: Some(crate::kinsoku::Kinsoku::of(
                crate::props::EastAsianScript::Simplified,
            )),
            punctuation: Some(super::Compression {
                ratio: 0,
                middle_dot: false,
                trailing_trim,
            }),
            ..frame(width)
        };
        // Each glyph has advance 10; 10 kanji + closing mark = 110, half-trimmed = 105.
        let comma = glyphs("漢漢漢漢漢漢漢漢漢漢、後");
        assert_eq!(
            texts(&break_lines(
                &comma,
                &make(105, super::TrailingTrim::Closing)
            )),
            ["漢漢漢漢漢漢漢漢漢漢、", "後"]
        );
        assert_eq!(
            texts(&break_lines(
                &comma,
                &make(104, super::TrailingTrim::Closing)
            )),
            ["漢漢漢漢漢漢漢漢漢", "漢、後"]
        );
        assert_eq!(
            texts(&break_lines(&comma, &make(105, super::TrailingTrim::None))),
            ["漢漢漢漢漢漢漢漢漢", "漢、後"]
        );
        // Japanese centers `;` (no trailing blank half), while Simplified Chinese trims it.
        let semi = glyphs("漢漢漢漢漢漢漢漢漢漢;後");
        assert_eq!(
            texts(&break_lines(
                &semi,
                &make(105, super::TrailingTrim::Closing)
            )),
            ["漢漢漢漢漢漢漢漢漢漢;", "後"]
        );
        assert_eq!(
            texts(&break_lines(
                &semi,
                &make(105, super::TrailingTrim::NonJapaneseCentered)
            )),
            ["漢漢漢漢漢漢漢漢漢", "漢;後"]
        );
    }

    #[test]
    fn overflow_punct_hangs_single_trailing_mark_and_ends_line() {
        use crate::kinsoku::Kinsoku;
        use crate::props::EastAsianScript;
        let cn = Kinsoku::of(EastAsianScript::Simplified);
        let ja = Kinsoku::of(EastAsianScript::Japanese);
        let free = Kinsoku::FREE.with_hanging_of(cn);
        for (text, kinsoku, want_texts, want_hung) in [
            (
                "漢漢漢漢漢漢漢漢漢漢、後",
                cn,
                &["漢漢漢漢漢漢漢漢漢漢、", "後"][..],
                true,
            ),
            (
                "漢漢漢漢漢漢漢漢漢漢、。後",
                cn,
                &["漢漢漢漢漢漢漢漢漢", "漢、。後"][..],
                false,
            ),
            (
                "漢漢漢漢漢漢漢漢漢漢、後",
                free,
                &["漢漢漢漢漢漢漢漢漢漢、", "後"][..],
                true,
            ),
            (
                "漢漢漢漢漢漢漢漢漢漢;後",
                ja,
                &["漢漢漢漢漢漢漢漢漢", "漢;後"][..],
                false,
            ),
            (
                "漢漢漢漢漢漢漢漢漢漢、",
                cn,
                &["漢漢漢漢漢漢漢漢漢漢、"][..],
                true,
            ),
        ] {
            let f = Frame {
                kinsoku: Some(kinsoku),
                overflow_punct: super::OverflowPunct::Hang,
                ..frame(102)
            };
            let lines = break_lines(&glyphs(text), &f);
            assert_eq!(texts(&lines), want_texts, "{text}");
            assert_eq!(lines.first().is_some_and(|l| l.hung), want_hung, "{text}");
            assert!(lines.iter().all(|l| !l.would_hang), "{text}");
        }
    }

    #[test]
    fn closes_up_pairs_after_a_blank_right_half_or_before_an_opening_mark() {
        use crate::props::EastAsianScript::{Japanese, Simplified, Traditional};
        let check = |script, yes: &[&str], no: &[&str]| {
            let kerned = |pair: &str| {
                let mut chars = pair.chars();
                super::kerned_pair(chars.next().unwrap(), chars.next().unwrap(), script).is_some()
            };
            assert!(yes.iter().all(|pair| kerned(pair)));
            assert!(no.iter().all(|pair| !kerned(pair)));
        };
        check(
            Some(Japanese),
            &[
                "。」", ",(", "」「", ")。", "。。", "、、", ":「", "・(", "((", ")・",
            ],
            &[
                "!,", "!(", ")!", "!?", "?(", ")?", "::", "・・",
            ],
        );
        check(
            Some(Simplified),
            &[
                "!,", "!(", "!!", ")!", ":,", "::", ";;", ",,",
            ],
            &[
                "!?", "?(", ")?", "・(", ")・", "测(", ")测", "」a",
            ],
        );
        check(
            Some(Traditional),
            &["),", "。「", ":(", "):", "、("],
            &[",,", ",。", "。、", "!,", "!(", "・(", "?("],
        );
        check(None, &[")【", "】)"], &["),", "。「"]);
    }

    #[test]
    fn a_tab_to_a_left_stop_past_the_line_end_starts_the_next_line_and_ends_at_its_end() {
        // A line 100 wide, a left stop at 120, and "a", a tab and "b", each glyph 10 wide.
        let stop = TabStop {
            position: Length::from_units(120),
            kind: TabKind::Left,
            leader: None,
        };
        let lay_out = |rule| {
            let mut f = frame(100);
            f.tabs = Tabs::new([stop], Length::from_units(25), None);
            f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
            let mut pieces = glyphs("a");
            pieces.push(Piece::Tab(None));
            pieces.extend(glyphs("b"));
            let lines = break_lines(&pieces, &f);
            let tab = lines
                .iter()
                .flat_map(|line| &line.placed)
                .find(|placed| matches!(placed.piece, Piece::Tab(_)))
                .map(|placed| (placed.x.units(), placed.advance.units()));
            (texts(&lines), tab)
        };
        // To the stop: the tab goes to the next line with "b", and the line runs on to the
        // stop past its end.
        let (texts_to_stop, tab_to_stop) = lay_out(LeftStopPastEnd::ToStop);
        assert_eq!(texts_to_stop, ["a", "|b"]);
        assert_eq!(tab_to_stop, Some((0, 120)));
        // To the line's end: the tab starts the next line, fills it, and "b" follows below.
        let (texts_to_end, tab_to_end) = lay_out(LeftStopPastEnd::ToLineEnd);
        assert_eq!(texts_to_end, ["a", "|", "b"]);
        assert_eq!(tab_to_end, Some((0, 100)));
    }

    #[test]
    fn a_tab_to_a_left_stop_inside_the_line_keeps_its_place_on_both_variants() {
        let stop = TabStop {
            position: Length::from_units(80),
            kind: TabKind::Left,
            leader: None,
        };
        for rule in [LeftStopPastEnd::ToStop, LeftStopPastEnd::ToLineEnd] {
            let mut f = frame(100);
            f.tabs = Tabs::new([stop], Length::from_units(25), None);
            f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
            let mut pieces = glyphs("a");
            pieces.push(Piece::Tab(None));
            pieces.extend(glyphs("b"));
            assert_eq!(texts(&break_lines(&pieces, &f)), ["a|b"], "{rule:?}");
        }
    }

    #[test]
    fn a_tab_to_a_hanging_indent_past_the_line_end_runs_on_on_both_variants() {
        // A line 100 wide whose hanging indent, at 120, is the next stop of the tab after "a".
        let lay_out = |rule| {
            let mut f = frame(100);
            f.tabs = Tabs::new([], Length::from_units(25), Some(Length::from_units(120)));
            f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
            let mut pieces = glyphs("a");
            pieces.push(Piece::Tab(None));
            pieces.extend(glyphs("b"));
            texts(&break_lines(&pieces, &f))
        };
        assert_eq!(
            lay_out(LeftStopPastEnd::ToLineEnd),
            lay_out(LeftStopPastEnd::ToStop)
        );
    }

    #[test]
    fn overflow_punct_uses_mark_run_east_asian_language() {
        use crate::kinsoku::Kinsoku;
        use crate::props::{EastAsianLanguage, EastAsianScript};
        let tag = |text: &str, lang: Option<EastAsianLanguage>| -> Vec<Piece> {
            glyphs(text)
                .into_iter()
                .map(|p| match p {
                    Piece::Glyph(mut g) => {
                        g.east_asian_language = lang;
                        Piece::Glyph(g)
                    }
                    other => other,
                })
                .collect()
        };
        let cn = Some(EastAsianLanguage::Script(EastAsianScript::Simplified));
        let ko = Some(EastAsianLanguage::Script(EastAsianScript::Korean));
        let non_ea = Some(EastAsianLanguage::NonEastAsian);
        let f_cn = Frame {
            kinsoku: Some(Kinsoku::of(EastAsianScript::Simplified)),
            overflow_punct: super::OverflowPunct::Hang,
            ..frame(100)
        };
        // Non-East-Asian run inside a zh-CN paragraph does not hang or pull the preceding char.
        let non_ea_lines = break_lines(&tag("甲乙丙丁戊己庚辛壬癸、异", non_ea), &f_cn);
        assert_eq!(texts(&non_ea_lines), ["甲乙丙丁戊己庚辛壬癸", "、异"]);
        assert!(!non_ea_lines[0].hung);
        // zh-CN run inside a non-EA paragraph hangs the mark.
        let f_free = Frame {
            kinsoku: Some(Kinsoku::FREE.with_restricted(true)),
            overflow_punct: super::OverflowPunct::Hang,
            ..frame(100)
        };
        let ea_lines = break_lines(&tag("甲乙丙丁戊己庚辛壬癸、异", cn), &f_free);
        assert_eq!(texts(&ea_lines), ["甲乙丙丁戊己庚辛壬癸、", "异"]);
        assert!(ea_lines[0].hung);
        // Korean word followed by space hangs trailing comma even with kinsoku == None (wordWrap on).
        let f_ko = Frame {
            kinsoku: None,
            overflow_punct: super::OverflowPunct::Hang,
            ..frame(100)
        };
        let ko_lines = break_lines(&tag("가나다라마바사아자차, 카타", ko), &f_ko);
        assert_eq!(texts(&ko_lines), ["가나다라마바사아자차, ", "카타"]);
        assert!(ko_lines[0].hung);
    }

    #[test]
    fn overflow_punct_allows_space_shrink_before_hang() {
        use crate::kinsoku::Kinsoku;
        use crate::props::EastAsianScript;
        let f = Frame {
            kinsoku: Some(Kinsoku::of(EastAsianScript::Simplified)),
            overflow_punct: super::OverflowPunct::Hang,
            shrink: Shrink {
                permille: 250,
                ..Shrink::default()
            },
            ..frame(98)
        };
        // "aaa bbb cc" is 100 units (2 spaces of 10 -> up to 5 units shrink -> fits in 98),
        // and trailing ',' overflows -> hangs with shrunk spaces.
        let lines = break_lines(&glyphs("aaa bbb cc, next"), &f);
        assert_eq!(texts(&lines), ["aaa bbb cc, ", "next"]);
        assert!(lines[0].hung);
    }
}