f-office-docx 0.3.0

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
//! Measuring: a paragraph's properties after the cascade, its list label, its runs as pieces
//! with their widths, and the frame that its lines fill.

use std::num::NonZeroU32;
use std::rc::Rc;

use f_office_paint::{Image, ImageColor, Opacity};
use f_office_units::{Edges, Length, div_round_i128};

use crate::body::{
    Content, GapMinimum, GrownMark, InlineDrawing, NoteMark, NumberRef, Paragraph, Run, RunRecord,
    StackMark,
};
use crate::character_class::CharacterClass;
use crate::kinsoku::{CharBreak, Kinsoku};
use crate::lines::{Frame, JointGaps, LeadingBreaks, Line, Piece, Shrink, advance, break_lines};
use crate::mode::ModeRules;
use crate::note_setup::NoteLabel;
use crate::numbering::{Label, LabelAlign, Suffix};
use crate::params;
use crate::params::{AUTO_TEXT_DARK_LUMA, LUMA_WEIGHTS};
use crate::picture::{Picture, bullet_natural_size};
use crate::properties::Property;
use crate::props::{
    Alignment, BidiLanguageClass, Color, EastAsianScript, HtmlAutoSpacing, ListLevel, ListRef,
    MarkChange, ParaProps, RunProps, TabKind, TabStop, Underline, WHITE,
};
use crate::styles::Justification;
use crate::tabs::Tabs;
use crate::text::{FaceIndex, SpaceKind};
use crate::warnings::Feature;

use super::decisions::{self, RevisionReading};
use super::{Layout, Resolved, Within};

/// The direction of the paragraph currently being measured, used for manual line break faces.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum ParagraphDirection {
    /// Left-to-right paragraph (`w:bidi` unset or false).
    #[default]
    LeftToRight,
    /// Right-to-left paragraph (`w:bidi` true).
    RightToLeft,
}

impl ParagraphDirection {
    /// Whether this direction is right to left.
    pub(super) const fn is_rtl(self) -> bool {
        matches!(self, Self::RightToLeft)
    }
}

mod accents;
mod bars;
mod border_boxes;
mod gap_minimums;
mod group_chrs;
mod grown_delimiters;
mod hyphen_points;
mod limits;
mod matrices;
mod radicals;
mod scripts;
mod slashes;
mod structures;

use gap_minimums::Stacked;
pub(super) use gap_minimums::bar_edges;
use grown_delimiters::Grown;
pub(super) use hyphen_points::HyphenRun;
use hyphen_points::WordRules;
use structures::{OpenStructures, last_italic_correction};

/// The most that each space of a justified line may shrink: a quarter of its width. To take one
/// more word, each space also shrinks by at most half the stretch per gap that the line would
/// need without that word.
pub(super) const JUSTIFIED_SHRINK: Shrink = Shrink {
    permille: params::JUSTIFIED_SPACE_SHRINK,
    stretch_permille: params::NEXT_WORD_STRETCH_SHARE,
    natural: (0, 0),
    joints: JointGaps { seen: 0, other: 0 },
};

/// The gaps that the letter joints of a justified line whose joints after a seen take kashidas
/// count as, beside its spaces, when the line takes one more word by shrinking its spaces.
const KASHIDA_JOINT_GAPS: JointGaps = JointGaps {
    seen: params::NEXT_WORD_SEEN_JOINT_GAPS,
    other: params::NEXT_WORD_JOINT_GAPS,
};

/// How far a justified line with the justification of `WordPerfect` may run past its width to
/// take a word: a share of its natural width up to the word's end. Its spaces shrink only as
/// its drawing narrows the line.
pub(super) const WORD_PERFECT_SHRINK: Shrink = Shrink {
    permille: 0,
    stretch_permille: 0,
    natural: params::WORDPERFECT_LINE_SHRINK,
    joints: JointGaps { seen: 0, other: 0 },
};

/// The text that Word's English edition shows for a page reference to a bookmark that the
/// document does not have.
const MISSING_BOOKMARK: &str = "Error! Bookmark not defined.";

/// The text of an English number REF whose source bookmark does not exist.
const MISSING_REFERENCE: &str = "Error! Reference source not found.";

/// What a character is for Word's automatic space between East Asian text and Latin text or
/// digits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Spacing {
    /// A Chinese, Japanese or Korean letter: an ideograph, kana or Hangul
    /// ([`CharacterClass::EastAsianSpacing`]).
    EastAsian,
    /// A digit from 0 to 9.
    Digit,
    /// A Latin letter.
    Latin,
    /// Anything else, such as a space or punctuation.
    Other,
}

fn spacing_class(ch: char) -> Spacing {
    match ch {
        ch if CharacterClass::EastAsianSpacing.contains(ch) => Spacing::EastAsian,
        '0'..='9' => Spacing::Digit,
        'A'..='Z' | 'a'..='z' | '\u{00C0}'..='\u{024F}' if ch.is_alphabetic() => Spacing::Latin,
        _ => Spacing::Other,
    }
}

/// How much the spaces of a line may shrink, for a paragraph alignment, a compatibility mode
/// and the justification that the line takes ([`decisions::justification`]).
pub(super) fn shrink(
    alignment: Option<Alignment>,
    rules: ModeRules,
    justification: Justification,
) -> Shrink {
    match (
        alignment.filter(|&alignment| alignment.justified()),
        justification,
    ) {
        (Some(_), _) if rules.shrinks_justified_spaces() => JUSTIFIED_SHRINK,
        (Some(Alignment::Both), Justification::WordPerfect) => WORD_PERFECT_SHRINK,
        _ => Shrink::default(),
    }
}

/// The text of runs that follow each other with the same properties, which waits for the runs
/// after it.
struct Pending {
    /// The properties of the runs.
    props: RunProps,
    /// Their text.
    text: String,
    /// Where each run after the first starts in the text, in bytes, when its revision IDs or
    /// its run record differ from those of the run before, when it starts a text buffer, or
    /// when a field mark lies before it.
    starts: Vec<usize>,
    /// Where each run after the first starts in the text, in bytes, whatever the runs differ
    /// in.
    joins: Vec<usize>,
    /// Where each run that starts a text buffer starts in the text, in bytes, the first run
    /// among them. Only the trace of the test tools reads it, through the glyphs.
    buffer_starts: Vec<usize>,
    /// Whether a field mark lies between the text so far and the text that joins next: a
    /// field result starts or a field ends there, or a hyperlink's edge on a target whose
    /// writer takes a hyperlink as a field.
    field_mark: bool,
    /// The revision IDs of the last run, as the writer reads them.
    revisions: [Option<u32>; 3],
    /// How the writer reads the revision IDs.
    reading: RevisionReading,
    /// The run record of the last run.
    record: RunRecord,
    /// Where a run starts in the text, in bytes, whose bidi language has another class than
    /// that of the run before, with that class.
    classes: Vec<(usize, Option<BidiLanguageClass>)>,
    /// The class of the bidi language of the last run.
    class: Option<BidiLanguageClass>,
    /// Where the text of each run starts in the text, in bytes, with the index of the run
    /// among the runs of its paragraph; empty for the value of a field that layout computes,
    /// whose glyphs take the index of the run that shows it.
    runs: Vec<(usize, u32)>,
    /// Whether the first text of this pending batch began at the head of its `<w:r>` (false
    /// after an in-run tab or line break).
    starts_at_run_head: bool,
}

/// Gives the glyphs of joined text the indexes of their runs: `firsts` holds the index of the
/// first piece of each run's text with the run's index, in order.
fn name_joined_runs(pieces: &mut [Piece], firsts: &[(usize, u32)]) {
    let end = pieces.len();
    for (at, &(first, run)) in firsts.iter().enumerate() {
        let next = firsts.get(at + 1).map_or(end, |&(next, _)| next);
        for piece in pieces.get_mut(first..next).unwrap_or_default() {
            if let Piece::Glyph(glyph) = piece {
                glyph.place.run = Some(run);
            }
        }
    }
}

/// Records a run index whose `w:rPr/w:snapToGrid` turns off the section's character grid.
fn record_off_grid(off_grid: &mut Vec<u32>, index: u32, props: &RunProps) {
    if props.snap_to_grid == Some(false) {
        off_grid.push(index);
    }
}

/// Gives each glyph of `pieces` from `from` on that has no run's index yet the index `run`: the
/// glyphs of a content of that run that is not text of the runs, such as a symbol or a computed
/// value.
fn name_runs(pieces: &mut [Piece], from: usize, run: u32) {
    for piece in pieces.get_mut(from..).unwrap_or_default() {
        if let Piece::Glyph(glyph) = piece
            && glyph.place.run.is_none()
        {
            glyph.place.run = Some(run);
        }
    }
}

/// Marks with `mark` each glyph of `pieces` at one of `indexes`.
fn mark_glyphs(pieces: &mut [Piece], indexes: &[usize], mark: impl Fn(&mut crate::text::Glyph)) {
    for &index in indexes {
        if let Some(Piece::Glyph(glyph)) = pieces.get_mut(index) {
            mark(glyph);
        }
    }
}

/// Adds run-start splits for runs whose resolved `w:eastAsia` font is not Word's default
/// (`Times New Roman`) and that begin with a `U+2000..=U+2BFF` symbol or punctuation character
/// not round-tripping in any legacy Windows ANSI/CJK code page (`is_unmapped_symbol`, including
/// General Punctuation spaces `U+2000..=U+200A`, `U+202F`, `U+205F` and unmapped math/geometric
/// symbols such as `U+2212` and `U+25BA`): Word groups that leading symbol and any immediately
/// following `U+2000..=U+2BFF` characters into their own text object and starts a new run (and
/// 256-character piece count) at the first character outside `U+2000..=U+2BFF`.
fn add_east_asian_leading_splits(
    pieces: &[Piece],
    firsts: &mut Vec<usize>,
    starts_at_run_head: bool,
) {
    let mut extra = Vec::new();
    let skip = usize::from(!starts_at_run_head);
    for (pos, &run_start) in firsts.iter().enumerate().skip(skip) {
        let run_end = firsts.get(pos + 1).copied().unwrap_or(pieces.len());
        let Some(Piece::Glyph(first)) = pieces.get(run_start) else {
            continue;
        };
        if !crate::character_class::is_unmapped_symbol(first.ch) {
            continue;
        }
        let mut cursor = run_start + 1;
        while cursor < run_end {
            match pieces.get(cursor) {
                Some(Piece::Glyph(glyph)) if ('\u{2000}'..='\u{2BFF}').contains(&glyph.ch) => {
                    cursor += 1;
                }
                _ => break,
            }
        }
        if cursor < run_end {
            extra.push(cursor);
        }
    }
    firsts.extend(extra);
}

impl Pending {
    /// Adds the text `text` of the run `run`, which draws with the same properties, and which
    /// is `first` when the text starts the run. Runs with the same properties, revision IDs and
    /// run records, an accepted insertion among them, are one text object, unless the run
    /// starts a text buffer. Text after a field mark starts a text object, also inside a run;
    /// it is still measured with the text before it.
    fn join(&mut self, text: &str, run: &Run, first: bool) {
        let revisions = self.reading.read(run.revisions);
        let new_run = run.starts_buffer || self.revisions != revisions || self.record != run.record;
        let after_mark = std::mem::take(&mut self.field_mark);
        if after_mark || (first && new_run) {
            self.starts.push(self.text.len());
        }
        if first && !self.text.is_empty() {
            self.joins.push(self.text.len());
        }
        if first && run.starts_buffer {
            self.buffer_starts.push(self.text.len());
        }
        self.revisions = revisions;
        self.record.clone_from(&run.record);
        self.text.push_str(text);
    }

    /// Notes, before the text of the run of index `run` among the runs of its paragraph joins,
    /// that the run's text starts here.
    fn start_run(&mut self, run: u32) {
        self.runs.push((self.text.len(), run));
    }

    /// Notes, before [`Self::join`] adds the text of a run, that the run's bidi language has
    /// the class `class`: the letters of the runs join, and each run keeps its class.
    fn start_class(&mut self, class: Option<BidiLanguageClass>) {
        if self.class != class {
            self.classes.push((self.text.len(), class));
            self.class = class;
        }
    }

    /// The text `text` of a first run `run`, with the properties `props`, which is the run of
    /// index `index` among the runs of its paragraph.
    fn new(props: &RunProps, text: &str, (run, index): (&Run, u32)) -> Self {
        Self {
            runs: vec![(0, index)],
            revisions: run.revisions,
            record: run.record.clone(),
            buffer_starts: if run.starts_buffer {
                vec![0]
            } else {
                Vec::new()
            },
            ..Self::alone(props, text.to_owned())
        }
    }

    /// The same text, whose revision IDs, its own and those of the runs that join it, the writer
    /// reads as `reading` says.
    fn reading(self, reading: RevisionReading) -> Self {
        Self {
            revisions: reading.read(self.revisions),
            reading,
            ..self
        }
    }

    /// Records whether the first text of this batch started at the head of its `<w:r>`.
    fn at_run_head(self, starts_at_run_head: bool) -> Self {
        Self {
            starts_at_run_head,
            ..self
        }
    }

    /// The text `text` with the properties `props`, which no other text joins: the value
    /// of a field that layout computes.
    fn alone(props: &RunProps, text: String) -> Self {
        Self {
            props: props.clone(),
            text,
            starts: Vec::new(),
            joins: Vec::new(),
            buffer_starts: Vec::new(),
            field_mark: false,
            revisions: [None; 3],
            reading: RevisionReading::AS_WRITTEN,
            record: RunRecord::default(),
            classes: Vec::new(),
            class: props.bidi_class,
            runs: Vec::new(),
            starts_at_run_head: true,
        }
    }
}

