f-office-docx 0.2.3

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
//! Paragraphs: their flow with spacing and borders, and the rules that move lines to the next
//! page, which keep a paragraph whole, with the next one, or without a lone first or last line.

use std::num::NonZeroU32;

use f_office_paint::{Item, Rect, Rgb};
use f_office_units::Length;
use f_office_units::scale::LINE;

use crate::body::{Content, Paragraph};
use crate::grid::LineRounding;
use crate::lines::{Frame, Line, LineEnd, Piece, break_lines};
use crate::props::{
    Border, Borders, Color, FrameMark, HtmlAutoSpacing, LineSpacing, ListRef, ParaProps,
};
use crate::quirks::Quirks;
use crate::text::FaceIndex;

use super::floating::{AnchorPages, holds_later};
use super::frames::frame_lead;
use super::line::height::SpaceBefore;
use super::line::{LinePlace, needed_room};
use super::measure::RunFeatures;
use super::page_items::FillsEntry;
use super::{Layout, Resolved, Rest, StoryKind, floating};

use crate::params::BORDER_REACH;
use crate::params::WIDOW_LINES;

/// For each line of a paragraph, the piece that a drawing beside it leaves.
type Narrowed = Vec<Option<floating::NarrowedPiece>>;

/// What the next paragraph needs to know about the one before it.
#[derive(Clone, Debug)]
pub(super) struct Previous {
    pub(super) style: Option<String>,
    contextual: bool,
    pub(super) after: Length,
    /// Whether the space after is automatic spacing.
    pub(super) after_auto: bool,
    /// The list (`w:numId`) of a list paragraph.
    list: Option<NonZeroU32>,
    /// How the document reads automatic spacing, for this paragraph's target.
    reading: HtmlAutoSpacing,
    /// Whether the paragraph is kept with the next one (`w:keepNext`).
    pub(super) kept: bool,
    /// What the next paragraph's own space before does at the top of a new page: it stays
    /// after a continuous section end.
    next_space: NewPageSpace,
}

/// What the own space before of a paragraph does when its first line starts the next page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum NewPageSpace {
    /// It goes, as at the top of a page after any natural break.
    #[default]
    Goes,
    /// It stays above the line, as after a continuous section end.
    Stays,
}

/// The rooms of a paragraph's top and bottom border that the boxes of its first and its last
/// line hold as space, under `BorderSpace::Held`, and the room that its last line needs below
/// its text at the foot of a page, under `FootBorderRoom::Fits`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct HeldBorders {
    /// The top border's width and space, which the first line's box holds as space before,
    /// until that line is placed.
    pub(super) top: Length,
    /// The bottom border's space and width, which the last line's box holds as space after.
    pub(super) bottom: Length,
    /// The bottom border's space and width, which must fit below the last line's text at the
    /// foot of a page ([`super::decisions::foot_border_room`]).
    pub(super) foot: Length,
}

impl HeldBorders {
    /// No border room in a box.
    pub(super) const NONE: Self = Self {
        top: Length::ZERO,
        bottom: Length::ZERO,
        foot: Length::ZERO,
    };
}

impl Previous {
    pub(super) fn of(props: &ParaProps) -> Self {
        let flags = props.flags();
        Self {
            style: props.style.clone(),
            contextual: flags.contextual_spacing,
            after: props.space_after(),
            after_auto: flags.after_auto,
            list: list_of(props),
            reading: props.html_auto_spacing.unwrap_or_default(),
            kept: flags.keep_next,
            next_space: if flags.continuous_end {
                NewPageSpace::Stays
            } else {
                NewPageSpace::Goes
            },
        }
    }

    /// Whether contextual spacing removes this paragraph's space after before a paragraph of
    /// the style `style`.
    pub(super) fn drops_after_before(&self, style: Option<&str>) -> bool {
        drops_contextual_spacing(self.contextual, self.style.as_deref(), style)
    }

    /// Whether this paragraph's space after stays at the end of a table cell: a written space
    /// after, an automatic one where the reading keeps every automatic space, and, where the
    /// target's `quirks` keep it ([`super::decisions::kept_list_space`]), the automatic space
    /// after of a list paragraph.
    pub(in crate::layout) fn keeps_after_at_cell_end(&self, quirks: &Quirks) -> bool {
        !self.after_auto
            || !self.reading.drops_automatic_spacing()
            || super::decisions::kept_list_space(quirks, self.list.as_ref()).is_some()
    }
}

/// The space between two paragraphs: the space after of the paragraph before and the space
/// before of the next one that count, and the reading that joins them.
#[derive(Clone, Copy, Debug)]
pub(super) struct Gap {
    /// The space after of the paragraph before that counts.
    pub(super) after: Length,
    /// The space before of the next paragraph that counts.
    pub(super) before: Length,
    /// How the document reads automatic spacing, which says how the two join.
    reading: HtmlAutoSpacing,
}

impl Gap {
    /// The whole space between the two paragraphs.
    pub(super) fn total(self) -> Length {
        self.reading.space_between(self.after, self.before)
    }

    /// The part of the whole space beyond the space after, which the next paragraph's own space
    /// before gives.
    pub(super) fn own(self) -> Length {
        self.total() - self.after
    }
}

/// Whether contextual spacing removes a paragraph's space on the side of a neighbour: the
/// paragraph has contextual spacing (`contextual`), and its style `own` is the neighbour's style
/// `other`. Its space after drops before such a paragraph, and its space before after one; the
/// edge of a table cell counts as a paragraph of the default paragraph style.
fn drops_contextual_spacing(contextual: bool, own: Option<&str>, other: Option<&str>) -> bool {
    contextual && own == other
}

/// Whether a run shows nothing: no text, tab, break, object or drawing. With `blank`, text of
/// only spaces counts as nothing too.
fn is_empty_run(run: &crate::body::Run, blank: bool) -> bool {
    run.content.iter().all(|content| match content {
        Content::Text(text) => text.chars().all(|c| blank && c == ' '),
        Content::FieldBegin
        | Content::FieldLock
        | Content::DropDown(_)
        | Content::FieldCode(_)
        | Content::FieldSeparate
        | Content::FieldEnd
        | Content::FieldMark
        | Content::HyperlinkEdge
        | Content::ControlEdge
        | Content::RemovedEdge
        | Content::Bookmark(_) => true,
        _ => false,
    })
}

impl Layout<'_> {
    /// Records the page number text of a paragraph's bookmarks, on the page of its first
    /// line, with the chapter number when page numbers there start with one.
    fn note_bookmarks(&mut self, paragraph: &Paragraph, resolved: &Resolved) {
        let number = self.page_number(self.output.pages.len());
        let text = self.chapter_prefix().unwrap_or_default() + &self.section.page_number(number);
        for content in paragraph.runs.iter().flat_map(|run| &run.content) {
            if let Content::Bookmark(name) = content {
                self.output.found_bookmarks.record(name, || text.clone());
                if let Some(label) = &resolved.label {
                    self.output
                        .found_numbers
                        .record(name, || label.reference.clone());
                }
            }
        }
    }

    /// Whether the paragraph mark of a paragraph is hidden (`w:vanish`), from its paragraph
    /// style, the mark's character style or the mark's own properties.
    fn mark_hidden(&self, resolved: &Resolved) -> bool {
        // F-Office hides the last empty paragraph of a cell or of the document in the same way.
        // quirk: HiddenLastMark::HidesEmptyParagraph (src/quirks.rs)
        self.mark_props(&resolved.run, &resolved.props)
            .hidden
            .unwrap_or(false)
    }

    /// Whether a paragraph shows nothing: its mark is hidden, and every run is empty or
    /// hidden, from the paragraph's style, the run's character style or its own properties.
    pub(super) fn shows_nothing(&self, paragraph: &Paragraph, resolved: &Resolved) -> bool {
        // A continuous section end shows nothing, with a list label or a paragraph border too.
        // quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
        (self.mark_hidden(resolved) || resolved.props.flags().continuous_end)
            && self.runs_show_nothing(paragraph, resolved, false)
    }

    /// Whether every run of a paragraph is empty or hidden, from the paragraph's style, the
    /// run's character style or its own properties. With `blank`, runs of only spaces count
    /// as empty too.
    fn runs_show_nothing(&self, paragraph: &Paragraph, resolved: &Resolved, blank: bool) -> bool {
        paragraph.runs.iter().all(|run| {
            let mut props = resolved.run.clone();
            if let Some(style) = &run.style {
                self.styles.apply_character(&mut props, style);
            }
            props.apply(&run.props);
            props.hidden.unwrap_or(false) || is_empty_run(run, blank)
        })
    }

    /// Whether the paragraph at `index` takes no room: an empty paragraph whose paragraph
    /// mark is hidden, but for the last paragraph of a table cell, whose mark ends the cell,
    /// and a paragraph that joins the one before it without a line. `rest` holds the blocks
    /// after the paragraphs.
    fn takes_no_room(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        index: usize,
        rest: Rest<'_>,
    ) -> bool {
        let cell_end =
            self.column.cell.is_some() && rest.table().is_none() && index + 1 == paragraphs.len();
        let hidden = !cell_end
            && paragraphs
                .get(index)
                .zip(resolved.get(index))
                .is_some_and(|(paragraph, r)| self.shows_nothing(paragraph, r));
        hidden || self.join_without_line(paragraphs, resolved, index)
    }

    /// Gives the paragraph that shows something after a run of paragraphs that show nothing and
    /// whose marks are hidden the border lines of the run's first paragraph, in place of its
    /// own, when it has a border or a fill of its own and the target and the mode join them
    /// so ([`super::decisions::joins_hidden_mark_borders`]). The run's paragraphs then have no
    /// borders, so that the joined paragraph starts its own group of borders. Its fill stays
    /// its own.
    fn join_hidden_mark_borders(&self, paragraphs: &[&Paragraph], resolved: &mut [Resolved]) {
        if !super::decisions::joins_hidden_mark_borders(
            &self.context.quirks,
            self.settings.mode_rules,
        ) {
            return;
        }
        let hidden: Vec<bool> = paragraphs
            .iter()
            .zip(resolved.iter())
            .map(|(paragraph, r)| self.shows_nothing(paragraph, r))
            .collect();
        let mut run_start = None;
        for (index, &shows_nothing) in hidden.iter().enumerate() {
            if shows_nothing {
                run_start.get_or_insert(index);
                continue;
            }
            let Some(first) = run_start.take() else {
                continue;
            };
            if !resolved.get(index).is_some_and(|r| decorated(&r.props)) {
                continue;
            }
            let lines = resolved.get(first).and_then(|r| r.props.borders());
            for paragraph in resolved.get_mut(first..index).into_iter().flatten() {
                paragraph.props.drop_borders();
            }
            if let Some(joined) = resolved.get_mut(index) {
                joined.props.borders = lines.map(Box::new);
            }
        }
    }

    /// Joins the paragraph at `index` to the paragraph before it, when that one shows
    /// something and its mark is hidden, and this one shows nothing but spaces and its mark,
    /// has no list label and ends no section. The join adds no line, and the joined paragraph
    /// ends with this paragraph's mark, so that its space after follows. Gives whether it
    /// joined them.
    fn join_without_line(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        index: usize,
    ) -> bool {
        let at = |i: usize| paragraphs.get(i).copied().zip(resolved.get(i));
        let (Some((before, before_resolved)), Some((paragraph, props))) =
            (index.checked_sub(1).and_then(at), at(index))
        else {
            return false;
        };
        let joins = self.mark_hidden(before_resolved)
            && !self.runs_show_nothing(before, before_resolved, false)
            && list_of(&props.props).is_none()
            && !props.props.flags().section_end
            && self.runs_show_nothing(paragraph, props, true);
        if joins && self.previous.is_some() {
            self.previous = Some(Previous::of(&props.props));
        }
        joins
    }
}

/// The color of a shaded paragraph's fill. A white fill is a fill like any other: it covers
/// the drawings behind the text under it.
fn paragraph_fill(props: &ParaProps) -> Option<Rgb> {
    props.shading.and_then(Color::rgb)
}

/// Whether a paragraph has a border line of its own on some side, or a fill.
fn decorated(props: &ParaProps) -> bool {
    let lined = props.borders().is_some_and(|b| {
        [b.top, b.bottom, b.left, b.right]
            .iter()
            .flatten()
            .any(|line| !line.is_none())
    });
    lined || paragraph_fill(props).is_some()
}

/// Whether a line starts after a clearing line break.
fn clears(line: &Line) -> bool {
    line.placed.first().is_some_and(|p| p.piece == Piece::Clear)
}

/// The line spacing of a paragraph with the properties `props`: single spacing when it sets
/// none.
fn line_spacing(props: &ParaProps) -> LineSpacing {
    props.line.unwrap_or(LineSpacing::Auto(LINE))
}

/// The side of a paragraph's text on which a border line lies from the rounded text edge
/// ([`Layout::text_edge_room`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TextEdgeSide {
    /// Above the first line, below a top border.
    Top,
    /// Below the last line, above a bottom border, with the part of the line below its text
    /// that the room takes: what multiple spacing above single spacing adds to the line under
    /// `MultipleBottomBorder::FromTextEdge`, and 0 elsewhere.
    Bottom(Length),
}

/// The list instance of a list paragraph, none when its list reference removes its list.
fn list_of(props: &ParaProps) -> Option<NonZeroU32> {
    props.numbering.and_then(ListRef::id)
}

/// The borders and outer horizontal indents that identify a paragraph's border group.
/// Consecutive paragraphs with equal keys form one group that shares a top line and a bottom
/// line; differing outer indents split the group.
#[derive(Clone, Copy, PartialEq, Eq)]
struct BorderKey {
    borders: Borders,
    left: Length,
    right: Length,
}

impl BorderKey {
    fn of(props: &ParaProps) -> Option<Self> {
        let borders = props.borders()?;
        let (left, right) = outer_indents(props);
        Some(Self {
            borders,
            left,
            right,
        })
    }
}

/// The outer left and right indents of a paragraph's border and shading box from the column's
/// edges: a hanging first line moves its side out by the hanging distance, while a positive
/// first-line indent leaves the box at the paragraph's side indents.
fn outer_indents(props: &ParaProps) -> (Length, Length) {
    let first = props.indent_first.unwrap_or(Length::ZERO).min(Length::ZERO);
    let (left_side, right_side, first_right) = props.side_indents();
    let (first_left, first_right) = if first_right {
        (Length::ZERO, first)
    } else {
        (first, Length::ZERO)
    };
    (left_side + first_left, right_side + first_right)
}

/// The border keys of the neighboring paragraphs. Paragraphs with equal borders and equal outer
/// horizontal indents form a group that shares one top line and one bottom line.
#[derive(Clone, Copy)]
struct Group {
    previous: Option<BorderKey>,
    next: Option<BorderKey>,
}

