f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
//! Paragraphs laid out with the fake fonts of the layout test harness: kerning, lists, line
//! heights, positional tabs, frames, text boxes, hidden marks, page breaks and the bars of
//! fractions.

use f_office_paint::{DisplayList, Painted};
use f_office_units::Length;

use crate::body::{Body, Sections};
use crate::grid::DOT;
use crate::layout::testing::{
    self, AnchoredShape, DEEP, Fake, FakeMath, NORMAL, ShapeText, TALL, base, base_context, du,
    find, find_all, lay_out, p, parse, table,
};
use crate::layout::{Context, Layout, SectionLayout};
use crate::ns::W;
use crate::numbering::Numbering;
use crate::quirks::{BodyFieldResults, ListLevelReading};
use crate::reader::PartReader;
use crate::styles::{FontTable, Settings, SideMargins, Styles, Theme};
use crate::text::{Shaper, ShaperSettings};

#[test]
fn draws_a_text_box_that_fits_its_text_as_tall_as_the_text() {
    // A box that says it is 100 pt tall, with insets of 3.6 pt, holds one 10 pt line of the
    // fake font and 10 pt of space after it.
    let text_box = |fit: &str| {
        let body = format!(
            r#"<wps:bodyPr lIns="45720" tIns="45720" rIns="45720" bIns="45720">{fit}</wps:bodyPr>"#
        );
        let shape = AnchoredShape {
            across: ("margin", 0),
            down: ("margin", 0),
            size: (2_540_000, 1_270_000),
            wrap: "<wp:wrapNone/>",
            outline: Some(12_700),
            text: Some(ShapeText {
                blocks: r#"<w:p><w:pPr><w:spacing w:after="200"/></w:pPr><w:r><w:t>Box</w:t></w:r></w:p>"#,
                body: &body,
            }),
        };
        format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing())
    };
    let outline_height = |list: &DisplayList| {
        list.pages()[0]
            .items()
            .iter()
            .find_map(|item| match item {
                f_office_paint::Item::Path(path) => {
                    let ys: Vec<i64> = path
                        .commands
                        .iter()
                        .filter_map(|c| match c {
                            f_office_paint::PathCommand::MoveTo(p)
                            | f_office_paint::PathCommand::LineTo(p) => Some(p.y.units()),
                            _ => None,
                        })
                        .collect();
                    Some(ys.iter().max()? - ys.iter().min()?)
                }
                _ => None,
            })
            .unwrap()
    };
    let point = Length::from_points(1).unwrap().units();
    // The outline runs 0.5 pt outside the box on each side.
    let fixed = outline_height(&lay_out(&text_box(""), "", None));
    assert_eq!(fixed, 101 * point);
    // Fitting: 3.6 pt, the 12 pt line of the fake font at 10 pt, 10 pt of space after, 3.6 pt.
    let fitted = outline_height(&lay_out(&text_box("<a:spAutoFit/>"), "", None));
    assert!(fitted < 40 * point, "{fitted}");
    assert!(fitted > 25 * point, "{fitted}");
}

#[test]
fn draws_a_text_box_whose_body_does_not_wrap_as_wide_as_its_widest_line() {
    // A box of 100 pt with insets of 7.2 pt and an outline of 1 pt holds a centered line of
    // `letters` letters of 5 pt and a centered "B".
    let text_box = |wrap: &str, letters: usize| {
        let body = format!(
            r#"<wps:bodyPr wrap="{wrap}" lIns="91440" tIns="45720" rIns="91440" bIns="45720"/>"#
        );
        let blocks = format!(
            r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>{}</w:t></w:r></w:p><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#,
            "A".repeat(letters)
        );
        let shape = AnchoredShape {
            across: ("margin", 0),
            down: ("margin", 0),
            size: (1_270_000, 1_270_000),
            wrap: "<wp:wrapNone/>",
            outline: Some(12_700),
            text: Some(ShapeText {
                blocks: &blocks,
                body: &body,
            }),
        };
        lay_out(
            &format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing()),
            "",
            None,
        )
    };
    let outline_width = |list: &DisplayList| {
        list.pages()[0]
            .items()
            .iter()
            .find_map(|item| match item {
                f_office_paint::Item::Path(path) => {
                    let xs: Vec<i64> = path
                        .commands
                        .iter()
                        .filter_map(|c| match c {
                            f_office_paint::PathCommand::MoveTo(p)
                            | f_office_paint::PathCommand::LineTo(p) => Some(p.x.units()),
                            _ => None,
                        })
                        .collect();
                    Some(xs.iter().max()? - xs.iter().min()?)
                }
                _ => None,
            })
            .unwrap()
    };
    let point = Length::UNITS_PER_POINT;
    let rows = |list: &DisplayList| {
        let mut ys: Vec<i64> = find_all(list, 'A').iter().map(|&(_, _, y)| y).collect();
        ys.dedup();
        ys.len()
    };
    // A box that wraps keeps its width and breaks its 200 pt of letters into lines.
    let square = text_box("square", 40);
    assert_eq!(outline_width(&square), 101 * point);
    assert!(rows(&square) > 1);
    // A box that does not wrap keeps them on one line and grows by their width: 20 more
    // letters make it 100 pt wider.
    let unbroken = text_box("none", 40);
    assert_eq!(rows(&unbroken), 1);
    assert_eq!(
        outline_width(&unbroken) - outline_width(&text_box("none", 20)),
        100 * point
    );
    // The "B" centers on the widest line, 97.5 pt after the line's start.
    let start = find(&unbroken, 'A').1;
    let shift = find(&unbroken, 'B').1 - start;
    assert!((shift - 195 * point / 2).abs() <= DOT, "{shift}");
}

/// The place and turn of the glyph "A" in a text box of the preset `preset`, 100 by 200 pt at
/// the margin's corner, without an outline, with the insets 3, 6, 12 and 24 pt on its left, top,
/// right and bottom sides, the attributes `xfrm` on its `a:xfrm` and the body's `vert`.
fn boxed_glyph(preset: &str, xfrm: &str, vert: &str) -> (i64, i64, Option<f_office_paint::Turn>) {
    boxed_glyphs((preset, xfrm, vert), "A")
        .into_iter()
        .find(|glyph| glyph.0 == 'A')
        .map(|(_, x, y, turn)| (x, y, turn))
        .unwrap()
}

/// The first character, origin and run turn of each glyph of `text`, in a text box of the
/// preset, transform and body `vert` of [`boxed_glyph`].
fn boxed_glyphs(
    (preset, xfrm, vert): (&str, &str, &str),
    text: &str,
) -> Vec<(char, i64, i64, Option<f_office_paint::Turn>)> {
    use crate::ns::{A, WP, WPS};
    let shape = format!(
        r#"<w:drawing><wp:anchor xmlns:wp="{WP}" behindDoc="0" distL="0" distR="0" distT="0" distB="0"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="margin"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="margin"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="2540000"/><wp:wrapNone/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:xfrm {xfrm}/><a:prstGeom prst="{preset}"/></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr vert="{vert}" lIns="38100" tIns="76200" rIns="152400" bIns="304800"/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
    );
    let list = lay_out(&format!("<w:p><w:r>{shape}</w:r></w:p>"), "", None);
    list.pages()[0]
        .painted()
        .iter()
        .flat_map(|item| match item {
            Painted::Glyphs(run) => run
                .glyphs
                .iter()
                .filter_map(|glyph| {
                    let ch = run.glyph_text(glyph)?.chars().next()?;
                    Some((ch, glyph.x.units(), glyph.y.units(), run.turn))
                })
                .collect(),
            _ => Vec::new(),
        })
        .collect()
}

#[test]
fn stands_the_east_asian_glyphs_of_an_east_asian_vertical_text_box_upright() {
    use crate::layout::table::DOWN;
    let upright = f_office_paint::Turn {
        xx: f_office_paint::Turn::SCALE,
        yx: 0,
        xy: 0,
        yy: f_office_paint::Turn::SCALE,
    };
    let glyphs = |vert: &str| boxed_glyphs(("rect", "", vert), "A\u{65E5}B");
    let turns = |vert: &str| glyphs(vert).iter().map(|g| (g.0, g.3)).collect::<Vec<_>>();
    // In `vert` every glyph turns with the line; in `eaVert` the ideograph stands upright.
    assert_eq!(
        turns("vert"),
        [
            ('A', Some(DOWN)),
            ('\u{65E5}', Some(DOWN)),
            ('B', Some(DOWN))
        ]
    );
    assert_eq!(
        turns("eaVert"),
        [
            ('A', Some(DOWN)),
            ('\u{65E5}', Some(upright)),
            ('B', Some(DOWN))
        ]
    );
    // The Latin glyphs lie where `vert` puts them; the ideograph's origin moves left of the
    // baseline, by half an em less the line's axis, and down from its pen by its face's top.
    let (turned, stood) = (glyphs("vert"), glyphs("eaVert"));
    assert_eq!((turned[0], turned[2]), (stood[0], stood[2]));
    let (pen, upright) = (turned[1], stood[1]);
    assert!(upright.1 < pen.1, "{pen:?} {upright:?}");
    assert!(upright.2 > pen.2, "{pen:?} {upright:?}");
}

#[test]
fn turns_the_text_of_a_text_box_whose_body_or_shape_turns_it() {
    use crate::layout::table::{DOWN, UP};
    let text_box = |xfrm: &str, vert: &str| boxed_glyph("rect", xfrm, vert);
    let point = Length::UNITS_PER_POINT;
    let near = |value: i64, want: i64| (value - want).abs() <= 2 * DOT;
    let (left, _, upright) = text_box("", "horz");
    let (down_x, down_y, down) = text_box("", "vert");
    let (up_x, up_y, up) = text_box("", "vert270");
    let (shape_x, shape_y, with_shape) = text_box(r#"rot="5400000""#, "horz");
    assert_eq!(
        (upright, down, up, with_shape),
        (None, Some(DOWN), Some(UP), Some(DOWN))
    );
    // Text that runs down starts below the top inset, and text that runs up above the bottom
    // inset, 200 - 6 - 24 pt further down.
    assert!(near(up_y - down_y, 170 * point), "{down_y} {up_y}");
    // The first line of text that runs down lies inside the right inset, and of text that
    // runs up inside the left inset, an ascent from each: their sum across is the box's left
    // side twice, its width, less the right inset and plus the left one.
    let side = left - 3 * point;
    assert!(
        near(down_x + up_x - 2 * side, 91 * point),
        "{down_x} {up_x} {side}"
    );
    // A shape turned a quarter turn about its centre shows its box 200 pt wide and 100 pt high,
    // from 50 pt left of its left side and 50 pt down. Its text turns with it: it starts 3 pt
    // below the box's top, the left inset turned, and its first line lies inside the top inset,
    // 6 pt from the box's right side, 150 pt right of the left side.
    assert!(near(shape_y - down_y, 47 * point), "{shape_y} {down_y}");
    assert!(near(shape_x - down_x, 56 * point), "{shape_x} {down_x}");
}

#[test]
fn lays_out_the_text_of_a_mirrored_shape_in_its_mirrored_text_rectangle_and_turns_it_down() {
    let text_box = |preset: &str, xfrm: &str| boxed_glyph(preset, xfrm, "horz");
    let point = Length::UNITS_PER_POINT;
    let near = |value: i64, want: i64| (value - want).abs() <= 2 * DOT;
    let (plain_x, plain_y, plain) = text_box("homePlate", "");
    let (across_x, across_y, across) = text_box("homePlate", r#"flipH="1""#);
    let (left, _, _) = text_box("rect", "");
    let (down_x, _, down) = text_box("rect", r#"flipV="1""#);
    assert_eq!(
        (plain, across, down),
        (None, None, crate::picture::turn(2, [false, false]))
    );
    // The text rectangle of a home plate 100 pt wide ends half its height's point short of
    // its right side, 25 pt; mirrored across, it starts 25 pt from the left side.
    assert!(near(across_x - plain_x, 25 * point), "{plain_x} {across_x}");
    assert_eq!(across_y, plain_y);
    // Turned by a half turn about the box's centre, the glyph starts 3 pt left of the box's
    // right side: its places across sum to the box's left side twice and its width.
    let side = left - 3 * point;
    assert!(
        near(down_x + left, 2 * side + 100 * point),
        "{left} {down_x} {side}"
    );
}

/// A text box at the margin's corner for the tests of its text anchor: `height` pt high, with
/// insets of `inset` EMU above and below and an outline of `outline` EMU, holding a line of
/// exactly 12 pt for each letter, the last with `after` twips after it.
#[derive(Clone, Copy)]
struct AnchoredBox<'a> {
    height: i64,
    inset: i64,
    outline: i64,
    after: i64,
    fit: &'a str,
    letters: &'a str,
    /// Blocks after the letters' paragraphs.
    after_letters: &'a str,
}

impl AnchoredBox<'_> {
    /// A box of 100 pt with insets of 3.6 pt, an outline of 1 pt and two lines.
    const PLAIN: Self = AnchoredBox {
        height: 100,
        inset: 45_720,
        outline: 12_700,
        after: 0,
        fit: "",
        letters: "AB",
        after_letters: "",
    };

    fn xml(self, anchor: &str) -> String {
        use std::fmt::Write as _;
        let last = self.letters.chars().count() - 1;
        let mut lines = String::new();
        for (i, c) in self.letters.chars().enumerate() {
            let after = if i == last { self.after } else { 0 };
            let _ = write!(
                lines,
                r#"<w:p><w:pPr><w:spacing w:after="{after}" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>{c}</w:t></w:r></w:p>"#
            );
        }
        lines.push_str(self.after_letters);
        let (inset, fit) = (self.inset, self.fit);
        let body = format!(
            r#"<wps:bodyPr lIns="91440" tIns="{inset}" rIns="91440" bIns="{inset}" anchor="{anchor}">{fit}</wps:bodyPr>"#
        );
        let shape = AnchoredShape {
            across: ("margin", 0),
            down: ("margin", 0),
            size: (2_540_000, self.height * 12_700),
            wrap: "<wp:wrapNone/>",
            outline: (self.outline != 0).then_some(self.outline),
            text: Some(ShapeText {
                blocks: &lines,
                body: &body,
            }),
        };
        format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing())
    }

    /// How far down the text lies with `anchor`, in device dots, from where the same box puts
    /// it at the top.
    fn shift(self, anchor: &str) -> i64 {
        let baseline = |anchor| find(&lay_out(&self.xml(anchor), "", None), 'A').2;
        baseline(anchor) - baseline("t")
    }
}

/// Whether a shift in device dots lies within a dot of a length in units.
fn near(shift: i64, units: i64) -> bool {
    (shift - f_office_units::div_round(units, DOT)).abs() <= 1
}

#[test]
fn moves_the_text_of_a_text_box_down_by_the_room_that_its_anchor_names() {
    let plain = AnchoredBox::PLAIN;
    let point = Length::UNITS_PER_POINT;
    let inset = plain.inset * Length::UNITS_PER_EMU;
    // The room lies inside the insets and half the outline's width at the top and at the
    // bottom: 100 − 7.2 − 1 pt, less two lines of 12 pt.
    let room = 100 * point - 2 * inset - point - 24 * point;
    assert!(near(plain.shift("b"), room));
    assert!(near(plain.shift("ctr"), room / 2));
    // Without insets the room grows by both insets, and without an outline by its width.
    assert!(near(
        AnchoredBox { inset: 0, ..plain }.shift("b"),
        room + 2 * inset
    ));
    assert!(near(
        AnchoredBox {
            outline: 0,
            ..plain
        }
        .shift("b"),
        room + point
    ));
    // The space after the last paragraph counts as text: 10 pt after leaves 10 pt less room.
    let after = AnchoredBox {
        after: 200,
        ..plain
    };
    assert!(near(after.shift("b"), room - 10 * point));
}

#[test]
fn keeps_the_text_of_a_text_box_at_the_top_when_the_box_has_no_room_below_it() {
    // Text taller than its box stays at the top, and a box that fits its text has no room.
    let tall = AnchoredBox {
        height: 60,
        letters: "ABCDEFGH",
        ..AnchoredBox::PLAIN
    };
    assert_eq!(tall.shift("b"), 0);
    assert_eq!(tall.shift("ctr"), 0);
    let fitted = AnchoredBox {
        fit: "<a:spAutoFit/>",
        ..AnchoredBox::PLAIN
    };
    assert_eq!(fitted.shift("b"), 0);
}

/// The layout, on a target with the text box clip `clip`, of a box 30 pt high with insets of
/// 3.6 pt and an outline of 1 pt: its text area is 21.8 pt high, so the first 12 pt line fits,
/// the second crosses the area's bottom and the third lies below it. A last paragraph holds an
/// inline shape with an outline.
/// A paragraph holding one inline ellipse drawing.
fn inline_ellipse() -> String {
    use crate::ns::{A, WP, WPS};
    format!(
        r#"<w:p><w:r><w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="127000"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="ellipse"/><a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#
    )
}

fn cut_box(clip: crate::quirks::TextBoxClip) -> DisplayList {
    let shape = inline_ellipse();
    let xml = AnchoredBox {
        height: 30,
        letters: "ABC",
        after_letters: &shape,
        ..AnchoredBox::PLAIN
    }
    .xml("t");
    let target = testing::on_base_with(|p| p.with_variant(clip));
    testing::pass_with(&xml, ("", None), None, Numbering::default(), target).list
}

/// The groups among the items of the first page of `list`.
fn page_groups(list: &DisplayList) -> Vec<f_office_paint::Group> {
    list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Group(group) => Some(group.clone()),
            _ => None,
        })
        .collect()
}

/// The text of the glyph runs among `items`.
fn letters_of(items: &[f_office_paint::Item]) -> String {
    items
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Glyphs(run) => Some(run.text.clone()),
            _ => None,
        })
        .collect()
}

/// The paths among `items`.
fn paths_of(items: &[f_office_paint::Item]) -> Vec<f_office_paint::Item> {
    items
        .iter()
        .filter(|item| matches!(item, f_office_paint::Item::Path(_)))
        .cloned()
        .collect()
}

/// The top left and the bottom right corner of the box around the points of `commands`.
fn corners_of(
    commands: &[f_office_paint::PathCommand],
) -> (f_office_paint::Point, f_office_paint::Point) {
    use f_office_paint::{PathCommand, Point};
    let points: Vec<Point> = commands.iter().flat_map(PathCommand::points).collect();
    let x = points.iter().map(|p| p.x);
    let y = points.iter().map(|p| p.y);
    let (left, right) = (x.clone().min().unwrap(), x.max().unwrap());
    let (top, bottom) = (y.clone().min().unwrap(), y.max().unwrap());
    (
        Point { x: left, y: top },
        Point {
            x: right,
            y: bottom,
        },
    )
}

#[test]
fn cuts_the_text_of_a_text_box_at_its_text_area_on_a_target_that_cuts_it() {
    use crate::quirks::TextBoxClip;
    use f_office_paint::GroupPlaces;
    let overflow = cut_box(TextBoxClip::Overflow);
    assert_eq!(page_groups(&overflow), []);
    let cut = cut_box(TextBoxClip::InsideOutline);
    let [group] = page_groups(&cut).try_into().unwrap();
    // The letters of every line lie in the group, which holds the page's items: the writer
    // places them as the page's.
    assert_eq!(letters_of(&group.items), "ABC");
    assert_eq!(letters_of(cut.pages()[0].items()), "");
    assert_eq!(group.places, GroupPlaces::Page);
    // The paths of the box and of the inline shape stay outside the group, uncut, as they are
    // on a target that does not cut the text.
    assert_eq!(paths_of(&group.items), []);
    let uncut = paths_of(overflow.pages()[0].items());
    assert_eq!(uncut.len(), 2);
    assert_eq!(paths_of(cut.pages()[0].items()), uncut);
}

#[test]
fn cuts_the_cells_of_a_table_in_a_text_box_also_at_the_text_box_s_clip() {
    use crate::quirks::{CellClip, TextBoxClip};
    use f_office_paint::Item;
    let table = testing::table("", &[1000], &[("", &[&p("D")])]);
    let xml = AnchoredBox {
        height: 30,
        letters: "A",
        after_letters: &table,
        ..AnchoredBox::PLAIN
    }
    .xml("t");
    let target = testing::on_base_with(|p| {
        p.with_variant(TextBoxClip::InsideOutline)
            .with_variant(CellClip::InsideLines)
    });
    let list = testing::pass_with(&xml, ("", None), None, Numbering::default(), target).list;
    // The cell's group lies in the text box's group, so that both clips cut the cell's text.
    let [group] = page_groups(&list).try_into().unwrap();
    assert_eq!(letters_of(&group.items), "A");
    let cells: Vec<_> = group
        .items
        .iter()
        .filter_map(|item| match item {
            Item::Group(cell) => Some(letters_of(&cell.items)),
            _ => None,
        })
        .collect();
    assert_eq!(cells, ["D"]);
}

#[test]
fn puts_the_clip_of_a_text_box_inside_its_outline_and_its_insets() {
    use crate::quirks::TextBoxClip;
    use f_office_paint::Item;
    // The clip lies half the outline inside the box across and the insets and half the
    // outline inside it down; the outline's path runs half its width outside the box.
    let cut = cut_box(TextBoxClip::InsideOutline);
    let [group] = page_groups(&cut).try_into().unwrap();
    let outline = cut.pages()[0]
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Path(path) => Some(corners_of(&path.commands)),
            _ => None,
        })
        .unwrap();
    let twips = |twips: i64| Length::from_twips(twips).unwrap();
    let clip = corners_of(&group.clip.unwrap().commands);
    assert_eq!(clip.0.x - outline.0.x, twips(20));
    assert_eq!(clip.0.y - outline.0.y, twips(92));
    assert_eq!(outline.1.x - clip.1.x, twips(20));
    assert_eq!(outline.1.y - clip.1.y, twips(92));
}

#[test]
fn keeps_uncut_items_in_paint_order_inside_a_clipped_text_box() {
    use crate::quirks::TextBoxClip;
    use f_office_paint::Item;
    let middle = format!("{}<w:p><w:r><w:t>Z</w:t></w:r></w:p>", inline_ellipse());
    let xml = AnchoredBox {
        height: 60,
        letters: "A",
        after_letters: &middle,
        ..AnchoredBox::PLAIN
    }
    .xml("t");
    let target = testing::on_base_with(|p| p.with_variant(TextBoxClip::InsideOutline));
    let list = testing::pass_with(&xml, ("", None), None, Numbering::default(), target).list;
    let items = list.pages()[0].items();
    let a_at = items
        .iter()
        .position(|item| matches!(item, Item::Group(group) if letters_of(&group.items) == "A"))
        .expect("first clipped group");
    let z_at = items
        .iter()
        .position(|item| matches!(item, Item::Group(group) if letters_of(&group.items) == "Z"))
        .expect("second clipped group");
    let shape_at = items[a_at..z_at]
        .iter()
        .position(|item| matches!(item, Item::Path(_)));
    assert!(
        shape_at.is_some(),
        "uncut item between A and Z must stay between their clipped groups"
    );
}

#[test]
fn leaves_out_the_lines_and_cells_outside_the_page_on_targets_that_leave_them_out() {
    // A text box at (x, y) pt from the page's corner, 72 pt wide and `height` pt high, with no
    // insets but `inset` pt at the bottom, with the blocks `lines`, or one paragraph for each
    // letter.
    let boxed = |(x, y): (i64, i64), (height, inset): (i64, i64), lines: &str| {
        let emu = |points: i64| points * 12_700;
        let (x, y, height, inset) = (emu(x), emu(y), emu(height), emu(inset));
        let body = format!(r#"<wps:bodyPr lIns="0" tIns="0" rIns="0" bIns="{inset}"/>"#);
        let shape = AnchoredShape {
            across: ("page", x),
            down: ("page", y),
            size: (emu(72), height),
            wrap: "<wp:wrapNone/>",
            outline: None,
            text: Some(ShapeText {
                blocks: lines,
                body: &body,
            }),
        };
        format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing())
    };
    let text_box = |(x, y): (i64, i64), (height, inset): (i64, i64), letters: &str| {
        let lines: String = letters.chars().map(|c| p(&c.to_string())).collect();
        boxed((x, y), (height, inset), &lines)
    };
    // Lines of 10 or 12 pt from 25 pt above the page: `A` and `B` lie wholly above it, `C`
    // crosses its top and `D` lies inside. `E` and `I` lie wholly above the page in boxes that
    // reach 6 pt into it; the text area of `E` ends 2 pt above the page, and that of `I` 6 pt
    // into it. From 775 pt, `F` lies inside, `G` crosses the bottom and `H` lies below it. `R`
    // lies wholly right of the page; `S` lies right of it in a box that reaches 6 pt into it;
    // `M` lies inside.
    let mut body = text_box((200, -25), (50, 0), "ABCD");
    body += &text_box((100, -30), (36, 8), "E");
    body += &text_box((400, -30), (36, 0), "I");
    body += &text_box((300, 775), (50, 0), "FGH");
    body += &text_box((620, 100), (36, 0), "R");
    body += &text_box((606, 160), (36, 0), "S");
    body += &text_box((250, 400), (36, 0), "M");
    // The same from 775 pt in the rows of a table, one letter in each, which a target that
    // cuts table cells puts into the groups of the cells' clips:
    // `J` lies inside, `K` crosses the bottom and
    // `L` lies below it.
    let (j, k, l) = (p("J"), p("K"), p("L"));
    let rows = [
        ("", &[j.as_str()][..]),
        ("", &[k.as_str()]),
        ("", &[l.as_str()]),
    ];
    body += &boxed((450, 775), (50, 0), &table("", &[1440], &rows));
    // A table indented 3 inches left of the margin of 1 inch: the cell of `X` lies wholly left
    // of the page, the cell of `Y` reaches into it, and the cell of `Z` lies inside.
    body += &table(
        r#"<w:tblInd w:w="-4320" w:type="dxa"/><w:tblLayout w:type="fixed"/>"#,
        &[2000, 2000, 2000],
        &[("", &[&p("X"), &p("Y"), &p("Z")])],
    );
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let mut seen = Vec::new();
    for target in crate::Target::all() {
        let quirk = crate::profile::Profile::of(target)
            .unwrap()
            .quirks()
            .off_page_objects;
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let drawn: String = "ABCDEFGHIRSMXYZJKL"
            .chars()
            .filter(|&c| !find_all(&list, c).is_empty())
            .collect();
        let expected = match quirk {
            crate::quirks::OffPageObjects::Drawn => "ABCDEFGHIRSMXYZJKL",
            crate::quirks::OffPageObjects::LeftOut => "ABCDFGISMYZJK",
        };
        assert_eq!(drawn, expected, "{target}");
        seen.push(quirk);
    }
    assert!(seen.contains(&crate::quirks::OffPageObjects::Drawn));
    assert!(seen.contains(&crate::quirks::OffPageObjects::LeftOut));
}

#[test]
fn keeps_the_records_of_a_text_box_in_a_row_whose_cells_get_fills() {
    // A text box anchored in the second cell of a row whose first cell is shaded. The row
    // inserts the fill of the first cell under its content after the cells' lines are placed,
    // and the text box's lines join the page as a whole, so no move of the page's items
    // applies to their records.
    let text_box = AnchoredBox::PLAIN.xml("t");
    let shaded = format!(
        r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="FFFF00"/></w:tcPr>{}"#,
        p("Shaded")
    );
    let body = table(
        "",
        &[3000, 3000],
        &[("", &[shaded.as_str(), text_box.as_str()])],
    );
    let pass = testing::pass_with_header(&body, NORMAL, None, None);
    let boxed: Vec<_> = pass
        .lines
        .iter()
        .filter(|line| line.story == crate::layout::LineStory::TextBox)
        .collect();
    assert_eq!(boxed.len(), 2);
    assert!(
        boxed
            .iter()
            .all(|line| line.item == crate::layout::FirstItem::Carried)
    );
}