/// Gives the glyphs of runs with `w:rtl` the class of their run's bidi language: `classes`
/// holds the index of the first piece of each run whose class differs from the run before.
fn set_classes(pieces: &mut [Piece], classes: &[(usize, Option<BidiLanguageClass>)]) {
    for &(from, class) in classes {
        for piece in pieces.iter_mut().skip(from) {
            if let Piece::Glyph(glyph) = piece {
                glyph.direction = glyph.direction.with_class(class);
            }
        }
    }
}

/// The length of a glyph's character in UTF-16 code units, in which Word counts the pieces of
/// a paragraph's text.
fn utf16_length(piece: &Piece) -> u32 {
    match piece {
        Piece::Glyph(glyph) => u32::try_from(glyph.ch.len_utf16()).unwrap_or(1),
        Piece::Shift(_)
        | Piece::Advance(_)
        | Piece::Bar { .. }
        | Piece::Vinculum { .. }
        | Piece::Diagonal { .. } => 0,
        _ => 1,
    }
}

/// A stack whose end is still to come: the index of its bar, if it has one, with the gap
/// minimum that its parts keep from it, of the shift before its first part, and of the shift
/// before its second part, whether it centers the narrower part, and how far its first part
/// starts left of its second, in half-EMUs.
pub(super) struct OpenStack {
    bar: Option<(usize, GapMinimum)>,
    first: usize,
    second: Option<usize>,
    centered: bool,
    lead: Length,
}

/// Places the mark of a stack of two parts in `pieces`, such as a stacked fraction or the
/// scripts of a sub-superscript. At its start the stack puts down its bar, if it has one,
/// with the stack's `face`, and a shift; at the end of its first part a shift; and at its end
/// a shift, after which the shifts put the second part under the first, the narrower part
/// centered on the wider one or starting where it starts. The stack then takes the room of its
/// wider part. In a stack with a bar, each part is as wide as its pieces and their
/// `correction`, the italic correction of the glyph that ends them, by which widths the parts
/// are centered and the bar and the stack run to the end of the wider part. The stack of the limits
/// beside a display's n-ary operator starts its first part `lead` left of its second, and ends
/// where the part that ends later ends.
///
/// The italic correction of the glyph that ends a span of pieces.
type SpanCorrection<'a> = dyn Fn(&[Piece]) -> Length + 'a;