impl Group {
    /// Where the side lines of a paragraph start: at its top line, which is at `now`, when it
    /// starts its group, and else at its `start`, so that they run through the space between
    /// the paragraphs of the group.
    fn sides_top(&self, props: &ParaProps, (start, now): (Length, Length)) -> Length {
        if self.previous == BorderKey::of(props) {
            start
        } else {
            now
        }
    }

    /// The line between this paragraph and the one before it that a paragraph with `props`
    /// draws: the side between the paragraphs of its borders, when it does not start its group.
    /// A target that does not draw that side has dropped it from the borders.
    fn between(&self, props: &ParaProps) -> Option<Border> {
        let key = BorderKey::of(props);
        key.and_then(|k| k.borders.between)
            .filter(|_| self.previous == key)
    }

    /// The top and the bottom border line that a paragraph with `props` draws: its top line
    /// when it starts its group, and its bottom line when it ends it.
    fn lines(&self, props: &ParaProps) -> (Option<Border>, Option<Border>) {
        let key = BorderKey::of(props);
        let top = key
            .and_then(|k| k.borders.top)
            .filter(|_| self.previous != key);
        let bottom = key
            .and_then(|k| k.borders.bottom)
            .filter(|_| self.next != key);
        (top, bottom)
    }
}

/// Whether a paragraph starts a page with `w:pageBreakBefore`, so that a chain of kept blocks
/// before it ends there.
pub(super) fn starts_page(r: &Resolved) -> bool {
    r.props.flags().page_break_before
}

/// Whether a paragraph is kept with the next one (`w:keepNext`).
fn kept(r: &Resolved) -> bool {
    r.props.flags().keep_next
}

/// Whether the kept paragraph `r` of `lines` lines may split at the page's foot: without
/// `w:keepLines`, with at least two lines, and under widow control with enough lines to leave
/// two on each page. It splits there when its lines run past the foot, and from Word 2013 on
/// also when they all fit (`KEPT_SPLIT_MODE`).
fn splits_kept(r: &Resolved, lines: usize) -> bool {
    let flags = r.props.flags();
    let least = if flags.widow_control {
        2 * WIDOW_LINES
    } else {
        2
    };
    flags.keep_next && !flags.keep_lines && !flags.section_end && lines >= least
}

/// The lines of a kept paragraph that splits that go to the next page with the paragraph after
/// it: its last line, and the line before it under widow control.
fn kept_tail_lines(r: &Resolved) -> usize {
    if r.props.flags().widow_control {
        WIDOW_LINES
    } else {
        1
    }
}

/// The number of its `lines` lines that a paragraph needs on the page of the chain of kept
/// paragraphs before it. The paragraph after the chain needs the lines that orphan control
/// keeps together. A paragraph of three lines cannot split under widow control, and one with
/// `w:keepLines` cannot split at all. The empty paragraph that ends a section before a new
/// page stays on its page anyway, so the chain needs no room for it. A kept paragraph that
/// `splits` needs only the lines of a paragraph that is not kept.
fn needed_lines(r: &Resolved, lines: usize, splits: bool) -> usize {
    let flags = r.props.flags();
    let whole = (flags.keep_next && !splits) || flags.keep_lines;
    if flags.section_end {
        0
    } else if whole {
        lines
    } else if flags.widow_control {
        // A paragraph too short to leave enough lines on both pages moves as a whole.
        if lines < 2 * WIDOW_LINES {
            lines
        } else {
            WIDOW_LINES
        }
    } else {
        1
    }
}

/// The widow break of a paragraph that is being placed.
#[derive(Clone, Copy)]
struct WidowBreak {
    /// The line before which widow control or `w:keepLines` breaks the page, if any.
    line: Option<usize>,
    /// The part of a split cell where the forecast found the break. Widow control finds its
    /// break for the part where the paragraph starts, from a forecast that does not see wraps;
    /// when a line goes on to the next part before the break, the break no longer applies.
    cell_part: Option<usize>,
    /// The column of the page that holds the paragraph's last placed line, and the first of
    /// the paragraph's lines there.
    column: ((usize, usize), usize),
    /// Whether the break was forecast again after a drawing broke the lines again
    /// ([`Layout::wrap_and_forecast`]). Such a break applies once its line has met the drawings
    /// of its place: a line that goes below a drawing breaks again at the whole width there,
    /// and the forecast from it can find that the paragraph fits.
    after_wraps: bool,
    /// Whether a `w:keepLines` paragraph in compatibility modes below 15 has already checked
    /// for wraps starting inside its vertical span.
    aligned_keep_wrap: bool,
}

impl WidowBreak {
    /// Notes that the line `index` stands in the column `here`, which a new column or page
    /// starts with it.
    fn placed(&mut self, here: (usize, usize), index: usize) {
        if here != self.column.0 {
            self.column = (here, index);
        }
    }

    /// Whether the page breaks before the line `index`, in the part `part` of a split cell,
    /// at the check before the line meets the drawings of its place or, with `after_wraps`,
    /// at the check after it.
    fn breaks_before(&self, index: usize, part: Option<usize>, after_wraps: bool) -> bool {
        self.line == Some(index) && self.cell_part == part && self.after_wraps == after_wraps
    }
}

/// The line of a paragraph that is about to be placed, with its start and width from the
/// column edge when no drawing narrows it, and the part of that start that it keeps past the
/// wrap edge of a drawing on its left ([`kept_past_wrap_edge`]).
#[derive(Clone, Copy)]
struct Wrap {
    index: usize,
    first: bool,
    normal: (Length, Length),
    kept: Length,
}

impl Wrap {
    /// Line `index` of a paragraph in its frame `frame`, on a page whose column is `width`
    /// wide: `first` says whether it is the paragraph's first line, `bidi` whether the
    /// paragraph runs from right to left, and `keeps_hanging_first_start` whether compatibility
    /// modes below 15 keep `first_start` on a hanging-indent first line beside a left drawing.
    fn of(
        frame: &Frame,
        (index, first): (usize, bool),
        width: Length,
        bidi: bool,
        keeps_hanging_first_start: bool,
    ) -> Self {
        let normal = frame.on_page(first, width, bidi);
        let kept = kept_past_wrap_edge(frame, first, bidi, normal.0, keeps_hanging_first_start);
        Self {
            index,
            first,
            normal,
            kept,
        }
    }
}

/// Resumable state for stepping through one contiguous chunk of paragraphs.
pub(super) struct ParagraphChunkState {
    resolved: Vec<Resolved>,
    after_kept_row: bool,
    framed_until: usize,
    with_frame: bool,
    index: usize,
}