#[test]
fn records_the_lines_of_frames_as_lines_of_the_story_that_holds_them() {
    use crate::layout::LineStory;
    use crate::lines::Step;
    let framed = r#"<w:p><w:pPr><w:framePr w:w="2000" w:hAnchor="page" w:x="8000" w:yAlign="bottom"/></w:pPr><w:r><w:t>ab</w:t></w:r></w:p>"#;
    let pass = testing::pass_with_header(&format!("{framed}{}", p("c")), "", None, Some(framed));
    let steps = |story: LineStory| -> Vec<Vec<Step>> {
        pass.lines
            .iter()
            .filter(|line| line.story == story)
            .map(|line| line.steps.clone())
            .collect()
    };
    let frame = vec![Step::Start, Step::Glyph];
    assert_eq!(steps(LineStory::Header), vec![frame.clone()]);
    assert_eq!(steps(LineStory::Body), vec![frame, vec![Step::Start]]);
    assert!(
        pass.lines
            .iter()
            .filter(|line| line.steps.len() == 2)
            .all(|line| line.item == crate::layout::FirstItem::Carried)
    );
}

#[test]
fn records_what_lies_before_each_drawn_glyph() {
    use crate::lines::Step;
    let body = r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve">ab c</w:t><w:tab/><w:t>d</w:t></w:r></w:p>"#;
    let pass = testing::pass_with_header(body, "", None, None);
    let line = &pass.lines[0];
    assert_eq!(line.alignment, crate::props::Alignment::Center);
    assert_eq!(
        line.steps,
        vec![Step::Start, Step::Glyph, Step::Space, Step::Tab]
    );
}

#[test]
fn names_aligned_tabs_and_a_tab_that_starts_the_line() {
    use crate::lines::Step;
    // A center stop at 1 inch and a right stop at 4 inches; the third tab goes to a default
    // stop past them. The second line starts with a tab to a default stop.
    let body = concat!(
        r#"<w:p><w:pPr><w:tabs><w:tab w:val="center" w:pos="1440"/><w:tab w:val="right" w:pos="5760"/></w:tabs></w:pPr>"#,
        r#"<w:r><w:tab/><w:t>a</w:t><w:tab/><w:t>b</w:t><w:tab/><w:t>c</w:t></w:r></w:p>"#,
        r#"<w:p><w:r><w:tab/><w:t>d</w:t></w:r></w:p>"#,
    );
    let pass = testing::pass_with_header(body, "", None, None);
    assert_eq!(
        pass.lines[0].steps,
        vec![Step::AlignedTab, Step::AlignedTab, Step::Tab]
    );
    assert_eq!(pass.lines[1].steps, vec![Step::Tab]);
}