/// At its end, a stack with a bar gives its bar and the ranges of its two parts.
pub(super) fn stack(
    open: &mut Vec<OpenStack>,
    pieces: &mut Vec<Piece>,
    mark: StackMark,
    (face, lead, correction): (Option<FaceIndex>, Length, &SpanCorrection<'_>),
) -> Option<Stacked> {
    match mark {
        StackMark::Start { bar, centered } => {
            let bar = bar.zip(face).map(|(minimum, face)| {
                pieces.push(Piece::Bar {
                    face,
                    width: Length::ZERO,
                });
                (pieces.len() - 1, minimum)
            });
            open.push(OpenStack {
                bar,
                first: pieces.len(),
                second: None,
                centered,
                lead: Length::ZERO,
            });
            pieces.push(Piece::Shift(Length::ZERO));
            None
        }
        StackMark::StartBeside(_) => {
            open.push(OpenStack {
                bar: None,
                first: pieces.len(),
                second: None,
                centered: false,
                lead,
            });
            pieces.push(Piece::Shift(Length::ZERO));
            None
        }
        StackMark::Middle => {
            if let Some(stack) = open.last_mut() {
                stack.second = Some(pieces.len());
            }
            pieces.push(Piece::Shift(Length::ZERO));
            None
        }
        StackMark::End => {
            let stack = open.pop()?;
            let end = pieces.len();
            let middle = stack.second.unwrap_or(end);
            let parts = end;
            // Each part's advance and the correction past it.
            let width = |range: std::ops::Range<usize>| -> (Length, Length) {
                let span = pieces.get(range).unwrap_or(&[]);
                let past = stack.bar.map_or(Length::ZERO, |_| correction(span));
                (span.iter().map(advance).sum(), past)
            };
            let (first, first_past) = width(stack.first + 1..middle);
            let (second, second_past) = width((middle + 1).min(end)..end);
            let wide = (first + first_past).max(second + second_past);
            let before = |part: Length| {
                if stack.centered {
                    (wide - part).div_toward_zero(2)
                } else {
                    Length::ZERO
                }
            };
            let (before_first, before_second) = (
                before(first + first_past) - stack.lead,
                before(second + second_past),
            );
            // The wider part ends at `wide` unless the first part starts to the left.
            let end = (before_first + first + first_past).max(before_second + second + second_past);
            let shift = |at: usize, by: Length, pieces: &mut Vec<Piece>| {
                if let Some(piece) = pieces.get_mut(at) {
                    *piece = Piece::Shift(by);
                }
            };
            shift(stack.first, before_first, pieces);
            if let Some(middle) = stack.second {
                shift(middle, before_second - before_first - first, pieces);
            }
            pieces.push(Piece::Shift(end - before_second - second));
            if let Some(Piece::Bar { width, .. }) = stack.bar.and_then(|(at, _)| pieces.get_mut(at))
            {
                *width = end;
            }
            stack.bar.map(|(bar, minimum)| Stacked {
                bar,
                minimum,
                numerator: stack.first + 1..middle,
                denominator: (middle + 1).min(parts)..parts,
            })
        }
    }
}

/// The indexes of the spaces (U+0020) of a paragraph's `pieces` that stand next to an East
/// Asian character, or among spaces next to one. A piece other than a glyph, such as a tab,
/// keeps spaces apart from the text beyond it.
pub(super) fn spaces_beside_east_asian(pieces: &[Piece]) -> Vec<usize> {
    let char_at = |at: usize| match pieces.get(at) {
        Some(Piece::Glyph(glyph)) if !glyph.part => Some(glyph.ch),
        _ => None,
    };
    let east = |at: Option<usize>| {
        at.and_then(char_at)
            .is_some_and(|ch| CharacterClass::EastAsianFont.contains(ch))
    };
    let mut found = Vec::new();
    let mut start = 0;
    while start < pieces.len() {
        if char_at(start) != Some(' ') {
            start += 1;
            continue;
        }
        let end = (start..pieces.len())
            .find(|&at| char_at(at) != Some(' '))
            .unwrap_or(pieces.len());
        if east(start.checked_sub(1)) || east(Some(end)) {
            found.extend(start..end);
        }
        start = end;
    }
    found
}

/// Gives each glyph of a paragraph's `pieces` its place in the paragraph's text.
pub(super) fn place_in_paragraph(pieces: &mut [Piece]) {
    let mut in_paragraph = 0;
    for piece in pieces {
        let length = utf16_length(piece);
        if let Piece::Glyph(glyph) = piece {
            glyph.place.in_paragraph = in_paragraph;
        }
        in_paragraph += length;
    }
}

/// The features that the runs of a paragraph that draw text show and F-Office does not draw,
/// each once with the part that sets the property that shows it (**Unsupported run property**),
/// in the order in which the paragraph first shows them. The list label counts as a run of
/// its paragraph, and the paragraph mark, which draws no text, as none.
#[derive(Debug, Default)]
pub(super) struct RunFeatures(Vec<(Feature, Rc<f_office_warnings::Name>)>);

impl RunFeatures {
    /// Adds the features that the unsupported properties of `props` show, when the run draws text:
    /// `draws_text` says that it holds text, and `props` do not hide it.
    fn add(&mut self, props: &RunProps, draws_text: impl FnOnce() -> bool) {
        let mut shown = props.unsupported.shown().peekable();
        if shown.peek().is_none() || props.hidden.unwrap_or(false) || !draws_text() {
            return;
        }
        for (feature, part) in shown {
            self.push(feature, part);
        }
    }

    /// Adds `feature` where the part `part` gives it, unless the paragraph shows it there
    /// already.
    fn push(&mut self, feature: Feature, part: &Rc<f_office_warnings::Name>) {
        let seen = self
            .0
            .iter()
            .any(|(seen, seen_part)| *seen == feature && seen_part == part);
        if !seen {
            self.0.push((feature, part.clone()));
        }
    }
}

impl IntoIterator for RunFeatures {
    type Item = (Feature, Rc<f_office_warnings::Name>);
    type IntoIter = std::vec::IntoIter<(Feature, Rc<f_office_warnings::Name>)>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

/// Whether a run's content draws text: characters in the run's face, such as text, the result
/// of a field, the reference mark of a note or a check box. Tabs, breaks, the codes and marks
/// of fields, bookmarks, the marks of comments and equations, note separators, objects and
/// drawings draw none.
fn draws_text(content: &Content) -> bool {
    match content {
        Content::Text(text) => !text.is_empty(),
        Content::CheckBox(_)
        | Content::PageNumber
        | Content::PageCount
        | Content::Date(_)
        | Content::DocProperty(_)
        | Content::FileName(_)
        | Content::StyleRef(_)
        | Content::PageRef(_)
        | Content::NumberRef(_)
        | Content::If(_)
        | Content::FootnoteReference(..)
        | Content::FootnoteMark
        | Content::EndnoteReference(..)
        | Content::EndnoteMark => true,
        Content::Tab
        | Content::PositionTab { .. }
        | Content::LineBreak
        | Content::ClearingBreak
        | Content::PageBreak
        | Content::ColumnBreak
        | Content::FieldBegin
        | Content::FieldLock
        | Content::DropDown(_)
        | Content::FieldCode(_)
        | Content::FieldSeparate
        | Content::FieldEnd
        | Content::FieldMark
        | Content::HyperlinkEdge
        | Content::ControlEdge
        | Content::RemovedEdge
        | Content::Bookmark(_)
        | Content::CommentAnchor(_)
        | Content::CommentMark
        | Content::Separator
        | Content::ContinuationSeparator
        | Content::Stack(_)
        | Content::Grown(_)
        | Content::Radical(_)
        | Content::Accent(_)
        | Content::Matrix(_)
        | Content::MathBar(_)
        | Content::MathSlash(_)
        | Content::MathLimit(_)
        | Content::GroupChr(_)
        | Content::MathBox(_)
        | Content::Scripts(_)
        | Content::Advance(_)
        | Content::Floating(_)
        | Content::Object { .. }
        | Content::Drawing(_) => false,
    }
}

/// Gives an automatic or missing text color the color of the story's text, `story`, such as
/// the font color of a shape's style around a text box, when it has one. Else turns it white
/// where the shading behind the text is dark: the run's own shading, white too, since the
/// run's fill covers what lies under it, or else the paragraph's or the cell's, `behind`. A
/// highlight does not count. The shading is dark when its luma, with the weights of ITU-R
/// BT.601, is below [`AUTO_TEXT_DARK_LUMA`]. Story font color takes precedence over dark shading.
fn automatic_color(props: &mut RunProps, (behind, story): (Option<[u8; 3]>, Option<[u8; 3]>)) {
    if !matches!(props.color, None | Some(Color::Auto)) {
        return;
    }
    if let Some(rgb) = story {
        props.color = Some(Color::Rgb(rgb));
        return;
    }
    let shading = match props.shading {
        Some(Color::Rgb(rgb)) => Some(rgb),
        _ => behind,
    };
    if shading.is_some_and(|rgb| luma(rgb) < AUTO_TEXT_DARK_LUMA) {
        props.color = Some(Color::Rgb(WHITE));
    }
}

/// The luma of a color in thousandths of a step, with the weights of ITU-R BT.601.
fn luma(rgb: [u8; 3]) -> i64 {
    rgb.iter()
        .zip(LUMA_WEIGHTS)
        .map(|(channel, weight)| i64::from(*channel) * weight)
        .sum()
}

/// The file name `name` without its extension: the part before its last period, or the whole
/// name where no period follows its first character.
fn without_extension(name: &str) -> &str {
    match name.rfind('.') {
        Some(at) if at > 0 => name.get(..at).unwrap_or(name),
        _ => name,
    }
}

impl Layout<'_> {
    /// Resolves the cascade. A list level's paragraph properties come after the paragraph style
    /// and before the direct properties.
    pub(super) fn resolve(&mut self, paragraph: &Paragraph) -> Resolved {
        let (style_props, run) = self.styles.paragraph(
            paragraph.props.style.as_deref(),
            self.column.cell.as_deref(),
        );
        let mut props = style_props.clone();
        props.apply(&paragraph.props);
        // The list and the level may come from different layers of the cascade.
        let list = props.numbering.and_then(ListRef::id);
        // A paragraph whose level reads as none shows no number and takes no property of its
        // list's levels.
        // quirk: ListLevelReading::ByOctet (src/quirks.rs)
        let ilvl = props.numbering_level.unwrap_or(ListLevel::FIRST).index();
        let numbered = list.zip(ilvl);
        let label = self.tracked_label(paragraph, numbered);
        let level = numbered.and_then(|(num_id, ilvl)| self.numbering.level(num_id, ilvl).cloned());
        if let Some(level) = level {
            // A list that the paragraph names itself puts the level after its styles. A list
            // from its style puts the level right below the style that names it.
            if paragraph.props.numbering.is_some() {
                props = style_props;
                props.apply(&level.para);
            } else {
                props = self.styles.paragraph_with_level(
                    paragraph.props.style.as_deref(),
                    self.column.cell.as_deref(),
                    &level.para,
                );
            }
            props.apply(&paragraph.props);
        }
        // A conditional table style region (`w:tblStylePr`) overrides direct default alignment
        // (`left` / `start`) when the paragraph's own style chain sets no `w:jc`.
        if let Some(region_align) = self
            .column
            .cell
            .as_deref()
            .and_then(|cell| cell.region_alignment)
            && paragraph.props.alignment == Some(Alignment::Start)
            && !self
                .styles
                .paragraph_style_sets_alignment(paragraph.props.style.as_deref())
        {
            props.alignment = Some(region_align);
        }
        decisions::take_border_sides(&self.context.quirks, &mut props);
        self.device.read_paragraph_borders(&mut props);
        if decisions::drop_between_border(&self.context.quirks, &mut props) {
            let part = self.context.main;
            self.warn_of_feature(crate::Feature::BetweenBorder, part);
        }
        let in_cell = self.column.cell.is_some();
        decisions::cell_frame(&self.context.quirks, in_cell, &mut props);
        if let reading @ HtmlAutoSpacing::Fixed =
            decisions::html_auto_spacing(self.settings, &self.context.quirks)
        {
            props.html_auto_spacing = Some(reading);
        }
        let line_unit = self
            .section
            .spacing_line_pitch
            .unwrap_or(params::SPACING_LINE_UNIT);
        props.resolve_line_spacing(line_unit);
        let label_shift = label
            .as_ref()
            .map_or(Length::ZERO, |label| self.label_shift(label, &run, &props));
        Resolved {
            props,
            run,
            label,
            label_shift,
        }
    }

    /// Counts a paragraph in its list of the new text, `list`, and in its list of the original
    /// text, and returns its label. A paragraph whose mark is deleted is not in the new text,
    /// and one whose mark is inserted is not in the original text. In the original text, the
    /// paragraph has its properties from before a tracked change of them, and the paragraph's
    /// indents stay those of the new text.
    fn tracked_label(
        &mut self,
        paragraph: &Paragraph,
        list: Option<(NonZeroU32, usize)>,
    ) -> Option<Label> {
        // The empty paragraph that ends a section neither shows a label nor counts in its list.
        let flags = paragraph.props.flags();
        if flags.section_end || flags.continuous_end {
            return None;
        }
        let change = paragraph.props.mark_change;
        let original_list = match &paragraph.props.original {
            Some(original) => {
                let props = self
                    .styles
                    .paragraph_properties_without_list_level(original, self.column.cell.as_deref());
                let ilvl = props.numbering_level.unwrap_or(ListLevel::FIRST).index();
                props.numbering.and_then(ListRef::id).zip(ilvl)
            }
            None => list,
        };
        let new = list.filter(|_| change != Some(MarkChange::Deleted));
        let original = original_list.filter(|_| change != Some(MarkChange::Inserted));
        self.numbering.next_label(new, original)
    }

    /// The run properties of a paragraph mark: the paragraph's, then the mark's character
    /// style (`w:rStyle` in `w:pPr/w:rPr`), then the mark's own.
    pub(super) fn mark_props(&self, run: &RunProps, props: &ParaProps) -> RunProps {
        mark_run_props(self.styles, run, props)
    }

    /// The stop of a positional tab: the left edge, the middle or the right edge of the text
    /// column, between the margins.
    fn position_stop(&self, kind: TabKind, leader: Option<char>) -> TabStop {
        let width = self.column.width;
        let position = match kind {
            TabKind::Center => width.div_toward_zero(2),
            TabKind::Right => width,
            _ => Length::ZERO,
        };
        TabStop {
            position,
            kind,
            leader,
        }
    }

    /// How far a label starts before the start of the first line: its width when it ends
    /// there (`w:lvlJc="right"`), half of it when it is centered there.
    fn label_shift(&mut self, label: &Label, run: &RunProps, props: &ParaProps) -> Length {
        if label.align == LabelAlign::Left {
            return Length::ZERO;
        }
        let mut label_props = self.mark_props(run, props);
        label_props.apply(&label.run);
        let width = if label.picture {
            label
                .bullet_image
                .as_ref()
                .and_then(|image| self.picture_bullet_size(image, label.bullet_size, &label_props))
                .map_or(Length::ZERO, |(width, _)| width)
        } else {
            let mut glyphs = Vec::new();
            self.shaper.measure(&label_props, &label.text, &mut glyphs);
            glyphs.iter().map(|g| g.advance).sum()
        };
        if label.align == LabelAlign::Center {
            width.div_toward_zero(2)
        } else {
            width
        }
    }

    /// Size `(width, height)` of a picture bullet for `image` (with optional declared
    /// `shape_size` from `v:shape/@style` or `wp:extent`) at the label's run properties `props`:
    /// `base = max(2 pt, font_size - 2 pt)`, scaled by `shape_size / natural_height` (or
    /// `natural_size / natural_height` when `shape_size` is absent) and snapped to device dots.
    fn picture_bullet_size(
        &self,
        image: &Image,
        shape_size: Option<(Length, Length)>,
        props: &RunProps,
    ) -> Option<(Length, Length)> {
        let (nat_w, nat_h) = bullet_natural_size(image)?;
        let (box_w, box_h) = shape_size
            .filter(|(w, h)| *w > Length::ZERO && *h > Length::ZERO)
            .unwrap_or((nat_w, nat_h));
        let font_size = Length::from_half_points(props.drawn_half_points())?;
        let two_pt = Length::from_points(2)?;
        let base = (font_size - two_pt).max(two_pt);
        let denom = nat_h.max(box_h);
        let scale = |side: Length| {
            Some(Length::from_units(
                i64::try_from(div_round_i128(
                    i128::from(base.units()) * i128::from(side.units()),
                    i128::from(denom.units()),
                ))
                .ok()?,
            ))
        };
        let dot = Length::from_units(Length::UNITS_PER_DOT);
        let width = self.device.snap(scale(box_w)?).max(dot);
        let height = self.device.snap(scale(box_h)?).max(dot);
        Some((width, height))
    }

    /// The color that the story gives its automatic text: the font color of the shape around
    /// a text box, if any.
    fn story_text_color(&self) -> Option<[u8; 3]> {
        match self.story.as_ref()?.kind {
            super::StoryKind::TextBox { text_color, .. } => text_color,
            _ => None,
        }
    }

    /// Whether the story is the text of a SmartArt graphic's shape.
    pub(in crate::layout) fn smartart_text(&self) -> bool {
        self.story.as_ref().is_some_and(|story| {
            matches!(
                story.kind,
                super::StoryKind::TextBox {
                    box_text: crate::floating::BoxText::SmartArt,
                    ..
                }
            )
        })
    }

    /// The shading that the text of a paragraph stands on: the paragraph's own, or else the
    /// fill of the table cell that holds it, or else the page color. A white fill covers the
    /// page color as any other fill does.
    fn text_background(&self, props: &ParaProps) -> Option<[u8; 3]> {
        let fill = |color: Option<Color>| match color {
            Some(Color::Rgb(rgb)) => Some(rgb),
            _ => None,
        };
        fill(props.shading)
            .or_else(|| fill(self.column.cell.as_deref()?.shading))
            .or(self.settings.page_color)
    }

    /// Measures a paragraph and breaks it into lines, and returns them with the face of its
    /// paragraph mark and the features that its runs and its list label that draw text show.
    pub(super) fn prepare(
        &mut self,
        paragraph: &Paragraph,
        resolved: &Resolved,
    ) -> (Vec<Line>, Option<FaceIndex>, RunFeatures) {
        self.prepare_with(paragraph, resolved, None)
    }

    /// As [`Self::prepare`], clearing `cell_before`'s space before when a leading page or column
    /// break in a table cell is ignored in a mode that drops space before after a page break.
    pub(super) fn prepare_with(
        &mut self,
        paragraph: &Paragraph,
        resolved: &Resolved,
        cell_before: Option<&mut ParaProps>,
    ) -> (Vec<Line>, Option<FaceIndex>, RunFeatures) {
        let (pieces, mark_face, features) = self.paragraph_pieces(paragraph, resolved, cell_before);
        let frame = self.frame(resolved);
        let mut lines = break_lines(&pieces, &frame);
        if resolved.props.flags().continuous_break_end
            && self.column.cell.is_none()
            && self.story.is_none()
        {
            super::paragraph::drop_trailing_empty_break_line(&mut lines);
        }
        (lines, mark_face, features)
    }

    /// The width that a paragraph needs at the least: its widest word, with its left indent
    /// (or the first line's start, when that lies further right) and its right indent.
    pub(super) fn least_width(&mut self, paragraph: &Paragraph, resolved: &Resolved) -> Length {
        let (pieces, ..) = self.paragraph_pieces(paragraph, resolved, None);
        let frame = self.frame(resolved);
        let right = resolved.props.indent_right.unwrap_or(Length::ZERO);
        crate::lines::widest_word(&pieces, &frame)
            + frame.start.max(frame.first_start).max(Length::ZERO)
            + right.max(Length::ZERO)
    }

    /// The width of a paragraph's widest line where only its own breaks end its lines, as in a
    /// text body that does not wrap, with its indents.
    pub(super) fn unbroken_width(&mut self, paragraph: &Paragraph, resolved: &Resolved) -> Length {
        let (pieces, ..) = self.paragraph_pieces(paragraph, resolved, None);
        let mut frame = self.frame(resolved);
        let unbounded = Length::from_units(Length::FILE_LIMIT);
        frame.first_width += unbounded;
        frame.width += unbounded;
        frame.area_width += unbounded;
        let right = resolved.props.indent_right.unwrap_or(Length::ZERO);
        let widest = break_lines(&pieces, &frame)
            .iter()
            .enumerate()
            .map(|(index, line)| {
                let start = if index == 0 {
                    frame.first_start
                } else {
                    frame.start
                };
                line.fit_width() + start.max(Length::ZERO)
            })
            .max()
            .unwrap_or(Length::ZERO);
        widest + right.max(Length::ZERO)
    }

    /// The face of a paragraph mark or manual line break with properties `props` in a paragraph
    /// whose direction is `direction`.
    fn mark_face_of(
        &mut self,
        props: &RunProps,
        direction: ParagraphDirection,
    ) -> Option<FaceIndex> {
        decisions::mark_face(
            &self.context.quirks,
            props.uses_complex_formatting(),
            direction.is_rtl(),
            |kind| match kind {
                decisions::MarkFaceKind::Complex => self.shaper.complex_face(props),
                decisions::MarkFaceKind::ComplexSize => {
                    let mut sized = props.clone();
                    sized.size = props.size_cs;
                    self.shaper.face(&sized, true)
                }
                decisions::MarkFaceKind::Ascii => self.shaper.face(props, true),
            },
        )
    }

    /// Measures a paragraph into its pieces, with its list label, and returns them with the
    /// face of its paragraph mark and the features that its runs and its label that draw text
    /// show.
    fn paragraph_pieces(
        &mut self,
        paragraph: &Paragraph,
        resolved: &Resolved,
        cell_before: Option<&mut ParaProps>,
    ) -> (Vec<Piece>, Option<FaceIndex>, RunFeatures) {
        let base_run = &resolved.run;
        let mark = self.mark_props(base_run, &resolved.props);
        let right_to_left = resolved.props.bidi.unwrap_or(false);
        let direction = if right_to_left {
            ParagraphDirection::RightToLeft
        } else {
            ParagraphDirection::LeftToRight
        };
        let mark_face = self.mark_face_of(&mark, direction);
        let mut pieces = Vec::new();
        let mut features = RunFeatures::default();
        let behind = self.text_background(&resolved.props);
        if let Some(label) = resolved.label.as_ref() {
            self.measure_label(
                label,
                (&mark, behind, right_to_left),
                (&mut pieces, &mut features),
            );
        }
        let previous = self.number_context.take();
        self.number_context = resolved.label.as_ref().map(|label| label.reference.clone());
        let rules = self.word_rules(&resolved.props);
        // A paragraph inside this one, such as one of a text box, keeps its own runs.
        let outer = std::mem::replace(&mut self.hyphen_runs, rules.map(|_| Vec::new()));
        let outer_bidi = std::mem::replace(&mut self.paragraph_bidi, direction);
        let offset = pieces.len();
        pieces.extend(self.measure(paragraph, base_run, behind, &mut features));
        self.paragraph_bidi = outer_bidi;
        let runs = std::mem::replace(&mut self.hyphen_runs, outer);
        self.number_context = previous;
        self.auto_space(&mut pieces, resolved);
        self.stretching_no_break_spaces(pieces.get_mut(offset..).unwrap_or_default());
        if let (Some(rules), Some(runs)) = (rules, runs) {
            pieces = hyphen_points::with_points(pieces, offset, &runs, rules);
        }
        if self.column.cell.is_some() {
            decisions::cell_breaks(&self.context.quirks, &mut pieces, offset, cell_before);
        }
        let breaking = decisions::line_breaking(&self.context.quirks, self.settings.mode_rules);
        label_after_page_breaks(&mut pieces, offset, breaking.leading_breaks);
        (pieces, mark_face, features)
    }

    /// Adds Word's space of a quarter em between an East Asian character and a digit
    /// (`w:autoSpaceDN`) or a Latin letter (`w:autoSpaceDE`) next to it, to the advance of the
    /// first of the two. Both are on unless the paragraph turns them off, and only a document
    /// whose run defaults name a font made for East Asian text in their East Asian slot gets
    /// them, whatever the language.
    fn auto_space(&self, pieces: &mut [Piece], resolved: &Resolved) {
        let flags = resolved.props.flags();
        let (digits, latin) = (flags.auto_space_digits, flags.auto_space_latin);
        if (!digits && !latin)
            || !self
                .shaper
                .names_east_asian_default(self.styles.default_run())
        {
            return;
        }
        for index in 1..pieces.len() {
            let (Some(Piece::Glyph(a)), Some(Piece::Glyph(b))) =
                (pieces.get(index - 1), pieces.get(index))
            else {
                continue;
            };
            let spaced = match (spacing_class(a.ch), spacing_class(b.ch)) {
                (Spacing::EastAsian, Spacing::Digit) | (Spacing::Digit, Spacing::EastAsian) => {
                    digits
                }
                (Spacing::EastAsian, Spacing::Latin) | (Spacing::Latin, Spacing::EastAsian) => {
                    latin
                }
                _ => false,
            };
            let balanced =
                self.settings.full_width_spacing == crate::styles::FullWidthSpacing::Twice;
            let space = self.shaper.faces().get(a.face).map_or_default(|f| {
                decisions::east_asian_auto_space(&self.context.quirks, f.size, &f.metrics, balanced)
            });
            if let (true, Some(Piece::Glyph(a))) = (spaced, pieces.get_mut(index - 1)) {
                a.advance += space.advance;
                a.auto_space += space.extra;
                a.trailing_auto_space += space.advance;
            }
        }
    }

    /// Marks each no-break space of a paragraph's runs (`pieces`) as one that a justified line
    /// stretches and shrinks as a plain space, where the target and the document's compatibility
    /// mode and run defaults give it that share (`NoBreakSpaceShare`): the run defaults are Word's
    /// own template's, or their East Asian font is one made for East Asian text. A no-break space
    /// that is the first glyph of a text object keeps its width.
    fn stretching_no_break_spaces(&self, pieces: &mut [Piece]) {
        let defaults = self.styles.template_run_defaults()
            || self
                .shaper
                .names_east_asian_default(self.styles.default_run());
        let stretch = decisions::no_break_spaces_stretch(
            &self.context.quirks,
            self.settings.mode_rules,
            defaults,
        );
        if !stretch {
            return;
        }
        for piece in pieces {
            if let Piece::Glyph(glyph) = piece
                && glyph.ch == '\u{a0}'
                && glyph.space == SpaceKind::Free
                && !glyph.starts_run
            {
                glyph.space = SpaceKind::NoBreak;
            }
        }
    }

    /// Adds the pitch of the section's character grid to each glyph whose run snaps to the grid
    /// (`w:rPr/w:snapToGrid`, on by default; runs listed in `off_grid` turned it off): the whole
    /// pitch to a full-width character, and half of it to any other.
    fn char_grid(&self, pieces: &mut [Piece], off_grid: &[u32]) {
        let Some(pitch) = self.section.char_pitch else {
            return;
        };
        for piece in pieces {
            if let Piece::Glyph(glyph) = piece
                && !glyph.place.run.is_some_and(|run| off_grid.contains(&run))
            {
                glyph.advance += if CharacterClass::FullWidthCell.contains(glyph.ch) {
                    pitch
                } else {
                    pitch.div_toward_zero(2)
                };
            }
        }
    }

    /// Which automatic hyphenation points the words of a paragraph with the properties `props`
    /// take, or `None` where the document's automatic hyphenation is off, the target
    /// hyphenates no language or the paragraph keeps its words whole
    /// (`w:suppressAutoHyphens`). The compatibility mode decides the fewest letters before and
    /// after a point.
    fn word_rules(&self, props: &ParaProps) -> Option<WordRules> {
        let hyphenation = self.settings.hyphenation?;
        decisions::hyphenation(&self.context.quirks, || {
            (!props.flags().suppress_auto_hyphens).then(|| WordRules {
                least: self.settings.mode_rules.hyphen_least_letters(),
                capitals: hyphenation.capitals,
            })
        })
    }

    /// The indents, tab stops and space shrinking of a paragraph's lines in the column.
    pub(super) fn frame(&self, resolved: &Resolved) -> Frame {
        let props = &resolved.props;
        let column = self.column.width;
        // The left indent of a hanging indent is one more tab stop. In a list paragraph of a
        // document that turns that off, in a compatibility mode that still reads the
        // setting, the indent comes after the custom stops.
        let indent_last = resolved.label.is_some()
            && !self.settings.indent_is_numbering_tab_stop
            && self.settings.mode_rules.reads_numbering_indent_setting();
        let left = props.indent_left.unwrap_or(Length::ZERO);
        let right = props.indent_right.unwrap_or(Length::ZERO);
        // A label that ends or is centered at the start of the first line starts before it.
        let first = props.indent_first.unwrap_or(Length::ZERO) - resolved.label_shift;
        let overflow_punct = self.overflow_punct(props);
        Frame {
            first_width: column - left - right - first,
            width: column - left - right,
            area_width: column,
            first_start: left + first,
            start: left,
            tabs: {
                let indent = (first < Length::ZERO).then_some(left);
                let mut tabs = Tabs::new(props.tab_stops(), self.settings.default_tab_stop, indent);
                if indent_last {
                    tabs = tabs.with_indent_after_custom_stops();
                }
                if self.settings.mode_rules.truncates_negative_default_tabs() {
                    tabs = tabs.with_truncated_negative_default_tabs();
                }
                tabs
            },
            // A justified line whose joints after a seen take kashidas takes one more word by
            // shrinking its spaces as another justified line does, but the stretch per gap that
            // it would need without the word spreads over its letter joints too.
            shrink: {
                let shrink = shrink(
                    props.alignment,
                    self.settings.mode_rules,
                    decisions::justification(&self.context.quirks, self.settings),
                );
                if decisions::kashida_joints(&self.context.quirks, self.settings, props.kashidas)
                    == Some(decisions::KashidaJoints::SeensThenFinals)
                {
                    Shrink {
                        joints: KASHIDA_JOINT_GAPS,
                        ..shrink
                    }
                } else {
                    shrink
                }
            },
            thai_keeps_spaces: props.alignment == Some(Alignment::ThaiDistribute),
            end_space_fit: decisions::end_space_fit(&self.context.quirks, props.flags().bidi),
            kinsoku: self.paragraph_kinsoku(
                props,
                resolved.run.east_asian_script(),
                overflow_punct,
            ),
            joined_spaces: self.settings.mode_rules.joins_space_runs(),
            breaking: decisions::line_breaking(&self.context.quirks, self.settings.mode_rules),
            limits_past_end: self.settings.mode_rules.limits_text_past_the_line_end(),
            punctuation: self.line_punctuation(props),
            // The zone holds only in the older compatibility modes.
            hyphenation: self
                .word_rules(props)
                .and(self.settings.hyphenation)
                .map(|hyphenation| crate::lines::Hyphenation {
                    zone: self
                        .settings
                        .mode_rules
                        .hyphenation_zone_holds()
                        .then_some(hyphenation.zone),
                    limit: hyphenation.limit,
                }),
            overflow_punct,
        }
    }

    /// Punctuation compression settings for a paragraph's lines: justified blank-half shrinking
    /// under `compressPunctuation`, plus trailing closing-mark blank-half trimming in
    /// compatibility modes before `TRAILING_PUNCTUATION_TRIM_MODE` regardless of alignment.
    fn line_punctuation(&self, props: &ParaProps) -> Option<crate::lines::Compression> {
        if self.settings.punctuation != crate::styles::Punctuation::Compressed {
            return None;
        }
        let justified = props.alignment.is_some_and(Alignment::justified);
        let script = self.east_asian_punctuation_script();
        let trailing_trim = if self
            .settings
            .mode_rules
            .trims_trailing_closing_punctuation()
        {
            match script {
                Some(EastAsianScript::Japanese) => crate::lines::TrailingTrim::NonJapaneseCentered,
                Some(EastAsianScript::Traditional) => {
                    crate::lines::TrailingTrim::NonTraditionalCentered
                }
                _ => crate::lines::TrailingTrim::Closing,
            }
        } else {
            crate::lines::TrailingTrim::None
        };
        if !justified && trailing_trim == crate::lines::TrailingTrim::None {
            return None;
        }
        Some(crate::lines::Compression {
            ratio: if justified {
                params::PUNCTUATION_SHRINK_RATIO
            } else {
                0
            },
            middle_dot: script == Some(EastAsianScript::Japanese),
            trailing_trim,
        })
    }

    /// Whether overflowing trailing punctuation marks hang past the right margin (`w:overflowPunct`)
    /// rather than wrapping: outside table cells, in left-to-right paragraphs with `w:overflowPunct`
    /// on, when `w:docDefaults` names an East Asian font, and either the compatibility mode precedes
    /// `HANGING_PUNCTUATION_JUSTIFIED_MODE` (all alignments, regardless of `w:kinsoku`) or the
    /// paragraph is justified with `w:kinsoku` enabled.
    fn overflow_punct(&self, props: &ParaProps) -> crate::lines::OverflowPunct {
        let flags = props.flags();
        if !flags.overflow_punct {
            return crate::lines::OverflowPunct::Off;
        }
        let active = self.column.cell.is_none()
            && !flags.bidi
            && self
                .shaper
                .names_east_asian_default(self.styles.default_run())
            && (self
                .settings
                .mode_rules
                .hangs_punctuation_on_all_alignments()
                || (props.alignment.is_some_and(Alignment::justified) && flags.kinsoku));
        if active {
            crate::lines::OverflowPunct::Hang
        } else {
            crate::lines::OverflowPunct::Warn
        }
    }

    /// Line-breaking and kinsoku rules for a paragraph, from its East Asian language, the
    /// document's East Asian language, `w:kinsoku`, `w:overflowPunct`, `w:wordWrap`, and
    /// compatibility mode.
    fn paragraph_kinsoku(
        &self,
        props: &ParaProps,
        run_script: Option<EastAsianScript>,
        overflow_punct: crate::lines::OverflowPunct,
    ) -> Option<Kinsoku> {
        let flags = props.flags();
        let break_words =
            !flags.word_wrap && self.settings.mode_rules.breaks_words_when_word_wrap_off();
        let sets = |script: EastAsianScript| {
            let full = Kinsoku::of(script);
            let base = if flags.kinsoku {
                full
            } else if overflow_punct == crate::lines::OverflowPunct::Hang {
                Kinsoku::FREE.with_hanging_of(full)
            } else {
                Kinsoku::FREE
            };
            if flags.overflow_punct {
                base
            } else {
                base.without_hanging()
            }
        };
        let non_korean_mode = if break_words {
            CharBreak::Any
        } else {
            CharBreak::CjkNonHangul
        };
        match (run_script, self.settings.east_asian_script) {
            (Some(EastAsianScript::Korean), _) => break_words
                .then(|| sets(EastAsianScript::Korean).with_char_break(CharBreak::FullWidth)),
            (Some(script), _) => Some(sets(script).with_char_break(non_korean_mode)),
            (None, Some(_)) => Some(
                Kinsoku::FREE
                    .with_restricted(flags.kinsoku)
                    .with_char_break(non_korean_mode),
            ),
            (None, None) => break_words.then(|| {
                Kinsoku::FREE
                    .with_restricted(flags.kinsoku)
                    .with_char_break(CharBreak::Any)
            }),
        }
    }

    /// Measures a list label with the paragraph mark's properties and the level's run
    /// properties, followed by its suffix. The mark's underline does not reach the label,
    /// which only the level's own run properties underline, and the mark's bold and italic do
    /// not reach a label in a symbol font ([`symbol_label_style`]). The label of a paragraph
    /// that is right to left (`right_to_left`) is a right-to-left run
    /// ([`Self::list_label_props`]).
    fn measure_label(
        &mut self,
        label: &Label,
        (mark, behind, right_to_left): (&RunProps, Option<[u8; 3]>, bool),
        (pieces, features): (&mut Vec<Piece>, &mut RunFeatures),
    ) {
        let mut props = self.list_label_props(label, mark, right_to_left);
        automatic_color(&mut props, (behind, self.story_text_color()));
        self.drawn_effects(&mut props);
        features.add(&props, || !label.picture && !label.text.is_empty());
        // A picture bullet shows a picture instead of the level's text, scaled from the label's
        // font size; when the image is missing or unreadable, warn when the label is not hidden.
        let width = if label.picture {
            if let Some(image) = label.bullet_image.as_ref()
                && let Some((width, height)) =
                    self.picture_bullet_size(image, label.bullet_size, &props)
            {
                self.output.pictures.push(Picture {
                    embed: String::new(),
                    image: Some(image.clone()),
                    opacity: Opacity::FULL,
                    color: ImageColor::default(),
                    left: Length::ZERO,
                    top: Length::ZERO,
                    width,
                    height,
                    crop: Edges::default(),
                    turn: None,
                    drops: false,
                    line: None,
                    shadow: None,
                    soft_edge: None,
                    glow: None,
                    reflection: None,
                    geometry: f_office_drawingml::shape::Geometry::Rect,
                    scale_steps: None,
                    on_device_dots: true,
                });
                pieces.push(Piece::Object {
                    width,
                    height,
                    raised: props.position.unwrap_or(Length::ZERO),
                    picture: Some(self.output.pictures.len() - 1),
                    drawing: None,
                    underlined: false,
                    run_face: None,
                    joins_before: false,
                });
                width
            } else {
                if !props.hidden.unwrap_or(false) {
                    features.push(Feature::PictureBullet, self.numbering.part());
                }
                Length::ZERO
            }
        } else {
            let mut glyphs = Vec::new();
            self.shaper.measure_label(&props, &label.text, &mut glyphs);
            let width: Length = glyphs.iter().map(|g| g.advance).sum();
            pieces.extend(glyphs.into_iter().map(|glyph| {
                Piece::Glyph(crate::text::Glyph {
                    label: true,
                    ..glyph
                })
            }));
            width
        };
        match label.suffix {
            // The tab after a label has no underline.
            Suffix::Tab => {
                let plain = RunProps {
                    underline: Some(Underline::None),
                    ..props.clone()
                };
                pieces.push(Piece::Tab(self.shaper.face(&plain, true)));
            }
            Suffix::Space => self.measure_content(&Content::Text(" ".to_owned()), &props, pieces),
            Suffix::Nothing => {}
            // The text starts the legacy indent after the start of the label, and at least
            // the legacy space after its end, without a tab.
            Suffix::Legacy { space, indent } => pieces.push(Piece::Object {
                width: (indent - width).max(space),
                height: Length::ZERO,
                raised: Length::ZERO,
                picture: None,
                drawing: None,
                underlined: false,
                run_face: None,
                joins_before: false,
            }),
        }
        if props.snap_to_grid.unwrap_or(true) {
            self.char_grid(pieces, &[]);
        }
    }

    /// The run properties of a list label: the paragraph mark's without its underline, with the
    /// level's own on top. The label is a right-to-left run, with complex script properties,
    /// only in a paragraph that is right to left (`right_to_left`), whatever the mark's
    /// direction, and never in a symbol font; elsewhere the mark's `w:rtl` does not reach it.
    fn list_label_props(&self, label: &Label, mark: &RunProps, right_to_left: bool) -> RunProps {
        list_label_props(&self.shaper, label, mark, right_to_left)
    }

    /// Places a mark of a stack, with the face of its run. At the end of a fraction, a part
    /// whose ink comes closer to the bar than the gap minimum moves away from it.
    fn measure_stack(
        &mut self,
        mark: StackMark,
        props: &RunProps,
        (stacks, pieces): (&mut Vec<OpenStack>, &mut Vec<Piece>),
    ) {
        let face = self.shaper.face(props, true);
        let lead = match (mark, face) {
            (StackMark::StartBeside(operator), Some(face)) => {
                self.shaper.italic_correction(face, operator)
            }
            _ => Length::ZERO,
        };
        let correction = |part: &[Piece]| last_italic_correction(&self.shaper, part);
        if let Some(stacked) = stack(stacks, pieces, mark, (face, lead, &correction)) {
            gap_minimums::keep((&mut self.shaper, self.device), pieces, &stacked);
        }
    }

    /// Places a mark of a grown delimiter, with the properties of its run, on a target that grows
    /// delimiters: the mark ends the text before it, and the delimiter's end draws the glyphs of
    /// its characters. On the other targets the marks place nothing and end no text, and the
    /// thin spaces beside a delimiter lose their width.
    fn measure_grown(
        &mut self,
        mark: GrownMark,
        props: &RunProps,
        (pending, grown, pieces): (&mut Option<Pending>, &mut Grown, &mut Vec<Piece>),
    ) {
        if !decisions::grows_delimiters(&self.context.quirks) {
            if matches!(mark, GrownMark::SpaceBefore | GrownMark::SpaceAfter) {
                self.measure_pending(pending.take(), pieces);
                let last = pieces.len().checked_sub(1);
                grown_delimiters::hide(pieces, last);
            }
            return;
        }
        self.measure_pending(pending.take(), pieces);
        grown_delimiters::mark(
            (&mut self.shaper, self.device),
            (grown, pieces),
            mark,
            props,
        );
    }

    /// Leaves out of the unsupported properties of `props` the text effects that the target
    /// draws: `w14:shadow`, `w14:glow`, `w14:reflection`, and legacy WordprocessingML text effects
    /// (`w:shadow`, `w:outline`, `w:emboss`, `w:imprint`).
    fn drawn_effects(&self, props: &mut RunProps) {
        let (shadow, glow, reflection, legacy) = self.shaper.draws_text_effects(props);
        if shadow {
            props.unsupported.shadow_drawn();
        }
        if glow {
            props.unsupported.glow_drawn();
        }
        if reflection {
            props.unsupported.reflection_drawn();
        }
        if legacy {
            props.unsupported.legacy_effects_drawn();
        }
    }

    /// Measures the runs of a paragraph. The text of runs that follow each other with the same
    /// properties is measured as one text, so that ligatures join across them.
    fn measure(
        &mut self,
        paragraph: &Paragraph,
        base_run: &RunProps,
        behind: Option<[u8; 3]>,
        features: &mut RunFeatures,
    ) -> Vec<Piece> {
        let mut pieces = Vec::new();
        let mut pending: Option<Pending> = None;
        let mut stacks = Vec::new();
        let mut grown = Grown::default();
        let mut structures = OpenStructures::default();
        // The index of the next floating drawing, in the order of the paragraph's content.
        let mut drawings = 0;
        // The pieces before this index have the index of their run.
        let mut named = 0;
        let mut index = 0;
        let mut off_grid = Vec::new();
        for (place, run) in paragraph.runs.iter().enumerate() {
            index = u32::try_from(place).unwrap_or(u32::MAX);
            let mut props = self.run_props(run, base_run);
            record_off_grid(&mut off_grid, index, &props);
            automatic_color(&mut props, (behind, self.story_text_color()));
            self.drawn_effects(&mut props);
            features.add(&props, || run.content.iter().any(draws_text));
            let mut first = true;
            for content in &run.content {
                match (content, &mut pending) {
                    // Runs whose bidi languages have different classes join their letters.
                    (Content::Text(text), Some(joined)) if joined.props.joins(&props) => {
                        joined.start_class(props.bidi_class);
                        if first {
                            joined.start_run(index);
                        }
                        joined.join(text, run, first);
                    }
                    (Content::Text(text), _) => {
                        self.measure_pending(pending.take(), &mut pieces);
                        pending = Some(
                            Pending::new(&props, text, (run, index))
                                .at_run_head(first)
                                .reading(RevisionReading::of(&self.context.quirks)),
                        );
                    }
                    // A field mark, and on some targets the edge of a hyperlink, of a content
                    // control or of removed text, starts a text object at the text after it;
                    // the text on both sides is still one text.
                    (
                        Content::FieldMark
                        | Content::HyperlinkEdge
                        | Content::ControlEdge
                        | Content::RemovedEdge,
                        Some(joined),
                    ) => {
                        joined.field_mark |=
                            decisions::starts_text_object(&self.context.quirks, content);
                    }
                    (Content::Stack(mark), _) => {
                        self.measure_pending(pending.take(), &mut pieces);
                        self.measure_stack(*mark, &props, (&mut stacks, &mut pieces));
                    }
                    (Content::Grown(mark), _) => {
                        self.measure_grown(*mark, &props, (&mut pending, &mut grown, &mut pieces));
                    }
                    (
                        Content::Radical(_)
                        | Content::Accent(_)
                        | Content::MathBar(_)
                        | Content::MathSlash(_)
                        | Content::MathLimit(_)
                        | Content::GroupChr(_)
                        | Content::MathBox(_)
                        | Content::Matrix(_)
                        | Content::Scripts(_),
                        _,
                    ) => {
                        self.measure_pending(pending.take(), &mut pieces);
                        structures.mark(
                            (&mut self.shaper, self.device),
                            &mut pieces,
                            content,
                            &props,
                        );
                    }
                    // A drawing that waits for the line of its anchor leaves a mark there, so
                    // that the line that holds the mark places it, and so does a drawing placed
                    // down from its paragraph, whose layout finds the page of its anchor by the
                    // mark. A drawing with no piece before it lies on the first line, which
                    // counts from the paragraph's top as the paragraph does, and leaves none.
                    (Content::Floating(drawing), _) => {
                        self.measure_pending(pending.take(), &mut pieces);
                        if !pieces.is_empty() && self.marks_anchor(drawing) {
                            pieces.push(Piece::Anchor(drawings));
                        }
                        drawings += 1;
                    }
                    _ => self.measure_other(content, &props, (&mut pending, &mut pieces)),
                }
                first &= !matches!(content, Content::Text(_));
                name_runs(&mut pieces, named, index);
                named = pieces.len();
            }
        }
        self.measure_pending(pending, &mut pieces);
        name_runs(&mut pieces, named, index);
        self.balance_spaces(&mut pieces);
        self.char_grid(&mut pieces, &off_grid);
        place_in_paragraph(&mut pieces);
        pieces
    }

    /// Ends the text that waits for the next run before a content that is not text, and measures
    /// the content. A bookmark's start ends nothing on a target that measures the text on both
    /// sides of it as one.
    fn measure_other(
        &mut self,
        content: &Content,
        props: &RunProps,
        (pending, pieces): (&mut Option<Pending>, &mut Vec<Piece>),
    ) {
        if decisions::ends_text(&self.context.quirks, content) {
            self.measure_pending(pending.take(), pieces);
        }
        self.measure_content(content, props, pieces);
    }

    /// Gives the spaces of a paragraph's `pieces` that [`spaces_beside_east_asian`] finds half
    /// an em, when the document's settings say so.
    fn balance_spaces(&self, pieces: &mut [Piece]) {
        if !self.shaper.balances_spaces() {
            return;
        }
        for at in spaces_beside_east_asian(pieces) {
            if let Some(Piece::Glyph(glyph)) = pieces.get_mut(at) {
                self.shaper.balance_space(glyph);
            }
        }
    }

    /// Measures text that waits for the runs after it, and marks the first glyph of each run in
    /// it.
    fn measure_pending(&mut self, pending: Option<Pending>, pieces: &mut Vec<Piece>) {
        let Some(Pending {
            props,
            text,
            starts,
            joins,
            buffer_starts,
            classes,
            runs,
            starts_at_run_head,
            ..
        }) = pending
        else {
            return;
        };
        let start = pieces.len();
        let glyph_at = |shaper: &mut crate::text::Shaper<'_>, at: usize| {
            start + shaper.count(&props, text.get(..at).unwrap_or(""))
        };
        let mut firsts = vec![start];
        for &at in &starts {
            firsts.push(glyph_at(&mut self.shaper, at));
        }
        let buffer_firsts: Vec<usize> = buffer_starts
            .iter()
            .map(|&at| glyph_at(&mut self.shaper, at))
            .collect();
        let join_firsts: Vec<usize> = joins
            .iter()
            .map(|&at| glyph_at(&mut self.shaper, at))
            .collect();
        let run_firsts: Vec<(usize, u32)> = runs
            .iter()
            .map(|&(at, run)| (glyph_at(&mut self.shaper, at), run))
            .collect();
        let classes: Vec<(usize, Option<BidiLanguageClass>)> = classes
            .into_iter()
            .map(|(at, class)| (glyph_at(&mut self.shaper, at), class))
            .collect();
        self.measure_content(&Content::Text(text), &props, pieces);
        self.correct_italics_at_joins(pieces, &join_firsts);
        self.keep_hyphen_run(&props, (start, pieces.len()));
        // Each run of the joined text has the class of its own bidi language. A number that
        // Word computes keeps the class that the reader of fields gives it.
        if props.field_rtl.is_none() {
            set_classes(pieces, &classes);
        }
        if self.shaper.has_non_default_east_asia(&props) {
            add_east_asian_leading_splits(pieces, &mut firsts, starts_at_run_head);
        }
        mark_glyphs(pieces, &firsts, |glyph| glyph.starts_run = true);
        name_joined_runs(pieces, &run_firsts);
        mark_glyphs(pieces, &buffer_firsts, |glyph| {
            glyph.place.starts_buffer = true;
        });
        // Word counts the pieces of the text from the start of each text object: from a run
        // whose properties or revision IDs differ from the run before, and from a run that
        // starts a text buffer. The count goes through a run that continues the text object
        // of the run before it.
        let mut in_run = 0;
        for (index, piece) in pieces.iter_mut().enumerate().skip(start) {
            if firsts.contains(&index) {
                in_run = 0;
            }
            let length = utf16_length(piece);
            if let Piece::Glyph(glyph) = piece {
                glyph.place.in_run = in_run;
            }
            in_run += length;
        }
    }

    /// Keeps the measured text of the pieces from `start` to `end` among the texts whose words may
    /// take automatic hyphenation points, with the hyphen of its properties, when a paragraph
    /// that hyphenates is measured and the target hyphenates the text's language.
    fn keep_hyphen_run(&mut self, props: &RunProps, (start, end): (usize, usize)) {
        if self.hyphen_runs.is_none() || start == end {
            return;
        }
        let Some(language) = props
            .lang
            .as_deref()
            .and_then(|tag| decisions::hyphenation_language(&self.context.quirks, tag))
        else {
            return;
        };
        // The hyphen is a hyphen-minus of the run, in the face and on the font side that the run
        // gives that character.
        let mut hyphen = Vec::new();
        self.shaper.measure(props, "-", &mut hyphen);
        if let (Some(&hyphen), Some(runs)) = (hyphen.first(), self.hyphen_runs.as_mut()) {
            runs.push(HyphenRun {
                start,
                end,
                language,
                hyphen,
            });
        }
    }

    /// The rule of a note separator, `width` long, in the face of its run.
    fn measure_rule(&mut self, width: Length, props: &RunProps, pieces: &mut Vec<Piece>) {
        pieces.extend(
            self.shaper
                .face(props, true)
                .map(|face| Piece::Rule { face, width }),
        );
    }

    /// Whether an inline object's run (`props`) draws an underline below the object. Word keeps
    /// room below the baseline for it when the object is alone on its line and taller than its
    /// font line (`UnderlinedObjectRoom`).
    fn object_underlined(&mut self, props: &RunProps) -> bool {
        self.shaper
            .face(props, true)
            .and_then(|index| self.shaper.faces().get(index))
            .is_some_and(|face| face.lines.under != Underline::None)
    }

    /// The unshifted face of an inline object's run (`props`), used to size the line and scale
    /// multiple spacing on targets with `ObjectLineMultiple::ObjectRun` from compatibility mode
    /// 15. Vertical position (`w:position`) is cleared because `Piece::Object::raised` carries it
    /// separately.
    fn object_run_face(&mut self, props: &RunProps) -> Option<FaceIndex> {
        if props.position.is_some() {
            let unshifted = RunProps {
                position: None,
                ..props.clone()
            };
            self.shaper.face(&unshifted, true)
        } else {
            self.shaper.face(props, true)
        }
    }

    /// Measures an inline object of `width` and `height` that shows `picture`, with the room
    /// that the target gives its height on its line, raised or lowered with its run (`props`).
    fn measure_object(
        &mut self,
        (width, height): (Length, Length),
        (picture, extent): (Option<&Picture>, Option<Length>),
        props: &RunProps,
        pieces: &mut Vec<Piece>,
    ) {
        // In the frame of a turned cell a picture that stays upright on the page takes its
        // height along the line and its width across it.
        let upright = match self.column.within {
            Within::TurnedFrame(..) => decisions::upright_picture(&self.context.quirks, picture),
            Within::Page | Within::Cell(_) => None,
        };
        let (width, height, extent) = if upright.flatten().is_some() {
            (height, width, extent.map(|_| width))
        } else {
            (width, height, extent)
        };
        let picture = picture.map(|picture| {
            self.output.pictures.push(picture.clone());
            self.output.pictures.len() - 1
        });
        let underlined = self.object_underlined(props);
        let run_face = self.object_run_face(props);
        pieces.push(Piece::Object {
            width,
            height: self.device.inline_room_height(height, extent),
            raised: props.position.unwrap_or(Length::ZERO),
            picture,
            drawing: None,
            underlined,
            run_face,
            joins_before: false,
        });
    }

    /// Measures an inline drawing, with the room that the target gives its height on its line,
    /// raised or lowered with its run (`props`).
    fn measure_drawing(
        &mut self,
        drawing: &Rc<InlineDrawing>,
        props: &RunProps,
        pieces: &mut Vec<Piece>,
    ) {
        let index = self.output.add_drawing(Rc::clone(drawing));
        // An outlined VML shape can take the room of its outline instead of its size.
        let (width, height) = self
            .outline_room(drawing)
            .unwrap_or((drawing.width, drawing.height));
        let underlined = self.object_underlined(props);
        let run_face = self.object_run_face(props);
        pieces.push(Piece::Object {
            width,
            height: self.device.inline_room_height(height, drawing.extent),
            raised: props.position.unwrap_or(Length::ZERO),
            picture: None,
            drawing: Some(index),
            underlined,
            run_face,
            joins_before: drawing.drops && drawing.shape.parts.is_empty(),
        });
    }

    fn measure_content(&mut self, content: &Content, props: &RunProps, pieces: &mut Vec<Piece>) {
        match content {
            Content::Text(text) => self.measure_text(text, props, pieces),
            Content::Tab => pieces.push(Piece::Tab(self.shaper.face(props, true))),
            Content::PositionTab { kind, leader } => {
                let stop = self.position_stop(*kind, *leader);
                pieces.push(Piece::PositionTab(self.shaper.face(props, true), stop));
            }
            Content::Separator => self.measure_rule(self.separator_rule_width(), props, pieces),
            Content::ContinuationSeparator => {
                self.measure_rule(self.continuation_rule_width(), props, pieces);
            }
            Content::LineBreak => {
                let face = self.mark_face_of(props, self.paragraph_bidi);
                pieces.push(Piece::LineBreak(face));
            }
            Content::ClearingBreak => {
                let face = self.mark_face_of(props, self.paragraph_bidi);
                pieces.push(Piece::LineBreak(face));
                pieces.push(Piece::Clear);
            }
            Content::PageBreak => pieces.push(Piece::PageBreak),
            // The run of a column break sizes the line that the break ends.
            Content::ColumnBreak => {
                if self.settings.mode_rules.column_break_line_has_height() {
                    pieces.extend(self.shaper.face(props, true).map(Piece::Strut));
                }
                pieces.push(Piece::ColumnBreak);
            }
            Content::PageNumber
            | Content::PageCount
            | Content::Date(_)
            | Content::DocProperty(_)
            | Content::FileName(_)
            | Content::StyleRef(_)
            | Content::PageRef(_)
            | Content::NumberRef(_)
            | Content::If(_) => {
                // The value is a field result, which starts a text object.
                let text = self.field_text(content);
                if matches!(content, Content::StyleRef(_)) && text.contains(['\t', '\n']) {
                    self.measure_style_ref(&text, props, pieces);
                } else {
                    self.measure_pending(Some(Pending::alone(props, text)), pieces);
                }
            }
            Content::Object {
                width,
                height,
                picture,
                extent,
            } => self.measure_object(
                (*width, *height),
                (picture.as_deref(), *extent),
                props,
                pieces,
            ),
            Content::Drawing(drawing) => self.measure_drawing(drawing, props, pieces),
            Content::Advance(by) => pieces.push(Piece::Advance(*by)),
            Content::FootnoteReference(_, _)
            | Content::FootnoteMark
            | Content::EndnoteReference(_, _)
            | Content::EndnoteMark => self.measure_note_content(content, props, pieces),
            Content::CheckBox(check_box) => self.measure_check_box(*check_box, props, pieces),
            Content::CommentMark => pieces.extend(self.shaper.face(props, true).map(Piece::Strut)),
            Content::CommentAnchor(id) => {
                pieces.extend(self.comment_markup.index(id).map(Piece::Comment));
            }
            // `floating` places a floating drawing, and `measure` the marks of equations.
            Content::Floating(_)
            | Content::Stack(_)
            | Content::Grown(_)
            | Content::Radical(_)
            | Content::Accent(_)
            | Content::Matrix(_)
            | Content::MathBar(_)
            | Content::MathSlash(_)
            | Content::MathLimit(_)
            | Content::GroupChr(_)
            | Content::MathBox(_)
            | Content::Scripts(_)
            | Content::Bookmark(_)
            | Content::FieldMark
            | Content::HyperlinkEdge
            | Content::ControlEdge
            | Content::RemovedEdge
            | Content::FieldBegin
            | Content::FieldLock
            | Content::DropDown(_)
            | Content::FieldCode(_)
            | Content::FieldSeparate
            | Content::FieldEnd => {}
        }
    }

    /// Measures a footnote or endnote reference or mark into `pieces`.
    fn measure_note_content(
        &mut self,
        content: &Content,
        props: &RunProps,
        pieces: &mut Vec<Piece>,
    ) {
        match content {
            Content::FootnoteReference(id, mark) => {
                let number = self.note_number(*id, *mark);
                if *mark == NoteMark::Number {
                    let label = self.note_label(number);
                    self.measure_content(&Content::Text(label.to_string()), props, pieces);
                }
                pieces.push(Piece::Note(number));
            }
            Content::FootnoteMark => {
                let label = self.footnote_label().unwrap_or(NoteLabel::FIRST);
                self.measure_content(&Content::Text(label.to_string()), props, pieces);
                pieces.push(Piece::NoteMarkEnd);
            }
            Content::EndnoteReference(id, mark) => {
                let label = self.endnote_label(Some((*id, *mark)));
                if *mark == NoteMark::Number {
                    let before = pieces.len();
                    self.measure_content(&Content::Text(label.to_string()), props, pieces);
                    if let Ok(count) = u16::try_from(pieces.len().saturating_sub(before))
                        && count > 0
                    {
                        pieces.push(Piece::Endnote(count));
                    }
                }
            }
            Content::EndnoteMark => {
                let label = self.endnote_label(None);
                let before = pieces.len();
                self.measure_content(&Content::Text(label.to_string()), props, pieces);
                let count = u16::try_from(pieces.len().saturating_sub(before)).unwrap_or(0);
                pieces.push(Piece::EndnoteMarkEnd(count));
            }
            _ => {}
        }
    }

    /// The width of the separator's rule: 2 inches, and no wider than the column that the
    /// footnotes stand in where each footnote stands in the column of its reference.
    fn separator_rule_width(&self) -> Length {
        if self.settings.mode_rules.notes_in_reference_column() {
            params::NOTE_SEPARATOR_WIDTH.min(self.column.width)
        } else {
            params::NOTE_SEPARATOR_WIDTH
        }
    }

    /// The width of the rule above the rest of the notes: as wide as the column below the
    /// compatibility mode of Word 2013, and above endnotes that go on in every mode.
    fn continuation_rule_width(&self) -> Length {
        let endnotes = self
            .story
            .as_ref()
            .is_some_and(|story| story.kind == super::StoryKind::EndnoteContinuation);
        if self.settings.mode_rules.shortens_continuation_rule() && !endnotes {
            params::NOTE_SEPARATOR_WIDTH
        } else {
            self.column.width
        }
    }

    /// Measures text and joins its first glyph to the preceding glyph when no piece separates them.
    fn measure_text(&mut self, text: &str, props: &RunProps, pieces: &mut Vec<Piece>) {
        let mut glyphs = Vec::new();
        self.shaper.measure(props, text, &mut glyphs);
        // A variation selector that opens its run joins the character before it in the
        // paragraph, where there is one: it takes no room and draws nothing, and its face
        // sizes the line.
        // quirk: InvisibleCharacters::OperatorsDrawnSelectorsJoined (src/quirks.rs)
        let joined = glyphs
            .first()
            .filter(|first| {
                crate::text::is_selector(first)
                    && pieces.iter().any(|piece| matches!(piece, Piece::Glyph(_)))
            })
            .map(|first| Piece::Strut(first.face));
        let mut glyphs: Vec<_> = glyphs
            .into_iter()
            .skip(usize::from(joined.is_some()))
            .collect();
        let before = pieces
            .iter_mut()
            .rev()
            .find(|piece| !matches!(piece, Piece::Glyph(g) if g.part));
        if let (Some(Piece::Glyph(left)), Some(right)) = (before, glyphs.first_mut()) {
            self.shaper.kern_across(left, right);
            self.shaper.correct_italic(left, right);
        }
        pieces.extend(joined);
        pieces.extend(glyphs.into_iter().map(Piece::Glyph));
    }

    /// Gives the glyph before each of `firsts`, the first glyphs of runs measured in one text
    /// with the run before them, the italic correction that the shaper leaves out inside a run.
    fn correct_italics_at_joins(&self, pieces: &mut [Piece], firsts: &[usize]) {
        for &first in firsts {
            let Some((before, after)) = pieces.split_at_mut_checked(first) else {
                continue;
            };
            let left = before
                .iter_mut()
                .rev()
                .find(|piece| !matches!(piece, Piece::Glyph(g) if g.part));
            if let (Some(Piece::Glyph(left)), Some(Piece::Glyph(right))) = (left, after.first()) {
                self.shaper.correct_italic_at_join(left, right);
            }
        }
    }

    /// Measures the box of a check box form field. It takes the run's face, at the box's own
    /// size when it has one, and is as wide as the face's single line.
    fn measure_check_box(
        &mut self,
        check_box: crate::body::CheckBox,
        props: &RunProps,
        pieces: &mut Vec<Piece>,
    ) {
        let mut props = props.clone();
        if check_box.size.is_some() {
            props.size = check_box.size;
        }
        if let Some(face) = self.shaper.face(&props, true) {
            let width = self
                .shaper
                .faces()
                .get(face)
                .map_or(Length::ZERO, crate::text::Face::line_height);
            pieces.push(Piece::CheckBox { face, width });
        }
    }

    /// Measures the text of a `STYLEREF` field that holds tabs or line breaks, as the tabs and
    /// line breaks of the paragraph that it shows: each stretch between them starts a text
    /// object, a tab goes to the next stop and a line break starts a new line.
    fn measure_style_ref(&mut self, text: &str, props: &RunProps, pieces: &mut Vec<Piece>) {
        let mut rest = text;
        loop {
            let end = rest.find(['\t', '\n']).unwrap_or(rest.len());
            if end > 0 {
                let stretch = Pending::alone(props, rest[..end].to_owned());
                self.measure_pending(Some(stretch), pieces);
            }
            match rest[end..].chars().next() {
                Some('\t') => pieces.push(Piece::Tab(self.shaper.face(props, true))),
                Some('\n') => {
                    let face = self.mark_face_of(props, self.paragraph_bidi);
                    pieces.push(Piece::LineBreak(face));
                }
                _ => break,
            }
            rest = &rest[end + 1..];
        }
    }

    /// The text of a `PAGE` or `NUMPAGES` field. In the body, a page count is the count of an
    /// earlier pass, or else the page number so far.
    fn page_text(&self, content: &Content) -> String {
        let (number, count) = self.story_pages().unwrap_or_else(|| {
            let number = self.page_number(self.output.pages.len());
            (number, self.context.earlier.page_count.unwrap_or(number))
        });
        if *content == Content::PageNumber {
            self.chapter_prefix().unwrap_or_default() + &self.section.page_number(number)
        } else {
            count.to_string()
        }
    }

    /// The properties of `run` over `base_run`, the properties of its paragraph.
    fn run_props(&self, run: &Run, base_run: &RunProps) -> RunProps {
        let mut props = base_run.clone();
        if let Some((style, direct)) = self.error_format(run) {
            // Word prints a field's error text in the whole format of the field's code run, with
            // its bold turned the other way.
            if let Some(style) = style {
                self.styles.apply_character(&mut props, style);
            }
            props.apply(direct);
            props.bold = Some(!props.bold.unwrap_or(false));
            props.bold_cs = Some(!props.bold_cs.unwrap_or(false));
        } else {
            let (style, direct) = decisions::run_format(&self.context.quirks, run);
            if let Some(style) = style {
                self.styles.apply_character(&mut props, style);
            }
            props.apply(&direct);
        }
        props.math_script = props
            .math_script
            .map(|script| script.at_paragraph_size(base_run.drawn_half_points()));
        props
    }

    /// The character style and the direct properties of the format that `run` takes when it
    /// shows the error text of a page or `REF` field whose bookmark is missing: those of the
    /// field's code run, or the run's own where the field has none, as a simple field.
    fn error_format<'r>(&self, run: &'r Run) -> Option<(&'r Option<String>, &'r RunProps)> {
        run.content.iter().find_map(|content| {
            let code = match content {
                Content::PageRef(field) => field.code.as_ref(),
                Content::NumberRef(field) => field.code.as_ref(),
                _ => return None,
            };
            let text = self.field_text(content);
            (text == MISSING_BOOKMARK || text == MISSING_REFERENCE)
                .then(|| code.map_or((&run.style, &run.props), |code| (&code.style, &code.props)))
        })
    }

    /// The text of a field that layout computes.
    pub(super) fn field_text(&self, content: &Content) -> String {
        match content {
            // A date shows the time of layout when the caller gives one, and else its stored
            // result.
            Content::Date(field) => self
                .context
                .now
                .map_or_else(|| field.stored.clone(), |now| now.write(&field.picture)),
            // A document property shows its text, or its date as the target writes it with the
            // field's picture, and else the stored result.
            // The built-in time of the last save is the time when Word printed, since it saves
            // the document as it makes the PDF.
            Content::DocProperty(field) if field.name.eq_ignore_ascii_case("LastSavedTime") => {
                let picture = field.picture.clone().unwrap_or_else(|| {
                    format!(
                        "{} {}",
                        crate::dates::DATE_PICTURE,
                        crate::dates::TIME_PICTURE
                    )
                });
                self.context
                    .now
                    .map_or_else(|| field.stored.clone(), |now| now.write(&picture))
            }
            Content::DocProperty(field) => {
                match (self.context.properties.get(&field.name), &field.picture) {
                    (Some(Property::Text(text)), None) => text.clone(),
                    (Some(Property::Date(date)), picture) => decisions::property_date(
                        &self.context.quirks,
                        self.context.zone_minutes,
                        *date,
                        picture.as_deref(),
                    )
                    .unwrap_or_else(|| field.stored.clone()),
                    // Word reads a text value as a date for a picture.
                    (Some(Property::Text(text)), Some(picture)) => {
                        crate::dates::DateTime::parse_text(text)
                            .map_or_else(|| field.stored.clone(), |date| date.write(picture))
                    }
                    _ => field.stored.clone(),
                }
            }
            // A file name shows the name that the caller gives without its extension, in the
            // case of the field's format switch, and else the stored result.
            Content::FileName(field) => self.context.file_name.map_or_else(
                || field.stored.clone(),
                |name| field.case.apply(without_extension(name)),
            ),
            Content::StyleRef(field) => self.style_ref_text(field),
            // A page reference shows the page of its bookmark in an earlier pass, or Word's
            // error text when the document has no such bookmark. A first pass, which knows no
            // pages yet, shows the stored result.
            Content::PageRef(field) => match &self.context.earlier.bookmarks {
                Some(pages) => pages
                    .get(&field.bookmark)
                    .cloned()
                    .unwrap_or_else(|| MISSING_BOOKMARK.to_owned()),
                None => field.stored.clone(),
            },
            Content::NumberRef(field) => self.number_ref_text(field),
            Content::If(field) => self.if_text(field),
            Content::PageNumber | Content::PageCount => self.page_text(content),
            _ => String::new(),
        }
    }

    /// Existing unnumbered bookmarks have number zero; missing bookmarks show an error. A field
    /// of text shows its stored result where its bookmark exists.
    /// A first pass retains the stored result until it has found the bookmarks, and so do the
    /// passes that find the pages of the bookmarks for `PAGEREF` fields.
    fn number_ref_text(&self, field: &NumberRef) -> String {
        let earlier = &self.context.earlier;
        let Some(bookmarks) = earlier
            .bookmarks
            .as_ref()
            .filter(|_| !earlier.stored_number_refs)
        else {
            return field.stored.clone();
        };
        if !bookmarks.contains_key(&field.bookmark) {
            return MISSING_REFERENCE.to_owned();
        }
        let Some(kind) = field.kind else {
            return field.stored.clone();
        };
        self.context
            .earlier
            .bookmark_numbers
            .get(&field.bookmark)
            .map_or_else(
                || "0".to_owned(),
                |number| {
                    number
                        .reference(kind, self.number_context.as_ref())
                        .unwrap_or_else(|| field.stored.clone())
                },
            )
    }
}