impl Layout<'_> {
    /// Prepares a contiguous paragraph chunk for incremental stepping via [`Self::flow_step`].
    pub(super) fn begin_paragraph_chunk(
        &mut self,
        paragraphs: &[&Paragraph],
        first: usize,
    ) -> ParagraphChunkState {
        let mut resolved: Vec<Resolved> = paragraphs.iter().map(|p| self.resolve(p)).collect();
        self.join_hidden_mark_borders(paragraphs, &mut resolved);
        let after_kept_row = std::mem::take(&mut self.table_chain) == super::TableChain::GoesOn;
        ParagraphChunkState {
            resolved,
            after_kept_row,
            framed_until: 0,
            with_frame: false,
            index: first,
        }
    }

    /// Advances `state` through `paragraphs`, stopping early when `stop_pages` is reached or
    /// `max_paragraphs` paragraphs have been processed. Returns `true` when the chunk is finished
    /// and the number of paragraphs processed.
    pub(super) fn flow_step(
        &mut self,
        paragraphs: &[&Paragraph],
        rest: Rest<'_>,
        state: &mut ParagraphChunkState,
        stop_pages: Option<usize>,
        max_paragraphs: usize,
    ) -> (bool, usize) {
        if paragraphs.is_empty() {
            return (true, 0);
        }
        let run_start = self
            .keeps_page_marks()
            .then(|| (self.numbering.clone(), self.table_chain));
        let mut processed = 0usize;
        while state.index < paragraphs.len() {
            let index = state.index;
            state.index += 1;
            if index < state.framed_until {
                continue;
            }
            if !self.flow_one_paragraph(paragraphs, rest, state, index, run_start.as_ref()) {
                continue;
            }
            processed += 1;
            let hit_limit = stop_pages.is_some_and(|n| self.output.pages.len() >= n)
                || processed >= max_paragraphs;
            if hit_limit {
                return (state.index >= paragraphs.len(), processed);
            }
        }
        (true, processed)
    }

    fn flow_one_paragraph(
        &mut self,
        paragraphs: &[&Paragraph],
        rest: Rest<'_>,
        state: &mut ParagraphChunkState,
        index: usize,
        run_start: Option<&(crate::numbering::Numbering, super::TableChain)>,
    ) -> bool {
        let Some(&paragraph) = paragraphs.get(index) else {
            return false;
        };
        let border_key = |i: Option<usize>| {
            i.and_then(|i| state.resolved.get(i))
                .filter(|r| !r.props.flags().continuous_end)
                .and_then(|r| BorderKey::of(&r.props))
        };
        self.note_paragraph_start(index, run_start.filter(|_| !state.with_frame));
        let group = Group {
            previous: border_key(index.checked_sub(1)),
            next: border_key(Some(index + 1)),
        };
        if self.takes_no_room(paragraphs, &state.resolved, index, rest) {
            return false;
        }
        if let Some((end, moved)) = self.frame_at(paragraphs, &state.resolved, index, rest) {
            state.framed_until = end;
            state.with_frame = moved;
            return true;
        }
        self.place_body_paragraph(paragraphs, rest, state, index, paragraph, &group);
        true
    }

    fn place_body_paragraph(
        &mut self,
        paragraphs: &[&Paragraph],
        rest: Rest<'_>,
        state: &mut ParagraphChunkState,
        index: usize,
        paragraph: &Paragraph,
        group: &Group,
    ) {
        let with_frame = std::mem::take(&mut state.with_frame);
        let Some(resolved_paragraph) = state.resolved.get(index) else {
            return;
        };
        self.page_start(paragraph, resolved_paragraph, with_frame);
        let chained = index
            .checked_sub(1)
            .and_then(|before| state.resolved.get(before))
            .map_or(state.after_kept_row, kept);
        let drawings_top =
            self.y + gap_parts(self.previous.as_ref(), &resolved_paragraph.props).after;
        let floating_pushes =
            !self.page_has_no_line() && self.floating_overflows_page(paragraph, drawings_top);
        if self.column.cell.is_none()
            && (self.keep_breaks(paragraphs, &state.resolved, (index, chained), rest)
                || floating_pushes)
        {
            self.next_column();
            self.previous = None;
            let stays = self
                .section_previous
                .as_ref()
                .is_some_and(|p| p.next_space == NewPageSpace::Stays);
            if !stays {
                self.advance_space(-resolved_paragraph.props.space_before());
            }
        }
        let previous = Previous::of(&resolved_paragraph.props);
        self.following_after = state.resolved.get(index + 1).map(|next| {
            if drops_after(&previous, &next.props) {
                Length::ZERO
            } else {
                previous.after
            }
        });
        self.kept_tail = self.kept_tail(paragraphs, &state.resolved, index, rest);
        self.before_frame_band((paragraphs, &state.resolved), index, |layout| {
            layout.paragraph(paragraph, resolved_paragraph, group);
        });
        self.following_after = None;
        self.kept_tail = None;
        let last = index + 1 == paragraphs.len();
        self.end_header_or_footer(paragraph, resolved_paragraph, (last, rest));
    }

    /// The paragraphs before `first` are laid out already, and the layout stands at the mark
    /// of `first`.
    pub(super) fn flow(&mut self, paragraphs: &[&Paragraph], rest: Rest<'_>, first: usize) {
        if paragraphs.is_empty() {
            return;
        }
        let mut state = self.begin_paragraph_chunk(paragraphs, first);
        let _ = self.flow_step(paragraphs, rest, &mut state, None, usize::MAX);
    }

    /// Ends a header or a footer at its last paragraph, `paragraph`, laid out just now: the
    /// last of its run of paragraphs when `last`, with no block in `rest` after it. When it
    /// shows something and its mark is hidden, no paragraph comes after it to join, and on a
    /// target that drops its space after the story ends at its last line, as when it joins an
    /// empty paragraph without space after.
    fn end_header_or_footer(
        &mut self,
        paragraph: &Paragraph,
        resolved: &Resolved,
        (last, rest): (bool, Rest<'_>),
    ) {
        let header_or_footer = matches!(
            self.story.as_ref().map(|story| &story.kind),
            Some(StoryKind::Header { .. } | StoryKind::Footer { .. })
        );
        if last
            && rest.is_end()
            && header_or_footer
            && self.column.cell.is_none()
            && self.mark_hidden(resolved)
            && !self.runs_show_nothing(paragraph, resolved, false)
            && let Some(previous) =
                super::decisions::dropped_end_space(&self.context.quirks, self.previous.as_mut())
                    .flatten()
        {
            previous.after = Length::ZERO;
            previous.after_auto = false;
        }
    }

    /// Whether a paragraph that is kept with the next one must start a new page, because
    /// the chain of kept blocks that it starts and the first lines of the paragraph after
    /// them, or the start of the table after them, do not fit on this page. Only the first
    /// block of a chain tests it: with `chained`, the paragraph goes on a chain that the
    /// blocks before it started, and it goes where they leave it. So a chain that does not
    /// fit even at the top of a page fills the page and breaks at its foot.
    fn keep_breaks(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        (index, chained): (usize, bool),
        rest: Rest<'_>,
    ) -> bool {
        if chained || self.page_has_no_line() || !resolved.get(index).is_some_and(kept) {
            return false;
        }
        self.chain_breaks(paragraphs, resolved, index, rest)
    }

    /// The last lines of the paragraph at `index` that go to the next page with the paragraph
    /// after it: a kept paragraph that splits leaves them there when the blocks after it do not
    /// fit below its last line. Whether its own lines fit, widow control decides.
    fn kept_tail(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        index: usize,
        rest: Rest<'_>,
    ) -> Option<usize> {
        let (paragraph, r) = paragraphs.get(index).zip(resolved.get(index))?;
        let mode_splits = self.settings.mode_rules.splits_kept_paragraphs();
        if self.column.cell.is_some() || !mode_splits || !kept(r) {
            return None;
        }
        let lines = self.prepare(paragraph, r).0.len();
        if !splits_kept(r, lines) {
            return None;
        }
        self.chain_breaks_from(paragraphs, resolved, (index, true), rest)
            .then(|| kept_tail_lines(r))
    }

    /// Whether the paragraph at `index`, the chain of kept paragraphs that it starts, and the
    /// first lines of the paragraph after them or the start of the table after them, do not
    /// fit on this page. A paragraph with `w:pageBreakBefore` starts a page anyway, so the
    /// chain ends before it and needs no room for it.
    ///
    /// A paragraph in a frame takes no room in the flow, so it takes none in the chain. A frame
    /// that hangs on the text must fit on the page as a whole. From Word 2013 on, a drop cap
    /// is no link of the chain, which goes on to the paragraph after it. At every other frame
    /// the chain ends, whether or not the frame's paragraph is kept with the next one.
    pub(super) fn chain_breaks(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        index: usize,
        rest: Rest<'_>,
    ) -> bool {
        self.chain_breaks_from(paragraphs, resolved, (index, false), rest)
    }

    /// As [`Self::chain_breaks`], where the paragraph at `index` needs all its lines when
    /// `whole_first` is set, so that a kept paragraph that splits does not end the chain there.
    fn chain_breaks_from(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        (index, whole_first): (usize, bool),
        rest: Rest<'_>,
    ) -> bool {
        let bottom = self.body_end();
        let mut y = self.y;
        let mut previous = self.previous.clone();
        // The chain's first paragraph has the space above it that `space_before` gives it:
        // after a continuous section end, only the part of its space before beyond the end's
        // space after.
        let mut section = self
            .section_previous
            .clone()
            .filter(|p| p.next_space == NewPageSpace::Stays);
        let mut at = index;
        while let Some((paragraph, r)) = paragraphs.get(at).zip(resolved.get(at)) {
            if at > index && starts_page(r) {
                return false;
            }
            if let Some((frame, end)) = self.frame_run(resolved, at) {
                let run = paragraphs.get(at..end).unwrap_or_default();
                let run_resolved = resolved.get(at..end).unwrap_or_default();
                let reach = self.frame_reach(run, run_resolved, frame);
                let top = y + frame_lead(previous.as_ref());
                if reach.is_some_and(|reach| top + reach > bottom) {
                    return true;
                }
                if !self.goes_with_text(frame) {
                    return false;
                }
                at = end;
                continue;
            }
            let (gap, own) = if let Some(end) = section.take() {
                let rest = gap_parts(Some(&end), &r.props).own();
                (rest, rest)
            } else {
                let parts = gap_parts(previous.as_ref(), &r.props);
                (parts.total(), parts.own())
            };
            y += gap;
            let link = (r, resolved.get(at + 1));
            let whole = whole_first && at == index;
            let Some((end, ends)) = self.link_end(paragraph, link, (y, own), (bottom, whole))
            else {
                return true;
            };
            // A page break in a kept paragraph ends the chain at the break, as a paragraph
            // with `w:pageBreakBefore` ends it before that paragraph, and a kept paragraph
            // that splits ends it after its first lines.
            if !kept(r) || ends {
                return false;
            }
            y = end;
            previous = Some(Previous::of(&r.props));
            at += 1;
        }
        // A chain that runs into a table stays with the table's first row, and goes on through
        // the table's kept rows.
        let Some((table, after)) = rest.table() else {
            return false;
        };
        let top = y + previous.map_or(Length::ZERO, |p| p.after);
        self.table_chain_breaks(table, (top, bottom), after)
    }

    /// Where the lines end that the paragraph `paragraph` needs on this page as a link of a
    /// chain of kept paragraphs, when its first line starts at `y`, and whether a page break
    /// ends them, or `None` when they run past `bottom`. `next` is the paragraph after it,
    /// which can remove its space after. `space_before` is the part of the paragraph's space
    /// before that the space after of the paragraph before it does not give.
    ///
    /// A line that a drawing of the page leaves no room beside goes below the drawing, with
    /// that space before for the paragraph's first line, as in the layout. What follows a page
    /// break starts the next page, so the paragraph needs no room for it. A kept paragraph that
    /// splits needs only its first lines, and the chain ends with them, unless `whole` asks for
    /// all its lines. The flag that it gives is whether the chain ends there.
    fn link_end(
        &mut self,
        paragraph: &Paragraph,
        (r, next): (&Resolved, Option<&Resolved>),
        (mut y, mut space_before): (Length, Length),
        (bottom, whole): (Length, bool),
    ) -> Option<(Length, bool)> {
        if self.floating_overflows_page(paragraph, y - space_before) {
            return None;
        }
        let (lines, mark, _) = self.prepare(paragraph, r);
        let may_split = !whole && splits_kept(r, lines.len());
        let frame = self.frame(r);
        let dropped = next.is_some_and(|next| drops_after(&Previous::of(&r.props), &next.props));
        let own = if dropped {
            Length::ZERO
        } else {
            r.props.space_after()
        };
        let first = needed_lines(r, lines.len(), true);
        let needed = if whole {
            lines.len()
        } else {
            needed_lines(r, lines.len(), false)
        };
        let page_break = lines
            .iter()
            .take(needed)
            .position(|line| line.end == LineEnd::PageBreak);
        let needed = page_break.map_or(needed, |at| at + 1);
        let first_line = Line::first_index(&lines, frame.breaking.leading_breaks);
        for (n, line) in lines.iter().enumerate().take(needed) {
            let size = self.line_box_of(line, (mark, n + 1 == lines.len()), &r.props);
            let bidi = r.props.flags().bidi;
            let (start, width) = frame.on_page(n == first_line, self.column.width, bidi);
            let kept = kept_past_wrap_edge(
                &frame,
                n == first_line,
                bidi,
                start,
                !self.uses_modern_floating_layout(),
            );
            if let Some(floating::Beside::Below(below) | floating::Beside::Step(below)) = self
                .beside(
                    (y, self.wrap_band(&size), size.step()),
                    (start, width),
                    kept,
                )
            {
                y = below + space_before;
            }
            let after = if n + 1 == lines.len() {
                own
            } else {
                Length::ZERO
            };
            if y + needed_room(&size, after, self.body_notes()) > bottom {
                // In every mode, a kept paragraph whose lines run past the foot splits there
                // when its first lines fit.
                return (may_split && n >= first).then_some((y, true));
            }
            y += size.height;
            space_before = Length::ZERO;
        }
        // From Word 2013 on, a kept paragraph that may split splits also when all its lines
        // fit, and its first lines end the chain.
        let splits = may_split && self.settings.mode_rules.splits_kept_paragraphs();
        Some((y, page_break.is_some() || splits))
    }

    /// The frame of the paragraph at `index` and the end of the run of paragraphs that share
    /// it, when the frame has a place of its own. A frame that lies where its text would lie,
    /// at the start of the text column, is laid out in the flow, so that a run of such frames
    /// stacks. Neighbor paragraphs with equal frame properties share one frame.
    pub(super) fn frame_run(
        &self,
        resolved: &[Resolved],
        index: usize,
    ) -> Option<(crate::props::FramePr, usize)> {
        let frame = *resolved.get(index)?.props.frame.as_deref()?;
        if !self.holds_frames() || frame.mark == FrameMark::Plain || frame.in_place() {
            return None;
        }
        let shared = resolved
            .get(index..)
            .unwrap_or_default()
            .iter()
            .take_while(|r| r.props.frame.as_deref() == Some(&frame))
            .count();
        Some((frame, index + shared))
    }

    /// Lays out the frame of the paragraph at `index`, when it has a frame with a place of its
    /// own, and gives the end of the run of paragraphs in that frame, and whether the frame
    /// started the next page. A frame that has no room on this page, or whose text has none,
    /// starts the next page, and its text follows it there.
    fn frame_at(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        index: usize,
        rest: Rest<'_>,
    ) -> Option<(usize, bool)> {
        let (frame, end) = self.frame_run(resolved, index)?;
        let run = paragraphs.get(index..end).unwrap_or_default();
        let run_resolved = resolved.get(index..end).unwrap_or_default();
        let moved = self.frame_leaves_page(paragraphs, resolved, (index, end), rest);
        if moved {
            self.next_column();
            self.previous = None;
            self.frame_places.clear();
        }
        let place = self.held_frame_place(index);
        self.frame_paragraphs((run, run_resolved), frame, place);
        Some((end, moved))
    }

    /// The place that the paragraph before held for the frame of the paragraph at `index`.
    fn held_frame_place(&self, index: usize) -> Option<Length> {
        self.frame_places
            .iter()
            .find(|&&(at, _)| at == index)
            .map(|&(_, place)| place)
    }

    /// Whether a paragraph that starts after a page break — or the endnote separator starting
    /// the endnotes flow — drops its space before in the document's compatibility mode.
    pub(super) fn drops_leading_break_space(&self) -> bool {
        self.settings.mode_rules.drops_space_after_page_break()
    }

    /// Starts a page for a paragraph that asks for one. A paragraph with `w:pageBreakBefore`
    /// starts a page, as after a page break. So does a paragraph that the wrap of its own
    /// drawing moved off the page before. `with_frame` says that a frame took the paragraph to
    /// the next page: it starts that page without space above it, as a paragraph does that is
    /// kept with the next one.
    fn page_start(&mut self, paragraph: &Paragraph, resolved: &Resolved, with_frame: bool) {
        let break_before =
            resolved.props.flags().page_break_before || self.held_for_wrap(paragraph);
        let space_before = resolved.props.space_before();
        if break_before && self.column.cell.is_none() && !self.page_has_no_line() {
            self.new_page();
            if self.drops_leading_break_space() {
                // From Word 2013 on, the paragraph has no space above it there.
                self.previous = None;
                self.advance_space(-space_before);
            } else if resolved.props.flags().page_break_before
                && super::decisions::space_above_after(&self.context.quirks, space_before).is_some()
            {
                // Before it, a paragraph with a page break before it keeps the part of its
                // space before that is larger than the space after of the paragraph before
                // the break, which stays on the page before, as at the top of a section that
                // starts a new page.
                self.section_previous = self.previous.take();
            } else {
                self.previous = None;
            }
        }
        if with_frame {
            self.advance_space(-space_before);
        }
    }

    /// Whether a frame goes with the paragraph after it: a drop cap, from Word 2013 on.
    fn goes_with_text(&self, frame: crate::props::FramePr) -> bool {
        frame.drop_cap && self.settings.mode_rules.moves_drop_cap_with_text()
    }

    /// Whether the frame of the paragraphs from `start` to `end` starts the next page: a frame
    /// of the body that hangs on the text and does not fit on this page as a whole, and from
    /// Word 2013 on also a drop cap whose text, the paragraph after it, has no room on this
    /// page for the lines that it needs there.
    fn frame_leaves_page(
        &mut self,
        paragraphs: &[&Paragraph],
        resolved: &[Resolved],
        (start, end): (usize, usize),
        rest: Rest<'_>,
    ) -> bool {
        if self.column.cell.is_some() || self.story.is_some() || self.page_has_no_line() {
            return false;
        }
        let Some(&frame) = resolved.get(start).and_then(|r| r.props.frame.as_deref()) else {
            return false;
        };
        let run = paragraphs.get(start..end).unwrap_or_default();
        let run_resolved = resolved.get(start..end).unwrap_or_default();
        let Some(reach) = self.frame_reach(run, run_resolved, frame) else {
            return false;
        };
        let place = self
            .held_frame_place(start)
            .unwrap_or_else(|| self.frame_text_place());
        if place + reach > self.body_end() {
            return true;
        }
        self.goes_with_text(frame)
            && end < paragraphs.len()
            && self.chain_breaks(paragraphs, resolved, end, rest)
    }

    /// Starts the next column or page for a paragraph whose first line, of `lines`, has no
    /// room on this one below a top border that takes `room`. A paragraph with drawings
    /// (`anchors`) takes its drawings with it, and a paragraph with a top border takes the
    /// border with it: the border stands above the line on the new page and not at the foot
    /// of the old one. An empty line that stays and a page break that leads the paragraph
    /// stay on their page, as they do without a border.
    fn first_leaves_page(
        &mut self,
        lines: &[Line],
        props: &ParaProps,
        mark: Option<FaceIndex>,
        (anchors, room): (bool, Length),
    ) {
        let Some(line) = lines.first() else { return };
        let last = lines.len() == 1;
        let stays = self.empty_lines() == super::EmptyLines::Stay && line.placed.is_empty();
        let held = stays || line.starts_with_page_break(0, last);
        if !anchors && (room == Length::ZERO || held) {
            return;
        }
        self.y += room;
        let leaves = self.leaves_page(line, props, (mark, 0, last));
        self.y -= room;
        if leaves {
            self.own_space_before = self.leave_column(self.own_space_before);
        }
    }

    /// Places the space before of a paragraph that starts here, sets its own space before and
    /// what that space does at the top of a new page, and gives the place where it starts.
    fn paragraph_top(&mut self, props: &ParaProps) -> Length {
        let start = self.y;
        // After a continuous section end, the space after of the paragraph before it is
        // placed already, and the rest of this paragraph's space before stays above it at the
        // top of the next page too.
        let new_page_space = self
            .section_previous
            .as_ref()
            .map_or(NewPageSpace::Goes, |p| p.next_space);
        let after = match new_page_space {
            NewPageSpace::Goes => gap_parts(self.previous.as_ref(), props).after,
            NewPageSpace::Stays => Length::ZERO,
        };
        let alone_break = self.alone_break.take().filter(|_| self.after_break);
        self.space_before(props);
        // The paragraph starts below the space after the paragraph before it, so that its own
        // space before lies inside it.
        self.start_space_before((self.y - start - after).max(Length::ZERO));
        // After a page break in a paragraph without text, which keeps its space after on the
        // page before, the part of this paragraph's own space before that is larger than that
        // space after is a space that the new page dropped.
        if let Some(alone) = alone_break.filter(|_| self.column.cell.is_none()) {
            self.first_space_before = gap_parts(Some(&alone), props).own();
        }
        self.new_page_space = new_page_space;
        start
    }

    /// Sets the own space before of the paragraph being laid out, `before`, and the space that
    /// its first line is below, as the paragraph starts and, with 0, once that line is placed.
    fn start_space_before(&mut self, before: Length) {
        self.own_space_before = before;
        self.first_space_before = before;
    }

    /// Places a line of a paragraph. A column break that starts a paragraph which goes on
    /// after the break takes the paragraph's own space before to the next column, above the
    /// text there, and the column that it ends gets none of it. `carries` says whether the
    /// paragraph can do so: with the anchor of a floating drawing before the break, the
    /// space stays above the break's line. Before compatibility mode 15, a line of the body
    /// that holds only a column break takes no room.
    fn line_at_break(
        &mut self,
        line: &Line,
        props: &ParaProps,
        (mark, carries): (Option<FaceIndex>, bool),
        place: LinePlace,
    ) {
        let only_break = line.end == LineEnd::ColumnBreak
            && line
                .placed
                .iter()
                .all(|placed| matches!(placed.piece, Piece::Strut(_)));
        let leads = only_break && place.index == 0 && !place.last;
        let no_room = only_break
            && self.column.cell.is_none()
            && !self.settings.mode_rules.column_break_line_has_height();
        // A line without room has no space above it either, so before mode 15 the space
        // before of a paragraph with an anchor before the break stands in no column.
        let before = if leads && (carries || no_room) {
            self.own_space_before
        } else {
            Length::ZERO
        };
        let page = self.output.pages.len();
        self.y -= before;
        if no_room {
            self.next_column();
        } else {
            let spaced = self.written_end_spaces(line, props);
            self.line(
                &self.with_kashidas(&spaced, props, place),
                props,
                mark,
                place,
            );
        }
        if carries && self.output.pages.len() == page {
            self.y += before;
        }
    }

    fn paragraph(&mut self, paragraph: &Paragraph, resolved: &Resolved, group: &Group) {
        let mut props = resolved.props.clone();
        // A table cell's lines follow the line grid only when the document sets
        // `w:adjustLineHeightInTable`.
        let cell_grid =
            self.table_number == 0 || self.settings.cell_grid == crate::styles::CellGrid::Follows;
        self.grid_pitch = self
            .section
            .line_pitch
            .filter(|_| props.flags().snap_to_grid && cell_grid);
        let cell_before = self.drops_leading_break_space().then_some(&mut props);
        let (lines, mark_face, features) = self.prepare_with(paragraph, resolved, cell_before);
        // A drawing placed down from its paragraph whose anchor stands on a later page than
        // the paragraph's first line counts from the top of the paragraph's part on that page.
        // A pass places such a drawing from the paragraph's top, finds the page of its anchor
        // and records the drawing when that page is a later one; the next pass lets the
        // drawings that an earlier pass recorded wait for the lines of their anchors.
        if !self.may_anchor_later(paragraph, &lines) {
            self.paragraph_lines(
                paragraph,
                (resolved, props, group),
                (lines, mark_face, features),
                &[],
            );
            return;
        }
        let later = self.context.earlier.later_anchors.of(paragraph.id);
        let lines = (lines, mark_face, features);
        let pages = self.paragraph_lines(paragraph, (resolved, props, group), lines, &later);
        for drawing in pages.later() {
            self.output.found_later.push((paragraph.id, drawing));
        }
    }

    /// Lays out a paragraph from its prepared `lines`, with the face of its mark and the
    /// features that its runs show, after [`Self::paragraph`] set its grid. The drawings of
    /// `later`, placed down from the paragraph, wait for the lines of their anchors and count
    /// from the top of the paragraph's part on their page, and the paragraph does not take
    /// them with it when its first line goes to the next page. Gives the pages of the
    /// paragraph's lines that hold the anchor marks of drawings placed down from it.
    fn paragraph_lines(
        &mut self,
        paragraph: &Paragraph,
        (resolved, props, group): (&Resolved, ParaProps, &Group),
        (lines, mark_face, features): (Vec<Line>, Option<FaceIndex>, RunFeatures),
        later: &[usize],
    ) -> AnchorPages {
        let dropped_end = self.start_trailing_break_end(&props, &lines);
        let mut frame = self.frame(resolved);
        let mut column_width = self.column.width;
        let start = self.paragraph_top(&props);
        let anchors = anchors_drawings(paragraph, later);
        let mut pages = AnchorPages::default();
        let (top, bottom, between) = self.border_lines(group, &props, (&lines, mark_face, anchors));
        // A shaded paragraph keeps a fills entry before its items for its fill, which comes
        // after them.
        let fills = self.open_paragraph_fill(&props);
        let mut fill_from = (fills, self.output.pages.len(), self.y);
        // The paragraph's drawings count from its top, above its top border.
        let drawings_top = self.y - self.own_space_before;
        let mut waiting = self.floating(paragraph, (drawings_top, &lines), later);
        let mut sides_from = (
            self.output.pages.len(),
            group.sides_top(&props, (start, self.y)),
        );
        if let Some(border) = between {
            self.between_line(&props, border);
        }
        let (line_top, fill_top) = top.map_or((None, None), |border| {
            self.top_border((&lines, mark_face), &props, border)
        });
        sides_from.1 = line_top.unwrap_or(sides_from.1);
        fill_from.2 = fill_top.unwrap_or(fill_from.2);
        let mut widows = self.widow_start(&lines, &props, mark_face);
        self.text_part = ((self.output.pages.len(), self.column_index), 0);
        let mut lines = lines;
        // The start and width of the lines that a drawing beside them narrows.
        let mut narrow: Narrowed = vec![None; lines.len()];
        let mut index = 0;
        // Whether the line goes on the baseline of the one before, in a further free piece.
        let mut continues = false;
        // Whether the line before stood beside a drop cap in the text.
        let mut beside_drop_cap = false;
        while index < lines.len() {
            if widows.breaks_before(index, self.filled_part(), false) {
                self.break_before_line();
            }
            let stays = self.empty_lines() == super::EmptyLines::Stay
                && lines.get(index).is_some_and(|l| l.placed.is_empty());
            // A page break that starts a paragraph which goes on after the break needs no
            // room: it stays on a page that is full.
            let leading_break = lines
                .get(index)
                .is_some_and(|l| l.starts_with_page_break(index, index + 1 == lines.len()));
            // A line that goes to the next page meets the wraps of that page there, those of
            // its header and footer among them. A paragraph that anchors drawings has placed
            // them on this page, so its lines keep their room here; but a line that holds the
            // anchor of a drawing that waits for its page goes before the drawing is placed.
            if !stays
                && !leading_break
                && let Some(line) = lines.get(index)
                && (!anchors || holds_later(line, later))
                && self.leaves_page(line, &props, (mark_face, index, index + 1 == lines.len()))
            {
                self.own_space_before = self.leave_column(self.own_space_before);
            }
            // The lines that go on in a column of another width break for that width.
            let rest = (&mut lines, &mut narrow, index);
            self.column_frame((&mut column_width, &mut frame), rest, resolved);
            trim_rebroken_end(&mut lines, &mut narrow, dropped_end);
            // The paragraph's first line, which may come after leading page breaks.
            let first = index == Line::first_index(&lines, frame.breaking.leading_breaks);
            let bidi = props.flags().bidi;
            let now = self.wrap_for(&frame, (index, first), bidi);
            // A drawing that waits for the line of its anchor is placed before the line meets
            // the wraps, as a drawing placed from the paragraph is placed before its lines.
            self.floating_on_line(paragraph, (&lines, index), &mut waiting);
            if self.wrap_and_forecast(
                (&mut lines, &mut narrow),
                (now, &frame),
                (&props, mark_face),
                (&mut widows, stays || continues),
            ) {
                trim_rebroken_end(&mut lines, &mut narrow, dropped_end);
                continue;
            }
            trim_rebroken_end(&mut lines, &mut narrow, dropped_end);
            let Some(line) = lines.get(index) else {
                break;
            };
            let piece = narrow.get(index).copied().flatten();
            beside_drop_cap = self.lines_under_drop_cap(line, piece.is_some(), beside_drop_cap);
            let line_of = (index, lines.len(), paragraph.id);
            let place = line_place(&frame, (piece, now.normal), (line_of, first), bidi);
            self.note_styled(paragraph, resolved.label.as_ref());
            let (top, page) = (self.y, self.output.pages.len());
            let carries = !anchors || !anchors_before_column_break(paragraph);
            let placed = self.output.placed.len();
            self.line_at_break(line, &props, (mark_face, carries), place);
            if let Some(placed) = self.output.placed.get(placed) {
                pages.note(paragraph, line, placed.page);
            }
            widows.placed((self.output.pages.len(), self.column_index), index);
            self.start_space_before(Length::ZERO);
            self.held_borders.top = Length::ZERO;
            continues = self.go_on_beside(&mut lines, &mut narrow, index, &frame, (top, page));
            trim_rebroken_end(&mut lines, &mut narrow, dropped_end);
            if index == 0 {
                self.note_bookmarks(paragraph, resolved);
            }
            index += 1;
        }
        self.warn_of_paragraph_features(&lines, &props, features);
        self.finish_paragraph_frame(
            (&lines, mark_face),
            (&props, bottom),
            (sides_from, fill_from),
            dropped_end,
        );
        pages
    }

    /// Notes when a continuous section-end paragraph dropped its trailing empty line after a
    /// line break so that its space after requires no room at the foot of the page.
    fn start_trailing_break_end(&mut self, props: &ParaProps, lines: &[Line]) -> bool {
        let dropped = props.flags().continuous_break_end
            && self.column.cell.is_none()
            && self.story.is_none()
            && lines
                .last()
                .is_some_and(|line| matches!(line.end, LineEnd::Break(_)));
        if dropped {
            self.following_after = Some(Length::ZERO);
        }
        dropped
    }

    /// Closes a paragraph's bottom border, side lines, fill and trailing spacing state.
    fn finish_paragraph_frame(
        &mut self,
        (lines, mark_face): (&[Line], Option<FaceIndex>),
        (props, bottom): (&ParaProps, Option<crate::props::Border>),
        (sides_from, fill_from): ((usize, Length), (Option<FillsEntry>, usize, Length)),
        dropped_end: bool,
    ) {
        // The last line's box as the page placed it, with the room of the bottom border that it
        // holds.
        let last = lines
            .last()
            .map(|line| self.line_box_of(line, (mark_face, true), props));
        self.held_borders = HeldBorders::NONE;
        let fill_to = bottom.and_then(|border| self.bottom_border(props, border, last));
        self.last_bar = None;
        self.side_lines(sides_from, props);
        self.fill_paragraph(fill_from, fill_to, props);
        self.finish_paragraph_spacing(lines, props, dropped_end);
    }

    /// Records the spacing state that the finished paragraph leaves for the block after it.
    /// After a page break at its end, the paragraph's space after stays on its page. After a
    /// dropped trailing empty line on a continuous section end (before mode 15), the paragraph's
    /// space after does not push the next block down, and the next section's first paragraph
    /// keeps only the part of its space before beyond it.
    fn finish_paragraph_spacing(&mut self, lines: &[Line], props: &ParaProps, dropped_end: bool) {
        if dropped_end {
            self.previous = None;
            self.section_previous = Some(Previous::of(props));
            self.alone_break = None;
            return;
        }
        let broken =
            lines.last().is_some_and(Line::breaks_page_or_column) && self.column.cell.is_none();
        self.previous = (!broken).then(|| Previous::of(props));
        self.alone_break = (broken && breaks_page_alone(lines)).then(|| Previous::of(props));
    }

    /// Gives the warnings of the paragraph's features that F-Office lays out in another way,
    /// once for the paragraph each, from its laid out `lines`, its properties and the features
    /// that its runs that draw text show, `runs`: once for each feature and part.
    fn warn_of_paragraph_features(&mut self, lines: &[Line], props: &ParaProps, runs: RunFeatures) {
        self.warn_of_text_alignment(lines, props);
        self.warn_of_hanging_punctuation(lines, props);
        self.warn_of_text_direction(props);
        self.warn_of_paragraph_settings(props);
        for (feature, part) in runs {
            self.warn_of_feature(feature, part.as_str());
        }
    }

    /// Warns once for the paragraph of each of its settings that F-Office does not apply, where
    /// the setting would change the page:
    /// mirrored indents whose left and
    /// right indents differ (`w:mirrorIndents`), a right indent that moves to the section's grid
    /// of characters in a paragraph on the grid (`w:adjustRightInd`, on by default), lines that
    /// take part in the tight wrap of their text box (`w:textboxTightWrap`), and an HTML div
    /// with margins or borders (`w:divId`), which Word adds to the paragraph. Each warning names
    /// the part that sets the setting
    /// ([`Layout::setting_part`]).
    fn warn_of_paragraph_settings(&mut self, props: &ParaProps) {
        let flags = props.flags();
        let indent = |side: Option<Length>| side.unwrap_or(Length::ZERO);
        let in_text_box = self
            .story
            .as_ref()
            .is_some_and(|story| matches!(story.kind, super::StoryKind::TextBox { .. }));
        let shapes = props
            .div
            .as_ref()
            .filter(|div| self.context.html_divs.shapes(div.value));
        let features = [
            (
                flags.mirror_indents && indent(props.indent_left) != indent(props.indent_right),
                crate::Feature::MirrorIndents,
                props.mirror_indents.as_ref().map(|set| set.part.as_str()),
            ),
            (
                flags.adjust_right_indent
                    && flags.snap_to_grid
                    && self.section.char_pitch.is_some(),
                crate::Feature::GridRightIndent,
                props
                    .adjust_right_indent
                    .as_ref()
                    .map(|set| set.part.as_str()),
            ),
            (
                flags.tight_wrap && in_text_box,
                crate::Feature::TextBoxTightWrap,
                props.tight_wrap.as_ref().map(|set| set.part.as_str()),
            ),
            (
                shapes.is_some(),
                crate::Feature::HtmlDiv,
                shapes.map(|set| set.part.as_str()),
            ),
        ];
        for (_, feature, part) in features.into_iter().filter(|(acts, ..)| *acts) {
            let part = self.setting_part(part);
            self.warn_of_feature(feature, part);
        }
    }

    /// Warns once for the paragraph when its text alignment lies off the baseline and one of
    /// its `lines` holds pieces of two heights ([`Layout::holds_two_heights`]) that F-Office
    /// sets on one baseline, where the text alignment sets the smaller run of such lines higher:
    /// every such line but a centered line
    /// whose pieces' middles F-Office puts on one line ([`Layout::centered_line`]). The warning
    /// names the part that sets the text alignment.
    fn warn_of_text_alignment(&mut self, lines: &[Line], props: &ParaProps) {
        let Some(set) = props
            .text_alignment
            .as_ref()
            .filter(|set| set.value.off_baseline())
        else {
            return;
        };
        // A centered line whose pieces' middles lie on one line is drawn as Word draws it.
        // quirk: CenteredLine::MiddlesShared (src/quirks.rs)
        if lines
            .iter()
            .any(|line| self.holds_two_heights(line) && self.centered_line(line, props).is_none())
        {
            self.warn_of_feature(crate::Feature::TextAlignment, set.part.as_str());
        }
    }

    /// Warns once for the paragraph when a line ends before a word that Word keeps on it by
    /// letting the word's last mark stand past the end of the line, as `w:overflowPunct` asks
    /// by default: F-Office hangs no mark and moves the word.
    /// The warning names the part that
    /// sets `w:overflowPunct`, or the main document's where no layer sets it.
    fn warn_of_hanging_punctuation(&mut self, lines: &[Line], props: &ParaProps) {
        if lines.iter().any(|line| line.would_hang) {
            let part =
                self.setting_part(props.overflow_punct.as_ref().map(|set| set.part.as_str()));
            self.warn_of_feature(crate::Feature::HangingPunctuation, part);
        }
    }

    /// Warns once for the paragraph when it stands in a frame and its text direction turns the
    /// text: Word uses a paragraph's text direction only in a frame ([MS-OI29500] 2.1.63), and
    /// F-Office lays the paragraph out upright. Outside frames, the text stays upright, as
    /// F-Office lays it out. The warning names the part
    /// that sets the text direction.
    fn warn_of_text_direction(&mut self, props: &ParaProps) {
        let framed = props
            .frame
            .as_deref()
            .is_some_and(|frame| frame.mark == crate::props::FrameMark::Frame);
        let Some(set) = props.text_direction.as_ref().filter(|set| set.value) else {
            return;
        };
        if framed {
            self.warn_of_feature(crate::Feature::ParagraphTextDirection, set.part.as_str());
        }
    }

    /// When the column has another width than `width`, the width of the column for which
    /// the lines from `index` on were broken: takes the paragraph's frame in this column and
    /// breaks those lines again for it.
    fn column_frame(
        &self,
        (width, frame): (&mut Length, &mut Frame),
        (lines, narrow, index): (&mut Vec<Line>, &mut Narrowed, usize),
        resolved: &Resolved,
    ) {
        if std::mem::replace(width, self.column.width) != self.column.width {
            *frame = self.frame(resolved);
            break_again(lines, narrow, index, frame);
        }
    }

    /// The room that a line of the box `size` with the space `after` below it needs to stay
    /// where it is: in a cell of a row that splits, its whole height and that space; in the
    /// body, what the footnotes of the page ask for.
    fn line_room(&self, size: &super::line::height::LineBox, after: Length) -> Length {
        if self.column.cell.is_some() {
            size.height + after
        } else {
            needed_room(size, after, self.body_notes())
        }
    }

    /// The line of a paragraph before which widow control or `w:keepLines` breaks the page,
    /// or, in a cell of a row that splits, moves the rest of the cell to the next page. In a
    /// cell, widow control applies from Word 2013 on.
    fn forced_break(
        &mut self,
        lines: &[Line],
        props: &ParaProps,
        mark: Option<FaceIndex>,
    ) -> Option<usize> {
        if self.column.cell.is_none() {
            return self.widow_break(lines, props, mark, None);
        }
        self.carry_limit()
            .filter(|_| self.settings.mode_rules.controls_widows_in_cells())
            .and_then(|limit| self.widow_break(lines, props, mark, Some(limit)))
    }

    /// Starts the next column or page before a line, or, in a cell, moves the rest of the
    /// cell to the next page.
    fn break_before_line(&mut self) {
        if self.column.cell.is_some() {
            self.carry_rest();
        } else if !self.page_has_no_line() {
            self.next_column();
        }
    }

    /// Goes on with the line at `index`, placed from `top` on `page`, in the next free piece
    /// beside drawings on its baseline, when that piece holds the line that follows: breaks the
    /// rest of the paragraph for it, and keeps the lowest bottom of the line's parts for the
    /// line after them. Gives whether the line goes on.
    fn go_on_beside(
        &mut self,
        lines: &mut Vec<Line>,
        narrow: &mut Narrowed,
        index: usize,
        frame: &Frame,
        (top, page): (Length, usize),
    ) -> bool {
        if !self.same_baseline.is_empty() && page == self.output.pages.len() {
            let piece = self.same_baseline.remove(0);
            let rest = Line::pieces(lines.get(index + 1..).unwrap_or_default());
            let shift = piece
                .edge
                .filter(|_| !self.uses_modern_floating_layout())
                .unwrap_or(Length::ZERO);
            let next = break_part(&rest, frame, (piece.start, piece.width), (false, shift));
            if next.first().is_some_and(|line| holds(line, piece.width)) {
                let bottom = self.line_floor.map_or(self.y, |floor| floor.max(self.y));
                lines.truncate(index + 1);
                narrow.truncate(index + 1);
                narrow.push(Some(piece));
                narrow.extend(std::iter::repeat_n(None, next.len().saturating_sub(1)));
                lines.extend(next);
                self.move_to(top);
                self.line_floor = Some(bottom);
                return true;
            }
        }
        self.same_baseline.clear();
        if let Some(bottom) = self.line_floor.take()
            && bottom > self.y
        {
            self.move_to(bottom);
        }
        false
    }

    /// The [`Wrap`] of line `index` of a paragraph in `frame` (`first` says whether it is the
    /// paragraph's first line, `bidi` whether it runs from right to left).
    fn wrap_for(&self, frame: &Frame, (index, first): (usize, bool), bidi: bool) -> Wrap {
        Wrap::of(
            frame,
            (index, first),
            self.column.width,
            bidi,
            !self.uses_modern_floating_layout(),
        )
    }

    /// In compatibility modes below 15, shifts a `w:keepLines` body paragraph down when one of
    /// its lines starts above a wrapped drawing's top yet overlaps that wrap's band.
    fn align_keep_lines_to_wrap(
        &mut self,
        lines: &[Line],
        (first_index, first, keeps): (usize, bool, bool),
        (props, mark): (&ParaProps, Option<FaceIndex>),
        checked: &mut bool,
    ) {
        if !first
            || *checked
            || keeps
            || !props.flags().keep_lines
            || self.uses_modern_floating_layout()
            || self.column.cell.is_some()
            || self.story.is_some()
            || self.squares.is_empty()
        {
            return;
        }
        *checked = true;
        let bands: Vec<(Length, Length)> = lines
            .get(first_index..)
            .unwrap_or_default()
            .iter()
            .enumerate()
            .map(|(offset, line)| {
                let last = first_index + offset + 1 == lines.len();
                let size = self.line_box_of(line, (mark, last), props);
                (size.height, self.wrap_band(&size))
            })
            .collect();
        if let Some((target, keeps_before)) = self.keep_lines_wrap_target(&bands) {
            let space = if keeps_before {
                std::mem::take(&mut self.own_space_before)
            } else {
                Length::ZERO
            };
            self.move_to(target + space);
        }
    }

    /// Breaks `pieces` in `frame` for `piece` (or `normal` when no drawing narrows the line),
    /// shifting custom and default tab stops to the left wrap edge in compatibility modes below 15.
    fn break_for_piece(
        &self,
        pieces: &[Piece],
        frame: &Frame,
        piece: Option<floating::NarrowedPiece>,
        normal: (Length, Length),
    ) -> Vec<Line> {
        let shift = piece
            .and_then(|p| p.edge)
            .filter(|_| !self.uses_modern_floating_layout())
            .unwrap_or(Length::ZERO);
        let bounds = piece.map_or(normal, |p| (p.start, p.width));
        break_part(pieces, frame, bounds, (piece.is_some(), shift))
    }

    /// Clears stacked `wrapTopAndBottom` bands and full-width or stepped `wrapSquare` wraps
    /// iteratively until `self.y` either lands clear of every wrap or beside a `wrapSquare`
    /// drawing with horizontal room. Keeps `self.own_space_before` above the final cleared wrap.
    fn clear_stacked_wraps(
        &mut self,
        size: &super::line::height::LineBox,
        now: Wrap,
    ) -> (Option<floating::NarrowedPiece>, Length) {
        let space = self.own_space_before;
        let mut moved = false;
        let mut last_below = self.y;
        loop {
            let next_bottom = if let Some(below) = self.band_below(size) {
                Some(below)
            } else {
                let at = (self.y, self.wrap_band(size), size.step());
                match self.beside(at, now.normal, now.kept) {
                    Some(floating::Beside::Line(piece, below, more)) => {
                        if moved {
                            self.own_space_before = Length::ZERO;
                        }
                        self.same_baseline = more;
                        return (Some(piece), below);
                    }
                    Some(floating::Beside::Below(bottom) | floating::Beside::Step(bottom)) => {
                        Some(bottom)
                    }
                    None => None,
                }
            };
            let Some(bottom) = next_bottom.filter(|&b| b + space > self.y) else {
                break;
            };
            self.move_to(bottom + space);
            moved = true;
            last_below = bottom;
        }
        if moved {
            self.own_space_before = Length::ZERO;
        }
        (None, last_below)
    }

    /// Breaks the lines of a paragraph from `now.index` on again when a drawing that text
    /// flows beside narrows the line there, or when the line has passed the drawing.
    fn wrap_beside(
        &mut self,
        lines: &mut Vec<Line>,
        narrow: &mut Narrowed,
        now: Wrap,
        frame: &Frame,
        (props, mark): (&ParaProps, Option<FaceIndex>),
    ) {
        let Some(line) = lines.get(now.index) else {
            return;
        };
        self.same_baseline.clear();
        if clears(line) {
            self.clear_floats();
        }
        let last = now.index + 1 == lines.len();
        let size = self.line_box_of(line, (mark, last), props);
        let (mut wanted, below) = self.clear_stacked_wraps(&size, now);
        // A line without text chooses its free piece: a line of inline objects takes the first
        // one from the left that holds them, as a line of text does, and another line, such as
        // an empty paragraph's or one of tabs, keeps to the widest one.
        let no_text = !holds_glyph_besides_ascii_space(line);
        let objects = no_text && holds_object(line);
        let objects_width = line.width();
        if no_text && !self.same_baseline.is_empty() {
            let pieces: Vec<_> = wanted
                .into_iter()
                .chain(self.same_baseline.drain(..))
                .collect();
            wanted = if objects {
                pieces
                    .iter()
                    .copied()
                    .find(|piece| objects_width <= piece.width)
                    .or_else(|| pieces.first().copied())
            } else {
                pieces.into_iter().max_by_key(|piece| piece.width)
            };
        }
        let tail = lines.get(now.index..).unwrap_or_default();
        let modern = self.uses_modern_floating_layout();
        let needs_fallback = wanted.is_some_and(|piece| {
            (!self.same_baseline.is_empty() && rejects_piece(tail, piece.width, modern))
                || (below > self.y && overflows_piece(tail, piece.width, modern))
        });
        if narrow.get(now.index).copied().flatten() == wanted && !needs_fallback {
            return;
        }
        let pieces = Line::pieces(tail);
        let rest = self.break_for_piece(&pieces, frame, wanted, now.normal);
        // A piece that cannot hold one whole word stays empty, and the line goes on in the
        // next free piece on its baseline.
        if let Some(piece) = wanted
            && !self.same_baseline.is_empty()
            && rejects_piece(&rest, piece.width, modern)
        {
            let next = self.same_baseline.remove(0);
            let more = std::mem::take(&mut self.same_baseline);
            narrow.truncate(now.index);
            lines.truncate(now.index + 1);
            let rest = self.break_for_piece(&pieces, frame, Some(next), now.normal);
            self.same_baseline = more;
            lines.truncate(now.index);
            narrow.extend(std::iter::repeat_n(Some(next), rest.len()));
            lines.extend(rest);
            return;
        }
        // A line beside a drawing that cannot hold one whole word, or a line of inline pictures
        // that no free piece holds, goes below the drawing.
        if let Some(piece) = wanted
            && below > self.y
            && overflows_piece(&rest, piece.width, modern)
        {
            self.move_to(below);
            lines.truncate(now.index + 1);
            narrow.truncate(now.index);
            lines.splice(
                now.index..,
                break_part(&pieces, frame, now.normal, (false, Length::ZERO)),
            );
            self.wrap_beside(lines, narrow, now, frame, (props, mark));
            return;
        }
        lines.truncate(now.index);
        narrow.truncate(now.index);
        narrow.extend(std::iter::repeat_n(wanted, rest.len()));
        lines.extend(rest);
    }

    /// The first line of a paragraph that has no room on the page where the paragraph starts,
    /// if the lines before it hold no page or column break. In the body, each line needs its
    /// room above the footnotes of the page, those of the lines before it and its own among
    /// them, as when the line is placed; the caller takes the recorded footnotes away again.
    fn first_break(
        &mut self,
        lines: &[Line],
        props: &ParaProps,
        mark: Option<FaceIndex>,
        limit: Option<Length>,
    ) -> Option<usize> {
        let mut y = self.y;
        for (index, line) in lines.iter().enumerate() {
            let last = index + 1 == lines.len();
            let size = self.line_box_of(line, (mark, last), props);
            let after = self.kept_after(props, last);
            let first = index == 0 && self.page_has_no_line();
            let over = if let Some(limit) = limit {
                y + self.line_room(&size, after) > limit
            } else {
                self.forecast_over(line, (y, &size, after), first)
            };
            if over && !first {
                return Some(index);
            }
            if line.breaks_page_or_column() {
                return None;
            }
            y += size.height;
        }
        None
    }

    /// Whether a line of the body at `y`, with the box `size` and the space `after`, has no
    /// room above the footnotes of the page, in a forecast: it records the line's footnotes.
    /// A line whose footnote goes on to the next page has room, and the lines after it have
    /// none. `first` is the first line of a page, which stays in any case.
    fn forecast_over(
        &mut self,
        line: &Line,
        (y, size, after): (Length, &super::line::height::LineBox, Length),
        first: bool,
    ) -> bool {
        let (numbers, room) = self.new_notes(line);
        if self.body_has_ended() {
            return true;
        }
        let over = self.lacks_room_at(y, size, after, room);
        let part = if over && !first {
            self.split_part(&numbers, (y, size, after), Length::ZERO)
        } else {
            None
        };
        let Some((room, part)) = part else {
            self.add_notes(numbers, room);
            return over;
        };
        self.add_notes(numbers, room);
        self.keep_part(part);
        false
    }

    /// The line before which a page break must come so that neither the first nor the last
    /// line of the paragraph stands alone on a page, or so that a paragraph with
    /// `w:keepLines` stays whole. `None` means that the lines can break where they fill the
    /// page. `limit` is where the rest of a cell must end; without it the lines are the
    /// body's, which end above the footnotes of the page.
    fn widow_break(
        &mut self,
        lines: &[Line],
        props: &ParaProps,
        mark: Option<FaceIndex>,
        limit: Option<Length>,
    ) -> Option<usize> {
        let flags = props.flags();
        let (widows, whole) = (flags.widow_control, flags.keep_lines);
        let tail = self.kept_tail.take();
        if !(widows || whole || tail.is_some()) || lines.len() < 2 {
            return None;
        }
        // The forecast records the footnotes of the lines, and the page gets its footnotes
        // back as they were before it.
        let notes = self.page_notes.clone();
        let first_break = self.first_break(lines, props, mark, limit);
        let splits = self.forecast_splits(&notes);
        self.page_notes = notes;
        // A kept paragraph whose lines all fit leaves its last lines to the paragraph after it.
        if first_break.is_none() {
            return tail.map(|moved| lines.len().saturating_sub(moved));
        }
        if !(widows || whole) {
            return None;
        }
        // A line whose footnote goes on to the next page ends the body of its page. Widow
        // control moves that break down: the lines that it binds to the line stay.
        if splits && !whole {
            if let Some(first) = first_break {
                self.reserve_bound_lines(lines, (props, mark), first);
            }
            return None;
        }
        let first_break = first_break.filter(|index| *index > 0)?;
        let count = lines.len();
        if whole || first_break == 1 {
            Some(0)
        } else if first_break + 1 == count {
            // Moving one more line down must not leave the first line alone.
            let moved = count.saturating_sub(WIDOW_LINES);
            Some(if moved < WIDOW_LINES { 0 } else { moved })
        } else {
            None
        }
    }

    /// The widow break that a paragraph of the lines `lines` starts with: the forecast of its
    /// start ([`Self::forced_break`]), in the column where it starts.
    fn widow_start(
        &mut self,
        lines: &[Line],
        props: &ParaProps,
        mark: Option<FaceIndex>,
    ) -> WidowBreak {
        WidowBreak {
            line: self.forced_break(lines, props, mark),
            cell_part: self.filled_part(),
            column: ((self.output.pages.len(), self.column_index), 0),
            after_wraps: false,
            aligned_keep_wrap: false,
        }
    }

    /// Breaks the lines of a paragraph from `now.index` on again beside the drawings of the page
    /// ([`Self::wrap_beside`]), unless the line `keeps` its place: an empty line that stays, or
    /// a line that goes on on the baseline of the one before. A line that a drawing or a frame
    /// of the page before narrowed has its whole width again on a page without them. Where the
    /// target counts the lines as the drawings break them and they broke again in the body,
    /// widow control forecasts its break again from that line ([`Self::widow_break_from`]),
    /// and the break replaces the one of the paragraph's start, whose line numbers belong to
    /// the lines before; it applies to its line once the line has met the drawings of its
    /// place. Gives whether the line goes to the next page, with the last line, before it is
    /// placed.
    fn wrap_and_forecast(
        &mut self,
        (lines, narrow): (&mut Vec<Line>, &mut Narrowed),
        (now, frame): (Wrap, &Frame),
        (props, mark): (&ParaProps, Option<FaceIndex>),
        (widows, keeps): (&mut WidowBreak, bool),
    ) -> bool {
        let was = (lines.len(), narrow.get(now.index).copied().flatten());
        if keeps {
            return false;
        }
        self.align_keep_lines_to_wrap(
            lines,
            (now.index, now.first, false),
            (props, mark),
            &mut widows.aligned_keep_wrap,
        );
        if was.1.is_some() || !self.squares.is_empty() {
            self.wrap_beside(lines, narrow, now, frame, (props, mark));
            let broken = (lines.len(), narrow.get(now.index).copied().flatten()) != was;
            if broken
                && self.column.cell.is_none()
                && self.story.is_none()
                && super::decisions::widows_as_wrapped(&self.context.quirks)
            {
                self.forecast_after_wraps(lines, now.index, (props, mark), widows);
            }
        }
        if !widows.breaks_before(now.index, self.filled_part(), true) {
            return false;
        }
        self.break_before_line();
        widows.line = None;
        true
    }

    /// Forecasts the widow break of [`Self::wrap_and_forecast`] again from the line `from`,
    /// which a drawing has just broken again, with the lines as they now break.
    fn forecast_after_wraps(
        &mut self,
        lines: &[Line],
        from: usize,
        (props, mark): (&ParaProps, Option<FaceIndex>),
        widows: &mut WidowBreak,
    ) {
        let here = (self.output.pages.len(), self.column_index);
        let part_start = if here == widows.column.0 {
            widows.column.1
        } else {
            from
        };
        widows.line = self.widow_break_from(lines, (from, part_start), props, mark);
        widows.cell_part = self.filled_part();
        widows.after_wraps = true;
    }

    /// The line before which widow control breaks the page, forecast again from the line
    /// `from` at the current place, after a drawing beside the lines has broken them again
    /// there; the lines from `part_start` on stand on the current page. Only the paragraph's
    /// last line counts: when it alone would go to the next page, the line before it goes too,
    /// if that leaves two lines on the page where the paragraph starts, or one on a later page.
    /// `None` means that the lines break where they fill the page.
    fn widow_break_from(
        &mut self,
        lines: &[Line],
        (from, part_start): (usize, usize),
        props: &ParaProps,
        mark: Option<FaceIndex>,
    ) -> Option<usize> {
        let flags = props.flags();
        if !flags.widow_control || flags.keep_lines {
            return None;
        }
        // The forecast records the footnotes of the lines, and the page gets its footnotes
        // back as they were before it.
        let notes = self.page_notes.clone();
        let first_break = self.first_break(lines.get(from..)?, props, mark, None);
        let splits = self.forecast_splits(&notes);
        self.page_notes = notes;
        let at = from + first_break.filter(|_| !splits)?;
        let least = if part_start == 0 { WIDOW_LINES } else { 1 };
        let moved = at.checked_sub(1)?;
        let alone = at + 1 == lines.len();
        (alone && moved >= from && moved.saturating_sub(part_start) >= least).then_some(moved)
    }

    /// Draws the top border of a paragraph whose first lines are `lines` and adds its width
    /// and space to the paragraph. A target can place the line of a paragraph of single or
    /// at-least spacing from the rounded text edge below it, in every story
    /// ([`Layout::top_line_from_text_edge`]). Otherwise, above a first line whose at-least
    /// minimum sets its height, the line stands on the text's single line
    /// ([`Layout::on_ascent_shift`]), and above any other first line of the body and its tables,
    /// a target can place the line from the content start below it
    /// ([`Layout::top_line_from_content_start`]). Headers, footers and the other stories keep
    /// the nearest dot. In the body above a first line without extra room, it returns the
    /// line's top where a target places the line from the text edge or the content start: the
    /// side lines of a box start there. It also returns the line's bottom as drawn where the
    /// paragraph's fill starts there ([`Layout::fill_edge`]).
    fn top_border(
        &mut self,
        (lines, mark_face): (&[Line], Option<FaceIndex>),
        props: &ParaProps,
        border: Border,
    ) -> (Option<Length>, Option<Length>) {
        let first = lines
            .first()
            .map(|line| self.line_box_of(line, (mark_face, lines.len() == 1), props));
        let least = first.filter(|size| size.least_extra() > Length::ZERO);
        if let Some(size) = self.device.text_edge_line(line_spacing(props), first) {
            let (top, inner) = self.top_line_from_text_edge(&size, props, border);
            let sides = (least.is_none() && self.story.is_none()).then_some(top);
            return (sides, self.fill_edge(inner));
        }
        if super::decisions::multiple_top_from_text_edge(&self.context.quirks, line_spacing(props))
        {
            let (top, inner) = self.multiple_top_line(props, border);
            return (self.story.is_none().then_some(top), self.fill_edge(inner));
        }
        if least.is_none()
            && self.story.is_none()
            && let Some((top, inner)) = self.top_line_from_content_start(props, border)
        {
            return (Some(top), self.fill_edge(inner));
        }
        let shift = least.map_or(Length::ZERO, |size| self.on_ascent_shift(&size, border));
        self.y += shift;
        let inner = self.border_line(props, border, true);
        self.y -= shift;
        (None, self.fill_edge(inner))
    }

    /// How far below the place before a top border its line lies, above a first line of the box
    /// `size` with extra room from an at-least minimum, where the line does not lie from the
    /// rounded text edge: it stands on the text's single line, the line's baseline as the page
    /// places it less the line's ascent and the border's width and space rounded to the device
    /// together.
    fn on_ascent_shift(&self, size: &super::line::height::LineBox, border: Border) -> Length {
        let rule = border.width + border.space;
        let space = SpaceBefore::of(self.first_space_before, self.own_space_before);
        let at = (self.y + rule, space);
        let (ties, box_top) = (self.ties(), self.box_top(at));
        let base = super::line::height::placed_baseline(
            &self.device,
            at,
            size,
            (ties, box_top),
            (self.y_rest, None),
        );
        base - self.device.snap(size.ascent + rule) - self.y
    }

    /// Draws a paragraph's bottom border line, lengthens the last bar of a list to it, and
    /// returns the line's top as drawn where the paragraph's fill ends there. A target can place
    /// the line of a paragraph of single or at-least spacing whose last line has the box `last`
    /// from the rounded text edge above it ([`Layout::bottom_line_from_text_edge`]), with the
    /// space after that follows the paragraph where the target joins it
    /// ([`super::decisions::bottom_border_space_after_joined`]), and the
    /// line of a paragraph of multiple spacing above single spacing whose last line's baseline
    /// that spacing places from the rounded text edge with the part that the spacing adds below
    /// the text and the space after that follows the paragraph
    /// ([`super::decisions::multiple_bottom_from_text_edge`]).
    fn bottom_border(
        &mut self,
        props: &ParaProps,
        border: Border,
        last: Option<super::line::height::LineBox>,
    ) -> Option<Length> {
        let above = self.y;
        let spacing = line_spacing(props);
        let multiple = last.filter(|size| {
            size.multiple
                && super::decisions::multiple_bottom_from_text_edge(&self.context.quirks, spacing)
        });
        let inner = if let Some(size) = self.device.text_edge_line(spacing, last) {
            let joined = super::decisions::bottom_border_space_after_joined(&self.context.quirks);
            let after = if joined {
                self.kept_after(props, true)
            } else {
                Length::ZERO
            };
            self.bottom_line_from_text_edge(&size, props, border, (Length::ZERO, after))
        } else if let Some(size) = multiple {
            // The space after that follows the line joins the border's width and space.
            let after = self.kept_after(props, true);
            self.bottom_line_from_text_edge(&size, props, border, (size.multiple_extra(), after))
        } else {
            self.border_line(props, border, false)
        };
        self.lengthen_last_bar(self.y - above);
        self.fill_edge(inner)
    }

    /// The whole dots between a paragraph's rounded outer edge and its rounded text edge, next
    /// to a line of the box `line_box` on the side `side`, with the border's width and space
    /// `rule`. Below a top border: `rule` with the line's extra room from an at-least minimum
    /// above the text, rounded to the nearest dot, but no more than the line's height with
    /// `rule`, rounded to the nearest dot, less the line's ascent and descent, each rounded to
    /// the nearest dot. Above a bottom border, with the part `below` of the line below its text
    /// that the side names: `rule` with `below`, rounded to the nearest dot, less `below`
    /// rounded to the nearest dot, but no more than the line's height with `rule`, rounded to
    /// the nearest dot, less its extra room, `below`, its ascent and its descent, each rounded
    /// to the nearest dot.
    fn text_edge_room(
        &self,
        line_box: &super::line::height::LineBox,
        rule: Length,
        side: TextEdgeSide,
    ) -> Length {
        let device = self.device;
        let extra = line_box.least_extra();
        let glyphs = device.snap(line_box.ascent) + device.snap(line_box.descent);
        let (outer, line) = match side {
            TextEdgeSide::Top => (
                device.snap(rule + extra),
                device.snap(rule + line_box.height) - glyphs,
            ),
            TextEdgeSide::Bottom(below) => (
                device.snap(rule + below) - device.snap(below),
                device.snap(rule + line_box.height)
                    - device.snap(extra)
                    - device.snap(below)
                    - glyphs,
            ),
        };
        outer.min(line)
    }

    /// Draws a paragraph's top border line from the rounded text edge below it, under
    /// `BorderTextEdge::Rounded`, above a first line of the box `size`: the place before the
    /// border rounded to the nearest dot, plus the whole dots of [`Self::text_edge_room`], less
    /// the border's space and each of its lines and gaps rounded down to whole dots, a line or a
    /// gap at least one dot. It adds the border's width and space to the paragraph and returns
    /// the top and the bottom of the line as drawn.
    fn top_line_from_text_edge(
        &mut self,
        size: &super::line::height::LineBox,
        props: &ParaProps,
        border: Border,
    ) -> (Length, Length) {
        let rule = border.width + border.space;
        let edge = self.device.snap(self.y) + self.text_edge_room(size, rule, TextEdgeSide::Top);
        self.top_line_above(edge, props, border)
    }

    /// Draws a paragraph's top border line of multiple spacing from the rounded text edge,
    /// under `MultipleTopBorder::FromTextEdge`: the place before the border rounded to the
    /// nearest dot, plus the border's width and space rounded to the nearest dot, less the
    /// border's space and each of its lines and gaps rounded down to whole dots, a line or a gap
    /// at least one dot. It adds the border's width and space to the paragraph and returns the
    /// top and the bottom of the line as drawn.
    fn multiple_top_line(&mut self, props: &ParaProps, border: Border) -> (Length, Length) {
        let edge = self.device.snap(self.y) + self.device.snap(border.width + border.space);
        self.top_line_above(edge, props, border)
    }

    /// Draws a paragraph's top border line above the text edge `edge`: the border's space and
    /// each of its lines and gaps rounded down to whole dots, a line or a gap at least one dot,
    /// stack up from it. It adds the border's width and space to the paragraph and returns the
    /// top and the bottom of the line as drawn.
    fn top_line_above(
        &mut self,
        edge: Length,
        props: &ParaProps,
        border: Border,
    ) -> (Length, Length) {
        let rule = border.width + border.space;
        let edges = self.border_edges(props);
        let parts = self.drawn_parts(border);
        let room = parts.iter().copied().sum::<Length>() + self.device.floor(border.space);
        let top = edge - room;
        let bottom = self.stacked_lines(&parts, edges, top, &border.line_colors());
        self.y += rule;
        (top, bottom)
    }

    /// Draws a paragraph's bottom border line from the rounded text edge above it, under
    /// `BorderTextEdge::Rounded` or `MultipleBottomBorder::FromTextEdge`, below a last line of
    /// the box `size` whose part `below` lies below its text, with the space `after` that
    /// follows the paragraph joining the border's space and width (0 where it does not join
    /// them): the place below the border's space and width and `after` rounded to the nearest
    /// dot, less the whole dots of [`Self::text_edge_room`] of the three, plus the border's
    /// space rounded down to whole dots, from where its lines and gaps stack down, each rounded
    /// down to whole dots, a line or a gap at least one dot. It adds the border's space and
    /// width to the paragraph and returns the line's top as drawn.
    fn bottom_line_from_text_edge(
        &mut self,
        size: &super::line::height::LineBox,
        props: &ParaProps,
        border: Border,
        (below, after): (Length, Length),
    ) -> Length {
        let rule = border.space + border.width;
        let room = self.text_edge_room(size, rule + after, TextEdgeSide::Bottom(below));
        let edge = self.device.snap(self.y + rule + after) - room;
        let top = edge + self.device.floor(border.space);
        let edges = self.border_edges(props);
        let parts = self.drawn_parts(border);
        self.stacked_lines(&parts, edges, top, &border.line_colors());
        self.y += rule;
        top
    }

    /// Draws a paragraph's top border line from the start of its content below it, under
    /// `TopBorderPlace::FromContentStart`: the place after the border's width and space,
    /// rounded up to a dot, less the border's space and each of its lines and gaps rounded down
    /// to whole dots, a line or a gap at least one dot
    /// ([`crate::grid::Device::content_start_top`]). It adds the border's width and space to
    /// the paragraph and returns the top and the bottom of the line as drawn, and `None` on a
    /// target that places the line otherwise.
    fn top_line_from_content_start(
        &mut self,
        props: &ParaProps,
        border: Border,
    ) -> Option<(Length, Length)> {
        let parts = self.drawn_parts(border);
        let top = self.device.content_start_top(self.y, border, &parts)?;
        let edges = self.border_edges(props);
        let bottom = self.stacked_lines(&parts, edges, top, &border.line_colors());
        self.y += border.width + border.space;
        Some((top, bottom))
    }

    /// The lines and gaps of `border` as drawn when they are stacked: each rounded down to whole
    /// dots, a line or a gap at least one dot. The lines of a border whose lines touch have no
    /// gaps between them ([`Border::touches`]).
    fn drawn_parts(&self, border: Border) -> Vec<Length> {
        let touches = border.touches();
        border
            .parts
            .sizes()
            .iter()
            .enumerate()
            .map(|(index, size)| {
                if touches && index % 2 == 1 {
                    Length::ZERO
                } else {
                    self.border_thickness(*size)
                }
            })
            .collect()
    }

    /// The thickness of a paragraph border's line as drawn: rounded down to whole device dots,
    /// and at least one.
    fn border_thickness(&self, thickness: Length) -> Length {
        self.device.line_thickness(thickness, LineRounding::Down)
    }

    /// Draws the lines of `parts`, a line, a gap, a line and so on, stacked down from `top`
    /// between the ends `left` and `right`, each line in its color of `colors`, and returns the
    /// place below the last part.
    fn stacked_lines(
        &mut self,
        parts: &[Length],
        (left, right): (Length, Length),
        top: Length,
        colors: &[Rgb],
    ) -> Length {
        let mut y = top;
        for (index, size) in parts.iter().enumerate() {
            if index % 2 == 0 {
                self.items.push(Item::Rect(Rect {
                    x: left,
                    y,
                    width: right - left,
                    height: *size,
                    color: colors.get(index / 2).copied().unwrap_or(Rgb::BLACK),
                }));
            }
            y += *size;
        }
        y
    }

    /// The rooms of a paragraph's top border, `top` (its width and space), and of its bottom
    /// border, `bottom`, that the boxes of its first and its last line hold as space before and
    /// after: both under `BorderSpace::Held` outside table cells, and none otherwise
    /// ([`crate::grid::Device::held_border_room`]); and the room that the last line needs for the
    /// bottom border at the foot of a page outside table cells
    /// ([`super::decisions::foot_border_room`]).
    fn held_borders_of(&self, (top, border): (Length, Option<Border>)) -> HeldBorders {
        let in_cell = self.column.cell.is_some();
        let (top, bottom) = self.device.held_border_room(in_cell, (top, border));
        // A table's rows, not its paragraphs' lines, find the page in a cell.
        let foot = if in_cell {
            Length::ZERO
        } else {
            super::decisions::foot_border_room(&self.context.quirks, border)
        };
        HeldBorders { top, bottom, foot }
    }

    /// The top, bottom and between lines that a paragraph with `props` of the group `group`
    /// draws ([`Group::lines`], [`Group::between`]). It holds the rooms of its top and bottom
    /// lines in its line boxes ([`Self::held_borders_of`]), and takes its first line of `lines`
    /// to the next page when it does not fit with the room of its top or between line
    /// ([`Self::first_leaves_page`]).
    fn border_lines(
        &mut self,
        group: &Group,
        props: &ParaProps,
        (lines, mark_face, anchors): (&[Line], Option<FaceIndex>, bool),
    ) -> (Option<Border>, Option<Border>, Option<Border>) {
        let (top, bottom) = group.lines(props);
        let between = group.between(props);
        let room = top.map_or(Length::ZERO, |b| b.width + b.space);
        self.held_borders = self.held_borders_of((room, bottom));
        self.clear_reserve();
        let between_room = between.map_or(Length::ZERO, |b| b.width + b.space + b.space);
        self.first_leaves_page(lines, props, mark_face, (anchors, room + between_room));
        (top, bottom, between)
    }

    /// Draws the line between a paragraph and the one before it in their group, `border`, and
    /// adds its space, its width and its space again to the paragraph above its first line. The
    /// line lies its space below the space after of the paragraph before, and the paragraph's own
    /// space before lies below the line's second space. At the top of a column the line lies at
    /// the column's top, without the space above it.
    fn between_line(&mut self, props: &ParaProps, border: Border) {
        let above = self.y - self.own_space_before;
        let space = if above <= self.column_top {
            Length::ZERO
        } else {
            border.space
        };
        let end = self.y + space + border.width + border.space;
        self.y = above + space;
        self.border_line(props, border, true);
        self.y = end;
    }

    /// Draws a paragraph border line and adds its space and width to the paragraph. Above the
    /// text the line comes first, and below the text the space comes first. It returns the
    /// line's edge on the text's side as drawn: the bottom of its lowest part above the text,
    /// and the top of its highest part below it.
    fn border_line(&mut self, props: &ParaProps, border: Border, above: bool) -> Length {
        let edges = self.border_edges(props);
        if !above {
            self.y += border.space;
        }
        let stacked = if above {
            None
        } else {
            self.device
                .stacked_bottom_top(self.y, border.parts.sizes().len())
        };
        let edge = if let Some(top) = stacked {
            let parts = self.drawn_parts(border);
            self.stacked_lines(&parts, edges, top, &border.line_colors());
            top
        } else {
            self.nearest_lines(border, edges, above)
        };
        self.y += border.width;
        if above {
            self.y += border.space;
        }
        edge
    }

    /// Draws the lines of `border` from the place `self.y`, each at its own offset rounded to the
    /// nearest dot, between the ends `left` and `right`, and returns the line's edge on the text's
    /// side as drawn, as [`Self::border_line`] does. The lines of a border whose lines touch
    /// stack from the nearest dot of `self.y` ([`Border::touching_lines`]).
    fn nearest_lines(
        &mut self,
        border: Border,
        (left, right): (Length, Length),
        above: bool,
    ) -> Length {
        let lines: Vec<(Length, Length)> = if border.touches() {
            let top = self.device.snap(self.y);
            border
                .touching_lines(|thickness| self.border_thickness(thickness))
                .into_iter()
                .map(|(offset, height)| (top + offset, height))
                .collect()
        } else {
            border
                .lines()
                .into_iter()
                .map(|(offset, thickness)| {
                    (
                        self.device.snap(self.y + offset),
                        self.border_thickness(thickness),
                    )
                })
                .collect()
        };
        let mut inner = None;
        for ((y, height), color) in lines.into_iter().zip(border.line_colors()) {
            self.items.push(Item::Rect(Rect {
                x: left,
                y,
                width: right - left,
                height,
                color,
            }));
            let edge = if above { y + height } else { y };
            inner = Some(inner.map_or(edge, |inner: Length| {
                if above {
                    inner.max(edge)
                } else {
                    inner.min(edge)
                }
            }));
        }
        inner.unwrap_or(self.y)
    }

    /// The left and right ends of a paragraph's text, at its indents: the column's edges moved
    /// in by the side indents, and out on the side where a hanging first line starts. They are
    /// not on the device grid.
    fn indented_ends(&self, props: &ParaProps) -> (Length, Length) {
        let (left, width) = (self.column.left, self.column.width);
        let (left_outer, right_outer) = outer_indents(props);
        (left + left_outer, left + width - right_outer)
    }

    /// The dot of the end `x` of a right-to-left paragraph in the body, where a right-to-left
    /// line of the paragraph would start there: such a line takes its place on the device
    /// grid from the column's right edge, as `right_edge_shift` gives it, so the end lies the
    /// dot of that edge less the end's distance from it, rounded as a line's start. On a
    /// target whose glyphs take the edge steps, the line's glyphs lie
    /// `params::RIGHT_TO_LEFT_LINE_DOTS` further right, and so does the end.
    fn right_to_left_end(&self, x: Length) -> Length {
        let right = self.column.left + self.column.width;
        let shift = match self.device.advances() {
            crate::grid::Advances::RightEdge { .. } => {
                self.device.dots(crate::params::RIGHT_TO_LEFT_LINE_DOTS)
            }
            crate::grid::Advances::PdfSteps => Length::ZERO,
        };
        let start = self.device.line_start(right - x);
        self.device.snap(right) - self.device.snap(start) + shift
    }

    /// The left and right ends of a paragraph's top and bottom lines, which are also the inner
    /// edges of its side lines. They reach past both indents, with their ends on the device
    /// grid, and a side line lies its space further out, rounded down to whole device dots.
    fn border_edges(&self, props: &ParaProps) -> (Length, Length) {
        let c = &self.column;
        let reach = self.device.floor(BORDER_REACH);
        // In the body, each end lands on the dot where a line of the paragraph would start
        // there: the dot of the column's edge, and past it the indented offset, rounded as a
        // line's start; in a right-to-left paragraph, from the column's right edge. A table
        // cell keeps the nearest dot of the end itself.
        let dot = self.column_dot();
        let right_to_left = props.flags().bidi;
        let edge = |x: Length| {
            if c.cell.is_some() {
                self.device.snap(x)
            } else if right_to_left {
                self.right_to_left_end(x)
            } else {
                dot + self.device.snap(self.device.line_start(x - c.left))
            }
        };
        let space =
            |side: Option<Border>| side.map_or(Length::ZERO, |b| self.device.floor(b.space));
        let borders = props.borders().unwrap_or_default();
        let (left, right) = self.indented_ends(props);
        (
            edge(left) - reach - space(borders.left),
            edge(right) + reach + space(borders.right),
        )
    }

    /// Draws the side lines of a paragraph's border from `top` down to the paragraph's end,
    /// outside the ends of its top and bottom lines. On a paragraph that runs onto another
    /// page, they start at the top of the last page's column, as the shading does.
    fn side_lines(&mut self, (page, top): (usize, Length), props: &ParaProps) {
        let Some(borders) = props.borders() else {
            return;
        };
        let top = if self.output.pages.len() == page {
            top
        } else {
            self.column_top
        };
        let (left, right) = self.border_edges(props);
        let sides = [(borders.left, left, -1), (borders.right, right, 1)];
        for (border, inner, outward) in sides {
            let Some(border) = border else { continue };
            // Each line's left edge, from the inner edge of the side, and its width. The left
            // line's offsets count from its inner edge, on the right; the lines of a border
            // whose lines touch stack out from it.
            let lines: Vec<(Length, Length)> = if border.touches() {
                let lines = border.touching_lines(|thickness| self.border_thickness(thickness));
                let width: Length = lines.iter().map(|(_, width)| *width).sum();
                lines
                    .into_iter()
                    .map(|(offset, line)| {
                        let x = if outward < 0 {
                            inner - width + offset
                        } else {
                            inner + offset
                        };
                        (x, line)
                    })
                    .collect()
            } else if outward < 0 {
                border
                    .lines_from_end()
                    .into_iter()
                    .map(|(offset, thickness)| {
                        let width = self.border_thickness(thickness);
                        (inner - offset - width, width)
                    })
                    .collect()
            } else {
                border
                    .lines()
                    .into_iter()
                    .map(|(offset, thickness)| (inner + offset, self.border_thickness(thickness)))
                    .collect()
            };
            for ((x, width), color) in lines.into_iter().zip(border.line_colors()) {
                let y = self.device.snap(top);
                self.items.push(Item::Rect(Rect {
                    x,
                    y,
                    width,
                    height: self.device.snap(self.y) - y,
                    color,
                }));
            }
        }
    }

    /// Where a shaded paragraph's fill stops next to its own top or bottom line, whose edge on
    /// the text's side as drawn is `inner` ([`crate::grid::Device::fill_edge`]): the paragraph
    /// lies in the body when it is in no story and no table cell.
    fn fill_edge(&self, inner: Length) -> Option<Length> {
        self.device
            .fill_edge(inner, self.story.is_none() && self.column.cell.is_none())
    }

    /// Opens the fills entry of a shaded paragraph, before its items. In a table cell, a
    /// drawings entry comes before it, which takes the drawings behind the text that the
    /// paragraph anchors, so that its fill lies above them.
    fn open_paragraph_fill(&mut self, props: &ParaProps) -> Option<FillsEntry> {
        let shaded = paragraph_fill(props).is_some();
        self.drawings_under_fill =
            (shaded && self.column.cell.is_some()).then(|| self.items.open_drawings());
        shaded.then(|| self.items.open_fills())
    }

    /// Fills the area of a paragraph with its shading, under its text: across to the ends of
    /// its top and bottom border lines, whether it has them or not, and down from below its
    /// space before to the end of its last line. A side with a border fills out to it, over
    /// the border's space. In a table cell, the fill keeps to the indents on a side without a
    /// border. The part of a paragraph on an earlier page stays unfilled.
    ///
    /// The fill goes from `top` into the paragraph's fills entry `entry` on the page `page`,
    /// down to `bottom` when it is given and to the paragraph's end otherwise. When the
    /// paragraph ends on a later page, or in a later part of a cell of a row that splits, the
    /// fill of its last part goes into the page's own fills, before all the page's items, from
    /// the top of that page or part. In a table cell, the fill lies above the drawings behind
    /// the text that the paragraph anchors, which its drawings entry holds.
    fn fill_paragraph(
        &mut self,
        (entry, page, top): (Option<FillsEntry>, usize, Length),
        bottom: Option<Length>,
        props: &ParaProps,
    ) {
        self.drawings_under_fill = None;
        let Some(color) = paragraph_fill(props) else {
            return;
        };
        let part_top = entry
            .filter(|entry| !self.items.holds_fills(*entry))
            .and_then(|_| self.part_top());
        let (entry, top) = match part_top {
            _ if self.output.pages.len() != page => (None, self.column_top),
            Some(part_top) => (None, part_top),
            None => (entry, top),
        };
        // In the body, the fill reaches as far as the top and bottom lines, whether the
        // paragraph has them or not. In a table cell, it fills between the indents, and out to
        // a side's border.
        let (left, right) = match (self.column.cell.is_some(), props.borders()) {
            (false, _) => self.border_edges(props),
            (true, None) => self.indented_ends(props),
            (true, Some(borders)) => {
                let (left, right) = self.indented_ends(props);
                let (border_left, border_right) = self.border_edges(props);
                (
                    if borders.left.is_some() {
                        border_left
                    } else {
                        left
                    },
                    if borders.right.is_some() {
                        border_right
                    } else {
                        right
                    },
                )
            }
        };
        // The fill's top and bottom lie on the nearest dots, as the border lines do, so that a
        // fill right below a line starts at the line's lower edge.
        let (top, bottom) = (
            self.device.snap(top),
            self.device.snap(bottom.unwrap_or(self.y)),
        );
        let fill = Item::Rect(Rect {
            x: left,
            y: top,
            width: right - left,
            height: bottom - top,
            color,
        });
        // The fill of an empty paragraph on the page that a page break began keeps a section
        // from starting on that page no more than its line number does.
        let only_empty = self.page_from_break == Some(self.output.pages.len())
            && self.items.count() == self.break_numbers.0;
        match entry {
            Some(entry) => self.items.put_fills(entry, vec![fill]),
            None => self.items.put_page_fill(fill),
        }
        if only_empty {
            self.break_numbers.0 = self.items.count();
        }
    }

    fn space_before(&mut self, props: &ParaProps) {
        // Automatic space before is left out above the first paragraph of the document, even
        // when that paragraph is empty.
        let first = !std::mem::replace(&mut self.started, true);
        let pending = std::mem::take(&mut self.section_top) == super::columns::SectionTop::Pending;
        let above_columns = pending && self.column.cell.is_none();
        let top = first && self.output.pages.is_empty() && self.column.cell.is_none();
        let section_previous = self.section_previous.take();
        let flags = props.flags();
        // The fixed reading of automatic spacing keeps it there, and at the top of a cell.
        let dropped = flags.before_auto
            && props
                .html_auto_spacing
                .unwrap_or_default()
                .drops_automatic_spacing();
        if top && dropped {
            return;
        }
        // So is it above the first paragraph of a table cell.
        let cell_top = self.column.cell.is_some() && self.previous.is_none();
        if cell_top && dropped {
            return;
        }
        // At the top of a table cell, contextual spacing compares against the paragraph
        // immediately before the cell in document stream order (the previous cell's last
        // paragraph, the paragraph before the table for row 0 cell 0, or the previous row's
        // end-of-row mark as the default paragraph style).
        if cell_top
            && drops_contextual_spacing(
                flags.contextual_spacing,
                props.style.as_deref(),
                self.cell_prev_style
                    .as_deref()
                    .or_else(|| self.styles.default_paragraph_style()),
            )
        {
            return;
        }
        // A paragraph that starts a page after a page break has no space above it.
        if std::mem::take(&mut self.after_break) {
            return;
        }
        // At the top of a section that starts a new page, the space between the paragraphs
        // loses the space after, which stays on the page before. So it does below balanced
        // columns, whose section holds the space after of its last paragraph.
        if let Some(previous) = section_previous {
            let own = gap_parts(Some(&previous), props).own();
            if above_columns {
                self.column_top = self.y;
            }
            self.advance_space(own);
            return;
        }
        // Above the columns of a section that balances them, the space after of the paragraph
        // before the section lies above all columns, which start level below it. The rest of
        // this paragraph's space before belongs to the first column.
        if above_columns {
            let parts = gap_parts(self.previous.as_ref(), props);
            self.advance_space(parts.after);
            self.column_top = self.y;
            self.advance_space(parts.own());
            return;
        }
        // The space between the paragraphs, a length of whole twips, adds its twips rest.
        // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
        self.advance_space(gap(self.previous.as_ref(), props));
    }
}