#[test]
fn kerns_a_pair_across_two_runs_of_the_same_font_and_size() {
    // A run of "V" and a run of "A". At 10 pt, -100 of 1000 units is -1 pt.
    let x_of_a = |second: &str| {
        let body = format!(
            r#"<w:p><w:r><w:rPr><w:kern w:val="2"/></w:rPr><w:t>V</w:t></w:r><w:r><w:rPr>{second}</w:rPr><w:t>A</w:t></w:r></w:p>"#
        );
        find(&lay_out(&body, "", None), 'A').1
    };
    let plain = x_of_a("");
    let kerned = x_of_a(r#"<w:kern w:val="2"/>"#);
    assert_eq!(plain - kerned, Length::from_points(1).unwrap().units());
    // Another size or a tab in between keeps the pair apart.
    assert_eq!(x_of_a(r#"<w:kern w:val="2"/><w:sz w:val="24"/>"#), plain);
    let body = r#"<w:p><w:r><w:rPr><w:kern w:val="2"/></w:rPr><w:t>V</w:t><w:tab/><w:t>A</w:t></w:r></w:p>"#;
    let with_tab = lay_out(body, "", None);
    let body = r"<w:p><w:r><w:t>V</w:t><w:tab/><w:t>A</w:t></w:r></w:p>";
    assert_eq!(find(&with_tab, 'A'), find(&lay_out(body, "", None), 'A'));
}

/// Lays out the paragraphs of `body` with a numbering whose list 2 has a decimal level with a
/// left indent of 720 and a hanging indent of 360 twips, and the run properties `label_run`.
fn lay_out_numbered(body: &str, label_run: &str, settings: &Settings) -> DisplayList {
    lay_out_numbered_with(body, "", label_run, settings)
}

/// Lays out paragraphs as `lay_out_numbered` does, with more elements `level` in the level.
fn lay_out_numbered_with(
    body: &str,
    level: &str,
    label_run: &str,
    settings: &Settings,
) -> DisplayList {
    lay_out_numbered_styled(
        body,
        level,
        label_run,
        settings,
        ("", ListLevelReading::AsWritten),
    )
}

/// Lays out paragraphs as `lay_out_numbered_with` does, with the styles `styles`, whose list
/// levels and those of the body read as `reading` says.
fn lay_out_numbered_styled(
    body: &str,
    level: &str,
    label_run: &str,
    settings: &Settings,
    (styles, reading): (&str, ListLevelReading),
) -> DisplayList {
    let numbering = parse(&format!(
        r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/>{level}<w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr><w:rPr>{label_run}</w:rPr></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
    ));
    let body_doc = parse(&format!(r#"<w:body xmlns:w="{W}">{body}</w:body>"#));
    let body = Body::read(
        &mut PartReader::new(&body_doc)
            .with_list_levels(crate::reader::settings::ListLevels::with_reading(reading)),
        body_doc.root().unwrap(),
        (
            crate::reader::settings::ReaderSettings::base()
                .with_body_results(BodyFieldResults::ComputesFields)
                .with_section_ends(crate::quirks::ContinuousSectionEnd::OnlyBlockKeepsLine),
            settings.mode_rules,
        ),
    );
    let styles_doc = parse(&format!(
        r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault/><w:pPrDefault/></w:docDefaults>{styles}</w:styles>"#
    ));
    let styles = Styles::read(
        &mut PartReader::new(&styles_doc)
            .with_list_levels(crate::reader::settings::ListLevels::with_reading(reading)),
        styles_doc.root().unwrap(),
    );
    let (theme, fonts) = (Theme::default(), FontTable::default());
    let context = Context {
        numbering: std::rc::Rc::new(Numbering::read(
            &mut PartReader::new(&numbering),
            numbering.root().unwrap(),
            crate::reader::settings::ReaderSettings::with_built_in_list(
                crate::quirks::BuiltInList::WithoutPart,
            ),
        )),
        ..base_context(&styles, settings)
    };
    let stories = context.for_stories();
    let section = &body.sections.last().section;
    let sections = Sections::one(SectionLayout::plain(section, body.blocks.len()));
    Layout::new(
        (&context, &stories),
        &sections,
        Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
    )
    .run_with_wraps(&body)
    .list
}

/// A numbered paragraph of the text "X".
const NUMBERED_X: &str = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>X</w:t></w:r></w:p>"#;

#[test]
fn starts_page_numbers_with_the_number_of_the_last_chapter_heading() {
    // "heading 1" is numbered with list 2, so the second heading is chapter 2.
    let heading = r#"<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr></w:style>"#;
    let titled = |text: &str| {
        format!(
            r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let field = r#"<w:p><w:fldSimple w:instr="PAGE"><w:r><w:t>9</w:t></w:r></w:fldSimple></w:p>"#;
    // The text of the PAGE field, the last run of the page.
    let page = |numbers: &str, styles: &str| {
        let body = format!(
            "{}{}{field}<w:sectPr><w:pgNumType {numbers}/></w:sectPr>",
            titled("A"),
            titled("B")
        );
        let list = lay_out_numbered_styled(
            &body,
            "",
            "",
            &Settings::default(),
            (styles, ListLevelReading::AsWritten),
        );
        list.pages()[0]
            .items()
            .iter()
            .rev()
            .find_map(|item| match item {
                f_office_paint::Item::Glyphs(run) => Some(run.text.clone()),
                _ => None,
            })
            .unwrap_or_default()
    };
    assert_eq!(page(r#"w:chapStyle="1" w:chapSep="colon""#, heading), "2:1");
    assert_eq!(page(r#"w:chapStyle="1""#, heading), "2-1");
    // Without a numbered heading of that style, and without w:chapStyle, the page number
    // stands alone.
    assert_eq!(page(r#"w:chapStyle="1""#, ""), "1");
    assert_eq!(page(r#"w:start="1""#, heading), "1");
}

#[test]
fn numbers_body_lines_in_the_left_margin() {
    let p = |text: &str| format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>");
    let suppressed = r"<w:p><w:pPr><w:suppressLineNumbers/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>";
    let cell = format!(
        "<w:tbl><w:tblGrid><w:gridCol w:w=\"2000\"/></w:tblGrid><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>",
        p("C")
    );
    // Lines 1 to 4 are "A", the empty paragraph, "D" and "E", and every second one shows.
    let body = format!(
        "{}<w:p/>{suppressed}{cell}{}{}<w:sectPr><w:lnNumType w:countBy=\"2\" w:distance=\"200\"/></w:sectPr>",
        p("A"),
        p("D"),
        p("E")
    );
    let list = lay_out(&body, NORMAL, None);
    let twips = |n: i64| n * Length::UNITS_PER_TWIP;
    // A digit is 100 twips wide, so it starts 300 twips left of the 1440 twip margin.
    let two = find_all(&list, '2');
    assert_eq!(two.len(), 1);
    assert_eq!(two[0].1, twips(1140));
    let four = find(&list, '4');
    assert_eq!((four.1, four.2), (twips(1140), find(&list, 'E').2));
    assert!(find_all(&list, '1').is_empty() && find_all(&list, '3').is_empty());
    // By default the count starts again on each page.
    let body = format!(
        "{}<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>B</w:t></w:r></w:p><w:sectPr><w:lnNumType w:countBy=\"1\"/></w:sectPr>",
        p("A")
    );
    let pages: Vec<usize> = find_all(&lay_out(&body, NORMAL, None), '1')
        .iter()
        .map(|found| found.0)
        .collect();
    assert_eq!(pages, [0, 1]);
}

#[test]
fn numbers_a_line_after_the_largest_start_with_the_largest_number() {
    let body = r#"<w:p><w:r><w:t>A</w:t></w:r></w:p><w:sectPr><w:lnNumType w:countBy="1" w:start="9223372036854775807"/></w:sectPr>"#;
    let list = lay_out(body, NORMAL, None);
    let texts: Vec<String> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Glyphs(run) => Some(run.text.clone()),
            _ => None,
        })
        .collect();
    assert!(texts.contains(&i64::MAX.to_string()), "{texts:?}");
}

#[test]
fn the_empty_paragraph_that_ends_a_section_has_no_line_number_and_no_count() {
    let p = |text: &str| format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>");
    let end = |runs: &str| {
        format!(
            r#"<w:p><w:pPr><w:sectPr><w:lnNumType w:countBy="1" w:restart="continuous"/></w:sectPr></w:pPr>{runs}</w:p>"#
        )
    };
    let last = r#"<w:sectPr><w:lnNumType w:countBy="1" w:restart="continuous"/></w:sectPr>"#;
    let count = |body: &str, digit: char| find_all(&lay_out(body, NORMAL, None), digit).len();
    // "A" is line 1, the empty paragraph at the section's end is no line, and "B" in the
    // next section is line 2.
    let body = format!("{}{}{}{last}", p("A"), end(""), p("B"));
    assert_eq!((count(&body, '2'), count(&body, '3')), (1, 0));
    // With text, the paragraph that ends the section is line 2, and "B" is line 3.
    let body = format!(
        "{}{}{}{last}",
        p("A"),
        end("<w:r><w:t>C</w:t></w:r>"),
        p("B")
    );
    assert_eq!((count(&body, '2'), count(&body, '3')), (1, 1));
    // So it is with one space.
    let space = r#"<w:r><w:t xml:space="preserve"> </w:t></w:r>"#;
    let body = format!("{}{}{}{last}", p("A"), end(space), p("B"));
    assert_eq!((count(&body, '2'), count(&body, '3')), (1, 1));
}

/// The step from "L" to "N", in dots, on the base with the variant `ends` of the quirk
/// `ContinuousSectionEnd`, with `before` and the paragraph "L" before the empty paragraph that
/// ends a section of one column before a continuous section, or with no paragraph between "L"
/// and "N" when `end` is none. `end` gives the empty paragraph's space after, its properties
/// and its content, and `numbering` the lists of a numbering part.
fn section_end_step(
    (ends, mode): (crate::quirks::ContinuousSectionEnd, Option<u32>),
    (before, line_after): (&str, u32),
    end: Option<(u32, &str, &str)>,
    (next_before, numbering): (u32, &str),
) -> i64 {
    let spaced = |before: u32, after: u32, text: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:before="{before}" w:after="{after}"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let end = end.map_or(String::new(), |(after, props, content)| {
        format!(
            r#"<w:p><w:pPr>{props}<w:spacing w:before="360" w:after="{after}"/><w:sectPr/></w:pPr>{content}</w:p>"#
        )
    });
    let body = format!(
        r#"{}{before}{end}{}<w:sectPr><w:type w:val="continuous"/></w:sectPr>"#,
        spaced(0, line_after, "L"),
        spaced(next_before, 0, "N")
    );
    let doc = parse(&format!(
        r#"<w:numbering xmlns:w="{W}">{numbering}</w:numbering>"#
    ));
    let numbering = Numbering::read(
        &mut PartReader::new(&doc),
        doc.root().unwrap(),
        crate::reader::settings::ReaderSettings::with_built_in_list(
            crate::quirks::BuiltInList::WithoutPart,
        ),
    );
    let target = testing::on_base_with(|p| p.with_variant(ends));
    let list = testing::pass_with(&body, (NORMAL, mode), None, numbering, target).list;
    find(&list, 'N').2 - find(&list, 'L').2
}

/// Lays out a section of two columns that ends at a continuous section break, on a page
/// 20,000 pt high: "A", "B" and "C", each one exact line of `points` points, then "D", one exact
/// line of 1 pt, so that the limit of balanced columns grows by 1 pt. Gives whether each
/// paragraph is in the first column, and the counts of the warnings of the trial limit.
fn balanced_columns(points: i64) -> ([bool; 4], u32) {
    let line = |text: char, twips: i64, section: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="{twips}" w:lineRule="exact"/>{section}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let page = r#"<w:pgSz w:w="12240" w:h="400000"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
    let columns = format!(r#"<w:sectPr>{page}<w:cols w:num="2" w:space="720"/></w:sectPr>"#);
    let body = format!(
        r#"{}{}{}{}<w:sectPr><w:type w:val="continuous"/>{page}</w:sectPr>"#,
        line('A', points * 20, ""),
        line('B', points * 20, ""),
        line('C', points * 20, ""),
        line('D', 20, &columns),
    );
    let pass = testing::pass_with(
        &body,
        (NORMAL, None),
        None,
        Numbering::default(),
        testing::on_base(),
    );
    let first = find(&pass.list, 'A').1;
    let in_first = ['A', 'B', 'C', 'D'].map(|ch| find(&pass.list, ch).1 == first);
    let trials = pass
        .warnings
        .iter()
        .filter(|(warning, _)| {
            matches!(
                warning,
                crate::Warning::LimitReached {
                    limit: crate::warnings::Limit::BalanceTrials,
                    ..
                }
            )
        })
        .map(|(_, count)| count)
        .sum();
    (in_first, trials)
}

#[test]
fn balances_columns_within_the_trial_limit_and_keeps_them_as_they_fill_past_it() {
    // Lines of 2,000 pt fit when the limit has grown from the mean of 3,000 pt to 4,000 pt,
    // after about 1,000 trials: "A" and "B" in the first column, "C" and "D" in the second.
    assert_eq!(balanced_columns(2_000), ([true, true, false, false], 0));
    // Lines of 5,000 pt would need about 2,500 trials, more than the limit: the columns stay
    // as they fill, all four paragraphs in the first column, with the warning.
    let (in_first, trials) = balanced_columns(5_000);
    assert_eq!(in_first, [true; 4]);
    assert!(trials > 0);
}

#[test]
fn balances_the_last_page_of_columns_that_start_on_an_earlier_page_where_the_target_does() {
    use crate::quirks::LastPageBalance::{LastPage, OnePage};
    // Columns of three exact lines of 100 pt on each page: "A" to "F" fill the first page,
    // "G" and "H" go on to the second, and a continuous section with "N" follows. Gives the
    // page and the x of "G" and "H" and the baseline of "N".
    let layout = |balance| {
        let line = |text: char, section: &str| {
            format!(
                r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="2000" w:lineRule="exact"/>{section}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
            )
        };
        let page = r#"<w:pgSz w:w="12240" w:h="8880"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
        let columns = format!(r#"<w:sectPr>{page}<w:cols w:num="2" w:space="720"/></w:sectPr>"#);
        let lines: String = "ABCDEFG".chars().map(|ch| line(ch, "")).collect();
        let body = format!(
            r#"{lines}{}{}<w:sectPr><w:type w:val="continuous"/>{page}</w:sectPr>"#,
            line('H', &columns),
            line('N', ""),
        );
        let target = testing::on_base_with(|p| p.with_variant(balance));
        let list =
            testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
        let (g, h, n) = (find(&list, 'G'), find(&list, 'H'), find(&list, 'N'));
        ((g.0, g.1), (h.0, h.1), n.2)
    };
    let (g, h, n) = layout(LastPage);
    let (plain_g, plain_h, plain_n) = layout(OnePage);
    // Both stay on the second page; balanced, "H" goes to the second column, and "N" starts
    // one line higher, below "G".
    assert_eq!((g.0, h.0, plain_g.0, plain_h.0), (1, 1, 1, 1));
    assert_eq!(plain_g.1, plain_h.1);
    assert!(h.1 > g.1);
    assert_eq!(g, plain_g);
    assert!(n < plain_n);
}

/// Columns that fill the page, of exact lines of 100 pt: three fill the first column, or two
/// below "T" of a section of one column when `title` holds, and "D", with 20 pt before, starts
/// the second. Gives the page, x and baseline of "A" and "D".
fn column_top(
    space: crate::quirks::ColumnTopSpace,
    title: bool,
) -> ((usize, i64, i64), (usize, i64, i64)) {
    let line = |text: char, before: u32, section: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:before="{before}" w:after="0" w:line="2000" w:lineRule="exact"/>{section}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let page = r#"<w:pgSz w:w="12240" w:h="8880"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
    let (start, lines) = if title {
        (line('T', 0, &format!("<w:sectPr>{page}</w:sectPr>")), "AB")
    } else {
        (String::new(), "ABC")
    };
    let lines: String = lines.chars().map(|ch| line(ch, 0, "")).collect();
    let body = format!(
        r#"{start}{lines}{}<w:sectPr><w:type w:val="continuous"/>{page}<w:cols w:num="2" w:space="720"/></w:sectPr>"#,
        line('D', 400, ""),
    );
    let target = testing::on_base_with(|p| p.with_variant(space));
    let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
    (find(&list, 'A'), find(&list, 'D'))
}

#[test]
fn leaves_out_the_space_before_at_the_top_of_a_column_at_the_page_top_where_the_target_does() {
    use crate::quirks::ColumnTopSpace::{GoesAtPageTop, Stays};
    let (a, d) = column_top(GoesAtPageTop, false);
    let (kept_a, kept_d) = column_top(Stays, false);
    let (below_a, below_d) = column_top(GoesAtPageTop, true);
    // At the page top, "D" starts the second column level with "A" where the space goes, and
    // below it where it stays.
    assert_eq!((a.0, d.0, d.2, kept_a), (0, 0, a.2, a));
    assert!(d.1 > a.1 && kept_d.2 > a.2);
    // Below "T", the second column's top is not the page's, and "D" keeps the space.
    assert!(below_d.1 > below_a.1 && below_d.2 > below_a.2);
    assert_eq!(column_top(Stays, true), (below_a, below_d));
}

#[test]
fn starts_unbalanced_continuous_columns_level_below_preceding_space_after() {
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
    let s1 = format!(
        r#"<w:p><w:pPr><w:spacing w:after="240"/><w:sectPr>{page}</w:sectPr></w:pPr><w:r><w:t>T</w:t></w:r></w:p>"#
    );
    let col2 = r#"<w:p><w:r><w:br w:type="column"/><w:t>D</w:t></w:r></w:p>"#;
    let s2 = format!(
        r#"<w:sectPr><w:type w:val="continuous"/>{page}<w:cols w:num="2" w:space="720"/></w:sectPr>"#
    );

    // First block is a table: column 2 starts level with the table below S1's space_after.
    let tbl = testing::table("", &[4000], &[("", &[&p("A")])]);
    let list_tbl = lay_out(&(s1.clone() + &tbl + col2 + &s2), NORMAL, None);
    let (a, d) = (find(&list_tbl, 'A'), find(&list_tbl, 'D'));
    assert!(d.1 > a.1 && d.2 == a.2, "table: a={a:?} d={d:?}");

    // First block is a paragraph with before > after: column 2 starts below S1's after, while
    // column 1 also takes the excess before - after.
    let p_a = r#"<w:p><w:pPr><w:spacing w:before="360"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
    let list_p = lay_out(&(s1 + p_a + col2 + &s2), NORMAL, None);
    let (pa, pd) = (find(&list_p, 'A'), find(&list_p, 'D'));
    assert!(pd.1 > pa.1 && pa.2 > pd.2, "para: pa={pa:?} pd={pd:?}");
    assert_eq!(pd.2, a.2, "col 2 top matches after-only baseline");
}

/// The page and the baseline in dots of "A", which has 12 pt before it, after a table whose
/// rows all went, in a document of the mode `mode` on a target with the variant `top`. The
/// table stands at a section's top after "T" (`start` "section"), after a page break ("break"),
/// at the document's top ("body") or below the line "T" ("middle").
fn deleted_table_top(top: crate::quirks::DeletedTableTop, mode: u32, start: &str) -> (usize, i64) {
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
    let first = match start {
        "section" => {
            format!("<w:p><w:pPr><w:sectPr>{page}</w:sectPr></w:pPr><w:r><w:t>T</w:t></w:r></w:p>")
        }
        "break" => r#"<w:p><w:r><w:t>T</w:t><w:br w:type="page"/></w:r></w:p>"#.to_owned(),
        "middle" => "<w:p><w:r><w:t>T</w:t></w:r></w:p>".to_owned(),
        _ => String::new(),
    };
    let body = format!(
        r#"{first}<w:tbl><w:tblPr/><w:tblGrid/></w:tbl><w:p><w:pPr><w:spacing w:before="240" w:after="0"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p><w:sectPr>{page}</w:sectPr>"#
    );
    let target = testing::on_base_with(|p| p.with_variant(top));
    let list = testing::pass_with(
        &body,
        (NORMAL, Some(mode)),
        None,
        Numbering::default(),
        target,
    )
    .list;
    let (page, _, y) = find(&list, 'A');
    (page, y)
}

#[test]
fn a_table_whose_rows_all_went_at_the_page_top_leaves_the_space_before_by_the_mode() {
    use crate::quirks::DeletedTableTop::{AsTable, ByMode};
    let kept = deleted_table_top(AsTable, 15, "section");
    let gone = deleted_table_top(ByMode, 14, "section");
    // Before mode 15, "A" has no space before at a section's top; from mode 15 it keeps it.
    assert_eq!((gone.0, kept.0), (1, 1));
    assert!(gone.1 < kept.1);
    assert_eq!(deleted_table_top(ByMode, 15, "section"), kept);
    // At the document's top likewise, and after a page break the space goes in both modes.
    let body = (
        deleted_table_top(ByMode, 14, "body").1,
        deleted_table_top(ByMode, 15, "body").1,
    );
    assert_eq!(body, (gone.1, kept.1));
    assert_eq!(deleted_table_top(ByMode, 15, "break"), gone);
    assert_eq!(deleted_table_top(AsTable, 15, "break"), kept);
    // Below a line, the table keeps its place in every mode.
    assert_eq!(
        deleted_table_top(ByMode, 14, "middle"),
        deleted_table_top(AsTable, 14, "middle")
    );
}

/// The page of the line "B" of exactly 15 pt with a bottom border of 5 pt of space and 1.5 pt of
/// width below a line "S" of exactly `spacer` twips at the top of a page 648 pt high, on a target
/// with the variant `room`.
fn foot_border_page(room: crate::quirks::FootBorderRoom, spacer: u32) -> usize {
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
    let body = format!(
        r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="{spacer}" w:lineRule="exact"/></w:pPr><w:r><w:t>S</w:t></w:r></w:p><w:p><w:pPr><w:widowControl w:val="0"/><w:pBdr><w:bottom w:val="single" w:sz="12" w:space="5" w:color="000000"/></w:pBdr><w:spacing w:before="0" w:after="0" w:line="300" w:lineRule="exact"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p><w:sectPr>{page}</w:sectPr>"#
    );
    let target = testing::on_base_with(|p| p.with_variant(room));
    let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
    find(&list, 'B').0
}

#[test]
fn a_last_line_at_the_foot_needs_room_for_its_bottom_border_where_the_target_does() {
    use crate::quirks::FootBorderRoom::{Fits, Hangs};
    // 632 pt above "B" leave 1 pt below its box: the border's 6.5 pt do not fit.
    assert_eq!(foot_border_page(Hangs, 12_640), 0);
    assert_eq!(foot_border_page(Fits, 12_640), 1);
    // 626 pt leave 7 pt, and the border fits on the page in both.
    assert_eq!(foot_border_page(Fits, 12_520), 0);
    assert_eq!(foot_border_page(Hangs, 12_520), 0);
}

#[test]
fn the_empty_paragraph_that_ends_a_section_takes_part_in_the_spacing_without_a_line() {
    use crate::quirks::ContinuousSectionEnd::{KeepsSpacesWithoutLine, OnlyBlockKeepsLine};
    let step = |ends, line_after, end: Option<(u32, &str)>, next_before| {
        let end = end.map(|(after, content)| (after, "", content));
        section_end_step((ends, None), ("", line_after), end, (next_before, ""))
    };
    let dots = |twips: i64| twips * 50 / 240;
    // The space after of "L" stays, and "N" has its whole space before beyond the empty
    // paragraph's space after of 0; the empty paragraph's space before does nothing.
    let joins = KeepsSpacesWithoutLine;
    assert_eq!(
        step(joins, 240, Some((0, "")), 240) - step(joins, 240, None, 240),
        dots(240)
    );
    // With 18 pt after the empty paragraph, the 12 pt before "N" lie within it.
    assert_eq!(
        step(joins, 120, Some((360, "")), 240) - step(joins, 120, None, 240),
        -dots(120)
    );
    // A paragraph of a bookmark takes no line either.
    let bookmark = r#"<w:bookmarkStart w:id="0" w:name="m"/><w:bookmarkEnd w:id="0"/>"#;
    assert_eq!(
        step(joins, 0, Some((0, bookmark)), 0),
        step(joins, 0, None, 0)
    );
    // With the other variant, the empty paragraph has no part in the spacing, and a paragraph
    // of a bookmark keeps its line.
    let base = OnlyBlockKeepsLine;
    assert_eq!(
        step(base, 240, Some((0, "")), 240),
        step(base, 240, None, 240)
    );
    assert!(step(base, 0, Some((0, bookmark)), 0) > step(base, 0, None, 0));
}

#[test]
fn a_continuous_section_end_shows_nothing_with_a_label_or_a_border() {
    // quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
    use crate::quirks::ContinuousSectionEnd::KeepsSpacesWithoutLine;
    let joins = (KeepsSpacesWithoutLine, Some(15));
    let numbering = r#"<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>"#;
    let label = r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr>"#;
    let border =
        r#"<w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="000000"/></w:pBdr>"#;
    let none = r#"<w:pBdr><w:bottom w:val="none" w:sz="0" w:space="0" w:color="auto"/></w:pBdr>"#;
    let with = |before: &str, props: &str| {
        section_end_step(joins, (before, 0), Some((0, props, "")), (0, numbering))
    };
    let without = |before: &str| section_end_step(joins, (before, 0), None, (0, numbering));
    // After a paragraph, the empty paragraph has no line, with a list label or a border too.
    assert_eq!(with("", ""), without(""));
    assert_eq!(with("", none), without(""));
    assert_eq!(with("", label), without(""));
    assert_eq!(with("", border), without(""));
    // It is in no group of borders: a paragraph before it with the same border draws its
    // bottom line below itself, as without the empty paragraph.
    let bordered = format!("<w:p><w:pPr>{border}</w:pPr><w:r><w:t>B</w:t></w:r></w:p>");
    assert_eq!(with(&bordered, border), without(&bordered));
    assert!(without(&bordered) > without(""));
}

#[test]
fn a_continuous_section_end_after_a_table_keeps_its_line_in_mode_15_only() {
    // quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
    use crate::quirks::ContinuousSectionEnd::KeepsSpacesWithoutLine;
    let cell = table(
        "",
        &[2000],
        &[("", &["<w:p><w:r><w:t>T</w:t></w:r></w:p>"])],
    );
    let step =
        |mode, end| section_end_step((KeepsSpacesWithoutLine, mode), (&cell, 0), end, (0, ""));
    let end = Some((0, "", ""));
    assert!(step(Some(15), end) > step(Some(15), None));
    assert_eq!(step(Some(14), end), step(Some(14), None));
    assert_eq!(step(None, end), step(None, None));
}

#[test]
fn after_a_continuous_section_end_the_rest_of_the_space_before_starts_the_next_page() {
    // quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
    use crate::quirks::ContinuousSectionEnd::{KeepsSpacesWithoutLine, OnlyBlockKeepsLine};
    // 64 lines fill the first page, so "N" starts page 2 with the 48 twips of its space before
    // beyond the empty paragraph's 240 after: 10 dots below the top margin.
    let body = format!(
        r#"{}<w:p><w:pPr><w:spacing w:after="240"/><w:sectPr/></w:pPr></w:p><w:p><w:pPr><w:spacing w:before="288"/></w:pPr><w:r><w:t>N</w:t></w:r></w:p><w:sectPr><w:type w:val="continuous"/></w:sectPr>"#,
        testing::filler(64)
    );
    let place = |ends| {
        let target = testing::on_base_with(|p| p.with_variant(ends));
        let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
        find(&list.list, 'N')
    };
    assert_eq!(
        place(KeepsSpacesWithoutLine),
        (1, 1440 * 1270, base(1440) + 10)
    );
    // With the other variant, the empty paragraph takes no room and "N" has no space there.
    assert_eq!(place(OnlyBlockKeepsLine), (1, 1440 * 1270, base(1440)));
}

#[test]
fn after_a_continuous_section_end_a_kept_paragraph_keeps_the_rest_of_its_space_on_the_next_page() {
    // quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
    use crate::quirks::ContinuousSectionEnd::KeepsSpacesWithoutLine;
    // "N" fits below 60 lines, but "M", which it is kept with, does not when it has 200 pt
    // before; then the chain starts page 2, and "N" keeps there the 48 twips of its space
    // before beyond the empty paragraph's 240 after: 10 dots below the top margin.
    let body = |keep: &str, m_before: u32| {
        format!(
            r#"{}<w:p><w:pPr><w:spacing w:after="240"/><w:sectPr/></w:pPr></w:p><w:p><w:pPr>{keep}<w:spacing w:before="288"/></w:pPr><w:r><w:t>N</w:t></w:r></w:p><w:p><w:pPr><w:spacing w:before="{m_before}"/></w:pPr><w:r><w:t>M</w:t></w:r></w:p><w:sectPr><w:type w:val="continuous"/></w:sectPr>"#,
            testing::filler(60)
        )
    };
    let place = |body: &str| {
        let target = testing::on_base_with(|p| p.with_variant(KeepsSpacesWithoutLine));
        let list = testing::pass_with(body, (NORMAL, None), None, Numbering::default(), target);
        find(&list.list, 'N')
    };
    assert_eq!(place(&body("", 4000)).0, 0);
    assert_eq!(
        place(&body("<w:keepNext/>", 4000)),
        (1, 1440 * 1270, base(1440) + 10)
    );
    // The room test of the chain gives "N" the same rest of 48 twips above it as its layout,
    // not the whole 288: then "M" with 300 twips before fits below "N", and the chain stays
    // where it stands without the keep.
    assert_eq!(place(&body("<w:keepNext/>", 300)), place(&body("", 300)));
}

#[test]
fn continuous_section_end_drops_trailing_break_line_and_after_before_mode_15() {
    // quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
    use crate::quirks::ContinuousSectionEnd::KeepsSpacesWithoutLine;
    let dots = |twips: i64| twips * 50 / 240;
    let gap = |mode: Option<u32>, tail: &str, next: &str| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:after="240" w:line="240" w:lineRule="exact"/><w:sectPr/></w:pPr><w:r><w:t>A</w:t></w:r>{tail}</w:p>{next}<w:sectPr><w:type w:val="continuous"/></w:sectPr>"#
        );
        let target = testing::on_base_with(|p| p.with_variant(KeepsSpacesWithoutLine));
        let list = testing::pass_with(&body, (NORMAL, mode), None, Numbering::default(), target);
        find(&list.list, 'B').2 - find(&list.list, 'A').2
    };
    let next_p = |before: u32| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:before="{before}" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#
        )
    };
    let next_tbl = table(
        "",
        &[2000],
        &[(
            "",
            &[
                r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#,
            ],
        )],
    );
    let br = "<w:r><w:br/></w:r>";
    let br2 = format!("{br}{br}");
    let br_sp = format!(r#"{br}<w:r><w:t xml:space="preserve"> </w:t></w:r>"#);
    let one_line = dots(240);
    let p0 = next_p(0);
    let p120 = next_p(120);
    let p288 = next_p(288);
    let cases = [
        (Some(14), "", p0.as_str(), one_line + dots(240)),
        // In mode 14, trailing `<w:br/>` drops the empty line and `after` before a paragraph or table.
        (Some(14), br, p0.as_str(), one_line),
        (Some(14), br, next_tbl.as_str(), one_line),
        // The next paragraph keeps only the excess of its `before` beyond the dropped `after`.
        (Some(14), br, p120.as_str(), one_line),
        (Some(14), br, p288.as_str(), one_line + dots(48)),
        // Double `<w:br/>` drops only the final empty line (idempotent).
        (Some(14), br2.as_str(), p0.as_str(), one_line * 2),
        // A trailing space after `<w:br/>` keeps the final line and `after`.
        (
            Some(14),
            br_sp.as_str(),
            p0.as_str(),
            one_line * 2 + dots(240),
        ),
        // In mode 15, both the trailing empty line and `after` stay.
        (Some(15), br, p0.as_str(), one_line * 2 + dots(240)),
        (Some(15), br, next_tbl.as_str(), one_line * 2 + dots(240)),
    ];
    for (mode, tail, next, expected) in cases {
        assert_eq!(gap(mode, tail, next), expected);
    }
}

/// The counts of the warnings of picture bullets of a body of two paragraphs of a bullet list
/// whose level asks for the picture bullet `picture`, of which the numbering part has the
/// picture bullet 0.
fn picture_bullet_warnings(picture: &str) -> u32 {
    let numbering = format!(
        r#"<w:numbering xmlns:w="{W}"><w:numPicBullet w:numPicBulletId="0"><w:pict/></w:numPicBullet><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="{picture}"/></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
    );
    let doc = parse(&numbering);
    let numbering = Numbering::read(
        &mut PartReader::new(&doc),
        doc.root().unwrap(),
        crate::reader::settings::ReaderSettings::with_built_in_list(
            crate::quirks::BuiltInList::WithoutPart,
        ),
    );
    let item = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
    let body = format!("{item}{item}<w:sectPr/>");
    let pass = testing::pass_with(&body, (NORMAL, None), None, numbering, testing::on_base());
    pass.warnings
        .iter()
        .filter(|(warning, _)| {
            matches!(
                warning,
                crate::Warning::FeatureNotSupported {
                    feature: crate::Feature::PictureBullet,
                    ..
                }
            )
        })
        .map(|(_, count)| count)
        .sum()
}

#[test]
fn warns_of_a_picture_bullet_once_for_each_paragraph_that_shows_it() {
    assert_eq!(picture_bullet_warnings("0"), 2);
    // A level whose picture bullet the part does not have shows its text.
    assert_eq!(picture_bullet_warnings("5"), 0);
}

#[test]
fn draws_a_picture_bullet_scaled_from_label_font_size_without_warning() {
    use f_office_paint::Item;
    // Minimal 1x1 valid GIF header (64x32 aspect in logical screen descriptor).
    let gif_2x1: Vec<u8> = b"GIF89a\x40\x00\x20\x00\x00\x00\x00;".to_vec();
    let numbering = format!(
        r#"<w:numbering xmlns:w="{W}" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:numPicBullet w:numPicBulletId="0"><w:pict><v:shape style="width:24pt;height:12pt"><v:imagedata r:id="rId1"/></v:shape></w:pict></w:numPicBullet><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="0"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
    );
    let doc = parse(&numbering);
    let mut numbering = Numbering::read(
        &mut PartReader::new(&doc),
        doc.root().unwrap(),
        crate::reader::settings::ReaderSettings::with_built_in_list(
            crate::quirks::BuiltInList::WithoutPart,
        ),
    );
    numbering.attach_images(&mut |_| Some(f_office_paint::Image::new(gif_2x1.clone())));
    let body = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr><w:rPr><w:sz w:val="24"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="24"/></w:rPr><w:t>A</w:t></w:r></w:p><w:sectPr/>"#;
    let pass = testing::pass_with(body, (NORMAL, None), None, numbering, testing::on_base());
    let bullet_warns: u32 = pass
        .warnings
        .iter()
        .filter(|(w, _)| {
            matches!(
                w,
                crate::Warning::FeatureNotSupported {
                    feature: crate::Feature::PictureBullet,
                    ..
                }
            )
        })
        .map(|(_, c)| c)
        .sum();
    assert_eq!(bullet_warns, 0);
    let image = pass.list.pages()[0]
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Image(img) => Some(img),
            _ => None,
        })
        .expect("expected picture bullet image item");
    // At 12 pt (sz=24), target height is 12/2 - 1 = 5 pt -> ~5.04 pt; 2:1 aspect -> ~9.96 pt.
    assert!(
        (image.height.units() - Length::from_points(5).unwrap().units()).abs()
            <= Length::UNITS_PER_DOT
    );
    assert!(
        (image.width.units() - Length::from_points(10).unwrap().units()).abs()
            <= Length::UNITS_PER_DOT
    );
}

#[test]
fn a_numbered_paragraph_that_ends_a_section_counts_once_in_its_list() {
    let numbered = |text: &str, section: &str| {
        format!(
            r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr>{section}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let final_section = r#"<w:sectPr><w:type w:val="continuous"/></w:sectPr>"#;
    let numbering = format!(
        r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
    );
    // "A" is 1, "C", which ends a section of one or of two columns before a continuous
    // section, is 2, and "B" is 3.
    for columns in ["", r#"<w:cols w:num="2"/>"#] {
        let body = format!(
            "{}{}{}{final_section}",
            numbered("A", ""),
            numbered("C", &format!("<w:sectPr>{columns}</w:sectPr>")),
            numbered("B", "")
        );
        let list = testing::lay_out_with_numbering(&body, &numbering);
        assert_eq!(
            (find_all(&list, '3').len(), find_all(&list, '4').len()),
            (1, 0)
        );
    }
}

#[test]
fn a_section_starts_on_the_page_of_a_break_that_holds_only_line_numbers() {
    let p = |text: &str| format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>");
    // "A" is line 1 and the line of the page break line 2. The empty paragraph that ends the
    // numbered section comes after the break, and its number would be the only thing on the
    // new page. The next section starts on that page, and the number 3 is not drawn.
    let body = format!(
        "{}<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p><w:p><w:pPr><w:sectPr><w:lnNumType w:countBy=\"1\"/></w:sectPr></w:pPr></w:p>{}<w:sectPr/>",
        p("A"),
        p("B")
    );
    let list = lay_out(&body, NORMAL, None);
    assert_eq!(list.pages().len(), 2);
    assert_eq!(find(&list, 'B').0, 1);
    let pages = |digit: char| -> Vec<usize> {
        find_all(&list, digit).iter().map(|found| found.0).collect()
    };
    assert_eq!(
        (pages('1'), pages('2'), pages('3')),
        (vec![0], vec![0], vec![])
    );
}

#[test]
fn continuous_sections_update_line_numbers_mid_page() {
    let p = |text: &str| format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>");
    let texts = |body: &str, page: usize| -> Vec<String> {
        lay_out(body, NORMAL, None).pages()[page]
            .items()
            .iter()
            .filter_map(|item| match item {
                f_office_paint::Item::Glyphs(run) => Some(run.text.clone()),
                _ => None,
            })
            .collect()
    };
    let cont = "<w:type w:val=\"continuous\"/>";
    // Off -> on -> off mid-page draws numbers only for the middle section.
    let body = format!(
        "{}<w:p><w:pPr><w:sectPr/></w:pPr><w:r><w:t>A</w:t></w:r></w:p>\
         {}<w:p><w:pPr><w:sectPr>{cont}<w:lnNumType w:countBy=\"1\"/></w:sectPr></w:pPr><w:r><w:t>B</w:t></w:r></w:p>\
         {}<w:sectPr>{cont}</w:sectPr>",
        p("S1"),
        p("S2"),
        p("S3")
    );
    let page0 = texts(&body, 0);
    assert!(page0.contains(&"1".to_string()) && page0.contains(&"2".to_string()));
    assert!(!page0.contains(&"3".to_string()));

    // Mid-page restart="newSection" resets immediately and continues across a page break.
    let body = format!(
        "<w:p><w:pPr><w:sectPr><w:lnNumType w:countBy=\"1\"/></w:sectPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>\
         {}<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>C</w:t></w:r></w:p>\
         <w:sectPr>{cont}<w:lnNumType w:countBy=\"1\" w:restart=\"newSection\"/></w:sectPr>",
        p("B")
    );
    let list = lay_out(&body, NORMAL, None);
    let ones: Vec<usize> = find_all(&list, '1').iter().map(|found| found.0).collect();
    let twos: Vec<usize> = find_all(&list, '2').iter().map(|found| found.0).collect();
    assert_eq!((ones, twos), (vec![0, 0], vec![1]));

    // Mid-page restart="continuous" keeps counting; restart="newPage" keeps the page's start
    // offset until the next page.
    let body = format!(
        "<w:p><w:pPr><w:sectPr><w:lnNumType w:countBy=\"1\"/></w:sectPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>\
         <w:p><w:pPr><w:sectPr>{cont}<w:lnNumType w:countBy=\"1\" w:restart=\"continuous\"/></w:sectPr></w:pPr><w:r><w:t>B</w:t></w:r></w:p>\
         {}<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>D</w:t></w:r></w:p>\
         <w:sectPr>{cont}<w:lnNumType w:countBy=\"1\" w:restart=\"newPage\" w:start=\"10\"/></w:sectPr>",
        p("C")
    );
    let page0 = texts(&body, 0);
    let page1 = texts(&body, 1);
    assert!(
        page0.contains(&"1".to_string())
            && page0.contains(&"2".to_string())
            && page0.contains(&"3".to_string())
    );
    assert!(page1.contains(&"11".to_string()));
}

#[test]
fn a_section_starts_on_the_page_of_a_break_that_holds_only_an_empty_shaded_paragraph() {
    // The empty paragraph that ends the section after the page break is shaded white or gray.
    // Its fill keeps the next section off the new page no more than its line number would:
    // the next section starts on that page, and the fill is not drawn.
    for fill in ["FFFFFF", "D9D9D9"] {
        let body = format!(
            r#"<w:p><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r><w:br w:type="page"/></w:r></w:p><w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="{fill}"/><w:sectPr/></w:pPr></w:p><w:p><w:r><w:t>B</w:t></w:r></w:p><w:sectPr/>"#
        );
        let list = lay_out(&body, NORMAL, None);
        assert_eq!(list.pages().len(), 2, "{fill}");
        assert_eq!(find(&list, 'B').0, 1, "{fill}");
    }
}

#[test]
fn the_fill_of_a_paragraph_in_a_cell_lies_above_a_drawing_behind_the_text_that_it_anchors() {
    // The page's items in the order of painting, with the items of each group in its place.
    fn painted(items: &[f_office_paint::Item], out: &mut Vec<char>) {
        for item in items {
            match item {
                f_office_paint::Item::Group(group) => painted(&group.items, out),
                f_office_paint::Item::Path(_) => out.push('d'),
                f_office_paint::Item::Rect(rect)
                    if rect.color
                        == (f_office_paint::Rgb {
                            r: 0xD9,
                            g: 0xD9,
                            b: 0xD9,
                        }) =>
                {
                    out.push('f');
                }
                _ => {}
            }
        }
    }
    // In a table cell, a gray paragraph anchors an outlined drawing behind the text, and a
    // plain paragraph after it anchors another. The fill comes after the first drawing and
    // before the second, which no fill of its own paragraph covers.
    let behind = AnchoredShape {
        across: ("column", 0),
        down: ("paragraph", 0),
        size: (635_000, 254_000),
        wrap: "<wp:wrapNone/>",
        outline: Some(12_700),
        text: None,
    }
    .drawing()
    .replace(r#"behindDoc="0""#, r#"behindDoc="1""#);
    let cell = format!(
        r#"<w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:pPr><w:r>{behind}</w:r><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r>{behind}</w:r><w:r><w:t>B</w:t></w:r></w:p>"#
    );
    let body = format!(
        "{}<w:p/><w:sectPr/>",
        table("", &[3000], &[("", &[cell.as_str()])])
    );
    let list = lay_out(&body, NORMAL, None);
    let mut order = Vec::new();
    painted(list.pages()[0].items(), &mut order);
    assert_eq!(order.into_iter().collect::<String>(), "dfd");
}

#[test]
fn a_level_that_reads_as_none_by_its_octet_shows_no_number_at_the_margin() {
    // The list defines level 0 only, with a left indent of 720 twips. Read as written, 9 falls
    // to level 0; read by its octet, 9 has no number and no indent, and 265 reads as 9 does.
    let x = |value: &str, reading| {
        let body = format!(
            r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="{value}"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>X</w:t></w:r></w:p>"#
        );
        let list = lay_out_numbered_styled(&body, "", "", &Settings::default(), ("", reading));
        (find_all(&list, '1').len(), find(&list, 'X').1)
    };
    let twips = |n: i64| (1440 + n) * Length::UNITS_PER_TWIP;
    assert_eq!(x("9", ListLevelReading::AsWritten), (1, twips(720)));
    for value in ["9", "265", "-245"] {
        assert_eq!(
            x(value, ListLevelReading::ByOctet),
            (0, twips(0)),
            "{value}"
        );
    }
    // 256 and 15 read as level 0 by their octets, as 0 does.
    for value in ["0", "256", "15"] {
        assert_eq!(
            x(value, ListLevelReading::ByOctet),
            (1, twips(720)),
            "{value}"
        );
    }
}

#[test]
fn removing_a_style_list_drops_the_style_indents() {
    // "Bullet" puts its paragraphs in list 2 with a hanging indent of its own, "Plain" has the
    // same indent and no list, and "Cleared*" styles cancel numbering inside the style chain.
    let styles = concat!(
        r#"<w:style w:type="paragraph" w:styleId="Bullet"><w:pPr><w:numPr><w:numId w:val="2"/></w:numPr><w:ind w:left="357" w:right="500" w:hanging="357"/></w:pPr></w:style>"#,
        r#"<w:style w:type="paragraph" w:styleId="Plain"><w:pPr><w:ind w:left="357" w:right="500" w:hanging="357"/></w:pPr></w:style>"#,
        r#"<w:style w:type="paragraph" w:styleId="ClearedBullet"><w:basedOn w:val="Bullet"/><w:pPr><w:numPr><w:numId w:val="0"/></w:numPr></w:pPr></w:style>"#,
        r#"<w:style w:type="paragraph" w:styleId="ClearedPlain"><w:basedOn w:val="Plain"/><w:pPr><w:numPr><w:numId w:val="0"/></w:numPr></w:pPr></w:style>"#,
        r#"<w:style w:type="paragraph" w:styleId="ClearedWithOwn"><w:basedOn w:val="Bullet"/><w:pPr><w:numPr><w:numId w:val="0"/></w:numPr><w:ind w:left="720"/></w:pPr></w:style>"#,
    );
    let x = |style: &str, direct_num: &str, ind: &str| {
        let body = format!(
            r#"<w:p><w:pPr><w:pStyle w:val="{style}"/>{direct_num}{ind}</w:pPr><w:r><w:t>X</w:t></w:r></w:p>"#
        );
        let list = lay_out_numbered_styled(
            &body,
            "",
            "",
            &Settings::default(),
            (styles, ListLevelReading::AsWritten),
        );
        find(&list, 'X').1
    };
    let zero = r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="0"/></w:numPr>"#;
    let twips = |n: i64| (1440 + n) * Length::UNITS_PER_TWIP;
    // Direct and style-level `w:numId="0"` reset inherited left and first-line indents whether or
    // not any ancestor names a list, keeping only `w:ind` set at that layer.
    for (style, direct_num, ind, want) in [
        ("Bullet", zero, r#"<w:ind w:left="357"/>"#, 357),
        ("Bullet", zero, "", 0),
        ("Plain", zero, r#"<w:ind w:left="357"/>"#, 357),
        ("Plain", zero, "", 0),
        ("ClearedBullet", "", "", 0),
        ("ClearedPlain", "", "", 0),
        ("ClearedWithOwn", "", "", 720),
    ] {
        assert_eq!(x(style, direct_num, ind), twips(want), "{style}");
    }
    // Inherited right indent is preserved when `w:numId="0"` clears left and first-line indents.
    assert_eq!(
        x("ClearedPlain", "", r#"<w:jc w:val="right"/>"#),
        x("Plain", "", r#"<w:jc w:val="right"/>"#),
    );
}

#[test]
fn ends_or_centers_a_label_at_the_start_of_the_first_line() {
    // The label "1." is 200 twips wide and the first line starts at 360 twips, so the label
    // starts at 360, at 260 when centered there and at 160 when it ends there. The text
    // after the tab starts at the left indent of 720 twips in each case.
    let at = |level: &str| {
        let list = lay_out_numbered_with(NUMBERED_X, level, "", &Settings::default());
        (find(&list, '1').1, find(&list, 'X').1)
    };
    let twips = |n: i64| (1440 + n) * Length::UNITS_PER_TWIP;
    assert_eq!(at(""), (twips(360), twips(720)));
    assert_eq!(at(r#"<w:lvlJc w:val="center"/>"#), (twips(260), twips(720)));
    assert_eq!(at(r#"<w:lvlJc w:val="right"/>"#), (twips(160), twips(720)));
}

#[test]
fn starts_the_text_of_a_legacy_level_at_its_indent_from_the_label() {
    // The label "1." starts at 360 twips and is 200 twips wide. The text starts the legacy
    // indent after the label's start, or the legacy space after its end, without a tab.
    let text_at = |legacy: &str| {
        let list = lay_out_numbered_with(NUMBERED_X, legacy, "", &Settings::default());
        find(&list, 'X').1
    };
    let twips = |n: i64| (1440 + n) * Length::UNITS_PER_TWIP;
    let indent = r#"<w:legacy w:legacy="1" w:legacySpace="0" w:legacyIndent="400"/>"#;
    assert_eq!(text_at(indent), twips(760));
    let space = r#"<w:legacy w:legacy="1" w:legacySpace="50" w:legacyIndent="100"/>"#;
    assert_eq!(text_at(space), twips(610));
}

#[test]
fn leaves_out_automatic_space_only_above_the_first_paragraph_even_when_it_is_empty() {
    let auto = r#"<w:pPr><w:spacing w:beforeAutospacing="1" w:afterAutospacing="1"/></w:pPr>"#;
    // Each paragraph's automatic space after follows its line, so the baseline sits the fake
    // font's ascent of 8 pt, 33.33 device dots rounded to 33, below the line's top.
    let spaced = |top: i64| top * Length::UNITS_PER_TWIP / DOT + 33;
    let first = format!("<w:p>{auto}<w:r><w:t>A</w:t></w:r></w:p>");
    assert_eq!(find(&lay_out(&first, "", None), 'A').2, spaced(1440));
    // The empty first paragraph is 200 twips tall, and 14 pt (280 twips) of automatic space
    // come before the second one.
    let after_empty = format!("<w:p>{auto}</w:p><w:p>{auto}<w:r><w:t>X</w:t></w:r></w:p>");
    assert_eq!(
        find(&lay_out(&after_empty, "", None), 'X').2,
        spaced(1440 + 200 + 280)
    );
}

#[test]
fn a_last_line_whose_space_after_the_next_paragraph_removes_takes_the_single_rules() {
    // Two paragraphs of one style with 10 pt after. Where the space after follows the first
    // line, its baseline sits the rounded ascent of 33 device dots below its top at 1440
    // twips. Where contextual spacing removes the space, the line takes the single rules: the
    // descent, rounded to 8 dots, above the exact bottom 41.67 dots below the top.
    let spaced = |top: i64| du(top) + 33;
    let pair = |mark: &str| {
        let props = format!(r#"<w:pPr><w:spacing w:after="200"/>{mark}</w:pPr>"#);
        format!(
            "<w:p>{props}<w:r><w:t>A</w:t></w:r></w:p><w:p>{props}<w:r><w:t>B</w:t></w:r></w:p>"
        )
    };
    let kept = lay_out(&pair(""), "", None);
    assert_eq!(find(&kept, 'A').2, spaced(1440));
    assert_eq!(find(&kept, 'B').2, spaced(1440 + 200 + 200));
    let removed = lay_out(&pair("<w:contextualSpacing/>"), "", None);
    assert_eq!(find(&removed, 'A').2, base(1440));
    assert_eq!(base(1440), spaced(1440) + 1);
    // The last paragraph, which no paragraph follows, keeps its space after.
    assert_eq!(find(&removed, 'B').2, spaced(1440 + 200));
}

#[test]
fn an_empty_line_takes_its_height_from_the_line_break_that_ends_it() {
    // "A" is 10 pt, and a 20 pt run has two breaks before "B". The first line keeps its
    // 10 pt, the empty line is 20 pt tall, and "B" rises 16 pt above its baseline.
    let body = r#"<w:p><w:r><w:t>A</w:t></w:r><w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:br/><w:br/><w:t>B</w:t></w:r></w:p>"#;
    let list = lay_out(body, "", None);
    let gap = find(&list, 'B').2 - find(&list, 'A').2;
    let points = |n: i64| f_office_units::div_round(n * Length::UNITS_PER_POINT, DOT);
    assert!((gap - points(2 + 20 + 16)).abs() <= 1, "{gap}");
}

#[test]
fn a_comment_reference_mark_sizes_its_line_and_draws_nothing() {
    // "A" is 10 pt, and a 20 pt run holds only the reference mark of a comment. The line is
    // 20 pt tall, so "B" starts 400 twips down, and the mark draws no glyph.
    let body = format!(
        r#"<w:p><w:r><w:t>A</w:t></w:r><w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:annotationRef/></w:r></w:p>{}"#,
        p("B")
    );
    let list = lay_out(&body, "", None);
    assert_eq!(find(&list, 'B').2, base(1440 + 400));
    assert_eq!(find_all(&list, 'A').len(), 1);
}

#[test]
fn a_list_label_sizes_the_ascent_of_its_line_but_not_its_descent() {
    // The label is 20 pt and the text 10 pt, so the line rises 16 pt above its baseline and
    // goes 2 pt below it, and the next 10 pt line has its baseline 8 pt lower again.
    let body = format!("{NUMBERED_X}{}", p("Y"));
    let list = lay_out_numbered(&body, r#"<w:sz w:val="40"/>"#, &Settings::default());
    // Baselines are in device dots, and 10 pt are 41.67 of them.
    let ten_points = |gap: i64| (gap * DOT - 10 * Length::UNITS_PER_POINT).abs() <= DOT;
    let (x, y) = (find(&list, 'X').2, find(&list, 'Y').2);
    assert!(ten_points(y - x), "{}", y - x);
    assert_eq!(x, find(&list, '1').2);
    // A line that holds only the label takes its descent from the paragraph mark.
    let empty =
        r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr></w:p>"#;
    let list = lay_out_numbered(
        &format!("{empty}{}", p("Y")),
        r#"<w:sz w:val="40"/>"#,
        &Settings::default(),
    );
    let gap = find(&list, 'Y').2 - find(&list, '1').2;
    assert!(ten_points(gap), "{gap}");
}

#[test]
fn an_empty_list_item_takes_its_ascent_from_the_taller_of_its_label_and_mark() {
    // A 20 pt paragraph mark with a 10 pt list label on an empty list item rises by the 20 pt
    // mark's ascent (16 pt) rather than the smaller 10 pt label's ascent (8 pt), so its baseline
    // lies 16 pt below the line above's bottom (18 pt below an earlier 10 pt baseline).
    let empty = concat!(
        r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr>"#,
        r#"<w:rPr><w:sz w:val="40"/></w:rPr></w:pPr></w:p>"#,
    );
    let body = format!("{}{empty}{}", p("A"), p("B"));
    let list = lay_out_numbered(&body, r#"<w:sz w:val="20"/>"#, &Settings::default());
    let (a, label, b) = (find(&list, 'A').2, find(&list, '1').2, find(&list, 'B').2);
    // A is 10 pt (2 pt descent), empty item has 20 pt mark (16 pt ascent + 4 pt descent), B has
    // 8 pt ascent: A -> label is 18 pt, label -> B is 12 pt.
    let near = |gap: i64, pts: i64| (gap * DOT - pts * Length::UNITS_PER_POINT).abs() <= DOT;
    assert!(near(label - a, 18), "A->label gap: {}", label - a);
    assert!(near(b - label, 12), "label->B gap: {}", b - label);
}

#[test]
fn a_list_label_descent_sizes_its_line_where_the_target_counts_it() {
    use crate::quirks::ListLabelDescent;
    // The label is 20 pt and the text 10 pt: where the label's descent counts, the line goes
    // its 4 pt below the baseline, not the text's 2 pt, and the next line comes 2 pt lower,
    // also below a line that holds only the label.
    let numbering = format!(
        r#"<w:numbering xmlns:w="{W}">{}</w:numbering>"#,
        testing::LARGE_LABELS
    );
    let empty =
        r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr></w:p>"#;
    let gap = |body: &str, from: char, variant| {
        let list = testing::lay_out_with_numbering_as(body, &numbering, variant);
        find(&list, 'Y').2 - find(&list, from).2
    };
    let two_points = |more: i64| (more * DOT - 2 * Length::UNITS_PER_POINT).abs() <= DOT;
    for (body, from) in [
        (format!("{NUMBERED_X}{}", p("Y")), 'X'),
        (format!("{empty}{}", p("Y")), '1'),
    ] {
        let left = gap(&body, from, ListLabelDescent::LeftOutOfLine);
        let counted = gap(&body, from, ListLabelDescent::Counted);
        assert!(two_points(counted - left), "{from}: {left} {counted}");
    }
}

#[test]
fn a_list_label_alone_rises_with_the_spacing_where_the_target_scales_it() {
    use crate::quirks::LabelAloneRise;
    // The label is 20 pt, 16 pt of it above the baseline, and the mark 10 pt, 8 pt: where the
    // spacing scales the label's rise on a line that holds only the label, 1.5 lines put half
    // of its 8 pt more between the plain lines around it, and single spacing puts nothing.
    let numbering = format!(
        r#"<w:numbering xmlns:w="{W}">{}</w:numbering>"#,
        testing::LARGE_LABELS
    );
    let step = |line: u32, variant| {
        let empty = format!(
            r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr><w:spacing w:line="{line}" w:lineRule="auto"/></w:pPr></w:p>"#
        );
        let body = format!("{}{empty}{}", p("X"), p("Y"));
        let list = testing::lay_out_with_numbering_as(&body, &numbering, variant);
        find(&list, 'Y').2 - find(&list, 'X').2
    };
    for (line, more) in [(360, 4), (240, 0)] {
        let unscaled = step(line, LabelAloneRise::Unscaled);
        let scaled = step(line, LabelAloneRise::Scaled);
        let wanted = more * Length::UNITS_PER_POINT;
        assert!(
            ((scaled - unscaled) * DOT - wanted).abs() <= DOT,
            "{line}: {unscaled} {scaled}"
        );
    }
}

/// The x in units of the text after the label of a numbered paragraph with a left indent of
/// 720 and a hanging indent of 360 twips, with default tab stops every 708 twips.
fn text_after_label(indent_is_numbering_tab_stop: bool) -> i64 {
    let settings = Settings {
        default_tab_stop: Length::from_twips(708).unwrap(),
        indent_is_numbering_tab_stop,
        ..Settings::default()
    };
    let list = lay_out_numbered(NUMBERED_X, "", &settings);
    find(&list, 'X').1 - find(&list, '1').1
}

#[test]
fn a_list_label_tab_skips_the_indent_when_the_document_turns_that_off() {
    // The label starts at 360 twips and ends before 708, so the tab goes to the indent at 720,
    // or without it to the default stop at 708: 360 and 348 twips after the label's start.
    assert_eq!(text_after_label(true), 360 * Length::UNITS_PER_TWIP);
    assert_eq!(text_after_label(false), 348 * Length::UNITS_PER_TWIP);
}

/// The x in twips of the first glyph of "a", "b" and "c" on three pages, with a left margin of
/// 1440 twips, a gutter of 432 and a right margin of 2304, and the first page numbered
/// `first`.
fn page_lefts(side_margins: SideMargins, first: u32) -> Vec<i64> {
    let settings = Settings {
        side_margins,
        ..Settings::default()
    };
    let next = |text: &str| {
        format!("<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>")
    };
    let body = format!(
        r#"{}{}{}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="2304" w:bottom="1440" w:left="1440" w:gutter="432"/><w:pgNumType w:start="{first}"/></w:sectPr>"#,
        p("a"),
        next("b"),
        next("c")
    );
    let list = lay_out_numbered(&body, "", &settings);
    ['a', 'b', 'c']
        .iter()
        .enumerate()
        .map(|(page, ch)| {
            let (on, x, _) = find(&list, *ch);
            assert_eq!(on, page);
            x / Length::UNITS_PER_TWIP
        })
        .collect()
}

#[test]
fn mirrors_the_side_margins_of_pages_with_even_numbers() {
    // Odd pages start at the left margin and the gutter, 1872 twips; even pages at the right
    // margin, 2304 twips.
    assert_eq!(page_lefts(SideMargins::Mirrored, 1), [1872, 2304, 1872]);
    assert_eq!(page_lefts(SideMargins::Mirrored, 2), [2304, 1872, 2304]);
    assert_eq!(page_lefts(SideMargins::Section, 2), [1872, 1872, 1872]);
    // Portrait book-fold omits the gutter without swapping side margins.
    assert_eq!(page_lefts(SideMargins::BookFold, 1), [1440, 1440, 1440]);
}

#[test]
fn swaps_landscape_side_margins_and_places_gutter_on_inside_under_book_fold() {
    let lefts = |side_margins: SideMargins| {
        let settings = Settings {
            side_margins,
            ..Settings::default()
        };
        let next = |text: &str| {
            format!("<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>")
        };
        let body = format!(
            r#"{}{}{}<w:sectPr><w:pgSz w:w="8419" w:h="11906" w:orient="landscape"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="720" w:gutter="360"/></w:sectPr>"#,
            p("a"),
            next("b"),
            next("c")
        );
        let list = lay_out_numbered(&body, "", &settings);
        ['a', 'b', 'c']
            .iter()
            .enumerate()
            .map(|(page, ch)| {
                let (on, x, _) = find(&list, *ch);
                assert_eq!(on, page);
                x / Length::UNITS_PER_TWIP
            })
            .collect::<Vec<_>>()
    };
    // BookFold: inside (right + gutter = 1800) on left of odd pages, outside (720) on even.
    assert_eq!(lefts(SideMargins::BookFold), [1800, 720, 1800]);
    // BookFoldReverse: outside (720) on left of odd pages, inside (1800) on even.
    assert_eq!(lefts(SideMargins::BookFoldReverse), [720, 1800, 720]);
    // Plain landscape section: left + gutter (1080) on every page.
    assert_eq!(lefts(SideMargins::Section), [1080, 1080, 1080]);
}

#[test]
fn flips_inside_and_outside_horizontal_frame_alignment_on_even_pages() {
    let frame = |align: &str, ch: &str| {
        format!(
            r#"<w:p><w:pPr><w:framePr w:w="1440" w:wrap="around" w:vAnchor="text" w:hAnchor="margin" w:xAlign="{align}" w:y="1"/></w:pPr><w:r><w:t>{ch}</w:t></w:r></w:p>"#
        )
    };
    let page_two = "<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>2</w:t></w:r></w:p>";
    let body = format!(
        "{}{}{}{}{}{}",
        p("1"),
        frame("outside", "A"),
        frame("inside", "B"),
        page_two,
        frame("outside", "C"),
        frame("inside", "D"),
    );
    // Letter page (12240 twips) with 1440-twip margins: left edge = 1440, right frame start = 9360.
    let list = lay_out(&body, NORMAL, None);
    let at = |ch: char| {
        let (page, x, _) = find(&list, ch);
        (page, x / Length::UNITS_PER_TWIP)
    };
    assert_eq!(at('A'), (0, 9360));
    assert_eq!(at('B'), (0, 1440));
    assert_eq!(at('C'), (1, 1440));
    assert_eq!(at('D'), (1, 9360));
}

#[test]
fn sizes_an_empty_paragraph_by_the_character_style_of_its_mark() {
    let styles = r#"<w:style w:type="character" w:styleId="Big"><w:rPr><w:sz w:val="40"/></w:rPr></w:style>"#;
    let body = format!(
        r#"<w:p><w:pPr><w:rPr><w:rStyle w:val="Big"/></w:rPr></w:pPr></w:p>{}"#,
        p("B")
    );
    // The empty line is 20 pt (400 twips) tall, so "B" starts 400 twips down.
    assert_eq!(find(&lay_out(&body, styles, None), 'B').2, base(1440 + 400));
}

#[test]
fn lines_text_up_at_positional_tabs_on_the_margins() {
    let ptab = |alignment: &str| {
        format!(r#"<w:ptab w:relativeTo="margin" w:alignment="{alignment}" w:leader="none"/>"#)
    };
    let body = format!(
        "<w:p><w:r><w:t>a</w:t>{}<w:t>c</w:t>{}<w:t>b</w:t></w:r></w:p>",
        ptab("center"),
        ptab("right")
    );
    let list = lay_out(&body, NORMAL, None);
    // The text column runs from 1440 to 10800 twips, and glyphs are 100 twips wide: "c" is
    // centered at 6120, and "b" ends at the right margin.
    assert_eq!(find(&list, 'c').1, 6070 * Length::UNITS_PER_TWIP);
    assert_eq!(find(&list, 'b').1, 10_700 * Length::UNITS_PER_TWIP);
}

#[test]
fn stacks_paragraphs_in_frames_that_lie_in_place() {
    let framed = |text: &str| {
        format!(
            r#"<w:p><w:pPr><w:framePr w:wrap="auto" w:vAnchor="margin" w:hAnchor="text" w:xAlign="left" w:yAlign="inline"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let list = lay_out(&format!("{}{}", framed("a"), framed("b")), NORMAL, None);
    // Lines of 200 twips from the top margin at 1440 twips, one below the other.
    assert_eq!(find(&list, 'a').2, base(1440));
    assert_eq!(find(&list, 'b').2, base(1640));
}

#[test]
fn stacks_neighbor_paragraphs_with_equal_frames_in_one_frame() {
    let framed = |text: &str| {
        format!(
            r#"<w:p><w:pPr><w:framePr w:w="2000" w:hAnchor="page" w:x="8000" w:yAlign="bottom"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let list = lay_out(&format!("{}{}", framed("a"), framed("b")), NORMAL, None);
    // One frame of two 200 twip lines, which ends at the bottom margin at 14400 twips, 8000
    // twips from the page's left edge on the device grid.
    let (page, x, y) = find(&list, 'a');
    assert_eq!((page, y), (0, base(14_000)));
    assert!((x - 8000 * Length::UNITS_PER_TWIP).abs() < DOT, "{x}");
    assert_eq!(find(&list, 'b').2, base(14_200));
}

#[test]
fn flows_text_beside_a_frame_that_it_wraps_around() {
    // A frame 2000 twips wide at the left margin and 1440 twips from the top of the page,
    // as its `w:y` says without `w:vAnchor`, with text wrapping around it.
    let frame = r#"<w:p><w:pPr><w:framePr w:w="2000" w:wrap="around" w:hAnchor="page" w:x="1440" w:y="1440"/></w:pPr><w:r><w:t>f</w:t></w:r></w:p>"#;
    let list = lay_out(&format!("{frame}{}", p("q")), NORMAL, None);
    assert_eq!(find(&list, 'f').2, base(1440));
    // The line beside the frame starts at its right edge.
    let (_, x, y) = find(&list, 'q');
    assert_eq!(y, base(1440));
    assert!((x - 3440 * Length::UNITS_PER_TWIP).abs() < DOT, "{x}");
}

/// A paragraph of 80 words that anchors at its top a box 2 inches wide and half an inch high,
/// from 234 pt across the page, at the middle of the column, with the given wrap and no
/// distances.
fn beside_a_middle_box(wrap: &str) -> DisplayList {
    let words = vec!["zz"; 80].join(" ");
    let shape = AnchoredShape {
        across: ("page", 2_971_800),
        down: ("paragraph", 0),
        size: (1_828_800, 457_200),
        wrap,
        outline: None,
        text: None,
    };
    let body = format!(
        "<w:p><w:r>{}<w:t>{words}</w:t></w:r></w:p>",
        shape.drawing()
    );
    lay_out(&body, NORMAL, None)
}

/// The x of each glyph of the first line, left and right of the box of [`beside_a_middle_box`]:
/// how many lie left of it, how many right of it, and how many on it.
fn sides_of_the_first_line(list: &DisplayList) -> (usize, usize, usize) {
    let glyphs = find_all(list, 'z');
    let first = glyphs.iter().map(|g| g.2).min().unwrap();
    let point = Length::from_points(1).unwrap().units();
    let (left, right) = (234 * point, 378 * point);
    let line: Vec<i64> = glyphs
        .iter()
        .filter(|g| g.2 == first)
        .map(|g| g.1)
        .collect();
    (
        line.iter().filter(|&&x| x < left).count(),
        line.iter().filter(|&&x| x >= right).count(),
        line.iter().filter(|&&x| (left..right).contains(&x)).count(),
    )
}

#[test]
fn flows_a_line_on_the_sides_that_a_square_wrap_names() {
    let square = |sides: &str| {
        sides_of_the_first_line(&beside_a_middle_box(&format!(
            r#"<wp:wrapSquare wrapText="{sides}"/>"#
        )))
    };
    // Both sides: the line fills the piece left of the box, then goes on right of it.
    let (left, right, on) = square("bothSides");
    assert!(left > 0 && right > 0 && on == 0, "{left} {right} {on}");
    // The wider piece, of two equal ones the left one, and the named sides.
    assert!(matches!(square("largest"), (1.., 0, 0)));
    assert!(matches!(square("left"), (1.., 0, 0)));
    assert!(matches!(square("right"), (0, 1.., 0)));
}

#[test]
fn keeps_a_line_to_the_widest_piece_beside_a_polygon_that_is_not_its_bounds() {
    let tight = |points: &str| {
        sides_of_the_first_line(&beside_a_middle_box(&format!(
            r#"<wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="0">{points}</wp:wrapPolygon></wp:wrapTight>"#
        )))
    };
    // A rectangle on the box's edges lets the line flow on both sides.
    let rectangle = r#"<wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/>"#;
    let (left, right, on) = tight(rectangle);
    assert!(left > 0 && right > 0 && on == 0, "{left} {right} {on}");
    // Beside a triangle with the same bounds, the line takes the right one of the two equal
    // pieces.
    let triangle = r#"<wp:start x="10800" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="10800" y="0"/>"#;
    assert!(matches!(tight(triangle), (0, 1.., 0)));
}

#[test]
fn flows_a_line_on_both_sides_of_a_centered_frame_or_floating_table() {
    // An object 2000 twips wide at the middle of the page, from about 5120 to 7120 twips, and
    // a paragraph that flows around it: its first line holds words on both sides and none on
    // it.
    let words = p(&vec!["qq"; 60].join(" "));
    let frame = r#"<w:p><w:pPr><w:framePr w:w="2000" w:wrap="around" w:hAnchor="page" w:x="5120" w:y="1440"/></w:pPr><w:r><w:t>f</w:t></w:r></w:p>"#;
    let floating = table(
        r#"<w:tblpPr w:horzAnchor="page" w:tblpX="5120" w:vertAnchor="page" w:tblpY="1440"/><w:tblW w:w="2000" w:type="dxa"/>"#,
        &[2000],
        &[("", &[&p("f")])],
    );
    for object in [frame.to_owned(), floating] {
        let list = lay_out(&format!("{object}{words}"), NORMAL, None);
        let glyphs = find_all(&list, 'q');
        let first = glyphs.iter().map(|g| g.2).min().unwrap();
        let line: Vec<i64> = glyphs
            .iter()
            .filter(|g| g.2 == first)
            .map(|g| g.1)
            .collect();
        let twips = |t: i64| t * Length::UNITS_PER_TWIP;
        // The table's cell margins move its edges by a tenth of an inch at most.
        assert!(line.iter().any(|&x| x < twips(5000)), "{object}");
        assert!(line.iter().any(|&x| x > twips(7000)), "{object}");
        assert!(
            !line
                .iter()
                .any(|&x| (twips(5200)..twips(6900)).contains(&x)),
            "{object}"
        );
    }
}

#[test]
fn an_empty_paragraph_with_a_hidden_mark_takes_no_room() {
    let styles =
        r#"<w:style w:type="character" w:styleId="Hidden"><w:rPr><w:vanish/></w:rPr></w:style>"#;
    let empty = |mark: &str| format!("<w:p><w:pPr><w:rPr>{mark}</w:rPr></w:pPr></w:p>");
    // Hidden by the mark's character style and by the mark itself; the third mark turns its
    // style's hiding off again, so that paragraph keeps its line.
    let body = [
        p("A"),
        empty(r#"<w:rStyle w:val="Hidden"/>"#),
        empty("<w:vanish/>"),
        empty(r#"<w:rStyle w:val="Hidden"/><w:vanish w:val="0"/>"#),
        p("B"),
    ]
    .concat();
    let shown = [p("A"), empty(""), p("B")].concat();
    let b = |body: &str| find(&lay_out(body, styles, None), 'B');
    assert_eq!(b(&body), b(&shown));
    // In a table cell, the last paragraph ends the cell and keeps its line.
    let cell = |last: &str| table("", &[2000], &[("", &[&format!("{}{last}", p("A"))])]);
    let after = |last: &str| {
        find(
            &lay_out(&format!("{}{}", cell(last), p("B")), styles, None),
            'B',
        )
    };
    assert_eq!(after(&empty("<w:vanish/>")), after(&empty("")));
}

#[test]
fn an_empty_paragraph_after_a_hidden_mark_joins_the_paragraph_before_it() {
    // "A" has a hidden mark and 400 twips of space after it; the paragraph after it holds only
    // a space and has 100 twips after it. Joined, they take one line, which the second one's
    // space after follows, as after a paragraph "A" with 100 twips after it.
    let hidden = r#"<w:p><w:pPr><w:spacing w:after="400"/><w:rPr><w:vanish/></w:rPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
    let blank = r#"<w:p><w:pPr><w:spacing w:after="100"/></w:pPr><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p>"#;
    let shown = r#"<w:p><w:pPr><w:spacing w:after="100"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
    let b = |body: &str| find(&lay_out(body, NORMAL, None), 'B');
    assert_eq!(
        b(&[hidden, blank, &p("B")].concat()),
        b(&[shown, &p("B")].concat())
    );
    // Without the hidden mark, the paragraph of a space keeps its own line.
    let visible = hidden.replace("<w:vanish/>", "");
    assert!(b(&[&visible, blank, &p("B")].concat()).2 > b(&[shown, &p("B")].concat()).2);
}

#[test]
fn a_header_whose_last_paragraph_hides_its_mark_ends_without_its_space_after_on_a_target_that_asks()
{
    use crate::quirks::HiddenHeaderFooterEnd;
    // A header of four lines of 200 twips from the 720 twip header distance ends at 1520
    // twips, below the 1440 twip top margin, and its 400 twips of space after take the body
    // down to 1920. A target that drops the space after of a last paragraph with a hidden
    // mark starts the body at 1520; a mark that shows keeps it on every target.
    let header = |mark: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:after="400"/><w:rPr>{mark}</w:rPr></w:pPr><w:r><w:t>h</w:t><w:br/><w:t>i</w:t><w:br/><w:t>j</w:t><w:br/><w:t>k</w:t></w:r></w:p>"#
        )
    };
    for (end, hidden) in [
        (HiddenHeaderFooterEnd::KeepsSpaceAfter, 1920),
        (HiddenHeaderFooterEnd::DropsSpaceAfter, 1520),
    ] {
        let target = testing::on_base_with(|p| p.with_variant(end));
        let body_top = |mark: &str| {
            let header = header(mark);
            let pass = testing::pass_with(
                &p("b"),
                (NORMAL, None),
                Some(&header),
                Numbering::default(),
                target,
            );
            find(&pass.list, 'b').2
        };
        assert_eq!(body_top("<w:vanish/>"), base(hidden), "{end:?}");
        assert_eq!(body_top(""), base(1920), "{end:?}");
    }
}

#[test]
fn a_page_break_at_the_end_of_the_document_starts_no_page() {
    let last = r#"<w:p><w:r><w:t>a</w:t><w:br w:type="page"/></w:r></w:p>"#;
    assert_eq!(lay_out(last, NORMAL, None).pages().len(), 1);
    // An empty paragraph after the break goes onto the next page, which then stays.
    let then_empty = format!("{last}<w:p/>");
    assert_eq!(lay_out(&then_empty, NORMAL, None).pages().len(), 2);
}

#[test]
fn draws_a_check_box_field_as_a_square_as_wide_as_its_line() {
    let check_box = |check_box: &str| {
        format!(
            r#"<w:p><w:r><w:fldChar w:fldCharType="begin"><w:ffData><w:checkBox>{check_box}</w:checkBox></w:ffData></w:fldChar></w:r><w:r><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t>Y</w:t></w:r></w:p>"#
        )
    };
    let bars = |list: &DisplayList| {
        let mut sizes: Vec<(i64, i64)> = testing::rects(list, 0)
            .into_iter()
            .map(|(_, _, width, height)| (width, height))
            .collect();
        sizes.sort_unstable();
        sizes
    };
    let point = Length::from_points(1).unwrap().units();
    let plain = lay_out(&p("Y"), "", None);
    let auto = lay_out(&check_box("<w:sizeAuto/>"), "", None);
    // The fake font's single line at 10 pt is 10 pt, which is the box's advance.
    assert_eq!(find(&auto, 'Y').1 - find(&plain, 'Y').1, 10 * point);
    // The line rounds to 42 device dots, so the side between the middles of the strokes of
    // 3 units is 33 units: bars of 36 by 3 units across and 3 by 30 units down.
    assert_eq!(bars(&auto), [(3, 30), (3, 30), (36, 3), (36, 3)]);
    // A box of its own size takes the line of that size: 20 pt, 83 device dots.
    let sized = lay_out(&check_box(r#"<w:size w:val="40"/>"#), "", None);
    assert_eq!(find(&sized, 'Y').1 - find(&plain, 'Y').1, 20 * point);
    assert_eq!(bars(&sized), [(3, 71), (3, 71), (77, 3), (77, 3)]);
}

/// The widths and heights of the rectangles of a list's first page, in units, in order.
fn rect_sizes(list: &DisplayList) -> Vec<(i64, i64)> {
    let mut sizes: Vec<(i64, i64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Rect(r) => Some((r.width.units(), r.height.units())),
            f_office_paint::Item::Glyphs(_)
            | f_office_paint::Item::Path(_)
            | f_office_paint::Item::Gradient(_)
            | f_office_paint::Item::Image(_)
            | f_office_paint::Item::Group(_) => None,
        })
        .collect();
    sizes.sort_unstable();
    sizes
}

/// The widths and heights of the four bars of a check box square on a target's `device` with
/// its `quirks`, in units, in order, for a field that starts in a run of 10 pt and whose code
/// run sets 20 pt, in the fake font, whose single line is its size.
fn check_box_bars(device: &crate::grid::Device, quirks: &crate::quirks::Quirks) -> [(i64, i64); 4] {
    use crate::quirks::{CheckBoxSide, ComputedFieldFormat};
    let point = Length::from_points(1).unwrap();
    let cell = device.snap(match quirks.computed_field_format {
        ComputedFieldFormat::CodeRun => point * 20,
        ComputedFieldFormat::ResultRun => point * 10,
    });
    // Strokes of 0.72 pt to the nearest dot, and the side between their middles.
    let stroke = device.snap(Length::from_units(point.units() * 72 / 100));
    let side = match quirks.check_box_side {
        CheckBoxSide::ThreeStrokes => cell - stroke * 3,
        CheckBoxSide::ThreeStrokesAndDot => cell - stroke * 3 - device.dots(1),
    };
    let (across, down) = ((side + stroke).units(), (side - stroke).units());
    let stroke = stroke.units();
    [
        (stroke, down),
        (stroke, down),
        (across, stroke),
        (across, stroke),
    ]
}

#[test]
fn draws_a_check_box_with_the_stroke_side_and_sizing_run_of_each_target() {
    use crate::quirks::{CheckBoxSide, ComputedFieldFormat};
    // The field starts in a run of 10 pt, and the run of its code sets 20 pt.
    let body = concat!(
        r#"<w:p><w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:fldChar w:fldCharType="begin"><w:ffData><w:checkBox><w:sizeAuto/></w:checkBox></w:ffData></w:fldChar></w:r>"#,
        r#"<w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r>"#,
        r#"<w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t>Y</w:t></w:r></w:p>"#
    );
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let bytes = crate::tests::package(body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let (mut sides, mut formats) = (Vec::new(), Vec::new());
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let expected = check_box_bars(&profile.device(), &profile.quirks());
        assert_eq!(rect_sizes(&list), expected, "{target}");
        sides.push(profile.quirks().check_box_side);
        formats.push(profile.quirks().computed_field_format);
    }
    assert!(sides.contains(&CheckBoxSide::ThreeStrokes));
    assert!(sides.contains(&CheckBoxSide::ThreeStrokesAndDot));
    assert!(formats.contains(&ComputedFieldFormat::CodeRun));
    assert!(formats.contains(&ComputedFieldFormat::ResultRun));
}

#[test]
fn ends_the_underline_of_a_run_at_a_tab_of_another_run() {
    let underlined = r#"<w:rPr><w:u w:val="single"/></w:rPr>"#;
    let body = format!(
        r"<w:p><w:r>{underlined}<w:t>ab</w:t></w:r><w:r><w:tab/></w:r><w:r>{underlined}<w:t>cd</w:t></w:r></w:p>"
    );
    let lines = |body: &str| {
        let list = lay_out(body, "", None);
        let mut widths: Vec<i64> = testing::rects(&list, 0)
            .into_iter()
            .map(|(_, _, width, _)| width)
            .collect();
        widths.sort_unstable();
        widths
    };
    // Two lines, one under each text, and none under the tab between them.
    let split = lines(&body);
    assert_eq!(split.len(), 2, "{split:?}");
    // An underlined tab draws its own line, which joins the two.
    let joined = lines(&body.replace(
        "<w:r><w:tab/></w:r>",
        &format!("<w:r>{underlined}<w:tab/></w:r>"),
    ));
    assert_eq!(joined.len(), 3, "{joined:?}");
    assert!(joined.iter().sum::<i64>() > split.iter().sum::<i64>());
}

#[test]
fn draws_a_list_label_without_the_underline_of_its_paragraph_mark() {
    use crate::ns::W;
    // An underlined mark underlines the text after the label but not the label, and a level
    // whose own run properties underline it does underline the label.
    let numbering = |level_rpr: &str| {
        format!(
            r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:suff w:val="space"/>{level_rpr}</w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"#
        )
    };
    let body = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr><w:rPr><w:u w:val="single"/></w:rPr></w:pPr><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>Name</w:t></w:r></w:p>"#;
    // Where the underline starts, and the device dot nearest to where the text starts.
    let starts = |level_rpr: &str| {
        let list = testing::lay_out_with_numbering(body, &numbering(level_rpr));
        let line = testing::rects(&list, 0).iter().map(|r| r.0).min().unwrap();
        (line, f_office_units::div_round(find(&list, 'N').1, DOT))
    };
    let (line, text) = starts("");
    assert_eq!(line, text);
    let (line, text) = starts(r#"<w:rPr><w:u w:val="single"/></w:rPr>"#);
    assert!(line < text, "{line} {text}");
}

#[test]
fn fills_a_shaded_paragraph_out_to_its_side_borders() {
    let shaded = |borders: &str| {
        format!(
            r#"<w:p><w:pPr>{borders}<w:shd w:val="clear" w:color="auto" w:fill="306785"/></w:pPr><w:r><w:t>Name</w:t></w:r></w:p>"#
        )
    };
    // The fill is the widest rectangle of the page, in device dots.
    let fill_width = |body: &str| {
        let list = lay_out(body, "", None);
        testing::rects(&list, 0).iter().map(|r| r.2).max().unwrap()
    };
    let plain = fill_width(&shaded(""));
    let side = r#"w:val="single" w:sz="4" w:space="6" w:color="000000""#;
    let boxed = fill_width(&shaded(&format!(
        r"<w:pBdr><w:left {side}/><w:right {side}/></w:pBdr>"
    )));
    // 6 pt of space at each side is 25 device dots.
    assert!(boxed >= plain + 2 * 25, "{plain} {boxed}");
}

#[test]
fn a_shaded_body_paragraph_fills_out_to_the_reach_of_its_border_lines() {
    let shaded = r#"<w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="306785"/><w:ind w:left="723" w:right="1442"/></w:pPr><w:r><w:t>Name</w:t></w:r></w:p>"#;
    // The fill's left end and the first glyph's dot, in device dots.
    let ends = |body: &str| {
        let list = lay_out(body, "", None);
        let fill = testing::rects(&list, 0)
            .into_iter()
            .max_by_key(|r| r.2)
            .unwrap();
        (fill.0, f_office_units::div_round(find(&list, 'N').1, DOT))
    };
    // 1.5 pt, rounded down to whole device dots of 0.24 pt, is 6 units.
    let (fill, text) = ends(shaded);
    assert_eq!(fill, text - 6);
    // In a table cell, the fill keeps to the indent.
    let cell = format!(
        r#"<w:tbl><w:tblPr><w:tblW w:w="6000" w:type="dxa"/></w:tblPr><w:tblGrid><w:gridCol w:w="6000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="6000" w:type="dxa"/></w:tcPr>{shaded}</w:tc></w:tr></w:tbl><w:p/>"#
    );
    let (fill, text) = ends(&cell);
    assert!((fill - text).abs() <= 1, "{fill} {text}");
}

#[test]
fn a_right_to_left_paragraph_counts_its_fill_ends_from_the_column_right_edge() {
    // A left-to-right paragraph indented 723 and 1,442 twips, a right-to-left one with the
    // same indents on the same sides of the page (in it, `w:left` indents the right side), and
    // a right-to-left one without indents.
    let shaded = |bidi: &str, ind: &str| {
        format!(
            r#"<w:p><w:pPr>{bidi}<w:shd w:val="clear" w:color="auto" w:fill="306785"/><w:ind {ind}/></w:pPr><w:r><w:t>ab</w:t></w:r></w:p>"#
        )
    };
    let body = shaded("", r#"w:left="723" w:right="1442""#)
        + &shaded("<w:bidi/>", r#"w:left="1442" w:right="723""#)
        + &shaded("<w:bidi/>", r#"w:left="0""#);
    // The fills' left and right ends in the order of the paragraphs, on a page of `width`
    // twips with a left margin of `left`, for each target, with its device, the dot by which
    // a right-to-left line's glyphs lie right of their steps (one where the glyphs take the
    // edge steps) and the column's right edge in half-EMUs.
    let fills = |width: i64, left: i64| {
        let page = format!(
            r#"<w:pgSz w:w="{width}" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="{left}" w:header="720" w:footer="720" w:gutter="0"/>"#
        );
        let bytes = crate::tests::package(&body, "", &page);
        let package =
            f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
        crate::Target::all()
            .map(|target| {
                let device = crate::profile::Profile::of(target).unwrap().device();
                let options = crate::Options {
                    configuration: crate::Configuration::of(target),
                    ..crate::Options::default()
                };
                let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
                    .unwrap()
                    .value;
                let ends: Vec<(i64, i64)> = list.pages()[0]
                    .items()
                    .iter()
                    .filter_map(|item| match item {
                        f_office_paint::Item::Rect(r) => {
                            Some((r.x.units(), r.x.units() + r.width.units()))
                        }
                        f_office_paint::Item::Glyphs(_)
                        | f_office_paint::Item::Path(_)
                        | f_office_paint::Item::Gradient(_)
                        | f_office_paint::Item::Image(_)
                        | f_office_paint::Item::Group(_) => None,
                    })
                    .collect();
                assert_eq!(ends.len(), 3, "{target} {ends:?}");
                let steps = matches!(device.advances(), crate::grid::Advances::RightEdge { .. });
                let dot = if steps { device.dots(1).units() } else { 0 };
                let edge = Length::from_twips(width - 1440).unwrap().units();
                (target, device, dot, edge, ends)
            })
            .collect::<Vec<_>>()
    };
    // On a page of 8.5 inches with margins of one inch, both edges of the column lie on dots
    // of every device. There the right-to-left ends mirror the left-to-right ones, and lie one
    // dot further right where the glyphs take the edge steps, as the glyphs of a right-to-left
    // line do. The paragraph without indents gives the reach past the right edge.
    let (mut reaches, mut stepped) = (Vec::new(), false);
    for (target, _, dot, edge, ends) in fills(12240, 1440) {
        let (ltr, rtl) = (ends[0], ends[1]);
        assert_eq!((rtl.0 - ltr.0, rtl.1 - ltr.1), (dot, dot), "{target}");
        reaches.push(ends[2].1 - edge - dot);
        stepped |= dot > 0;
    }
    assert!(stepped);
    assert!(reaches.iter().all(|&reach| reach > 0), "{reaches:?}");
    // With a page of 11,906 twips and a left margin of 1,417, the right edge, 10,466 twips,
    // lies between dots on every device, and counted from the left edge it would land on
    // another dot on the device of 600 dots per inch. The right end of the paragraph without
    // indents lies on
    // the dot of the right edge, the glyphs' dot further right, and out by the same reach.
    for ((target, device, dot, edge, ends), reach) in fills(11906, 1417).into_iter().zip(reaches) {
        let right = device.snap(Length::from_units(edge)).units();
        assert_eq!(ends[2].1, right + dot + reach, "{target} {ends:?}");
    }
}

/// The fake fonts as the target's own faces, whose instructions give each glyph the device
/// width of its advance with the fraction of a dot taken off.
struct OwnFaces;

impl crate::Fonts for OwnFaces {
    fn face(
        &self,
        family: &f_office_fonts::FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<crate::ChosenFace> {
        Fake.face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Fake.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Fake.advance(font, glyph)
    }

    fn target_face(&self, _font: f_office_fonts::FontId) -> Option<(String, String)> {
        Some(("Fake".to_owned(), "1".to_owned()))
    }

    fn device_width(&self, font: f_office_fonts::FontId, glyph: u32, ppem: u16) -> Option<i32> {
        let units = i32::from(Fake.advance(font, glyph)?);
        Some(units * i32::from(ppem) / 1000)
    }
}

#[test]
fn steps_the_glyphs_of_right_to_left_text_as_the_quirk_says() {
    // The same bold glyph twelve times at 11.5 pt, in a left-to-right paragraph and in a
    // right-to-left one. Its advance, 600 of 1,000 units, is 6.9 pt, which the device widths
    // take down to whole dots where a dot is not a tenth of a point. Under
    // `RightToLeftSteps::DeviceWidths` the right-to-left glyphs step as the left-to-right
    // ones; under `RightToLeftSteps::Nearest` they step by their advance at the nearest dot,
    // which no device width enters.
    let run = |rtl: &str, ch: char| {
        let text: String = std::iter::repeat_n(ch, 12).collect();
        format!(
            r#"<w:r><w:rPr>{rtl}<w:b/><w:bCs/><w:sz w:val="23"/><w:szCs w:val="23"/></w:rPr><w:t>{text}</w:t></w:r>"#
        )
    };
    let body = format!(
        "<w:p>{}</w:p><w:p><w:pPr><w:bidi/></w:pPr>{}</w:p>",
        run("", 'a'),
        run("<w:rtl/>", '\u{5d0}')
    );
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    // The steps from each glyph to the next in reading order, in units: from left to right
    // for 'a', from right to left for the Hebrew letter.
    let steps = |list: &DisplayList, ch: char| -> Vec<i64> {
        let mut xs: Vec<i64> = find_all(list, ch).iter().map(|&(_, x, _)| x).collect();
        xs.sort_unstable();
        let mut steps: Vec<i64> = xs.windows(2).map(|pair| pair[1] - pair[0]).collect();
        if ch != 'a' {
            steps.reverse();
        }
        steps
    };
    let mut stepped = Vec::new();
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let device = profile.device();
        if !matches!(device.advances(), crate::grid::Advances::RightEdge { .. }) {
            continue;
        }
        let quirk = profile.quirks().right_to_left_steps;
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let with = |fonts: &dyn crate::Fonts| {
            crate::layout(&package, (fonts, &crate::ArtPictures::new()), &options).unwrap()
        };
        let (own, fake) = (with(&OwnFaces).value, with(&Fake).value);
        // The device widths change the left-to-right steps. The right-to-left glyphs, which all
        // have one width, step as the left-to-right ones do, or the same with either faces'
        // device widths, within the half-EMU of rounding each place once from the writer's
        // exact sum.
        assert_ne!(steps(&own, 'a'), steps(&fake, 'a'), "{target}");
        let hebrew = '\u{5d0}';
        assert!(
            right_to_left_steps_hold(
                quirk,
                (&steps(&own, hebrew), &steps(&fake, hebrew)),
                &steps(&own, 'a')
            ),
            "{target}"
        );
        stepped.push(quirk);
    }
    assert!(stepped.contains(&crate::quirks::RightToLeftSteps::Nearest));
}

/// Whether the right-to-left steps with the target's own faces and with the fake faces
/// (`own`, `fake`) are those that `quirk` says beside the left-to-right steps `ltr` with the
/// own faces: the left-to-right steps, or, by the advance at the nearest dot, the same with
/// either faces and not the left-to-right steps.
fn right_to_left_steps_hold(
    quirk: crate::quirks::RightToLeftSteps,
    (own, fake): (&[i64], &[i64]),
    ltr: &[i64],
) -> bool {
    match quirk {
        crate::quirks::RightToLeftSteps::DeviceWidths => within_one(own, ltr),
        crate::quirks::RightToLeftSteps::Nearest => within_one(own, fake) && !within_one(own, ltr),
    }
}

/// The targets whose right-to-left lines start on whole dots, each with its device's dot.
fn right_to_left_whole_dots_targets() -> Vec<(crate::Target, i64)> {
    crate::Target::all()
        .filter_map(|target| {
            let profile = crate::profile::Profile::of(target).unwrap();
            let quirks = profile.quirks();
            (quirks.right_to_left_line_start == crate::quirks::RightToLeftLineStart::WholeDots
                && quirks.aligned_ends == crate::quirks::AlignedEnds::OnDots)
                .then(|| (target, profile.device().dots(1).units()))
        })
        .collect()
}

/// The places of the glyphs of `letters` in the layout of `package` for `target`, by line from
/// the top, and in each line from the left.
fn letter_lines(
    package: &f_office_opc::Package,
    target: crate::Target,
    letters: &[char],
) -> Vec<Vec<i64>> {
    letter_lines_in(
        package,
        target,
        crate::profile::Overrides::default(),
        letters,
    )
}

/// The places of the glyphs of `letters` in the layout of `package` for `target` with the
/// development override `overrides`, by line from the top, and in each line from the left.
fn letter_lines_in(
    package: &f_office_opc::Package,
    target: crate::Target,
    overrides: crate::profile::Overrides,
    letters: &[char],
) -> Vec<Vec<i64>> {
    let options = crate::Options {
        configuration: crate::Configuration::of(target),
        overrides,
        ..crate::Options::default()
    };
    let list = crate::layout(package, (&Fake, &crate::ArtPictures::new()), &options)
        .unwrap()
        .value;
    let mut lines: std::collections::BTreeMap<i64, Vec<i64>> = std::collections::BTreeMap::new();
    for &ch in letters {
        for (_, x, y) in find_all(&list, ch) {
            lines.entry(y).or_default().push(x);
        }
    }
    lines
        .into_values()
        .map(|mut xs| {
            xs.sort_unstable();
            xs
        })
        .collect()
}

/// The three Hebrew letters of the right-to-left tests.
const HEBREW: [char; 3] = ['\u{5d0}', '\u{5d1}', '\u{5d2}'];

/// A package of `body` on a Letter page with margins of 1 inch.
fn letter_page(body: &str) -> f_office_opc::Package {
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let bytes = crate::tests::package(body, "", page);
    f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap()
}

#[test]
fn a_start_aligned_right_to_left_line_keeps_the_places_of_its_end_aligned_twin() {
    // Two right-to-left paragraphs with one text of two lines at 9.5 pt, whose advances are
    // not whole dots: start-aligned, at the right margin, and then end-aligned, at the left one.
    // A start at the line's exact place would move the steps of the first line too.
    let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(27);
    let paragraph = |jc: &str| {
        format!(
            r#"<w:p><w:pPr><w:bidi/>{jc}</w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="19"/><w:szCs w:val="19"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
        )
    };
    let package = letter_page(&(paragraph("") + &paragraph(r#"<w:jc w:val="end"/>"#)));
    let targets = right_to_left_whole_dots_targets();
    assert_ne!(targets, []);
    for (target, dot) in targets {
        let lines = letter_lines(&package, target, &HEBREW);
        assert_eq!(lines.len(), 4, "{target}");
        // The start-aligned first line, which does not end its paragraph, takes the places of
        // its end-aligned twin, moved right by whole dots.
        let (start, end) = (&lines[0], &lines[2]);
        assert_eq!(start.len(), end.len(), "{target}");
        let moves: Vec<i64> = start.iter().zip(end).map(|(s, e)| s - e).collect();
        assert!(moves.iter().all(|&m| m == moves[0]), "{target} {moves:?}");
        assert!(moves[0] > 0 && moves[0] % dot == 0, "{target} {moves:?}");
    }
}

#[test]
fn a_centered_right_to_left_paragraph_puts_only_its_last_line_on_dots() {
    // A centered right-to-left paragraph of two lines at 9.5 pt, whose advances are not whole
    // dots, with an end indent of 2 twips. With `RightToLeftCenteredLine::OnDots` its last line
    // moves as a whole by whole dots from where it lies with `Exact`. Its first line, which
    // does not end the paragraph, keeps its places, where the rule of the last line would move
    // it.
    let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(29);
    let package = letter_page(&format!(
        r#"<w:p><w:pPr><w:bidi/><w:ind w:right="2"/><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="19"/><w:szCs w:val="19"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
    ));
    let targets: Vec<(crate::Target, i64)> = right_to_left_whole_dots_targets()
        .into_iter()
        .filter(|&(target, _)| {
            crate::profile::Profile::of(target)
                .unwrap()
                .quirks()
                .right_to_left_centered_line
                == crate::quirks::RightToLeftCenteredLine::OnDots
        })
        .collect();
    assert_ne!(targets, []);
    for (target, dot) in targets {
        let on_dots = letter_lines(&package, target, &HEBREW);
        let exact =
            crate::profile::Overrides::default().with_quirk("RightToLeftCenteredLine", "Exact");
        let exact = letter_lines_in(&package, target, exact, &HEBREW);
        assert_eq!(on_dots.len(), 2, "{target}");
        assert_eq!(on_dots[0], exact[0], "{target}");
        let (last, before) = (&on_dots[1], &exact[1]);
        assert_eq!(last.len(), before.len(), "{target}");
        let moves: Vec<i64> = last.iter().zip(before).map(|(a, b)| a - b).collect();
        assert!(moves.iter().all(|&m| m == moves[0]), "{target} {moves:?}");
        assert!(moves[0] != 0 && moves[0] % dot == 0, "{target} {moves:?}");
    }
}

#[test]
fn the_spaces_that_start_a_start_aligned_right_to_left_line_keep_their_room() {
    // A start-aligned right-to-left paragraph of two lines at 9.5 pt that starts with two
    // spaces. They lie at the right end of its first line, which moves by the free whole dots
    // after its written text, the spaces included.
    let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(27);
    let package = letter_page(&format!(
        r#"<w:p><w:pPr><w:bidi/></w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="19"/><w:szCs w:val="19"/></w:rPr><w:t xml:space="preserve">  {text}</w:t></w:r></w:p>"#
    ));
    // The column's right edge, and the width of a glyph of the fake font at 9.5 pt.
    let (edge, glyph) = (
        540 * Length::UNITS_PER_POINT,
        Length::UNITS_PER_POINT * 95 / 20,
    );
    let targets = right_to_left_whole_dots_targets();
    assert_ne!(targets, []);
    for (target, dot) in targets {
        let lines = letter_lines(&package, target, &HEBREW);
        let right = lines[0].last().unwrap() + glyph;
        // The two spaces keep their room at the right end: the letters end at least their
        // width, less two dots, left of the edge. The device's steps of the line take the rest,
        // which is less than a third glyph.
        assert!(
            right <= edge - 2 * glyph + 2 * dot,
            "{target} {}",
            edge - right
        );
        assert!(right > edge - 3 * glyph, "{target} {}", edge - right);
    }
}

#[test]
fn a_start_indent_that_keeps_the_dot_of_its_right_edge_keeps_a_right_to_left_line_in_place() {
    // Two start-aligned right-to-left paragraphs with one text of two lines on an A4 page,
    // whose column's right edge lies 0.83 dot past a dot at 600 dots per inch. Their start
    // indents of 720 and 721 twips are 300 and 300.42 dots, which both go to the dot 300, so
    // the column's right edge less that dot gives one edge. The column's width less each indent
    // goes to two dots, 3,461 and 3,460, which would move the second line a dot left.
    let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(27);
    let paragraph = |start: u32| {
        format!(
            r#"<w:p><w:pPr><w:bidi/><w:ind w:left="{start}"/></w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="19"/><w:szCs w:val="19"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
        )
    };
    let page = r#"<w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let bytes = crate::tests::package(&(paragraph(720) + &paragraph(721)), "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let targets: Vec<crate::Target> = right_to_left_whole_dots_targets()
        .into_iter()
        .map(|(target, _)| target)
        .filter(|&target| {
            crate::profile::Profile::of(target)
                .unwrap()
                .quirks()
                .right_to_left_line_edge
                == crate::quirks::RightToLeftLineEdge::FromColumnRight
        })
        .collect();
    assert_ne!(targets, []);
    for target in targets {
        let lines = letter_lines(&package, target, &HEBREW);
        assert_eq!(lines.len(), 4, "{target}");
        // The first lines, which do not end their paragraphs, take the same places.
        assert_eq!(lines[0], lines[2], "{target}");
    }
}

#[test]
fn a_justified_right_to_left_line_moves_up_to_the_dot_of_its_right_edge() {
    // A justified right-to-left paragraph at 12 pt on an A4 page, and the same text
    // start-aligned. The page's column and the start indent of 613 twips end off the dots of
    // 600 dots per inch. Placed from its exact edges, the stretched first line would fill its
    // space from the dot of the space's left edge, 600, with its glyphs a dot right of it. Drawn
    // from that dot, its device steps end one dot past the dot of its right edge, so the line
    // moves one dot left, and its glyphs lie from the dot 600 on.
    let text = "\u{5d0}\u{5d1}\u{5d2} ".repeat(40);
    let paragraph = |jc: &str| {
        format!(
            r#"<w:p><w:pPr><w:bidi/><w:ind w:left="613"/>{jc}</w:pPr><w:r><w:rPr><w:rtl/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
        )
    };
    let page = r#"<w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let body = paragraph(r#"<w:jc w:val="both"/>"#) + &paragraph("");
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let targets: Vec<(crate::Target, i64)> = right_to_left_whole_dots_targets()
        .into_iter()
        .filter(|&(target, _)| {
            crate::profile::Profile::of(target)
                .unwrap()
                .quirks()
                .right_to_left_justified_line
                == crate::quirks::RightToLeftJustifiedLine::EndsAtEdge
        })
        .collect();
    assert_ne!(targets, []);
    for (target, dot) in targets {
        let lines = letter_lines(&package, target, &HEBREW);
        assert_eq!(lines.len() % 2, 0, "{target}");
        let (justified, twin) = (&lines[0], &lines[lines.len() / 2]);
        // The glyphs of the fake font lie a fixed part of a dot past their steps, which the
        // twin's places, whole dots from the dot of its start, show.
        let past = twin[0].rem_euclid(dot);
        assert_eq!(
            justified[0] - past,
            600 * dot,
            "{target} {}",
            justified[0] - past
        );
    }
}

#[test]
fn a_justified_right_to_left_line_before_a_soft_break_moves_up_to_its_right_edge_with_its_stretch()
{
    // A justified right-to-left paragraph whose first line, of three words of the fake font at
    // 12 pt, ends in a soft line break with no space before it, and a justified paragraph of
    // 40 such words whose first line ends in a space. Both first lines stretch their spaces to
    // fill the column, so where a line moves from the dot where its steps end to the dot of
    // its right edge, both start at the same dot: the steps of the short line end with the
    // stretch of its spaces, though no trailing space gives their end.
    let word = "\u{5d0}\u{5d1}\u{5d2}";
    let run = |text: &str| {
        format!(
            r#"<w:r><w:rPr><w:rtl/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r>"#
        )
    };
    let paragraph =
        |runs: String| format!(r#"<w:p><w:pPr><w:bidi/><w:jc w:val="both"/></w:pPr>{runs}</w:p>"#);
    let broken = run(&[word; 3].join(" ")) + "<w:r><w:br/></w:r>" + &run(word);
    let body = paragraph(broken) + &paragraph(run(&[word; 40].join(" ")));
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let targets: Vec<crate::Target> = crate::Target::all()
        .filter(|&target| {
            crate::profile::Profile::of(target)
                .unwrap()
                .quirks()
                .right_to_left_justified_line
                == crate::quirks::RightToLeftJustifiedLine::EndsAtEdge
        })
        .collect();
    assert_ne!(targets, []);
    for target in targets {
        let dot = crate::profile::Profile::of(target)
            .unwrap()
            .device()
            .dots(1)
            .units();
        let lines = letter_lines(&package, target, &HEBREW);
        assert_eq!(lines[0].len(), 9, "{target}");
        let moved = lines[0][0] - lines[2][0];
        assert!(moved.abs() <= dot, "{target} {moved}");
    }
}

#[test]
fn swaps_the_indents_of_a_right_to_left_paragraph() {
    let x = |bidi: &str, ind: &str| {
        let body =
            format!(r"<w:p><w:pPr>{bidi}<w:ind {ind}/></w:pPr><w:r><w:t>ab</w:t></w:r></w:p>");
        find(&lay_out(&body, NORMAL, Some(15)), 'a').1
    };
    let twips = |t: i64| t * Length::UNITS_PER_TWIP;
    let rtl = |ind: &str| x("<w:bidi/>", ind);
    let start = rtl(r#"w:left="0""#);
    // The short line starts at the right. `w:left` indents that side, and `w:right` the left
    // side, which the line does not reach.
    assert_eq!(rtl(r#"w:left="1440""#), start - twips(1440));
    assert_eq!(rtl(r#"w:right="1440""#), start);
    // The first line's indent lies at the right too, and a hanging one reaches out there.
    assert_eq!(rtl(r#"w:firstLine="720""#), start - twips(720));
    assert_eq!(rtl(r#"w:left="720" w:hanging="360""#), start - twips(360));
    // A left-to-right paragraph keeps `w:left` at the left.
    let ltr = x("", r#"w:left="0""#);
    assert_eq!(x("", r#"w:left="1440""#), ltr + twips(1440));
}

/// Twelve right-aligned lines with the right indent 721 twips and the left indents 720 to 731
/// twips, each a twelfth of a dot further right.
fn twelve_right_aligned_lines() -> String {
    (720..732)
        .map(|left| {
            format!(
                r#"<w:p><w:pPr><w:ind w:left="{left}" w:right="721"/><w:jc w:val="right"/></w:pPr><w:r><w:t>AB</w:t></w:r></w:p>"#
            )
        })
        .collect::<Vec<_>>()
        .concat()
}

/// Lays out `body` on an A4 page with side margins of 851 twips, 354.58 dots at 600 dots per
/// inch, for each target whose aligned lines start on whole dots and take the right edge of
/// their space from the column's edge, and checks that the twelve lines of
/// [`twelve_right_aligned_lines`] in it start on one dot.
fn assert_the_twelve_lines_start_on_one_dot(body: &str) {
    let page = r#"<w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="851" w:bottom="1440" w:left="851" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let bytes = crate::tests::package(body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let quirks = profile.quirks();
        if quirks.aligned_ends != crate::quirks::AlignedEnds::OnDots
            || quirks.aligned_line_edge != crate::quirks::AlignedLineEdge::FromColumnEdge
        {
            continue;
        }
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let unit = profile.device().dots(1).units();
        // A glyph's place is its dot plus the writer's offset, which is under a dot.
        let starts: Vec<i64> = find_all(&list, 'A').iter().map(|a| a.1 / unit).collect();
        assert_eq!(starts.len(), 12, "{target:?}");
        assert!(
            starts.iter().all(|&s| s == starts[0]),
            "{target:?} {starts:?}"
        );
    }
}

#[test]
fn a_right_aligned_line_ends_on_an_edge_that_its_left_indent_does_not_move() {
    assert_the_twelve_lines_start_on_one_dot(&twelve_right_aligned_lines());
}

#[test]
fn a_right_aligned_line_of_a_table_cell_ends_on_an_edge_that_its_left_indent_does_not_move() {
    // The same lines in the one cell of a table without lines, whose text edge lies at no
    // whole dot either: the page's margin of 851 twips and the cell's left margin of 113 twips.
    let body = format!(
        r#"<w:tbl><w:tblPr><w:tblW w:w="9000" w:type="dxa"/><w:tblLayout w:type="fixed"/><w:tblCellMar><w:left w:w="113" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w="9000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="9000" w:type="dxa"/></w:tcPr>{}</w:tc></w:tr></w:tbl><w:p/>"#,
        twelve_right_aligned_lines()
    );
    assert_the_twelve_lines_start_on_one_dot(&body);
}

#[test]
fn a_right_aligned_and_a_centered_line_keep_the_glyph_places_of_the_left_aligned_line() {
    let aligned = |jc: &str, text: &str| {
        format!(
            r#"<w:p><w:pPr><w:jc w:val="{jc}"/></w:pPr><w:r><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
        )
    };
    let body = p("ABCABCABC")
        + &aligned("right", "ABCABCABC")
        + &aligned("center", "ABCABCABC")
        + &aligned("right", "XY  ");
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1417" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let (a, c) = (find_all(&list, 'A'), find_all(&list, 'C'));
        assert_eq!((a.len(), c.len()), (9, 9));
        if profile.quirks().aligned_ends != crate::quirks::AlignedEnds::OnDots {
            continue;
        }
        let unit = profile.device().dots(1).units();
        // The lines of the three alignments start at the glyphs 0, 3 and 6. A glyph's place
        // is its dot plus the writer's offset, which is under a dot.
        let (left, right, center) = (a[0].1 / unit, a[3].1 / unit, a[6].1 / unit);
        let offsets = |from: usize| -> Vec<i64> {
            (0..3)
                .flat_map(|k| [a[from + k].1 - a[from].1, c[from + k].1 - a[from].1])
                .collect()
        };
        // Each place is the half-EMU nearest the writer's exact place, so an offset from the
        // line's start may differ by one half-EMU.
        assert!(within_one(&offsets(3), &offsets(0)));
        assert!(within_one(&offsets(6), &offsets(0)));
        assert_eq!(center - left, (right - left) / 2);
        // A shorter line with trailing spaces starts further right.
        assert!(find_all(&list, 'X')[0].1 / unit > right);
    }
}

#[test]
fn starts_the_text_after_a_right_or_a_center_stop_as_an_aligned_line() {
    // The left margin and the stop lie on dots of each device (1,440 and 4,320 twips), and
    // the fake glyphs of 10 pt are 5 pt wide, which is not a whole number of dots at 600 dots
    // per inch. Paragraph 1: a right stop, then "KL" and two spaces. Paragraph 2: "MN" and
    // two spaces, right-aligned in a space that ends at the stop. Paragraph 3: a center stop,
    // then "PQ". Paragraph 4: a right stop, then "RS". Paragraph 5: a center stop, then the
    // reference mark of a comment, a piece without a glyph or a width, and "UV". Paragraphs 6
    // and 7: a right stop, then "YZ" and a no-break space, and "GHJ".
    let tabbed = |kind: &str, text: &str| {
        format!(
            r#"<w:p><w:pPr><w:tabs><w:tab w:val="{kind}" w:pos="4320"/></w:tabs></w:pPr><w:r><w:tab/><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#
        )
    };
    let body = tabbed("right", "KL  ")
        + r#"<w:p><w:pPr><w:ind w:right="5040"/><w:jc w:val="right"/></w:pPr><w:r><w:t xml:space="preserve">MN  </w:t></w:r></w:p>"#
        + &tabbed("center", "PQ")
        + &tabbed("right", "RS")
        + r#"<w:p><w:pPr><w:tabs><w:tab w:val="center" w:pos="4320"/></w:tabs></w:pPr><w:r><w:tab/><w:annotationRef/><w:t>UV</w:t></w:r></w:p>"#
        + &tabbed("right", "YZ&#160;")
        + &tabbed("right", "GHJ");
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        if profile.quirks().aligned_ends != crate::quirks::AlignedEnds::OnDots {
            continue;
        }
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let unit = profile.device().dots(1).units();
        // A glyph's place is its dot plus the writer's offset, which is under a dot.
        let dot = |ch: char| find(&list, ch).1 / unit;
        let stop = (1440 + 4320) * Length::UNITS_PER_TWIP / unit;
        // The text after the right stop ends on the stop's dot, where the right-aligned line
        // ends: at its first trailing space, which the steps put a dot past the exact end.
        assert_eq!(dot('K'), dot('M'), "{target:?}");
        // The text after the center stop starts half of its written width, rounded down, left
        // of the stop's dot. The written width of "PQ" is that of "RS" after the right stop.
        let width = stop - dot('R');
        assert_eq!(dot('P'), stop - width / 2, "{target:?} {width}");
        // The text whose width a stop takes ends at the first piece that is not a glyph. After
        // the mark, no text is left to center, and "UV" starts on the stop.
        assert_eq!(dot('U'), stop, "{target:?}");
        // Only the space U+0020 trails: a no-break space at the end is written text, as wide
        // as a letter of the fake font.
        assert_eq!(dot('Y'), dot('G'), "{target:?}");
    }
}

#[test]
fn ends_an_aligned_line_of_only_a_label_and_its_tab_at_the_dot_after_the_tab() {
    // Empty list paragraphs, whose line is the label "AB1" of three fake glyphs of 10 pt and
    // the tab after it, which ends at the default stop of 36 pt: centered, then right-aligned,
    // with right indents of 0 to 11 twips, which move the space's right edge across dots. The
    // margin of 1,440 twips lies on dot 600 at 600 dots per inch.
    let numbering = parse(&format!(
        r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="AB%1"/></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>"#
    ));
    let label = |jc: &str, right: u32| {
        format!(
            r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr><w:ind w:left="0" w:right="{right}" w:firstLine="0"/><w:jc w:val="{jc}"/></w:pPr></w:p>"#
        )
    };
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        if profile.quirks().aligned_tab_end != crate::quirks::AlignedTabEnd::StopDot {
            continue;
        }
        let unit = profile.device().dots(1).units();
        let start = 1440 * Length::UNITS_PER_TWIP / unit;
        let places = |right: u32, variant| {
            let body = label("center", right) + &label("right", right);
            let aligned = profile.with_variant(variant);
            let (device, quirks) = (aligned.device(), aligned.quirks());
            let lists = Numbering::read(
                &mut PartReader::new(&numbering),
                numbering.root().unwrap(),
                crate::reader::settings::ReaderSettings::with_built_in_list(
                    crate::quirks::BuiltInList::WithoutPart,
                ),
            );
            let list = testing::pass_with(&body, ("", None), None, lists, (device, quirks)).list;
            match find_all(&list, 'A')[..] {
                [centered, right_aligned] => (centered.1 / unit, right_aligned.1 / unit),
                _ => panic!("{target:?}: two labels"),
            }
        };
        for right in 0..12 {
            // The right-aligned line moves by the free whole dots between the dot after its
            // tab and the space's right edge, and the centered one by half of them, rounded
            // down.
            let (centered, right_aligned) = places(right, crate::quirks::AlignedTabEnd::StopDot);
            assert_eq!(
                centered - start,
                (right_aligned - start) / 2,
                "{target:?} {right}"
            );
        }
        // Without the end, the centered line keeps its exact start, 1,799.58 dots right of
        // the margin with a right indent of 2 twips, on the dot above.
        let stopped = places(2, crate::quirks::AlignedTabEnd::StopDot).0;
        let unended = places(2, crate::quirks::AlignedTabEnd::Unended).0;
        assert_eq!(
            (stopped - start, unended - start),
            (1799, 1800),
            "{target:?}"
        );
    }
}

#[test]
fn lands_the_text_after_a_tab_in_a_centered_line_where_a_start_aligned_line_lands_it() {
    // The left margin of 1,701 twips lies three quarters of a dot past a dot at 600 dots per
    // inch, and the left stop at 851 twips a third of a dot past one. Both paragraphs have a
    // first-line indent of 567 twips and hold two fake glyphs of 5 pt, a tab and two more;
    // the first is centered, the second start-aligned.
    let paragraph = |jc: &str, text: (&str, &str)| {
        format!(
            r#"<w:p><w:pPr><w:tabs><w:tab w:val="left" w:pos="851"/></w:tabs><w:ind w:firstLine="567"/>{jc}</w:pPr><w:r><w:t>{}</w:t><w:tab/><w:t>{}</w:t></w:r></w:p>"#,
            text.0, text.1
        )
    };
    let body = paragraph(r#"<w:jc w:val="center"/>"#, ("AB", "CD")) + &paragraph("", ("EF", "GH"));
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1701" w:bottom="1440" w:left="1701" w:header="720" w:footer="720" w:gutter="0"/>"#;
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        if profile.quirks().aligned_line_segments
            != crate::quirks::AlignedLineSegments::FromExactStart
        {
            continue;
        }
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let unit = profile.device().dots(1).units();
        // A glyph's place is its dot plus the writer's offset, which is under a dot.
        let dot = |ch: char| find(&list, ch).1 / unit;
        // The start-aligned line lands the text after the tab on the dot of the stop's exact
        // place, the dot of the margin plus the stop's distance from it, and the centered line
        // lands it as far from its first glyph.
        assert_eq!(dot('C') - dot('A'), dot('G') - dot('E'), "{target:?}");
        assert!(dot('A') > dot('E'), "{target:?}");
    }
}

#[test]
fn draws_the_bar_of_a_fraction_in_a_part_at_the_axis_above_that_part() {
    // At 10 pt, the inline fraction x over (y, then a over b). Each bar's middle lies on the
    // axis, 585/2048 of its fraction's size, above its fraction's own baseline: the line's
    // for the outer bar at 10 pt, and the denominator's for the inner bar at the
    // denominator's 7 pt. The bar's top and bottom lie on dots, so its middle lies within a
    // dot of the axis.
    let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
    let r = |text: &str| format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{text}</m:t></m:r>");
    let f = |num: &str, den: &str| format!("<m:f><m:num>{num}</m:num><m:den>{den}</m:den></m:f>");
    let denominator = r("y") + &f(&r("a"), &r("b"));
    let body = format!(
        r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}">{}</m:oMath></w:p>"#,
        f(&r("x"), &denominator)
    );
    let list = lay_out(&body, "", None);
    let mut bars = testing::rects(&list, 0);
    bars.sort_by_key(|&(_, _, width, _)| std::cmp::Reverse(width));
    let [
        (_, outer_top, _, outer_height),
        (_, inner_top, _, inner_height),
    ] = bars[..]
    else {
        panic!("{bars:?}");
    };
    // In half dots, so that a bar's middle is whole.
    let axis = |half_points: i64| {
        let size = Length::from_half_points(half_points).unwrap().units();
        f_office_units::div_round(2 * f_office_units::div_round(size * 585, 2048), DOT)
    };
    let (line, part) = (2 * find(&list, 'A').2, 2 * find(&list, 'y').2);
    let outer = 2 * outer_top + outer_height;
    let inner = 2 * inner_top + inner_height;
    assert!((line - axis(20) - outer).abs() <= 2, "{line} {outer}");
    assert!((part - axis(14) - inner).abs() <= 2, "{part} {inner}");
    // The denominator lies below the line, so its bar lies below the outer bar's.
    assert!(part > line && inner > outer, "{outer} {inner}");
}

#[test]
fn draws_the_bar_of_a_fraction_whose_edges_round_to_one_dot_one_dot_thick() {
    // The bar takes the size of the fraction's control properties. At 1 pt it is 133/2048 pt
    // thick, about a quarter of a dot, and its top and its bottom round to the same dot; it is
    // drawn one dot thick, as every line of the text layout whose thickness comes from a font
    // is (`Device::line_thickness`). At 10 pt it is 0.65 pt, from 2.53 to 3.18 pt above the
    // baseline, and its edges round to 11 and 13 dots.
    let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
    for (half_points, dots) in [(2, 1), (20, 2)] {
        let size = format!(r#"<w:rPr><w:sz w:val="{half_points}"/></w:rPr>"#);
        let r = |text: &str| format!("<m:r><m:rPr><m:nor/></m:rPr>{size}<m:t>{text}</m:t></m:r>");
        let body = format!(
            r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}"><m:f><m:fPr><m:ctrlPr>{size}</m:ctrlPr></m:fPr><m:num>{}</m:num><m:den>{}</m:den></m:f></m:oMath></w:p>"#,
            r("x"),
            r("y")
        );
        let list = lay_out(&body, "", None);
        let [(_, _, _, height)] = testing::rects(&list, 0)[..] else {
            panic!("{:?}", testing::rects(&list, 0));
        };
        assert_eq!(height, dots, "{half_points}");
    }
}

#[test]
fn moves_a_part_whose_ink_comes_closer_to_the_bar_than_the_gap_minimum() {
    // At 10 pt, a fraction whose numerator, x and a glyph that reaches far down, and whose
    // denominator, y and a glyph that reaches far up, both cross the bar at the shifts. Each
    // part moves away from the bar until its ink keeps the gap minimum from the bar's edge,
    // to the nearest dot: 133/2048 of 10 pt in a line, where the parts are at 7 pt, and
    // 260/2048 of 10 pt in a display, where they keep 10 pt.
    let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
    let r = |text: String| format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{text}</m:t></m:r>");
    let fraction = format!(
        "<m:f><m:num>{}</m:num><m:den>{}</m:den></m:f>",
        r(format!("x{DEEP}")),
        r(format!("y{TALL}"))
    );
    let line = format!(
        r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}">{fraction}</m:oMath></w:p>"#
    );
    let display = format!(
        r#"<w:p><m:oMathPara xmlns:m="{math}"><m:oMath>{fraction}</m:oMath></m:oMathPara></w:p>"#
    );
    let pt = |points: i64| points * Length::UNITS_PER_POINT;
    for (body, part, gap) in [(line, pt(7), 133), (display, pt(10), 260)] {
        let list = lay_out(&body, "", None);
        let [(_, top, _, height)] = testing::rects(&list, 0)[..] else {
            panic!("{:?}", testing::rects(&list, 0));
        };
        let minimum = f_office_units::div_round(pt(10) * gap, 2048 * DOT);
        let reach = |units: i64| f_office_units::div_round(part * units, 1000 * DOT);
        // Down the page: the numerator's ink ends DEEP's depth below its baseline, and the
        // denominator's starts TALL's height above its own.
        let numerator = find(&list, 'x').2 + reach(900);
        let denominator = find(&list, 'y').2 - reach(1900);
        assert!(
            (top - numerator - minimum).abs() <= 1,
            "{top} {numerator} {minimum}"
        );
        assert!(
            (denominator - (top + height) - minimum).abs() <= 1,
            "{top} {height} {denominator} {minimum}"
        );
    }
}

#[test]
fn moves_the_scripts_of_one_base_apart_by_halves_of_the_shortfall_of_their_gap() {
    // At 10 pt, a base with a subscript that reaches far up and a superscript that reaches far
    // down, both at 7 pt: at their shifts the inks cross. The subscript drops and the
    // superscript rises by half of the shortfall each, so that the inks keep 300/2048 of 10 pt
    // between them, to the nearest dot.
    let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
    let r = |text: String| format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{text}</m:t></m:r>");
    let pair = format!(
        "<m:sSubSup><m:e>{}</m:e><m:sub>{}</m:sub><m:sup>{}</m:sup></m:sSubSup>",
        r("b".to_owned()),
        r(format!("{TALL}")),
        r(format!("{DEEP}"))
    );
    let body =
        format!(r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}">{pair}</m:oMath></w:p>"#);
    let list = lay_out(&body, "", None);
    let pt = |points: i64| points * Length::UNITS_PER_POINT;
    let dots = |size: i64, units: i64, em: i64| f_office_units::div_round(size * units, em * DOT);
    let (base, sub, sup) = (find(&list, 'b').2, find(&list, TALL).2, find(&list, DEEP).2);
    // Down the page: the subscript's ink starts TALL's height above its baseline, and the
    // superscript's ends DEEP's depth below its own.
    let gap = (sub - dots(pt(7), 1900, 1000)) - (sup + dots(pt(7), 900, 1000));
    let minimum = dots(pt(10), 300, 2048);
    assert!((gap - minimum).abs() <= 2, "{gap} {minimum}");
    let drop = sub - base - dots(pt(10), 418, 2048);
    let rise = base - sup - dots(pt(10), 750, 2048);
    assert!(drop > 0 && (drop - rise).abs() <= 2, "{drop} {rise}");
}

#[test]
fn gives_a_line_the_room_of_the_ink_of_its_inline_scripts_on_a_target_that_asks() {
    use crate::quirks::ScriptRoom;
    let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
    let r = |text: &str| format!("<m:r><m:t>{text}</m:t></m:r>");
    // The distances in dots from the baseline of a plain line to that of a line of text with
    // the equation `equation`, and from that line to the plain line after it, with the fake
    // fonts that have a `MATH` table, on a target with the quirk variant `variant`.
    let distances = |equation: &str, variant: ScriptRoom| {
        let body = format!(
            r#"{}<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{math}">{equation}</m:oMath></w:p>{}"#,
            p("Top"),
            p("End")
        );
        let (device, quirks) = testing::on_base_with(|p| p.with_variant(variant));
        let shaper = ShaperSettings::base_with(|p| p.with_variant(variant));
        let target = (device, quirks, crate::layout::EarlierPass::default());
        let fonts = (&FakeMath as &dyn crate::Fonts, shaper);
        let pass = testing::pass_on(
            &body,
            ("", None),
            None,
            Numbering::default(),
            target,
            &fonts,
        );
        let line = find(&pass.list, 'A').2;
        (
            line - find(&pass.list, 'T').2,
            find(&pass.list, 'E').2 - line,
        )
    };
    let plain = distances(&r("x"), ScriptRoom::Ink);
    let superscript = format!(
        "<m:sSup><m:e>{}</m:e><m:sup>{}</m:sup></m:sSup>",
        r("x"),
        r("x")
    );
    let subscript = format!(
        "<m:sSub><m:e>{}</m:e><m:sub>{}</m:sub></m:sSub>",
        r("x"),
        r("(")
    );
    // The other variant gives the scripts no room of their own.
    assert_eq!(distances(&superscript, ScriptRoom::FontLines), plain);
    assert_eq!(distances(&subscript, ScriptRoom::FontLines), plain);
    // At 10 pt, the scripts are at 7 pt. The superscript rises 750/2048 of 10 pt, to the
    // nearest dot, and its ink reaches 700/1000 of 7 pt above its baseline, with MathLeading,
    // 150/1000 of 10 pt, over it: beyond the line's ascent of 8 pt. The subscript drops
    // 418/2048 of 10 pt, and its parenthesis reaches 250/1000 of 7 pt below its baseline:
    // beyond the line's descent of 2 pt. Each other side keeps the room of the font's lines.
    // The baselines lie on whole dots, so each distance is within a dot of its room.
    let pt = |points: i64| points * Length::UNITS_PER_POINT;
    let dots = |units: i64| f_office_units::div_round(units, DOT);
    let rise = dots(f_office_units::div_round(pt(10) * 750, 2048)) * DOT;
    let above = rise + pt(7) * 7 / 10 + pt(10) * 15 / 100 - pt(8);
    let drop = dots(f_office_units::div_round(pt(10) * 418, 2048)) * DOT;
    let below = drop + pt(7) / 4 - pt(2);
    let (up, down) = distances(&superscript, ScriptRoom::Ink);
    assert!(
        (up - plain.0 - dots(above)).abs() <= 1,
        "{up} {plain:?} {above}"
    );
    assert!((down - plain.1).abs() <= 1, "{down} {plain:?}");
    let (up, down) = distances(&subscript, ScriptRoom::Ink);
    assert!((up - plain.0).abs() <= 1, "{up} {plain:?}");
    assert!(
        (down - plain.1 - dots(below)).abs() <= 1,
        "{down} {plain:?} {below}"
    );
}

#[test]
fn an_inline_object_moves_with_its_raised_or_lowered_run_and_its_line_holds_it() {
    use crate::ns::{A, WP, WPS};
    // A shape 30 pt tall in a run raised by `half_points`, beside a letter of the fake font at
    // 10 pt (8 pt above the baseline and 2 pt below it), above a paragraph of another letter:
    // the baselines of both letters in device dots, and the top of the shape in units.
    let laid = |half_points: i64| {
        let body = format!(
            r#"<w:p><w:r><w:rPr><w:position w:val="{half_points}"/></w:rPr><w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="381000"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/><a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r><w:r><w:t>a</w:t></w:r></w:p>{}"#,
            p("b")
        );
        let list = lay_out(&body, "", None);
        (
            find(&list, 'a').2,
            find(&list, 'b').2,
            testing::shape_top(&list),
        )
    };
    // The test device has dots of 0.24 pt.
    let six_points = 25;
    let (a, b, top) = laid(0);
    // Lowered by 6 pt, the shape reaches 24 pt above the baseline and 6 pt below it: the
    // baseline rises by 6 pt, and the line ends at the shape's bottom, 2 pt above the plain
    // line's end below the letter's descent. The shape stays where it was.
    let (lowered_a, lowered_b, lowered_top) = laid(-12);
    assert_eq!(lowered_a, a - six_points);
    assert_eq!(lowered_b, b - 8);
    assert_eq!(lowered_top, top);
    // Lowered by 12 pt, the baseline rises by 12 pt, and the line still ends at the shape's
    // bottom.
    let (deeper_a, deeper_b, _) = laid(-24);
    assert_eq!((deeper_a, deeper_b), (a - 2 * six_points, lowered_b));
    // Raised by 6 pt, it reaches 36 pt above the baseline: the baseline and the next line go
    // down by 6 pt, and the shape stays at the line's top.
    let (raised_a, raised_b, raised_top) = laid(12);
    assert_eq!(raised_a, a + six_points);
    assert_eq!(raised_b, b + six_points);
    assert_eq!(raised_top, top);
}

#[test]
fn a_lowered_object_in_multiple_spacing_keeps_the_extra_space_below_its_depth() {
    use crate::ns::{A, WP, WPS};
    // A shape 8 pt tall in a run lowered by `half_points`, beside a letter of the fake font at
    // 10 pt (8 pt above the baseline and 2 pt below it), in a paragraph of spacing 1.5, above a
    // paragraph of another letter: the baselines of both letters in device dots.
    let laid = |half_points: i64| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:line="360" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:position w:val="{half_points}"/></w:rPr><w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="101600"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r><w:r><w:t>a</w:t></w:r></w:p>{}"#,
            p("b")
        );
        let list = lay_out(&body, "", None);
        (find(&list, 'a').2, find(&list, 'b').2)
    };
    // The test device has dots of 0.24 pt.
    let six_points = 25;
    let (a, b) = laid(0);
    // Lowered by 8 pt, the shape reaches 6 pt below the letter's descent: the baseline stays,
    // and the next line goes down by those 6 pt, as the half line of spacing 1.5 stays below
    // the shape.
    let (lowered_a, lowered_b) = laid(-16);
    assert_eq!(lowered_a, a);
    assert!((lowered_b - b - six_points).abs() <= 1, "{b} {lowered_b}");
}

/// A paragraph of automatic spacing `line` that holds an inline shape 10 pt wide and `height`
/// EMU tall, in a run lowered by `lowered` half-points where given, then the letter `letter` in a
/// run of its own where given.
fn shape_paragraph(line: u32, lowered: Option<i32>, height: i64, letter: Option<char>) -> String {
    use crate::ns::{A, WP, WPS};
    let run = lowered.map_or_else(String::new, |half_points| {
        format!(r#"<w:rPr><w:position w:val="-{half_points}"/></w:rPr>"#)
    });
    let after = letter.map_or_else(String::new, |c| format!("<w:r><w:t>{c}</w:t></w:r>"));
    format!(
        r#"<w:p><w:pPr><w:spacing w:line="{line}" w:lineRule="auto"/></w:pPr><w:r>{run}<w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="{height}"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>{after}</w:p>"#
    )
}

/// The baselines of the letters `a` and `b` of `body` in device dots, laid out with the variant
/// `rule` of `ObjectAscent`, and with the part of a multiple spacing above single spacing below
/// the line's descent.
fn ascent_baselines(body: &str, rule: crate::quirks::ObjectAscent) -> (i64, i64) {
    use crate::quirks::MultipleBaseline;
    let target = testing::on_base_with(|p| {
        p.with_variant(rule)
            .with_variant(MultipleBaseline::DescentAboveExtra)
    });
    let list = testing::pass_with(body, (NORMAL, None), None, Numbering::default(), target);
    (find(&list.list, 'a').2, find(&list.list, 'b').2)
}

#[test]
fn a_lowered_object_above_the_ascent_moves_the_baseline_where_the_target_counts_the_ascent() {
    use crate::quirks::ObjectAscent::{Ascent, SingleLine};
    // A shape 11.5 pt tall in a run lowered by 2 pt, beside a letter of the fake font at 10 pt
    // (8 pt above the baseline and 2 pt below it), in a paragraph of automatic spacing `line`,
    // above a paragraph of another letter: its part above the baseline, 9.5 pt, is taller than
    // the letter's ascent and shorter than its single line of 10 pt.
    let laid = |rule, line: u32| {
        let body = format!(
            "{}{}",
            shape_paragraph(line, Some(4), 146_050, Some('a')),
            p("b")
        );
        ascent_baselines(&body, rule)
    };
    // Counted against the ascent, the part puts the baseline 1.5 pt (6.25 dots of the test
    // device) lower, and the next line goes 1.5 pt down too: in single spacing, and unscaled in
    // spacing above it.
    for line in [240, 276, 480] {
        let (a, b) = laid(SingleLine, line);
        let (counted_a, counted_b) = laid(Ascent, line);
        assert!((counted_a - a - 6).abs() <= 1, "{line}: {a} {counted_a}");
        assert!((counted_b - b - 6).abs() <= 1, "{line}: {b} {counted_b}");
    }
}

#[test]
fn an_object_not_lowered_above_the_ascent_moves_the_baseline_where_the_target_counts_the_ascent() {
    use crate::quirks::ObjectAscent::{Ascent, SingleLine};
    // A shape 9.5 pt tall in a run that is not lowered, beside a letter of the fake font at
    // 10 pt, in a paragraph of automatic spacing `line`, above a paragraph of another letter:
    // the shape is taller than the letter's ascent and shorter than its single line.
    let laid = |rule, line: u32| {
        let body = format!(
            "{}{}",
            shape_paragraph(line, None, 120_650, Some('a')),
            p("b")
        );
        ascent_baselines(&body, rule)
    };
    // Counted against the ascent, the shape moves both baselines 1.5 pt down, unscaled.
    for line in [240, 276, 480] {
        let (a, b) = laid(SingleLine, line);
        let (counted_a, counted_b) = laid(Ascent, line);
        assert!((counted_a - a - 6).abs() <= 1, "{line}: {a} {counted_a}");
        assert!((counted_b - b - 6).abs() <= 1, "{line}: {b} {counted_b}");
    }
}

#[test]
fn an_object_not_lowered_alone_on_its_line_keeps_the_single_line_where_the_target_counts_the_ascent()
 {
    use crate::quirks::ObjectAscent::{Ascent, SingleLine};
    // The same shape alone in its paragraph, whose mark takes the fake font at 10 pt, between
    // two paragraphs of a letter: the line of the shape does not grow on either variant.
    for line in [240, 360, 480] {
        let body = format!(
            "{}{}{}",
            p("a"),
            shape_paragraph(line, None, 120_650, None),
            p("b")
        );
        assert_eq!(
            ascent_baselines(&body, SingleLine),
            ascent_baselines(&body, Ascent),
            "{line}"
        );
    }
}

#[test]
fn object_run_face_sizes_short_inline_objects_in_mode_15_only() {
    use crate::ns::{A, WP, WPS};
    use crate::quirks::ObjectLineMultiple::{Mark, ObjectRun};
    let rect = |cy: i64| {
        format!(
            r#"<w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="{cy}"/><a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing>"#
        )
    };
    let layout_baselines =
        |body: &str, variant: crate::quirks::ObjectLineMultiple, mode: Option<u32>| {
            let target = testing::on_base_with(|p| p.with_variant(variant));
            let pass = testing::pass_with(body, (NORMAL, mode), None, Numbering::default(), target);
            (find(&pass.list, 'a').2, find(&pass.list, 'b').2)
        };
    // The fake font has single line equal to font size (ascent 80%, descent 20%).
    // 1. Short object (4 pt = 50_800 EMU) alone in a 10 pt run under a 20 pt mark:
    //    mode 15 ObjectRun uses 10 pt; mode 14 and Mark use 20 pt.
    let short_alone = format!(
        r#"{}<w:p><w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="20"/></w:rPr>{}</w:r></w:p>{}"#,
        p("a"),
        rect(50_800),
        p("b")
    );
    let (a15, b15) = layout_baselines(&short_alone, ObjectRun, Some(15));
    let (a14, b14) = layout_baselines(&short_alone, ObjectRun, Some(14));
    let (amk, bmk) = layout_baselines(&short_alone, Mark, Some(15));
    assert_eq!((a14, b14), (amk, bmk));
    // 10 pt shorter on the 300 dpi (0.24 pt/dot) test device is ~41-42 dots.
    assert!((b14 - b15 - 42).abs() <= 1, "{a15} {b15} vs {a14} {b14}");

    // 2. Medium object (16 pt = 203_200 EMU) alone in a 10 pt run under a 20 pt mark:
    //    mode 15 ObjectRun uses 16 pt (4 pt shorter than 20 pt mark = ~16-17 dots).
    let med_alone = format!(
        r#"{}<w:p><w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="20"/></w:rPr>{}</w:r></w:p>{}"#,
        p("a"),
        rect(203_200),
        p("b")
    );
    let (_, b15_m) = layout_baselines(&med_alone, ObjectRun, Some(15));
    let (_, b14_m) = layout_baselines(&med_alone, ObjectRun, Some(14));
    assert!((b14_m - b15_m - 17).abs() <= 1, "{b15_m} vs {b14_m}");

    // 3. Short object (4 pt) in a 20 pt run beside 10 pt text at 1.5x spacing:
    //    mode 15 ObjectRun expands the single line to 20 pt (30 pt at 1.5x) while keeping the
    //    10 pt text descent (baseline 18 pt below top = 10 pt lower than mode 14's 8 pt).
    let beside_text = format!(
        r#"<w:p><w:pPr><w:spacing w:line="360" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:t>a</w:t></w:r><w:r><w:rPr><w:sz w:val="40"/></w:rPr>{}</w:r></w:p>{}"#,
        rect(50_800),
        p("b")
    );
    let (first_15, next_15) = layout_baselines(&beside_text, ObjectRun, Some(15));
    let (first_14, next_14) = layout_baselines(&beside_text, ObjectRun, Some(14));
    // Baseline moves down 10 pt (~42 dots); next line moves down 15 pt (30 - 15 = 15 pt ~ 62-63 dots).
    assert!(
        (first_15 - first_14 - 42).abs() <= 1,
        "{first_15} vs {first_14}"
    );
    assert!(
        (next_15 - next_14 - 63).abs() <= 1,
        "{next_15} vs {next_14}"
    );
}

#[test]
fn a_shifted_run_adds_its_shift_once_in_multiple_spacing_where_the_target_counts_it_once() {
    use crate::quirks::RaisedRunSpacing::{Once, Scaled};
    // A letter of the fake font at 10 pt (8 pt above the baseline and 2 pt below it) and one in
    // a run raised or lowered by `half_points`, in a paragraph of spacing `line`, above a
    // paragraph of another letter: the baselines of both letters in device dots.
    let laid = |rule, line: u32, half_points: i32| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:line="{line}" w:lineRule="auto"/></w:pPr><w:r><w:t>a</w:t></w:r><w:r><w:rPr><w:position w:val="{half_points}"/></w:rPr><w:t>c</w:t></w:r></w:p>{}"#,
            p("b")
        );
        let target = testing::on_base_with(|p| p.with_variant(rule));
        let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
        (find(&list.list, 'a').2, find(&list.list, 'b').2)
    };
    // The test device has dots of 0.24 pt, so 3 pt are 12.5 dots.
    for half_points in [6, -6] {
        // In single spacing the variants agree.
        assert_eq!(laid(Scaled, 240, half_points), laid(Once, 240, half_points));
        // In double spacing, a raising or lowering of 3 pt comes twice when the spacing scales
        // it and once when it does not: the first letter stays, and the next paragraph comes
        // 3 pt higher.
        let (a, b) = laid(Scaled, 480, half_points);
        let (once_a, once_b) = laid(Once, 480, half_points);
        assert_eq!(once_a, a, "{half_points}");
        assert!((b - once_b - 12).abs() <= 1, "{half_points}: {b} {once_b}");
    }
    // A paragraph whose text is all lowered alike has no shift room: the variants agree.
    let alike = |rule| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:line="480" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:position w:val="-6"/></w:rPr><w:t>ac</w:t></w:r></w:p>{}"#,
            p("b")
        );
        let target = testing::on_base_with(|p| p.with_variant(rule));
        let list = testing::pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
        (find(&list.list, 'a').2, find(&list.list, 'b').2)
    };
    assert_eq!(alike(Scaled), alike(Once));
}

/// [`Fake`] fonts in which the family `Fake Deep` ascends 600 of the em's 1000 units and
/// descends 400: its single line is as tall as the others', and lies lower.
struct FakeDeep;

impl crate::Fonts for FakeDeep {
    fn face(
        &self,
        family: &f_office_fonts::FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<crate::ChosenFace> {
        let mut face = Fake.face(family, bold, italic)?;
        if family.is("Fake Deep") {
            face.font = f_office_fonts::FontId::from_index(face.font.index() + 4);
            let metrics = &mut face.metrics;
            (metrics.hhea_ascender, metrics.hhea_descender) = (600, -400);
            (metrics.line_top, metrics.script_top, metrics.descent) = (600, 600, 400);
        }
        Some(face)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Fake.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Fake.advance(font, glyph)
    }
}

#[test]
fn a_line_of_two_fonts_adds_its_face_room_once_in_multiple_spacing_where_the_target_counts_it_once()
{
    use crate::quirks::FaceRoomSpacing::{Once, Scaled};
    // A letter of the fake font at 10 pt (8 pt above the baseline and 2 pt below it) and one of
    // `second` at 10 pt, in a paragraph of spacing `line`, above a paragraph of another letter:
    // the baselines of both letters in device dots.
    let laid = |rule, line: u32, second: &str| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:line="{line}" w:lineRule="auto"/></w:pPr><w:r><w:t>a</w:t></w:r><w:r><w:rPr><w:rFonts w:ascii="{second}" w:hAnsi="{second}"/></w:rPr><w:t>c</w:t></w:r></w:p>{}"#,
            p("b")
        );
        let (device, quirks) = testing::on_base_with(|p| p.with_variant(rule));
        let target = (device, quirks, crate::layout::EarlierPass::default());
        let fonts = (&FakeDeep as &dyn crate::Fonts, ShaperSettings::base());
        let list = testing::pass_on(
            &body,
            (NORMAL, None),
            None,
            Numbering::default(),
            target,
            &fonts,
        );
        (find(&list.list, 'a').2, find(&list.list, 'b').2)
    };
    // The box of the two faces is 12 pt, 8 pt above the baseline and 4 pt below it, and the
    // single line of each is 10 pt, so the face room is 2 pt. The test device has dots of
    // 0.24 pt, so 2 pt are 8.33 dots.
    // In single spacing the variants agree.
    assert_eq!(laid(Scaled, 240, "Fake Deep"), laid(Once, 240, "Fake Deep"));
    // In double spacing, the room comes twice when the spacing scales it and once when it does
    // not: the first letter stays, and the next paragraph comes 2 pt higher.
    let (a, b) = laid(Scaled, 480, "Fake Deep");
    let (once_a, once_b) = laid(Once, 480, "Fake Deep");
    assert_eq!(once_a, a);
    assert!((b - once_b - 8).abs() <= 1, "{b} {once_b}");
    // Two faces of one shape have no face room: the variants agree.
    assert_eq!(laid(Scaled, 480, "Other"), laid(Once, 480, "Other"));
}

const MATH: &str = "http://schemas.openxmlformats.org/officeDocument/2006/math";

/// A math run of `text`.
fn math_run(text: &str) -> String {
    format!("<m:r><m:t>{text}</m:t></m:r>")
}

/// The display list of a 10 pt line of text with the equation `equation`, with the fonts
/// `fonts`.
fn equation_list(equation: &str, fonts: &dyn crate::Fonts) -> DisplayList {
    let body = format!(
        r#"<w:p><w:r><w:t>A</w:t></w:r><m:oMath xmlns:m="{MATH}">{equation}</m:oMath></w:p>"#
    );
    let (device, quirks) = testing::on_base();
    let target = (device, quirks, crate::layout::EarlierPass::default());
    let fonts = (fonts, ShaperSettings::base());
    testing::pass_on(
        &body,
        ("", None),
        None,
        Numbering::default(),
        target,
        &fonts,
    )
    .list
}

/// The glyph ID of the first root sign of a display list.
fn root_sign_glyph(list: &DisplayList) -> Option<u32> {
    list.pages()[0]
        .painted()
        .into_iter()
        .find_map(|item| match item {
            f_office_paint::Painted::Glyphs(run) => run
                .glyphs
                .iter()
                .find(|g| run.glyph_text(g).unwrap().starts_with('\u{221A}'))
                .map(|g| g.id),
            _ => None,
        })
}

/// A length in whole points, in units.
fn points(points: i64) -> i64 {
    points * Length::UNITS_PER_POINT
}

/// A length in units, to the nearest device dot.
fn nearest_dots(units: i64) -> i64 {
    f_office_units::div_round(units, DOT)
}

#[test]
fn draws_a_root_sign_with_a_bar_over_its_element() {
    let root = format!("<m:rad><m:e>{}</m:e></m:rad>", math_run("x"));
    let list = equation_list(&root, &FakeMath);
    // x's ink, from 0 to 7 pt, with the gap of 1 pt and the bar of 0.5 pt, needs 8.5 pt: the
    // root sign's own glyph, 10 pt tall, draws.
    assert_eq!(root_sign_glyph(&list), Some(0x221A));
    // The bar runs from the end of the sign over x's advance, 5 pt, 0.5 pt thick, with its top
    // at the top of the sign's ink, 7.5 pt above the sign's baseline. The rectangles' edges are
    // in whole dots, down.
    let (_, sign_x, sign_line) = find(&list, '\u{221A}');
    let (_, x_at, _) = find(&list, '\u{1D465}');
    assert_eq!(x_at, sign_x + points(5));
    let [(left, top, width, height)] = testing::rects(&list, 0)[..] else {
        panic!("not one bar");
    };
    assert_eq!((left, width), (x_at / DOT, points(5) / DOT));
    assert_eq!(height, nearest_dots(points(1) / 2));
    let bar_top = sign_line - nearest_dots(points(15) / 2);
    assert!((top - bar_top).abs() <= 1, "{top} {bar_top}");
    // The middle of the sign's ink, 2.5 pt above its baseline, lies the bar's thickness above
    // the middle of the element's height, from 0 to 7 pt: the sign rises 1.5 pt.
    let rise = find(&list, 'A').2 - sign_line;
    assert!((rise - nearest_dots(points(3) / 2)).abs() <= 1, "{rise}");
}

#[test]
fn draws_a_taller_root_sign_over_a_fraction_and_raises_a_degree() {
    let x = math_run("x");
    let fraction = format!("<m:f><m:num>{x}</m:num><m:den>{x}</m:den></m:f>");
    let over = equation_list(&format!("<m:rad><m:e>{fraction}</m:e></m:rad>"), &FakeMath);
    assert!(matches!(root_sign_glyph(&over), Some(8000 | 8001)));
    // A degree at 6 pt, 3 pt wide, rises to 60 % of the sign's ink height above its bottom,
    // and the sign starts 3 pt left of the degree's end, at the degree's start.
    let three = math_run("3");
    let cube = format!("<m:rad><m:deg>{three}</m:deg><m:e>{x}</m:e></m:rad>");
    let list = equation_list(&cube, &FakeMath);
    let (_, three_x, three_line) = find(&list, '3');
    let (_, sign_x, sign_line) = find(&list, '\u{221A}');
    assert_eq!(sign_x, three_x);
    let low = sign_line + nearest_dots(points(10) / 4);
    let high = sign_line - nearest_dots(points(15) / 2);
    let degree_line = low - (low - high) * 60 / 100;
    assert!(
        (three_line - degree_line).abs() <= 1,
        "{three_line} {degree_line}"
    );
}

#[test]
fn keeps_the_root_sign_in_a_font_without_the_radical_constants() {
    let root = format!("<m:rad><m:e>{}</m:e></m:rad>", math_run("x"));
    let plain = equation_list(&root, &testing::Fake);
    assert_eq!(root_sign_glyph(&plain), Some(0x221A));
    assert_eq!(testing::rects(&plain, 0), []);
}

#[test]
fn starts_scripts_by_the_corners_of_their_base_and_leaves_a_space_after_them() {
    use testing::{FakeScripts, MATH_X};
    let (x, two) = (math_run("x"), math_run("2"));
    let plus = math_run("+");
    let place = |structure: &str, fonts: &dyn crate::Fonts| {
        let script = structure[1..].to_lowercase();
        let equation = format!(
            "<m:{structure}><m:e>{x}</m:e><m:{script}>{two}</m:{script}></m:{structure}>{plus}"
        );
        let list = equation_list(&equation, fonts);
        let base = find(&list, MATH_X).1;
        (find(&list, '2').1 - base, find(&list, '+').1 - base)
    };
    // How far the script and the plus sign after it move from their places in a font without
    // the script values of a `MATH` table.
    let moves = |structure: &str| {
        let (start, after) = place(structure, &FakeScripts);
        let (plain_start, plain_after) = place(structure, &FakeMath);
        (start - plain_start, after - plain_after)
    };
    let near =
        |found: i64, expected: i64| assert!((found - expected).abs() <= DOT, "{found} {expected}");
    // At 10 pt, a superscript starts after x's italic correction, 1 pt, and its top right
    // kern, 0.5 pt; a subscript starts x's bottom right kern at the subscript's ink top, 1 pt,
    // to the left, the larger of that and the 3 pt at x's ink bottom. The space after the
    // script, 2 pt, comes before the plus sign.
    let (start, after) = moves("sSup");
    near(start, points(3) / 2);
    near(after, points(3) / 2 + points(2));
    let (start, after) = moves("sSub");
    near(start, -points(1));
    near(after, -points(1) + points(2));
}

#[test]
fn ends_a_script_after_the_italic_correction_of_its_last_glyph() {
    use testing::{FakeScripts, MATH_X};
    // x to the power of x, and x to the power of 2, each followed by a plus sign: the glyphs
    // of x and 2 have the same advance, and only x has an italic correction, 100 units.
    // The step from the script's start to the plus sign, and the script's size.
    let step = |script: &str, glyph: char| {
        let equation = format!(
            "<m:sSup><m:e>{}</m:e><m:sup>{}</m:sup></m:sSup>{}",
            math_run("x"),
            math_run(script),
            math_run("+")
        );
        let list = equation_list(&equation, &FakeScripts);
        let start = find_all(&list, glyph).last().unwrap().1;
        let size = list.pages()[0]
            .painted()
            .iter()
            .rev()
            .find_map(|item| match item {
                Painted::Glyphs(run) if run.text.starts_with(glyph) => Some(run.size),
                _ => None,
            })
            .unwrap();
        (find(&list, '+').1 - start, size)
    };
    let ((slanted, size), (upright, _)) = (step("x", MATH_X), step("2", '2'));
    let italic = size.units() / 10;
    assert!(
        (slanted - upright - italic).abs() <= DOT,
        "{slanted} {upright} {italic}"
    );
}

#[test]
fn ends_a_bar_and_a_root_past_the_italic_correction_that_a_subscript_on_an_overbar_gives_back() {
    use testing::{FakeScripts, MATH_X};
    let x = math_run("x");
    let bar = format!("<m:bar><m:barPr><m:pos m:val=\"top\"/></m:barPr><m:e>{x}</m:e></m:bar>");
    let root =
        format!("<m:rad><m:radPr><m:degHide m:val=\"1\"/></m:radPr><m:deg/><m:e>{x}</m:e></m:rad>");
    // The step from the first x to the first glyph `ch` after it.
    let step = |equation: &str, ch: char| {
        let list = equation_list(equation, &FakeScripts);
        let from = find_all(&list, MATH_X)[0].1;
        let to = find_all(&list, ch)
            .into_iter()
            .map(|(_, x, _)| x)
            .find(|&at| at > from)
            .unwrap();
        to - from
    };
    // x's italic correction, a tenth of its size: an x after a plain x stands at its advance,
    // and one after a bar or a root over x at the bar's end, past the correction.
    let size = equation_list(&x, &FakeScripts).pages()[0]
        .painted()
        .iter()
        .find_map(|item| match item {
            Painted::Glyphs(run) => Some(run.size),
            _ => None,
        })
        .unwrap();
    let italic = size.units() / 10;
    let plain = step(&format!("{x}{x}"), MATH_X);
    for structure in [&bar, &root] {
        let after = step(&format!("{structure}{x}"), MATH_X);
        assert!(
            (after - plain - italic).abs() <= DOT,
            "{after} {plain} {italic}"
        );
    }
    // A subscript on a bar over x starts at x's advance, a superscript at the bar's end; on a
    // root both start at the bar's end.
    let script = |base: &str, kind: &str, side: &str| {
        step(
            &format!(
                "<m:{kind}><m:e>{base}</m:e><m:{side}>{}</m:{side}></m:{kind}>",
                math_run("2")
            ),
            '2',
        )
    };
    let (sub, sup) = (script(&bar, "sSub", "sub"), script(&bar, "sSup", "sup"));
    assert!((sup - sub - italic).abs() <= DOT, "{sup} {sub} {italic}");
    let (sub, sup) = (script(&root, "sSub", "sub"), script(&root, "sSup", "sup"));
    assert!((sup - sub).abs() <= DOT, "{sup} {sub}");
    // Scripts on an underbar under x start where they start on x alone, by x's corners.
    let under = bar.replace("top", "bot");
    for (kind, side) in [("sSub", "sub"), ("sSup", "sup")] {
        let (on_bar, alone) = (script(&under, kind, side), script(&x, kind, side));
        assert!((on_bar - alone).abs() <= DOT, "{kind} {on_bar} {alone}");
    }
}

#[test]
fn keeps_the_italic_correction_before_a_digit_that_starts_the_next_math_run() {
    use testing::{FakeScripts, MATH_X};
    let step = |equation: &str| {
        let list = equation_list(equation, &FakeScripts);
        find_all(&list, '2')[0].1 - find_all(&list, MATH_X)[0].1
    };
    let plain = step(&math_run("x2"));
    // Two runs of the same properties, measured as one text, keep x's correction between them.
    let joined = step(&format!("{}{}", math_run("x"), math_run("2")));
    assert!(joined - plain > DOT, "{joined} {plain}");
}

#[test]
fn a_later_column_on_half_a_dot_takes_the_dot_of_its_parts_before_mode_15() {
    // quirk: ColumnEdgeHalves::ColumnParts (src/quirks.rs)
    use crate::quirks::ColumnEdgeHalves::{self, ColumnParts, WholeEdge};
    use crate::quirks::{ColumnWidths, LineStartHalves};
    // Two columns of 4,104 twips, 1,027 apart, from a left margin of 1,127 twips: the second
    // column's edge, 6,258 twips, is 2,607.5 dots. Its parts, the margin and the first
    // column's width with its space (5,131 twips), each round up in 1/65536 pt, so their sum
    // takes dot 2,608; the whole edge rounds down and takes dot 2,607.
    let body = r#"<w:p><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r><w:br w:type="column"/><w:t>B</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1878" w:bottom="1440" w:left="1127" w:header="720" w:footer="720" w:gutter="0"/><w:cols w:num="2" w:space="1027"/></w:sectPr>"#;
    let dots = |edge: ColumnEdgeHalves, mode, ch| {
        let target = crate::layout::testing::target_at(600, |p| {
            p.with_variant(LineStartHalves::FixedPoint)
                .with_variant(ColumnWidths::WholeTwips)
                .with_variant(edge)
        });
        let device = target.0;
        let pass = testing::pass_with(body, ("", Some(mode)), None, Numbering::default(), target);
        let (page, x, _) = find(&pass.list, ch);
        (page, x / device.dots(1).units(), x % device.dots(1).units())
    };
    for mode in [11, 12, 14] {
        assert_eq!(dots(ColumnParts, mode, 'B'), (0, 2_608, 0));
    }
    assert_eq!(dots(ColumnParts, 15, 'B'), (0, 2_607, 0));
    assert_eq!(dots(WholeEdge, 14, 'B'), (0, 2_607, 0));
    // The first column's edge, the margin alone, takes the same dot under both variants.
    assert_eq!(dots(ColumnParts, 14, 'A'), dots(WholeEdge, 14, 'A'));
}

#[test]
fn lays_out_a_text_box_s_text_in_one_column_whatever_the_section_s_columns() {
    // quirk: TextBoxColumns::OneColumn (src/quirks.rs)
    use crate::quirks::TextBoxColumns::{self, OneColumn, SectionColumns};
    // A box 200 pt wide at the margin's corner with a right-aligned letter: in one column the
    // letter ends at the right of the box's text area; in the first of the section's columns
    // it ends further left.
    let shape = AnchoredShape {
        across: ("margin", 0),
        down: ("margin", 0),
        size: (2_540_000, 1_270_000),
        wrap: "<wp:wrapNone/>",
        outline: None,
        text: Some(ShapeText {
            blocks: r#"<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>R</w:t></w:r></w:p>"#,
            body: "<wps:bodyPr/>",
        }),
    };
    let x = |variant: TextBoxColumns, columns: u32| {
        let body = format!(
            r#"<w:p><w:r>{}</w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/><w:cols w:num="{columns}" w:space="720"/></w:sectPr>"#,
            shape.drawing()
        );
        let target = testing::on_base_with(|p| p.with_variant(variant));
        let pass = testing::pass_with(&body, ("", None), None, Numbering::default(), target);
        find(&pass.list, 'R').1
    };
    assert_eq!(x(OneColumn, 2), x(OneColumn, 1));
    assert_eq!(x(OneColumn, 3), x(OneColumn, 1));
    assert!(x(SectionColumns, 2) < x(SectionColumns, 1));
    assert_eq!(x(SectionColumns, 1), x(OneColumn, 1));
}

#[test]
fn lays_the_columns_of_a_right_to_left_section_out_from_the_right_margin() {
    // quirk: RightToLeftSectionColumns::FromRight (src/quirks.rs)
    use crate::quirks::RightToLeftSectionColumns::{self, FromLeft, FromRight};
    // Two equal columns of 4,320 twips with 720 between them on a text area from 1,440 to
    // 10,800 twips: the letter A of the first column, then B after a column break.
    let x = |variant: RightToLeftSectionColumns, bidi: &str, letter: char| {
        let body = format!(
            r#"<w:p><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r><w:br w:type="column"/><w:t>B</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/><w:cols w:num="2" w:space="720"/>{bidi}</w:sectPr>"#
        );
        let target = testing::on_base_with(|p| p.with_variant(variant));
        let pass = testing::pass_with(&body, ("", None), None, Numbering::default(), target);
        find(&pass.list, letter).1
    };
    let twips = |t: i64| t * Length::UNITS_PER_TWIP;
    let near = |a: i64, b: i64| (a - b).abs() <= Length::UNITS_PER_POINT;
    assert!(near(x(FromRight, "<w:bidi/>", 'A'), twips(6_480)));
    assert!(near(x(FromRight, "<w:bidi/>", 'B'), twips(1_440)));
    assert_eq!(x(FromLeft, "<w:bidi/>", 'A'), x(FromRight, "", 'A'));
    assert!(near(x(FromRight, "", 'B'), twips(6_480)));
}

#[test]
fn gives_a_hidden_paragraphs_border_to_the_shaded_paragraph_after_it_from_mode_15() {
    // quirk: HiddenMarkBorders::ByMode (src/quirks.rs)
    use crate::quirks::HiddenMarkBorders::{self, ByMode, Dropped};
    use f_office_paint::{Item, Rgb};
    // A paragraph of hidden text with a hidden mark and a bottom border of 0.75 pt with 1 pt of
    // space, before a paragraph that shows text, shaded or plain.
    let hidden = r#"<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="000000"/></w:pBdr><w:rPr><w:vanish/></w:rPr></w:pPr><w:r><w:rPr><w:vanish/></w:rPr><w:t>H</w:t></w:r></w:p>"#;
    let black_lines = |variant: HiddenMarkBorders, mode: u32, shaded: bool| {
        let shading = if shaded {
            r#"<w:pPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:pPr>"#
        } else {
            ""
        };
        let body = format!(
            "<w:p><w:r><w:t>A</w:t></w:r></w:p>{hidden}<w:p>{shading}<w:r><w:t>B</w:t></w:r></w:p><w:p><w:r><w:t>C</w:t></w:r></w:p>"
        );
        let target = testing::target_at(600, |p| p.with_variant(variant));
        let pass = testing::pass_with(&body, ("", Some(mode)), None, Numbering::default(), target);
        pass.list.pages()[0]
            .items()
            .iter()
            .filter(|item| matches!(item, Item::Rect(r) if r.color == Rgb::BLACK))
            .count()
    };
    assert_eq!(black_lines(ByMode, 15, true), 1);
    // Before mode 15, before a plain paragraph and where the target drops the borders: none.
    assert_eq!(black_lines(ByMode, 14, true), 0);
    assert_eq!(black_lines(ByMode, 15, false), 0);
    assert_eq!(black_lines(Dropped, 15, true), 0);
}

#[test]
fn draws_the_line_between_two_columns_that_hold_text_where_the_target_draws_it() {
    // quirk: ColumnSeparator::SpaceMiddle (src/quirks.rs)
    use crate::quirks::ColumnSeparator::{self, NotDrawn, SpaceMiddle};
    use f_office_paint::Item;
    // Two equal columns of 4,320 twips with 720 between them on a text area from 1,440 to
    // 10,800 twips: the space's middle lies at 6,120 twips, dot 2,550 at 600 dots per inch.
    // The first column holds two lines of exactly 14 pt and the second, after a column break
    // at the end of the second line, one; without the break, the first column holds all three.
    let exact =
        r#"<w:pPr><w:spacing w:before="0" w:after="0" w:line="280" w:lineRule="exact"/></w:pPr>"#;
    let rects = |variant: ColumnSeparator, sep: &str, broken: bool| {
        let column_break = if broken {
            r#"<w:br w:type="column"/>"#
        } else {
            ""
        };
        let body = format!(
            r#"<w:p>{exact}<w:r><w:t>A</w:t></w:r></w:p><w:p>{exact}<w:r><w:t>A</w:t>{column_break}</w:r></w:p><w:p>{exact}<w:r><w:t>B</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/><w:cols w:num="2" w:space="720"{sep}/></w:sectPr>"#
        );
        let target = testing::target_at(600, |p| p.with_variant(variant));
        let dot = target.0.dots(1).units();
        let pass = testing::pass_with(&body, ("", Some(15)), None, Numbering::default(), target);
        pass.list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Rect(r) => Some([r.x, r.y, r.width, r.height].map(|v| v.units() / dot)),
                Item::Glyphs(_)
                | Item::Path(_)
                | Item::Gradient(_)
                | Item::Image(_)
                | Item::Group(_) => None,
            })
            .collect::<Vec<_>>()
    };
    let sep = r#" w:sep="1""#;
    // Six dots wide from three dots left of the middle, from the top margin, dot 600, to the
    // dot nearest to the bottom of the first column's second line, 100 pt.
    assert_eq!(rects(SpaceMiddle, sep, true), [[2_547, 600, 6, 233]]);
    let none: [[i64; 4]; 0] = [];
    assert_eq!(rects(NotDrawn, sep, true), none);
    assert_eq!(rects(SpaceMiddle, "", true), none);
    // The second column holds no text: no line.
    assert_eq!(rects(SpaceMiddle, sep, false), none);
}

#[test]
fn a_line_at_a_wrap_edge_takes_the_dot_of_the_edge_on_a_target_that_counts_from_it() {
    // quirk: WrapEdgeDot::WrapEdge (src/quirks.rs)
    use crate::quirks::WrapEdgeDot::{self, ColumnAndDistance, WrapEdge};
    // A left margin of 1,208 twips, 503.33 dots, and a box with square wrap from it, 692 twips
    // wide, so its wrap edge lies at 1,900 twips, 791.67 dots: the line beside it takes dot 792
    // from the edge as one length, and dot 503 plus dot 288 from the column's edge and the
    // distance. The line below the box starts at the margin's dot under both.
    let shape = AnchoredShape {
        across: ("margin", 0),
        down: ("margin", 0),
        size: (439_420, 457_200),
        wrap: testing::SQUARE_WRAP,
        outline: None,
        text: None,
    };
    let body = format!(
        r#"<w:p><w:pPr><w:spacing w:after="1440"/></w:pPr><w:r>{}</w:r><w:r><w:t>W</w:t></w:r></w:p><w:p><w:r><w:t>K</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1208" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#,
        shape.drawing()
    );
    let dots = |variant: WrapEdgeDot, ch| {
        let target = crate::layout::testing::target_at(600, |p| p.with_variant(variant));
        let device = target.0;
        let pass = testing::pass_with(&body, ("", Some(15)), None, Numbering::default(), target);
        let (page, x, _) = find(&pass.list, ch);
        (page, x / device.dots(1).units())
    };
    assert_eq!(dots(WrapEdge, 'W'), (0, 792));
    assert_eq!(dots(ColumnAndDistance, 'W'), (0, 791));
    assert_eq!(dots(WrapEdge, 'K'), (0, 503));
    assert_eq!(dots(ColumnAndDistance, 'K'), (0, 503));
}

#[test]
fn a_line_beside_a_drawing_on_its_left_keeps_only_a_first_line_indent_past_the_wrap_edge() {
    // Two paragraphs with a left indent of 720 twips, each anchoring at its top a box with
    // square wrap from the margin (1,440 twips), 1,440 twips wide, so the wrap edge lies at
    // 2,880 twips, dot 1,200: the first with a first-line indent of 360 twips, the second, on
    // the next page, with a hanging indent of 360 twips, each with a line break. The first line
    // of the first starts at the wrap edge plus its first-line indent, dot 1,350; every other
    // line beside a box starts at the wrap edge. With the indents counted past the wrap edge,
    // they would start at dots 1,650, 1,500, 1,350 and 1,500.
    let shape = AnchoredShape {
        across: ("margin", 0),
        down: ("paragraph", 0),
        size: (914_400, 457_200),
        wrap: testing::SQUARE_WRAP,
        outline: None,
        text: None,
    };
    let drawing = shape.drawing();
    let body = format!(
        r#"<w:p><w:pPr><w:ind w:left="720" w:firstLine="360"/></w:pPr><w:r>{drawing}</w:r><w:r><w:t>W</w:t><w:br/><w:t>K</w:t></w:r></w:p><w:p><w:pPr><w:pageBreakBefore/><w:ind w:left="720" w:hanging="360"/></w:pPr><w:r>{drawing}</w:r><w:r><w:t>V</w:t><w:br/><w:t>Z</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#
    );
    assert_eq!(
        dots_at_600(&body, &['W', 'K', 'V', 'Z']),
        [(0, 1_350), (0, 1_200), (1, 1_200), (1, 1_200)]
    );
}

#[test]
fn a_line_beside_a_frame_on_its_left_keeps_its_whole_start_past_the_wrap_edge() {
    // A frame of 2,880 twips from the page's left edge, with text around it, and a paragraph
    // beside it with a left indent of 720 twips, a first-line indent of 360 twips and a line
    // break: the frame's wrap edge lies at 2,880 twips, dot 1,200, and each line keeps its whole
    // start past it, the first line dot 1,650 and the second dot 1,500, unlike a line beside a
    // drawing.
    let body = r#"<w:p><w:pPr><w:framePr w:w="2880" w:h="1440" w:hRule="exact" w:wrap="around" w:vAnchor="text" w:hAnchor="page" w:x="0" w:y="0"/></w:pPr><w:r><w:t>F</w:t></w:r></w:p><w:p><w:pPr><w:ind w:left="720" w:firstLine="360"/></w:pPr><w:r><w:t>W</w:t><w:br/><w:t>K</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#;
    assert_eq!(dots_at_600(body, &['W', 'K']), [(0, 1_650), (0, 1_500)]);
}

/// The page and the dot from the page's left edge of the first glyph of each of `chars` in
/// `body`, laid out for the target's profile at 600 dots an inch.
fn dots_at_600(body: &str, chars: &[char]) -> Vec<(usize, i64)> {
    let target = testing::target_at(600, crate::profile::Profile::clone);
    let dot = target.0.dots(1).units();
    let pass = testing::pass_with(body, ("", Some(15)), None, Numbering::default(), target);
    chars
        .iter()
        .map(|&ch| {
            let (page, x, _) = find(&pass.list, ch);
            (page, x / dot)
        })
        .collect()
}

/// The top and the height of a box in the middle of a Letter page, beside lines 15 to 32, in
/// points from the page's top edge.
const MIDDLE_BOX: (i64, i64) = (246, 200);

/// The top and the height of a box whose bottom lies between the tops of the last two lines
/// of a Letter page, so that only the page's last line has the column's whole width below it.
const FOOT_BOX: (i64, i64) = (450, 252);

/// The lines on each page of one paragraph of `words` words "x" on lines of exactly 12 pt,
/// beside a box with a square wrap at `place` (its top and height in points) on a Letter page,
/// half the column wide, under the widow forecast `variant`.
fn lines_beside_a_box(
    variant: crate::quirks::WidowForecast,
    place: (i64, i64),
    words: usize,
) -> Vec<usize> {
    const EMU_PER_PT: i64 = 12_700;
    let (top, height) = place;
    let shape = AnchoredShape {
        across: ("page", 300 * EMU_PER_PT),
        down: ("page", top * EMU_PER_PT),
        size: (300 * EMU_PER_PT, height * EMU_PER_PT),
        wrap: testing::SQUARE_WRAP,
        outline: None,
        text: None,
    };
    let body = format!(
        r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="exact"/></w:pPr><w:r>{}</w:r><w:r><w:t xml:space="preserve">{}</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#,
        shape.drawing(),
        "x ".repeat(words)
    );
    let target = testing::target_at(600, |p| p.with_variant(variant));
    let pass = testing::pass_with(&body, ("", Some(15)), None, Numbering::default(), target);
    let lines: std::collections::BTreeSet<(usize, i64)> = find_all(&pass.list, 'x')
        .into_iter()
        .map(|(page, _, y)| (page, y))
        .collect();
    let mut pages = Vec::new();
    for (page, _) in lines {
        pages.resize(pages.len().max(page + 1), 0);
        if let Some(count) = pages.get_mut(page) {
            *count += 1;
        }
    }
    pages
}

/// The most words of [`lines_beside_a_box`] that fit on page 1 beside the box at `place` under
/// the forecast at the column's whole width, and one more.
fn words_at_the_page_end(place: (i64, i64)) -> (usize, usize) {
    use crate::quirks::WidowForecast::WholeWidth;
    let (mut fits, mut over) = (1, 6_000);
    assert_eq!(lines_beside_a_box(WholeWidth, place, fits).len(), 1);
    assert!(lines_beside_a_box(WholeWidth, place, over).len() > 1);
    while over - fits > 1 {
        let words = usize::midpoint(fits, over);
        if lines_beside_a_box(WholeWidth, place, words).len() == 1 {
            fits = words;
        } else {
            over = words;
        }
    }
    (fits, over)
}

#[test]
fn moves_the_line_before_a_last_line_that_a_wrap_pushes_alone_to_the_next_page_where_the_target_counts_wrapped_lines()
 {
    // quirk: WidowForecast::AsWrapped (src/quirks.rs)
    use crate::quirks::WidowForecast::{AsWrapped, WholeWidth};
    // The fewest words that reach page 2 beside the box: at the column's whole width they
    // would fit on page 1, so the forecast of the paragraph's start finds no widow break.
    let (fits, over) = words_at_the_page_end(MIDDLE_BOX);
    let whole = lines_beside_a_box(WholeWidth, MIDDLE_BOX, over);
    let wrapped = lines_beside_a_box(AsWrapped, MIDDLE_BOX, over);
    // The last line goes alone to page 2 under the forecast at the whole width; counted as the
    // box breaks the lines, the line before it goes with it.
    assert_eq!(whole.get(1), Some(&1));
    assert_eq!(
        wrapped,
        vec![whole.first().copied().unwrap_or_default() - 1, 2]
    );
    // One word fewer fits on page 1 under both.
    assert_eq!(lines_beside_a_box(AsWrapped, MIDDLE_BOX, fits).len(), 1);
}

#[test]
fn keeps_on_the_page_a_paragraph_whose_forecast_line_breaks_again_below_the_box_where_the_target_counts_wrapped_lines()
 {
    // quirk: WidowForecast::AsWrapped (src/quirks.rs)
    use crate::quirks::WidowForecast::AsWrapped;
    // Beside the box, the paragraph's narrow lines would put its last line alone on page 2,
    // but the line before it stands below the box and breaks again at the column's whole
    // width, where the paragraph fits on page 1: every paragraph that fits there under the
    // forecast at the whole width fits there as the box breaks its lines too.
    let (fits, _) = words_at_the_page_end(FOOT_BOX);
    for words in fits.saturating_sub(60)..=fits {
        assert_eq!(
            lines_beside_a_box(AsWrapped, FOOT_BOX, words).len(),
            1,
            "{words} words"
        );
    }
}

/// Whether `a` and `b` have one length and their numbers differ by at most one each.
fn within_one(a: &[i64], b: &[i64]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1)
}

fn narrow_wrap_anchor(x_pt: i64, width_pt: i64) -> String {
    const EMU_PER_PT: i64 = 12_700;
    let shape = AnchoredShape {
        across: ("column", x_pt * EMU_PER_PT),
        down: ("paragraph", 0),
        size: (width_pt * EMU_PER_PT, 48 * EMU_PER_PT),
        wrap: testing::SQUARE_WRAP,
        outline: None,
        text: None,
    };
    format!(
        r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="20" w:lineRule="exact"/></w:pPr><w:r>{}</w:r></w:p>"#,
        shape.drawing()
    )
}

fn read_test_numbering(inner: &str) -> Numbering {
    let xml = format!(r#"<w:numbering xmlns:w="{W}">{inner}</w:numbering>"#);
    let doc = parse(&xml);
    Numbering::read(
        &mut PartReader::new(&doc),
        doc.root().unwrap(),
        crate::reader::settings::ReaderSettings::base(),
    )
}

const LETTER_ONE_INCH_SECT: &str = r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#;

#[test]
fn list_label_beside_narrow_wrap_moves_below_unless_empty() {
    let numbering = read_test_numbering(
        r#"<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum>
           <w:abstractNum w:abstractNumId="2"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:suff w:val="space"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum>
           <w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num>
           <w:num w:numId="2"><w:abstractNumId w:val="2"/></w:num>"#,
    );
    let anchor = narrow_wrap_anchor(0, 444);
    for num_id in [1, 2] {
        let body = format!(
            r#"{anchor}<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="{num_id}"/></w:numPr></w:pPr><w:r><w:t>Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#
        );
        let pass = testing::pass_with(
            &body,
            ("", Some(15)),
            None,
            numbering.clone(),
            testing::on_base(),
        );
        let (_, lx, ly) = find(&pass.list, '1');
        let (_, bx, by) = find(&pass.list, 'S');
        assert_eq!(ly, by, "num_id={num_id}: label and body share one baseline");
        assert!(lx < bx && lx < Length::from_points(120).unwrap().units());
    }
    let empty = format!(
        r#"{anchor}<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr></w:p>{LETTER_ONE_INCH_SECT}"#
    );
    let pass = testing::pass_with(&empty, ("", Some(15)), None, numbering, testing::on_base());
    assert!(find(&pass.list, '1').1 > Length::from_points(500).unwrap().units());
}

#[test]
fn leading_tab_and_middle_wrap_list_label_do_not_orphan_prefix() {
    let anchor = narrow_wrap_anchor(0, 444);
    let tabbed = format!(
        "{anchor}<w:p><w:r><w:tab/><w:t>Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"
    );
    let pass = testing::pass_with(
        &tabbed,
        ("", Some(15)),
        None,
        Numbering::default(),
        testing::on_base(),
    );
    let (_, sx, sy) = find(&pass.list, 'S');
    assert!(sy * DOT > Length::from_points(120).unwrap().units());
    assert!(
        sx >= Length::from_points(107).unwrap().units()
            && sx <= Length::from_points(109).unwrap().units()
    );

    let mid_numbering = read_test_numbering(
        r#"<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="0" w:hanging="0"/></w:pPr></w:lvl></w:abstractNum>
           <w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num>"#,
    );
    let mid_body = format!(
        r#"{}<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#,
        narrow_wrap_anchor(24, 180)
    );
    let pass = testing::pass_with(
        &mid_body,
        ("", Some(15)),
        None,
        mid_numbering,
        testing::on_base(),
    );
    let (_, lx, ly) = find(&pass.list, '1');
    let (_, bx, by) = find(&pass.list, 'S');
    assert_eq!(ly, by);
    assert!(ly * DOT < Length::from_points(110).unwrap().units());
    assert!(lx > Length::from_points(270).unwrap().units() && bx > lx);
}

#[test]
fn leading_spaces_and_first_of_two_tabs_stay_beside_narrow_wrap() {
    let anchor = narrow_wrap_anchor(0, 444);
    let spaced = format!(
        r#"{anchor}<w:p><w:r><w:t xml:space="preserve">   Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#
    );
    let pass = testing::pass_with(
        &spaced,
        ("", Some(15)),
        None,
        Numbering::default(),
        testing::on_base(),
    );
    let (_, sx, sy) = find(&pass.list, 'S');
    assert!(sy * DOT > Length::from_points(120).unwrap().units());
    assert!(
        sx >= Length::from_points(71).unwrap().units()
            && sx <= Length::from_points(73).unwrap().units()
    );

    let two_tabs = format!(
        "{anchor}<w:p><w:r><w:tab/><w:tab/><w:t>Superlongword rest</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"
    );
    let pass = testing::pass_with(
        &two_tabs,
        ("", Some(15)),
        None,
        Numbering::default(),
        testing::on_base(),
    );
    let (_, tx, ty) = find(&pass.list, 'S');
    assert!(ty * DOT > Length::from_points(120).unwrap().units());
    assert!(
        tx >= Length::from_points(107).unwrap().units()
            && tx <= Length::from_points(109).unwrap().units()
    );
}

fn wrap_anchor_with(x_pt: i64, width_pt: i64, height_pt: i64, wrap: &str) -> String {
    const EMU_PER_PT: i64 = 12_700;
    let shape = AnchoredShape {
        across: ("column", x_pt * EMU_PER_PT),
        down: ("paragraph", 0),
        size: (width_pt * EMU_PER_PT, height_pt * EMU_PER_PT),
        wrap,
        outline: None,
        text: None,
    };
    format!(
        r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="20" w:lineRule="exact"/></w:pPr><w:r>{}</w:r></w:p>"#,
        shape.drawing()
    )
}

fn inline_rect_run(width_pt: i64, height_pt: i64) -> String {
    use crate::ns::{A, WP, WPS};
    const EMU_PER_PT: i64 = 12_700;
    let (cx, cy) = (width_pt * EMU_PER_PT, height_pt * EMU_PER_PT);
    format!(
        r#"<w:r><w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="{cx}" cy="{cy}"/><wp:effectExtent l="0" t="0" r="0" b="0"/><wp:docPr id="9" name="In"/><wp:cNvGraphicFramePr/><a:graphic xmlns:a="{A}"><a:graphicData uri="{WPS}"><wps:wsp xmlns:wps="{WPS}"><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="{cx}" cy="{cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="cccccc"/></a:solidFill></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#
    )
}

fn wide_word_beside_wrap(
    x_pt: i64,
    width_pt: i64,
    height_pt: i64,
    wrap: &str,
    compat: u32,
) -> (i64, i64) {
    use crate::quirks::BlockedLines;
    let long_word = format!(
        r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="72"/><w:szCs w:val="72"/></w:rPr><w:t>{}</w:t></w:r></w:p><w:p><w:r><w:t>E</w:t></w:r></w:p>"#,
        "W".repeat(16)
    );
    let body = format!(
        "{}{long_word}{LETTER_ONE_INCH_SECT}",
        wrap_anchor_with(x_pt, width_pt, height_pt, wrap)
    );
    let pass = testing::pass_with(
        &body,
        ("", Some(compat)),
        None,
        Numbering::default(),
        testing::on_base_with(|p| p.with_variant(BlockedLines::LineSteps)),
    );
    let (_, x, y) = find(&pass.list, 'W');
    (x, y * DOT)
}

#[test]
fn wrap_square_multi_piece_wide_word_overflow_follows_compat_mode() {
    let pt = |n: i64| Length::from_points(n).unwrap().units();
    // Centered 200x20 pt box (two 134 pt pieces): mode 15 drops to box bottom (~92 pt),
    // mode 12 steps down by one line height (~41 pt), and a 60 pt box in mode 12 takes two steps.
    let (w15_x, w15_y) = wide_word_beside_wrap(134, 200, 20, testing::SQUARE_WRAP, 15);
    let (w12_x, w12_y) = wide_word_beside_wrap(134, 200, 20, testing::SQUARE_WRAP, 12);
    let (_, tall_y) = wide_word_beside_wrap(134, 200, 60, testing::SQUARE_WRAP, 12);
    assert!(w15_x < pt(75) && w12_x < pt(75));
    assert!(w15_y > pt(85) && w15_y < pt(140));
    assert!(w12_y > w15_y + pt(10));
    assert!(tall_y > w12_y + pt(30));
}

#[test]
fn wrap_square_single_piece_wide_word_overflow_follows_wrap_kind_and_mode() {
    let pt = |n: i64| Length::from_points(n).unwrap().units();
    let tight_wrap = r#"<wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="0"><wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapTight>"#;
    // Single-piece left box (138 pt right piece): mode 15 drops below, mode 12 splits beside
    // wrapSquare, and mode 12 steps below rectangular wrapTight.
    let (lm15_x, _) = wide_word_beside_wrap(0, 330, 33, testing::SQUARE_WRAP, 15);
    let (lm12_x, _) = wide_word_beside_wrap(0, 330, 33, testing::SQUARE_WRAP, 12);
    let (tm12_x, _) = wide_word_beside_wrap(0, 330, 33, tight_wrap, 12);
    assert!(lm15_x < pt(75));
    assert!(lm12_x > pt(390));
    assert!(tm12_x < pt(75));
}

#[test]
fn wrap_square_inline_object_overflow_follows_compat_mode() {
    let pt = |n: i64| Length::from_points(n).unwrap().units();
    let inline_para = format!(
        r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr>{}</w:p><w:p><w:r><w:t>E</w:t></w:r></w:p>"#,
        inline_rect_run(300, 140)
    );
    // Centered 200x33 pt box + 300x140 pt inline drawing:
    // - Mode 15 drops the inline drawing below the box (E shifts down by ~33 pt).
    // - Mode 12 keeps the inline drawing at the paragraph top (E stays ~33 pt higher).
    let centered = format!(
        "{}{inline_para}{LETTER_ONE_INCH_SECT}",
        wrap_anchor_with(134, 200, 33, testing::SQUARE_WRAP)
    );
    let m15 = testing::pass_with(
        &centered,
        ("", Some(15)),
        None,
        Numbering::default(),
        testing::on_base(),
    );
    let m12 = testing::pass_with(
        &centered,
        ("", Some(12)),
        None,
        Numbering::default(),
        testing::on_base(),
    );
    let (_, _, e15) = find(&m15.list, 'E');
    let (_, _, e12) = find(&m12.list, 'E');
    assert!(
        e15 * DOT > e12 * DOT + pt(25),
        "mode 15 drops wide inline object below wrapSquare while mode 12 keeps it: e15={}, e12={}",
        e15 * DOT,
        e12 * DOT
    );

    // Full-width 468x33 pt box (no free pieces): even mode 12 drops the inline drawing below.
    let fullwidth = format!(
        "{}{inline_para}{LETTER_ONE_INCH_SECT}",
        wrap_anchor_with(0, 468, 33, testing::SQUARE_WRAP)
    );
    let fw12 = testing::pass_with(
        &fullwidth,
        ("", Some(12)),
        None,
        Numbering::default(),
        testing::on_base(),
    );
    let (_, _, efw) = find(&fw12.list, 'E');
    assert!(
        efw * DOT > e12 * DOT + pt(25),
        "full-width box still drops inline object in mode 12: efw={}, e12={}",
        efw * DOT,
        e12 * DOT
    );
}

#[test]
fn bidi_paragraph_mark_and_break_take_complex_script_size() {
    use crate::quirks::MarkFace;
    let measure_gap = |middle: &str, mark_face| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p>{middle}<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#
        );
        let (device, mut quirks) = testing::on_base();
        quirks.mark_face = mark_face;
        let pass = testing::pass_with(
            &body,
            ("", Some(15)),
            None,
            Numbering::default(),
            (device, quirks),
        );
        let (_, _, ya) = find(&pass.list, 'A');
        let (_, _, yb) = find(&pass.list, 'B');
        (yb - ya) * DOT
    };
    let ltr_empty = r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/><w:rPr><w:sz w:val="24"/><w:szCs w:val="40"/></w:rPr></w:pPr></w:p>"#;
    let bidi_empty = r#"<w:p><w:pPr><w:bidi/><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/><w:rPr><w:sz w:val="24"/><w:szCs w:val="40"/></w:rPr></w:pPr></w:p>"#;
    let bidi_no_szcs = r#"<w:p><w:pPr><w:bidi/><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/><w:rPr><w:sz w:val="40"/></w:rPr></w:pPr></w:p>"#;
    let bidi_break = r#"<w:p><w:pPr><w:bidi/><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/><w:rPr><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="24"/><w:szCs w:val="40"/></w:rPr><w:br/></w:r></w:p>"#;
    let ltr_break = r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/><w:rPr><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="24"/><w:szCs w:val="40"/></w:rPr><w:br/></w:r></w:p>"#;

    let cf = MarkFace::ComplexFormatting;
    let ascii = MarkFace::Ascii;
    // Direct w:bidi without w:rtl/w:cs sizes the empty paragraph at w:szCs (20 pt > 12 pt).
    assert!(measure_gap(bidi_empty, cf) > measure_gap(ltr_empty, cf));
    // Absent w:szCs on a w:bidi empty paragraph falls back to default 10 pt, not w:sz (20 pt).
    assert!(measure_gap(bidi_no_szcs, cf) < measure_gap(bidi_empty, cf));
    // A manual line break in a w:bidi paragraph also takes its run's w:szCs.
    assert!(measure_gap(bidi_break, cf) > measure_gap(ltr_break, cf));
    // MarkFace::Ascii keeps the ASCII w:sz on every case.
    assert_eq!(
        measure_gap(bidi_empty, ascii),
        measure_gap(ltr_empty, ascii)
    );
    assert_eq!(
        measure_gap(bidi_break, ascii),
        measure_gap(ltr_break, ascii)
    );
}

fn wrap_in_gap_place(
    mode: u32,
    wrap: &str,
    width_pt: i64,
    pos_v_pt: i64,
    (p1_after, p2_before): (i64, i64),
    target_text: &str,
) -> ((i64, i64), (i64, i64)) {
    use crate::quirks::BlockedLines;
    const EMU_PER_PT: i64 = 12_700;
    let shape = AnchoredShape {
        across: ("column", 0),
        down: ("paragraph", pos_v_pt * EMU_PER_PT),
        size: (width_pt * EMU_PER_PT, 2 * EMU_PER_PT),
        wrap,
        outline: None,
        text: None,
    };
    let body = format!(
        r#"<w:p><w:pPr><w:spacing w:before="0" w:after="{p1_after}" w:line="280" w:lineRule="exact"/></w:pPr><w:r>{}</w:r><w:r><w:t>A</w:t></w:r></w:p><w:p><w:pPr><w:spacing w:before="{p2_before}" w:after="0" w:line="280" w:lineRule="exact"/></w:pPr><w:r><w:t>{target_text}</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#,
        shape.drawing()
    );
    let pass = testing::pass_with(
        &body,
        ("", Some(mode)),
        None,
        Numbering::default(),
        testing::on_base_with(|p| p.with_variant(BlockedLines::LineSteps)),
    );
    let (_, ax, ay) = find(&pass.list, 'A');
    let first_ch = target_text.chars().next().unwrap();
    let (_, tx, ty) = find(&pass.list, first_ch);
    ((ax, ay * DOT), (tx, ty * DOT))
}

#[test]
fn non_polygon_wraps_in_space_before_and_legacy_space_after() {
    let pt = |n: i64| Length::from_points(n).unwrap().units();
    let tb = "<wp:wrapTopAndBottom/>";
    let sq = testing::SQUARE_WRAP;
    let tight = r#"<wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="0"><wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapTight>"#;

    // 1. wrapTopAndBottom & full-width wrapSquare inside own_space_before push Target down in modes 14 & 15;
    //    narrow wrapSquare wraps horizontally; wrapTight ignores spaceBefore.
    let (_, (_, tb14_y)) = wrap_in_gap_place(14, tb, 468, 18, (0, 240), "T");
    let (_, (_, tb15_y)) = wrap_in_gap_place(15, tb, 468, 18, (0, 240), "T");
    let (_, (_, sq15_y)) = wrap_in_gap_place(15, sq, 468, 18, (0, 240), "T");
    let (_, (nsq_x, nsq_y)) = wrap_in_gap_place(15, sq, 144, 18, (0, 240), "T");
    let (_, (tight_x, tight_y)) = wrap_in_gap_place(14, tight, 144, 18, (0, 240), "T");
    let (_, (_, over_y)) = wrap_in_gap_place(15, sq, 360, 18, (0, 240), &"W".repeat(24));

    assert_eq!((tb14_y, sq15_y, over_y), (tb15_y, tb15_y, tb15_y));
    assert!(tb15_y > tight_y + pt(5));
    assert!(nsq_x > tight_x + pt(140) && nsq_y == tight_y);

    // 2. Partial collapse (after=4 pt, before=12 pt -> own_before=8 pt): band in P1's after is
    //    ignored in mode 15, band in own_before shifts by own_before (8 pt).
    let (_, (_, in_after_y)) = wrap_in_gap_place(15, tb, 468, 15, (80, 240), "T");
    let (_, (_, in_own_y)) = wrap_in_gap_place(15, tb, 468, 20, (80, 240), "T");
    assert!(in_after_y == tight_y && in_own_y > tight_y + pt(3) && in_own_y < tb15_y);

    // 3. Space after (12 pt): mode 14 pushes Anchor below the band in its spaceAfter; mode 15 does not.
    let ((_, a14_y), _) = wrap_in_gap_place(14, tb, 468, 18, (240, 0), "T");
    let ((_, a15_y), _) = wrap_in_gap_place(15, tb, 468, 18, (240, 0), "T");
    assert!(a14_y > a15_y + pt(18));
}

#[test]
fn short_inline_object_alone_sits_at_line_bottom_without_descent() {
    use crate::quirks::UnderlinedObjectRoom;
    let pt = |n: i64| Length::from_points(n).unwrap().units();
    let shape_top = |line_twips: i64, rule: &str, rpr: &str, extra: &str| {
        let obj = inline_rect_run(72, 4).replace("<w:r>", &format!("<w:r><w:rPr>{rpr}</w:rPr>"));
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="44"/></w:rPr><w:t>A</w:t></w:r></w:p><w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="{line_twips}" w:lineRule="{rule}"/><w:rPr><w:sz w:val="44"/></w:rPr></w:pPr>{obj}{extra}</w:p><w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="44"/></w:rPr><w:t>C</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#
        );
        let pass = testing::pass_with(
            &body,
            ("", Some(15)),
            None,
            Numbering::default(),
            testing::on_base_with(|p| p.with_variant(UnderlinedObjectRoom::FontDescent)),
        );
        pass.list
            .pages()
            .first()
            .and_then(|p| {
                p.items().iter().find_map(|item| match item {
                    f_office_paint::Item::Path(path) => {
                        Some(corners_of(&path.commands).0.y.units())
                    }
                    _ => None,
                })
            })
            .unwrap()
    };
    let sz = r#"<w:sz w:val="44"/>"#;
    let sz_u = r#"<w:sz w:val="44"/><w:u w:val="single"/>"#;
    let txt = r#"<w:r><w:rPr><w:sz w:val="44"/></w:rPr><w:t>x</w:t></w:r>"#;
    let nbsp =
        "<w:r><w:rPr><w:sz w:val=\"44\"/></w:rPr><w:t xml:space=\"preserve\">\u{00A0}</w:t></w:r>";

    let top_auto = shape_top(240, "auto", sz, "");
    let top_mult = shape_top(360, "auto", sz, "");
    let top_text = shape_top(240, "auto", sz, txt);
    let top_nbsp = shape_top(240, "auto", sz, nbsp);
    let top_under = shape_top(240, "auto", sz_u, "");
    let top_at30 = shape_top(600, "atLeast", sz, "");
    let top_at30_txt = shape_top(600, "atLeast", sz, txt);

    // Short non-underlined inline object alone sits lower (at single-line / atLeast bottom without
    // font descent) than when paired with text, a non-breaking space, or an underline; 1.5x keeps
    // the single-line bottom.
    assert_eq!(
        (top_auto, top_text, top_nbsp),
        (top_mult, top_under, top_text)
    );
    assert!(top_auto > top_text + pt(3) && top_at30 > top_at30_txt + pt(3));
}

#[test]
fn at_least_line_spacing_keeps_below_text_drop_for_stacked_fractions() {
    let frac = r#"<w:r><w:t>x</w:t></w:r><m:oMath xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><m:f><m:num><m:r><m:t>1</m:t></m:r></m:num><m:den><m:r><m:t>2</m:t></m:r></m:den></m:f></m:oMath>"#;
    let measure = |line_twips: i64, rule: &str| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p><w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="{line_twips}" w:lineRule="{rule}"/></w:pPr>{frac}</w:p><w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:t>C</w:t></w:r></w:p>{LETTER_ONE_INCH_SECT}"#
        );
        let list = lay_out(&body, NORMAL, Some(15));
        // Baseline positions in device dots (1/600 in = 0.12 pt).
        (find(&list, 'A').2, find(&list, 'x').2, find(&list, 'C').2)
    };
    let (a_auto, x_auto, c_auto) = measure(240, "auto");
    let (a_13, x_13, c_13) = measure(260, "atLeast");
    let (a_48, x_48, c_48) = measure(960, "atLeast");
    let (_a_ex, x_ex, c_ex) = measure(960, "exact");

    // atLeast <= single + drop matches single spacing (auto 240) with below-text drop included.
    assert_eq!((a_13, x_13, c_13), (a_auto, x_auto, c_auto));
    // atLeast 48 pt (> single + drop) caps line height at 48 pt and keeps the same descent + drop
    // below the fraction baseline as auto 240 (within 1 device dot).
    assert_eq!(a_48, a_auto);
    assert!(((c_48 - x_48) - (c_auto - x_auto)).abs() <= 1);
    assert!((c_48 - c_auto) > 80);
    // exact 48 pt ignores below-text drop (uses 4/5 baseline, placing x higher than atLeast 48 pt).
    assert_eq!(c_ex, c_48);
    assert!(x_ex < x_48 - 10);
}