/// The run properties of a paragraph mark: the paragraph's, then the mark's character style
/// (`w:rStyle` in `w:pPr/w:rPr`), then the mark's own.
pub(crate) fn mark_run_props(
    styles: &crate::styles::Styles,
    run: &RunProps,
    props: &ParaProps,
) -> RunProps {
    let mut mark = run.clone();
    if let Some(style) = &props.mark_style {
        styles.apply_character(&mut mark, style);
    }
    mark.apply(&props.mark);
    mark
}

/// The run properties of a list label: the paragraph mark's without its underline, with the
/// level's own (`Label::run`) on top. Shared between layout and staged font discovery.
pub(crate) fn list_label_props(
    shaper: &crate::text::Shaper<'_>,
    label: &Label,
    mark: &RunProps,
    right_to_left: bool,
) -> RunProps {
    let mut props = RunProps {
        underline: None,
        rtl: None,
        ..mark.clone()
    };
    props.apply(&label.run);
    if shaper.names_symbol_font(&props) {
        symbol_label_style(&mut props, &label.run);
    } else if right_to_left {
        props.rtl = Some(true);
    }
    props
}

/// The style of a list label in a symbol font, whose properties `props` join the paragraph
/// mark's and the level's (`level`): bold and italic only where the level's own run properties
/// give them, so that the mark's bold and italic, such as an italic mark's, which would slant
/// a bullet of Symbol, do not reach it.
fn symbol_label_style(props: &mut RunProps, level: &RunProps) {
    if level.bold.is_none() {
        props.bold = Some(false);
    }
    if level.italic.is_none() {
        props.italic = Some(false);
    }
}