/// Whether a paragraph anchors a floating drawing other than those of `later`, which wait for
/// the page of their anchor: their indexes in the order of the paragraph's drawings.
fn anchors_drawings(paragraph: &Paragraph, later: &[usize]) -> bool {
    let content = paragraph.runs.iter().flat_map(|run| &run.content);
    let drawings = content.filter(|content| matches!(content, Content::Floating(_)));
    drawings
        .enumerate()
        .any(|(index, _)| !later.contains(&index))
}

/// The place of line `index` of a paragraph of `count` lines with the ID `paragraph`, which
/// lies in the piece `narrowed` that the wraps of its page leave, or else at `normal`, the
/// start and width in its column that the paragraph's frame `frame` gives: a wrap on the line's
/// left moves its start to the piece's wrap edge, and the line keeps part of its start past
/// it. The first line's own indent counts on a left-to-right line that starts at its indent;
/// `first` says whether the line is the paragraph's first.
fn line_place(
    frame: &Frame,
    (narrowed, normal): (Option<floating::NarrowedPiece>, (Length, Length)),
    ((index, count, paragraph), first): ((usize, usize, crate::body::ParagraphId), bool),
    bidi: bool,
) -> LinePlace {
    let (start, width) = narrowed.map_or(normal, |piece| (piece.start, piece.width));
    let edge = narrowed.and_then(|piece| piece.edge);
    let own = if first && start == normal.0 && !bidi {
        frame.first_start - frame.start
    } else {
        Length::ZERO
    };
    LinePlace {
        start,
        own,
        edge,
        width,
        index,
        last: index + 1 == count,
        paragraph,
    }
}

/// The part of a line's start `normal` from the column edge that the line keeps past the wrap
/// edge of a drawing on its left, which moves its start there ([`floating::StartPastWrap`]). A
/// left-to-right line keeps neither its left indent nor a hanging indent from compatibility mode
/// 15 on: the paragraph's first line keeps its first-line indent, and a later line starts at the
/// wrap edge. Below compatibility mode 15, a hanging-indent first line keeps its `first_start`
/// (`left - hanging`, signed) past the wrap edge. A right-to-left line keeps its whole start, the
/// indent on the side where it ends. `first` says whether the line is the paragraph's first.
fn kept_past_wrap_edge(
    frame: &Frame,
    first: bool,
    bidi: bool,
    normal: Length,
    keeps_hanging_first_start: bool,
) -> Length {
    if bidi {
        normal
    } else if first {
        let own = frame.first_start - frame.start;
        if own < Length::ZERO && keeps_hanging_first_start {
            frame.first_start
        } else {
            own.max(Length::ZERO)
        }
    } else {
        Length::ZERO
    }
}

/// Whether a paragraph anchors a floating drawing before its first column break.
fn anchors_before_column_break(paragraph: &Paragraph) -> bool {
    paragraph
        .runs
        .iter()
        .flat_map(|run| &run.content)
        .take_while(|content| !matches!(content, Content::ColumnBreak))
        .any(|content| matches!(content, Content::Floating(_)))
}