/// Moves the list label, the first `label` of a paragraph's `pieces`, after the page breaks
/// that start the paragraph's own pieces and that `breaks` puts before its first line, when
/// something other than page breaks follows them: the label goes on the paragraph's first line.
fn label_after_page_breaks(pieces: &mut [Piece], label: usize, breaks: LeadingBreaks) {
    let leading = pieces
        .get(label..)
        .unwrap_or_default()
        .iter()
        .take_while(|piece| matches!(piece, Piece::PageBreak))
        .count();
    let before = breaks.before_first_line(leading);
    if label > 0
        && before > 0
        && label + leading < pieces.len()
        && let Some(lead) = pieces.get_mut(..label + before)
    {
        lead.rotate_right(before);
    }
}

#[cfg(test)]
mod tests {
    use std::rc::Rc;

    use f_office_xml::{Document, Limits};

    use super::Pending;

    #[test]
    fn moves_a_list_label_after_the_page_breaks_that_start_its_paragraph() {
        use crate::lines::{LeadingBreaks, Piece};
        use crate::text::{FaceIndex, Glyph};
        let glyph = |ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch));
        let moved = |mut pieces: Vec<Piece>, label, breaks| {
            super::label_after_page_breaks(&mut pieces, label, breaks);
            pieces
        };
        let label = [glyph('1'), Piece::Tab(None)];
        let (text, page) = (glyph('a'), Piece::PageBreak);
        let mut pieces = label.to_vec();
        pieces.extend([page, page, text]);
        // With all leading breaks before the first line, both go before the label, which then
        // starts the text's line; with the first only, the label starts the second break's line.
        let mut all = vec![page, page];
        all.extend(label);
        all.push(text);
        assert_eq!(moved(pieces.clone(), 2, LeadingBreaks::All), all);
        let mut first = vec![page];
        first.extend(label);
        first.extend([page, text]);
        assert_eq!(moved(pieces.clone(), 2, LeadingBreaks::First), first);
        assert_eq!(moved(pieces.clone(), 2, LeadingBreaks::None), pieces);
        // Without text after the breaks, without a label, or with text before the break, the
        // pieces stay as they are.
        for (pieces, label) in [
            (vec![label[0], label[1], page], 2),
            (vec![label[0], label[1], page, page], 2),
            (vec![page, text], 0),
            (vec![label[0], label[1], text, page, text], 2),
        ] {
            for breaks in [LeadingBreaks::First, LeadingBreaks::All] {
                assert_eq!(moved(pieces.clone(), label, breaks), pieces);
            }
        }
    }

    #[test]
    fn a_symbol_label_takes_bold_and_italic_from_its_level_only() {
        let mark = RunProps {
            bold: Some(true),
            italic: Some(true),
            ..RunProps::default()
        };
        let mut props = mark.clone();
        super::symbol_label_style(&mut props, &RunProps::default());
        assert_eq!((props.bold, props.italic), (Some(false), Some(false)));
        let level = RunProps {
            italic: Some(true),
            ..RunProps::default()
        };
        let mut props = mark.clone();
        props.apply(&level);
        super::symbol_label_style(&mut props, &level);
        assert_eq!((props.bold, props.italic), (Some(false), Some(true)));
    }

    #[test]
    fn automatic_spacing_is_fixed_where_the_option_and_the_target_say_so() {
        use crate::props::HtmlAutoSpacing;
        use crate::quirks::FixedAutoSpacing;
        let set = crate::styles::Settings {
            html_auto_spacing: HtmlAutoSpacing::Fixed,
            ..crate::styles::Settings::default()
        };
        let unset = crate::styles::Settings::default();
        let quirks = |variant| crate::layout::testing::on_base_with(|p| p.with_variant(variant)).1;
        let followed = quirks(FixedAutoSpacing::OptionFollowed);
        let ignored = quirks(FixedAutoSpacing::Ignored);
        let reading = super::decisions::html_auto_spacing;
        assert_eq!(reading(&set, &followed), HtmlAutoSpacing::Fixed);
        assert_eq!(reading(&set, &ignored), HtmlAutoSpacing::Html);
        assert_eq!(reading(&unset, &followed), HtmlAutoSpacing::Html);
        assert_eq!(reading(&unset, &ignored), HtmlAutoSpacing::Html);
    }

    #[test]
    fn automatic_text_takes_the_story_color_before_the_white_of_dark_shading() {
        use crate::props::Color;
        let colored = |color, (behind, story)| {
            let mut props = RunProps {
                color,
                ..RunProps::default()
            };
            super::automatic_color(&mut props, (behind, story));
            props.color
        };
        let (dark, orange) = (Some([0, 0, 0x80]), Some([0xED, 0x7D, 0x31]));
        let rgb = |rgb: Option<[u8; 3]>| rgb.map(Color::Rgb);
        assert_eq!(colored(None, (None, orange)), rgb(orange));
        assert_eq!(colored(Some(Color::Auto), (dark, orange)), rgb(orange));
        assert_eq!(colored(None, (dark, None)), rgb(Some([255; 3])));
        assert_eq!(colored(None, (None, None)), None);
        let blue = rgb(Some([0, 0, 255]));
        assert_eq!(colored(blue, (dark, orange)), blue);
    }
    use crate::body::{Block, Content, Run, Section, Sections, read_story};
    use crate::layout::testing::{Fake, base_context};
    use crate::layout::{Layout, SectionLayout};
    use crate::lines::Piece;
    use crate::ns::{V, W};
    use crate::props::{BidiLanguageClass, RunProps};
    use crate::reader::PartReader;
    use crate::styles::{FontTable, Settings, Styles, Theme};
    use crate::text::{Shaper, ShaperSettings};

    #[test]
    fn shares_the_inline_drawing_of_a_paragraph_measured_twice() {
        // A paragraph that a kept chain measures again gives the layout the drawing that it
        // holds, not a copy of the drawing's text box.
        let xml = format!(
            r#"<w:hdr xmlns:w="{W}" xmlns:v="{V}"><w:p><w:r><w:pict><v:rect style="width:20pt;height:20pt"><v:textbox><w:txbxContent><w:p><w:r><w:t>a</w:t></w:r></w:p></w:txbxContent></v:textbox></v:rect></w:pict></w:r></w:p></w:hdr>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let blocks = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
        let Some(Block::Paragraph(paragraph)) = blocks.first() else {
            panic!("no paragraph");
        };
        let Some(Content::Drawing(drawing)) =
            paragraph.runs.first().and_then(|r| r.content.first())
        else {
            panic!("no inline drawing");
        };
        assert_eq!(drawing.shape.blocks.len(), 1);
        let (styles, settings) = (Styles::default(), Settings::default());
        let (theme, fonts) = (Theme::default(), FontTable::default());
        let context = base_context(&styles, &settings);
        let stories = context.for_stories();
        let sections = Sections::one(SectionLayout::plain(&Section::default(), blocks.len()));
        let mut layout = Layout::new(
            (&context, &stories),
            &sections,
            Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
        );
        for _ in 0..2 {
            layout.measure(
                paragraph,
                &RunProps::default(),
                None,
                &mut super::RunFeatures::default(),
            );
        }
        assert_eq!(layout.output.drawings.len(), 2);
        assert!(
            layout
                .output
                .drawings
                .iter()
                .all(|measured| Rc::ptr_eq(measured, drawing))
        );
    }

    /// Whether each glyph of the paragraph `xml`, read as a story, starts a glyph run, and its
    /// count in the text object.
    fn glyph_starts(paragraph_xml: &str) -> Vec<(bool, u32)> {
        glyph_starts_with(paragraph_xml, crate::profile::Profile::clone)
    }

    /// As [`glyph_starts`], with the base quirks as `adjust` changes them.
    fn glyph_starts_with(
        paragraph_xml: &str,
        adjust: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
    ) -> Vec<(bool, u32)> {
        let xml = format!(r#"<w:hdr xmlns:w="{W}">{paragraph_xml}</w:hdr>"#);
        measured(&xml, &Fake, adjust, |_, pieces| {
            pieces
                .iter()
                .filter_map(|piece| match piece {
                    Piece::Glyph(glyph) => Some((glyph.starts_run, glyph.place.in_run)),
                    _ => None,
                })
                .collect()
        })
    }

    /// What `read` gives of the pieces of the first paragraph of the story `xml`, measured
    /// with the faces of `fonts` on the base target's profile with some quirks of another
    /// variant (`change`), and of the layout that measured them.
    pub(super) fn measured<T>(
        xml: &str,
        fonts: &dyn crate::Fonts,
        change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
        read: impl FnOnce(&Layout<'_>, &[Piece]) -> T,
    ) -> T {
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let blocks = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
        let Some(Block::Paragraph(paragraph)) = blocks.first() else {
            panic!("no paragraph");
        };
        let (styles, settings) = (Styles::default(), Settings::default());
        let (theme, table) = (Theme::default(), FontTable::default());
        let mut context = base_context(&styles, &settings);
        (context.device, context.quirks) = crate::layout::testing::on_base_with(change);
        let shaper = ShaperSettings::of(&settings, &context.quirks, context.device.dot_size());
        let stories = context.for_stories();
        let sections = Sections::one(SectionLayout::plain(&Section::default(), blocks.len()));
        let mut layout = Layout::new(
            (&context, &stories),
            &sections,
            Shaper::new(fonts, &theme, &table, &shaper),
        );
        let pieces = layout.measure(
            paragraph,
            &RunProps::default(),
            None,
            &mut super::RunFeatures::default(),
        );
        read(&layout, &pieces)
    }

    #[test]
    fn starts_a_text_object_where_the_run_record_changes() {
        let objects = |first: &str, second: &str| {
            glyph_starts(&format!(
                "<w:p><w:r><w:rPr>{first}</w:rPr><w:t>ab</w:t></w:r><w:r><w:rPr>{second}</w:rPr><w:t>cd</w:t></w:r></w:p>"
            ))
        };
        let snap_off = r#"<w:snapToGrid w:val="0"/>"#;
        // Runs that draw alike and differ in a property that draws nothing: the second run
        // starts a text object, and Word counts its pieces from it.
        let cut = [(true, 0), (false, 1), (true, 0), (false, 1)];
        let joined = [(true, 0), (false, 1), (false, 2), (false, 3)];
        assert_eq!(objects("", "<w:noProof/>"), cut);
        assert_eq!(objects("", r#"<w:snapToGrid w:val="1"/>"#), cut);
        // The same children in another order, or an on/off value spelled otherwise: one object.
        let swapped = (
            format!("<w:noProof/>{snap_off}"),
            format!("{snap_off}<w:noProof/>"),
        );
        assert_eq!(objects(&swapped.0, &swapped.1), joined);
        assert_eq!(objects("<w:b/>", r#"<w:b w:val="1"/>"#), joined);
        assert_eq!(objects("", ""), joined);
    }

    #[test]
    fn starts_a_text_object_at_field_results_and_after_field_ends() {
        let field = |code: &str| {
            format!(
                r#"<w:fldChar w:fldCharType="begin"/><w:instrText xml:space="preserve"> {code} </w:instrText><w:fldChar w:fldCharType="separate"/><w:t>cd</w:t><w:fldChar w:fldCharType="end"/>"#
            )
        };
        let starts = [
            (true, 0),
            (false, 1),
            (true, 0),
            (false, 1),
            (true, 0),
            (false, 1),
        ];
        // A stored result and the text after the field's end each start a text object, also
        // inside one run, and Word counts their pieces from there.
        let stored = field("TITLE");
        assert_eq!(
            glyph_starts(&format!(
                "<w:p><w:r><w:t>ab</w:t>{stored}<w:t>ef</w:t></w:r></w:p>"
            )),
            starts
        );
        // A value that layout computes, here a date that shows its stored result without a
        // time of layout, starts one too.
        let date = field(r#"DATE \@ "d""#);
        assert_eq!(
            glyph_starts(&format!(
                "<w:p><w:r><w:t>ab</w:t>{date}<w:t>ef</w:t></w:r></w:p>"
            )),
            starts
        );
        // Without a field, the run is one text object.
        assert_eq!(
            glyph_starts("<w:p><w:r><w:t>abcdef</w:t></w:r></w:p>"),
            [0, 1, 2, 3, 4, 5].map(|count| (count == 0, count))
        );
    }

    #[test]
    fn starts_a_text_object_at_control_edges_and_after_removed_text_as_the_quirks_say() {
        // Three runs alike, the second in a content control; then two runs alike, the second
        // after deleted runs that the target accepted, as the acceptance notes it.
        let control = "<w:p><w:r><w:t>ab</w:t></w:r><w:sdt><w:sdtContent><w:r><w:t>cd</w:t></w:r></w:sdtContent></w:sdt><w:r><w:t>ef</w:t></w:r></w:p>";
        let removed = format!(
            r#"<w:p><w:r><w:t>ab</w:t></w:r><w:r xmlns:n="{}" n:buffered="1" n:removed="1"><w:t>cd</w:t></w:r></w:p>"#,
            crate::ns::NOTE
        );
        let objects = |count: usize, every: usize| -> Vec<(bool, u32)> {
            (0..count)
                .map(|at| (at % every == 0, u32::try_from(at % every).unwrap()))
                .collect()
        };
        let at_controls = |value| glyph_starts_with(control, |p| p.with_variant(value));
        assert_eq!(
            at_controls(crate::quirks::ControlObjects::StartsObject),
            objects(6, 2)
        );
        assert_eq!(
            at_controls(crate::quirks::ControlObjects::Joins),
            objects(6, 6)
        );
        let after_removed = |value| glyph_starts_with(&removed, |p| p.with_variant(value));
        assert_eq!(
            after_removed(crate::quirks::RemovedTextObjects::StartsObject),
            objects(4, 2)
        );
        assert_eq!(
            after_removed(crate::quirks::RemovedTextObjects::Joins),
            objects(4, 4)
        );
    }

    #[test]
    fn starts_a_text_object_at_the_edges_of_a_hyperlink_as_the_quirk_says() {
        let paragraph = "<w:p><w:r><w:t>ab</w:t></w:r><w:hyperlink><w:r><w:t>cd</w:t></w:r></w:hyperlink><w:r><w:t>ef</w:t></w:r></w:p>";
        // The hyperlink's content and the text after its end each start a text object, though
        // the three runs have the same properties.
        let starts = |objects| glyph_starts_with(paragraph, |p| p.with_variant(objects));
        assert_eq!(
            starts(crate::quirks::HyperlinkObjects::StartsObject),
            [
                (true, 0),
                (false, 1),
                (true, 0),
                (false, 1),
                (true, 0),
                (false, 1)
            ]
        );
        // On a target that keeps one object, the three runs are one text object.
        assert_eq!(
            starts(crate::quirks::HyperlinkObjects::Joins),
            [0, 1, 2, 3, 4, 5].map(|count| (count == 0, count))
        );
    }

    #[test]
    fn ends_the_measured_text_at_a_bookmark_start_as_the_quirk_says() {
        let paragraph = r#"<w:p><w:r><w:t>ab</w:t></w:r><w:bookmarkStart w:id="1" w:name="m"/><w:bookmarkEnd w:id="1"/><w:r><w:t>cd</w:t></w:r></w:p>"#;
        let starts = |text| glyph_starts_with(paragraph, |p| p.with_variant(text));
        // The text after the bookmark's start is measured alone: its first glyph counts as a
        // run's first glyph, though both runs have the same properties.
        assert_eq!(
            starts(crate::quirks::BookmarkText::Splits),
            [(true, 0), (false, 1), (true, 0), (false, 1)]
        );
        // On a target that joins them, the two runs are one measured text.
        assert_eq!(
            starts(crate::quirks::BookmarkText::Joins),
            [0, 1, 2, 3].map(|count| (count == 0, count))
        );
    }

    #[test]
    fn keeps_the_class_of_each_run_of_a_joined_text() {
        let persian = Some(BidiLanguageClass::OtherRightToLeft);
        let run = Run::default();
        let mut pending = Pending::new(&RunProps::default(), "ab", (&run, 0));
        // A run of the same class adds no start.
        pending.start_class(None);
        pending.join("cd", &run, true);
        pending.start_class(persian);
        pending.join("ef", &run, true);
        pending.start_class(None);
        pending.join("g", &run, true);
        assert_eq!(pending.text, "abcdefg");
        assert_eq!(pending.classes, [(4, persian), (6, None)]);
        assert_eq!(pending.starts, [] as [usize; 0]);
    }

    #[test]
    fn reads_a_revision_id_of_zero_as_the_quirk_says() {
        let without = Run::default();
        let zero = Run {
            revisions: [Some(0), Some(0), None],
            ..Run::default()
        };
        let other = Run {
            revisions: [Some(0x00A1_1111), None, None],
            ..Run::default()
        };
        // A run whose IDs are zero continues the text of a run without IDs only where zero is no
        // ID; a nonzero ID starts a text object either way.
        let cases: [(crate::quirks::ZeroRevision, &[usize]); 2] = [
            (crate::quirks::ZeroRevision::AnId, &[2, 4]),
            (crate::quirks::ZeroRevision::NoId, &[4]),
        ];
        for (zero_revision, starts) in cases {
            let mut pending = Pending::new(&RunProps::default(), "ab", (&without, 0))
                .reading(super::RevisionReading::with(zero_revision));
            pending.join("cd", &zero, true);
            pending.join("ef", &other, true);
            assert_eq!(pending.starts, starts);
        }
    }

    #[test]
    fn keeps_where_each_run_that_starts_a_text_buffer_starts() {
        let run = Run::default();
        let buffer = Run {
            starts_buffer: true,
            ..Run::default()
        };
        let mut pending = Pending::new(&RunProps::default(), "ab", (&buffer, 0));
        pending.join("cd", &run, true);
        pending.join("ef", &buffer, true);
        pending.join("g", &buffer, false);
        assert_eq!(pending.buffer_starts, [0, 4]);
        assert_eq!(pending.starts, [4]);
    }

    #[test]
    fn run_snap_to_grid_controls_character_pitch_independently_of_paragraph_snap() {
        let xml = format!(
            concat!(
                r#"<w:hdr xmlns:w="{W}"><w:p><w:pPr><w:snapToGrid w:val="0"/></w:pPr>"#,
                r#"<w:r><w:t>a</w:t></w:r>"#,
                r#"<w:r><w:rPr><w:snapToGrid w:val="0"/></w:rPr><w:t>a</w:t></w:r>"#,
                r#"<w:r><w:rPr><w:snapToGrid w:val="1"/></w:rPr><w:t>a</w:t></w:r>"#,
                r#"</w:p></w:hdr>"#,
            ),
            W = W
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let blocks = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
        let Some(Block::Paragraph(paragraph)) = blocks.first() else {
            panic!("no paragraph");
        };
        let (styles, settings) = (Styles::default(), Settings::default());
        let (theme, table) = (Theme::default(), FontTable::default());
        let context = base_context(&styles, &settings);
        let shaper = ShaperSettings::of(&settings, &context.quirks, context.device.dot_size());
        let stories = context.for_stories();
        let pitch = f_office_units::Length::from_points(2).unwrap();
        let section = Section {
            char_pitch: Some(pitch),
            ..Section::default()
        };
        let sections = Sections::one(SectionLayout::plain(&section, blocks.len()));
        let mut layout = Layout::new(
            (&context, &stories),
            &sections,
            Shaper::new(&Fake, &theme, &table, &shaper),
        );
        let pieces = layout.measure(
            paragraph,
            &RunProps::default(),
            None,
            &mut super::RunFeatures::default(),
        );
        let advances: Vec<f_office_units::Length> = pieces
            .iter()
            .filter_map(|piece| match piece {
                Piece::Glyph(glyph) => Some(glyph.advance),
                _ => None,
            })
            .collect();
        // Run 0 (default) and run 2 (w:val="1") take half the character pitch even with
        // w:pPr/w:snapToGrid=0; run 1 (w:rPr/w:snapToGrid=0) keeps its unpitched advance.
        let [a0, a1, a2] = advances.as_slice() else {
            panic!("expected 3 glyphs, got {}", advances.len());
        };
        assert_eq!(a0, a2);
        assert_eq!(*a0 - *a1, pitch.div_toward_zero(2));
    }

    #[test]
    fn east_asian_run_splits_after_leading_general_punctuation_space() {
        type Case = (&'static str, bool, &'static [(bool, u32)]);
        let run = |text: &str, east_asia: bool| {
            let ea = if east_asia {
                r#" w:eastAsia="Calibri""#
            } else {
                ""
            };
            let xml = format!(
                r#"<w:hdr xmlns:w="{W}"><w:p><w:r><w:rPr><w:rFonts w:ascii="Calibri"{ea}/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p></w:hdr>"#
            );
            let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
            let blocks = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
            let Block::Paragraph(paragraph) = &blocks[0] else {
                panic!("no paragraph");
            };
            let (styles, settings) = (Styles::default(), Settings::default());
            let (theme, table) = (Theme::default(), FontTable::default());
            let context = base_context(&styles, &settings);
            let shaper = ShaperSettings::of(&settings, &context.quirks, context.device.dot_size());
            let stories = context.for_stories();
            let sections = Sections::one(SectionLayout::plain(&Section::default(), blocks.len()));
            let mut layout = Layout::new(
                (&context, &stories),
                &sections,
                Shaper::new(&Fake, &theme, &table, &shaper),
            );
            layout
                .measure(
                    paragraph,
                    &RunProps::default(),
                    None,
                    &mut super::RunFeatures::default(),
                )
                .into_iter()
                .filter_map(|p| match p {
                    Piece::Glyph(g) => Some((g.starts_run, g.place.in_run)),
                    _ => None,
                })
                .collect::<Vec<_>>()
        };

        let cases: [Case; 10] = [
            ("\u{202F}A", true, &[(true, 0), (true, 0)]),
            (
                "\u{202F}\u{201C}W",
                true,
                &[(true, 0), (false, 1), (true, 0)],
            ),
            (
                "\u{202F}\u{00B7}K",
                true,
                &[(true, 0), (true, 0), (false, 1)],
            ),
            ("a\u{202F}b", true, &[(true, 0), (false, 1), (false, 2)]),
            (
                "\u{202F}\u{201C}W",
                false,
                &[(true, 0), (false, 1), (false, 2)],
            ),
            ("\u{25BA}A", true, &[(true, 0), (true, 0)]),
            (
                "\u{25BA}\u{2022}A",
                true,
                &[(true, 0), (false, 1), (true, 0)],
            ),
            (
                "\u{2022}\u{25BA}A",
                true,
                &[(true, 0), (false, 1), (false, 2)],
            ),
            ("\u{2212}A", false, &[(true, 0), (false, 1)]),
            ("a\u{25BA}b", true, &[(true, 0), (false, 1), (false, 2)]),
        ];
        for (text, east_asia, expected) in cases {
            assert_eq!(run(text, east_asia), expected, "{text:?} ea={east_asia}");
        }
    }
}