/// Breaks the lines of a paragraph from `index` on again for `frame`, the paragraph's frame
/// in a column of another width. A line after the paragraph's first one has no first-line
/// indent; the lines up to the first one, after leading page breaks, break as the paragraph.
fn break_again(lines: &mut Vec<Line>, narrow: &mut Narrowed, index: usize, frame: &Frame) {
    let pieces = Line::pieces(lines.get(index..).unwrap_or_default());
    let rest = if index <= Line::first_index(lines, frame.breaking.leading_breaks) {
        break_lines(&pieces, frame)
    } else {
        break_part(
            &pieces,
            frame,
            (frame.start, frame.width),
            (false, Length::ZERO),
        )
    };
    lines.truncate(index);
    narrow.truncate(index);
    narrow.extend(std::iter::repeat_n(None, rest.len()));
    lines.extend(rest);
}

/// Drops a trailing empty line that follows a line break (`LineEnd::Break`), returning whether a
/// line was dropped. A line holding only `Piece::Clear` (from `<w:br w:clear="..."/>`) and no
/// floating anchors counts as empty. Checking `LineEnd::Wrap` on the last line keeps the helper
/// idempotent when earlier empty break lines precede the final break.
pub(super) fn drop_trailing_empty_break_line(lines: &mut Vec<Line>) -> bool {
    let has_break = lines.len() >= 2
        && lines
            .get(lines.len() - 2)
            .is_some_and(|line| matches!(line.end, LineEnd::Break(_)))
        && lines.last().is_some_and(|line| {
            line.end == LineEnd::Wrap
                && line.anchors.is_empty()
                && line
                    .placed
                    .iter()
                    .all(|placed| placed.piece == Piece::Clear)
        });
    if has_break {
        lines.pop();
    }
    has_break
}

/// Keeps a dropped trailing empty line after a line break absent after re-breaking lines for
/// floating wraps or a column width change.
fn trim_rebroken_end(lines: &mut Vec<Line>, narrow: &mut Narrowed, dropped_end: bool) {
    if dropped_end && drop_trailing_empty_break_line(lines) {
        narrow.truncate(lines.len());
    }
}

/// Breaks the rest of a paragraph into lines that start at `start` with `width` from the
/// column edge: only its first line, or all of its lines when they flow beside a drawing.
/// When `tab_origin` is non-zero, measures custom and default tab stops from that wrap edge.
fn break_part(
    pieces: &[Piece],
    frame: &Frame,
    (start, width): (Length, Length),
    (all, tab_origin): (bool, Length),
) -> Vec<Line> {
    let mut part = frame.clone();
    part.first_start = start;
    part.first_width = width;
    if tab_origin != Length::ZERO {
        part.tabs.shift_origin(tab_origin);
    }
    if all {
        part.start = part.first_start;
        part.width = part.first_width;
    }
    break_lines(pieces, &part)
}

/// The space between the previous paragraph and this one: the larger of the space after and
/// the space before, or their sum in the fixed reading of automatic spacing, without either
/// of them between paragraphs of one style with contextual spacing.
pub(super) fn gap(previous: Option<&Previous>, props: &ParaProps) -> Length {
    gap_parts(previous, props).total()
}

/// Whether a paragraph of the properties `props` removes the space after of the `previous`
/// one: contextual spacing between paragraphs of one style, or automatic spacing between
/// paragraphs of the same list where the reading drops it.
fn drops_after(previous: &Previous, props: &ParaProps) -> bool {
    let same_list = previous.list.is_some() && previous.list == list_of(props);
    let dropped = previous.after_auto && previous.reading.drops_automatic_spacing();
    previous.drops_after_before(props.style.as_deref()) || (same_list && dropped)
}

/// Whether the paragraph of `lines` holds a page break and no text: one line, which the page
/// break ends and which has no width.
fn breaks_page_alone(lines: &[Line]) -> bool {
    matches!(lines, [line] if line.end == LineEnd::PageBreak && line.width() == Length::ZERO)
}

/// The space after the previous paragraph and the space before this one that count for the
/// space between them.
pub(super) fn gap_parts(previous: Option<&Previous>, props: &ParaProps) -> Gap {
    // Between two paragraphs of the same list, automatic spacing gives no space where the
    // reading drops it.
    let same_list = previous.is_some_and(|p| p.list.is_some() && p.list == list_of(props));
    let flags = props.flags();
    let reading = props.html_auto_spacing.unwrap_or_default();
    let before = if same_list && flags.before_auto && reading.drops_automatic_spacing() {
        Length::ZERO
    } else {
        props.space_before()
    };
    let contextual = flags.contextual_spacing;
    match previous {
        Some(previous) => {
            let after = if drops_after(previous, props) {
                Length::ZERO
            } else {
                previous.after
            };
            // When contextual spacing removes only the space after of the paragraph before,
            // the part of this paragraph's space before beyond that space after stays.
            let own = props.style.as_deref();
            let before = if drops_contextual_spacing(contextual, own, previous.style.as_deref()) {
                Length::ZERO
            } else if previous.drops_after_before(props.style.as_deref()) {
                (before - previous.after).max(Length::ZERO)
            } else {
                before
            };
            Gap {
                after,
                before,
                reading,
            }
        }
        None => Gap {
            after: Length::ZERO,
            before,
            reading,
        },
    }
}

/// Whether a line holds a glyph other than the ASCII space U+0020: every other space counts,
/// such as a no-break space (U+00A0), an ideographic space (U+3000) or an em space (U+2003).
/// A line without one chooses its free piece beside a drawing by its own rule
/// (`Layout::wrap_beside`).
///
/// It differs from `line::height::holds_glyph_besides_white_space`, which the line's height
/// asks, on a line of only white space with a space other than U+0020, such as a no-break,
/// ideographic or em space.
pub(super) fn holds_glyph_besides_ascii_space(line: &Line) -> bool {
    line.placed
        .iter()
        .any(|placed| matches!(&placed.piece, Piece::Glyph(glyph) if glyph.ch != ' '))
}

/// Whether a line holds an inline object, such as a picture or a shape.
fn holds_object(line: &Line) -> bool {
    line.placed
        .iter()
        .any(|placed| matches!(placed.piece, Piece::Object { .. }))
}

/// Whether a free piece of `width` beside a drawing holds the first line broken for it: a line
/// that splits no word and no object, and whose content fits the piece.
fn holds(line: &Line, width: Length) -> bool {
    line.end != LineEnd::Split && line.width() <= width
}

/// Whether a line holds body content beyond a list label, tabs, ASCII spaces, and zero-width
/// marks: a non-label glyph other than U+0020, an inline object other than a label's legacy
/// spacer, a rule, a check box, or an equation bar, vinculum, or diagonal.
fn holds_body_content(line: &Line) -> bool {
    line.placed.iter().any(|placed| match placed.piece {
        Piece::Glyph(glyph) => !glyph.label && glyph.ch != ' ',
        Piece::Object {
            picture, drawing, ..
        } => picture.is_some() || drawing.is_some(),
        Piece::Rule { .. }
        | Piece::CheckBox { .. }
        | Piece::Bar { .. }
        | Piece::Vinculum { .. }
        | Piece::Diagonal { .. } => true,
        _ => false,
    })
}

/// Whether a line holds at least one list-label glyph.
fn holds_label_glyph(line: &Line) -> bool {
    line.placed
        .iter()
        .any(|placed| matches!(placed.piece, Piece::Glyph(glyph) if glyph.label))
}

/// Whether a line holds at least one tab or positional tab.
fn holds_tab(line: &Line) -> bool {
    line.placed
        .iter()
        .any(|placed| matches!(placed.piece, Piece::Tab(_) | Piece::PositionTab(..)))
}

/// Whether `lines` starts with a wrapped line that holds only a list label or a tab wrapped before
/// a word that did not fit, while later lines carry the paragraph's text (modern floating layout,
/// compatibility mode 15+). Leading ASCII spaces and a tab wrapped before a second tab stay beside
/// the wrap.
fn orphans_prefix(lines: &[Line], modern: bool) -> bool {
    modern
        && lines.len() > 1
        && lines.first().is_some_and(|line| {
            line.end == LineEnd::Wrap
                && !holds_body_content(line)
                && (holds_label_glyph(line) || (line.wrapped.is_some() && holds_tab(line)))
        })
}

/// Whether a narrowed piece of `width` beside a drawing cannot hold the first line of `lines`,
/// sending it to the next free piece on the same baseline.
fn rejects_piece(lines: &[Line], width: Length, modern: bool) -> bool {
    lines
        .first()
        .is_some_and(|line| !holds(line, width) || orphans_prefix(lines, modern))
}

/// Whether `lines`, broken for a narrowed piece of `width` beside a drawing, cannot stay there and
/// must move below the drawing.
fn overflows_piece(lines: &[Line], width: Length, modern: bool) -> bool {
    lines
        .first()
        .is_some_and(|line| overflows_narrow(line, width) || orphans_prefix(lines, modern))
}

/// Whether a line broken for a narrowed piece of `width` beside a drawing cannot stay there and
/// must move below the drawing: it splits a word, or holds only inline objects wider than `width`.
fn overflows_narrow(line: &Line, width: Length) -> bool {
    line.end == LineEnd::Split
        || (!holds_glyph_besides_ascii_space(line) && holds_object(line) && !holds(line, width))
}

#[cfg(test)]
mod tests;