jubarte-markdown 0.20.0

Markdown in and out of Word documents for the jubarte engine: CriticMarkup as tracked changes, the agent view, and .doc reading
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
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0
//! The YAML header of the agent view.

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;

use super::agent::Handles;
use super::ooxml::Element;
use crate::markdown::view_notes::WORD_PAGE_SIZES;

/// Where the owner's name came from.
pub(crate) enum Owner {
    Creator(String),
    LastModifiedBy(String),
    /// `docProps/core.xml` is there but names nobody.
    Unnamed,
    /// No `docProps/core.xml`.
    None,
}

/// Where the page count and markers came from.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum PagesSource {
    /// `Options::pages` from the layout pass.
    Layout,
    /// `w:lastRenderedPageBreak` in the file.
    Cached,
    /// Hard page and section breaks only.
    Estimated,
}

/// A header or footer of one section.
#[derive(Clone)]
pub(crate) struct StoryFact {
    /// `header` or `footer`.
    pub kind: &'static str,
    /// `first`, `default`, `even`.
    pub ty: &'static str,
    /// `header2` (the part `header2.xml`, first paragraph), `footer1`, `header2.p2`.
    pub id: String,
    /// The part's own id, its first paragraph's (`header2`): a story printed
    /// paragraph by paragraph names it, then `pN:` for each.
    pub part: String,
    /// The paragraph `text` is, in the part.
    pub first: usize,
    pub text: String,
    /// The paragraphs after it, to the part's last (an empty one too, a
    /// line Word lays out): `text` then prints as a list (`text: [Page 1,
    /// Draft]`, `text: [DRAFT, ""]`).
    pub more: Vec<String>,
    /// `center`, `right`, or `None` for left.
    pub align: Option<&'static str>,
    /// `text` and `more`, one by one: what each paragraph carries itself.
    pub paras: Vec<ParaFact>,
    /// The paragraphs' styles when not all are the story's own
    /// ([`story_style`]): one for all (`style: Normal`), or one per
    /// paragraph from the part's first (`styles: [Header, ListParagraph]`).
    pub styles: Vec<String>,
    pub active: bool,
    /// Tracked view: the part's insertions, deletions and moves `text` prints
    /// no tag for (`header1.r3 @AC`), then its formatting changes.
    pub rev: Vec<String>,
    pub fmt: Vec<String>,
}

/// One paragraph of a header or footer: its own alignment, text colour and
/// borders.
#[derive(Clone, Default, PartialEq, Eq)]
pub(crate) struct ParaFact {
    /// `center`, `right`, or `None` for left.
    pub align: Option<&'static str>,
    /// The colour its text runs set themselves (`w:color`), when they all
    /// set the same one.
    pub color: Option<String>,
    /// Its own borders (`w:pBdr`), as a border prints them (`bottom single
    /// 0.5pt 8496B0 space 4pt`).
    pub border: Option<String>,
    /// The frame it lays out in (`w:framePr`, its style's under its own),
    /// as [`crate::markdown::frames::describe`] prints it.
    pub frame: Option<String>,
    /// Its own indent (`w:ind`), as the id lines say it: `first-line`,
    /// `hanging`, `left`, `right` and each one's inches.
    pub indent: Vec<(&'static str, String)>,
    /// Its own tab stops (`w:tabs`): `center 4680`, or `right dot 9360`
    /// when a leader is set. The position is twips.
    pub tabs: Vec<String>,
    /// Its own spacing (`w:spacing`), in the body's spacing words
    /// (`before 6pt`, `after 0pt`, `line 1`).
    pub spacing: Vec<String>,
    /// Its own shading (`w:shd`): `val`, `color` and `fill`, in that order.
    pub shading: Vec<(&'static str, String)>,
}

/// A section of the body (Task 11 fills these).
pub(crate) struct SectionFact {
    /// Paragraph range, inclusive.
    pub first: usize,
    pub last: usize,
    pub sect_pr: Option<Element>,
    pub stories: Vec<StoryFact>,
    pub title_page: bool,
}

pub(crate) struct CommentFact {
    pub id: String,
    pub author: Option<String>,
    pub parent: Option<String>,
    /// A range or reference to it sits in the body or a note. Without one
    /// Word draws no balloon, so it is no open thread.
    pub anchored: bool,
    /// Its first paragraph's style: `CommentText` for Word's own
    /// (`annotation text`), the document default's id for none.
    pub style: String,
}

pub(crate) struct Facts<'a> {
    pub source: &'a str,
    /// The SHA-256 of the bytes the view reads, in hex: the file, or the
    /// in-memory redline `jubarte A B` prints.
    pub sha256: String,
    /// `None` tracked, `Some(true)` accept-all, `Some(false)` reject-all.
    pub resolved: Option<bool>,
    pub comments_inline: bool,
    pub tracking_on: bool,
    /// One kind per change printed in the body.
    pub tags: Vec<&'static str>,
    /// The document's changes, as `jubarte changes` lists them: the one
    /// revision count.
    pub changes: Vec<crate::changes::Change>,
    pub comments: Vec<CommentFact>,
    pub handles: &'a Handles,
    /// Resolved comment ids (`w15:done`), from `agent::Threads`.
    pub done: &'a HashSet<String>,
    pub owner: Owner,
    /// `dc:title`, when the core properties give one.
    pub title: Option<String>,
    pub paragraphs: usize,
    pub tables: usize,
    pub pages: usize,
    pub pages_source: PagesSource,
    /// `range:` line after `body:` when a selection is active (Task 12).
    pub range: Option<String>,
    /// A header or footer holds a change `range`'s `--changed` selects.
    pub stories_changed: bool,
    pub styles: Option<&'a Element>,
    pub theme: Option<&'a Element>,
    pub default_style: Option<&'a str>,
    /// (level, style id) for every heading level used, lowest first.
    pub heading_styles: Vec<(usize, String)>,
    /// Every other paragraph style the body uses, in first-use order.
    pub other_styles: Vec<String>,
    /// Canonical note style ids whose legend uses a source definition's name
    /// and formatting, even when its localized id differs.
    pub note_style_sources: HashMap<String, String>,
    pub table_styles: Vec<String>,
    /// The tables differ in style: their lines name theirs, and the
    /// legend lists them all as `tables:`.
    pub tables_differ: bool,
    /// The body's sections in order; the first one is described in full.
    pub sections: Vec<SectionFact>,
    /// Tracked view: the changes (`rev`, `fmt`) of the notes no definition
    /// line shows, such as Word's footnote separators.
    pub note_changes: (Vec<String>, Vec<String>),
    /// The notes parts (`footnotes`, `endnotes`) the view shows no note
    /// of, such as a part holding only Word's separators.
    pub empty_notes: Vec<&'static str>,
    /// Tracked view of the whole document: the listed changes no other line
    /// prints (`r3 @AC in p0`), such as a text box's deleted picture.
    pub unplaced: Vec<String>,
}

/// `key: value` padded to 35 columns then `# comment`; a key/value longer
/// than 33 characters takes two spaces. An empty comment writes none.
fn kv(out: &mut String, key_value: &str, comment: Option<&str>) {
    match comment.filter(|c| !c.is_empty()) {
        Some(c) if key_value.chars().count() <= 33 => {
            out.push_str(&format!("{key_value:<35}# {c}\n"));
        }
        Some(c) => out.push_str(&format!("{key_value}  # {c}\n")),
        None => {
            out.push_str(key_value);
            out.push('\n');
        }
    }
}

/// `value` as a YAML scalar: plain when every YAML reader, 1.1 or 1.2, takes
/// it back as the same string, else double-quoted (a JSON string is a valid YAML one).
/// `flow` values sit inside `{…}` or `[…]`, where `,`, `[`, `]`, `{` and `}`
/// end them, and where libyaml refuses any `:` and a `?` (`@??`).
pub(crate) fn scalar(value: &str, flow: bool) -> String {
    const RESERVED: [&str; 12] = [
        "true", "false", "yes", "no", "on", "off", "y", "n", "null", "~", ".nan", ".inf",
    ];
    let plain = !value.is_empty()
        && value.trim() == value
        && !value.chars().any(char::is_control)
        && !value.starts_with([
            '-', '?', ':', ',', '[', ']', '{', '}', '#', '&', '*', '!', '|', '>', '\'', '"', '%',
            '@', '`',
        ])
        && !value.contains(": ")
        && !value.contains(" #")
        && !value.ends_with(':')
        && !(flow && value.contains([',', '[', ']', '{', '}', ':', '?']))
        && !RESERVED.contains(&value.to_ascii_lowercase().as_str())
        // One word that opens with a digit, `+` or `.` may be a number, a
        // time (`12:30`, base 60 in YAML 1.1) or a date to some reader.
        && (!value.starts_with(|c: char| c.is_ascii_digit() || c == '+' || c == '.')
            || value.contains(char::is_whitespace));
    if plain {
        value.to_string()
    } else {
        serde_json::to_string(value).unwrap_or_else(|_| format!("\"{value}\""))
    }
}

fn plural(n: usize, one: &str, many: &str) -> String {
    if n == 1 {
        format!("1 {one}")
    } else {
        format!("{n} {many}")
    }
}

fn join(items: &[String]) -> String {
    items.join(", ")
}

/// The `revisions:` line's comment: the body's marks and the changes the
/// view shows them as, then formatting (body and styles) and each other
/// story's changes, with its marks when they differ: `9 marks shown as 5
/// changes: 1 insertion, 4 substitutions; 2 formatting; 3 in header1 (7
/// marks)`. Resolved views describe the raw marks by kind, without
/// `shown as`. Empty for no change.
fn revisions_comment(f: &Facts) -> String {
    use crate::changes::ChangeKind;
    let story = |c: &crate::changes::Change| {
        crate::ids::change_id(&c.id).map_or_else(|| "body".to_string(), |id| id.story)
    };
    let marks = f
        .changes
        .iter()
        .filter(|c| story(c) == "body" && c.kind != ChangeKind::Formatting)
        .count();
    let formatting = f
        .changes
        .iter()
        .filter(|c| {
            c.kind == ChangeKind::Formatting && matches!(story(c).as_str(), "body" | "styles")
        })
        .count();
    // A part's group prints where its block does — headers then footers,
    // first, default, even, section by section — not where its relationship
    // happens to sit, which a writer cannot keep.
    let mut counts: HashMap<String, usize> = HashMap::new();
    for c in &f.changes {
        let s = story(c);
        if matches!(s.as_str(), "body" | "styles") {
            continue;
        }
        *counts.entry(s).or_default() += 1;
    }
    let mut order: Vec<String> = Vec::new();
    for section in &f.sections {
        for kind in ["header", "footer"] {
            for ty in ["first", "default", "even"] {
                if let Some(s) = section
                    .stories
                    .iter()
                    .find(|s| s.kind == kind && s.ty == ty && counts.contains_key(&s.part))
                    && !order.contains(&s.part)
                {
                    order.push(s.part.clone());
                }
            }
        }
    }
    for c in &f.changes {
        let s = story(c);
        if counts.contains_key(&s) && !order.contains(&s) {
            order.push(s);
        }
    }
    // Each story counts the changes `jubarte changes` lists for it, as the
    // body does, and its marks when they differ; a resolved view counts
    // the raw marks.
    let listed = f
        .resolved
        .is_none()
        .then(super::agent::story_changes)
        .flatten();
    let others: Vec<(String, usize, usize)> = order
        .into_iter()
        .filter_map(|s| {
            let marks = *counts.get(&s)?;
            let changes = listed
                .as_ref()
                .map_or(marks, |l| l.get(&s).copied().unwrap_or(marks));
            Some((s, changes, marks))
        })
        .collect();
    let mut parts = Vec::new();
    let raw_kinds = if f.resolved.is_some() {
        f.changes
            .iter()
            .filter(|c| story(c) == "body" && c.kind != ChangeKind::Formatting)
            .map(|c| match (c.target, c.kind) {
                ("paragraph_mark", _) => "mark",
                ("table_row", _) => "row",
                ("table_cell", _) => "cell",
                (_, ChangeKind::Insertion) => "ins",
                (_, ChangeKind::Deletion) => "del",
                (_, ChangeKind::Move) => "move",
                (_, ChangeKind::Formatting) => "fmt",
                (_, ChangeKind::Replacement) => "sub",
            })
            .collect::<Vec<_>>()
    } else {
        Vec::new()
    };
    let tags = if f.resolved.is_some() {
        &raw_kinds
    } else {
        &f.tags
    };
    if marks > 0 || !tags.is_empty() {
        let mut kinds = Vec::new();
        for (kind, one, many) in [
            ("ins", "insertion", "insertions"),
            ("del", "deletion", "deletions"),
            ("sub", "substitution", "substitutions"),
            ("mark", "paragraph mark", "paragraph marks"),
            ("row", "table row", "table rows"),
            ("cell", "table cell", "table cells"),
            ("move", "move", "moves"),
        ] {
            let n = tags.iter().filter(|&&t| t == kind).count();
            if n > 0 {
                kinds.push(plural(n, one, many));
            }
        }
        let marks = plural(marks, "mark", "marks");
        parts.push(if tags.is_empty() {
            marks
        } else if f.resolved.is_some() {
            format!("{marks}: {}", join(&kinds))
        } else {
            format!(
                "{marks} shown as {}: {}",
                plural(tags.len(), "change", "changes"),
                join(&kinds)
            )
        });
    }
    if formatting > 0 {
        parts.push(format!("{formatting} formatting"));
    }
    for (name, changes, marks) in others {
        parts.push(if changes == marks {
            format!("{changes} in {name}")
        } else {
            format!("{changes} in {name} ({})", plural(marks, "mark", "marks"))
        });
    }
    parts.join("; ")
}

pub(crate) fn render(f: &Facts) -> String {
    let mut out = String::from("---\n");
    kv(
        &mut out,
        &format!("source: {}", scalar(f.source, false)),
        None,
    );
    kv(&mut out, &format!("sha256: {}", f.sha256), None);
    if let Some(title) = &f.title {
        kv(&mut out, &format!("title: {}", scalar(title, false)), None);
    }
    let handle_list: Vec<String> = f
        .handles
        .order
        .iter()
        .filter(|a| {
            f.changes
                .iter()
                .any(|c| c.author.as_deref() == Some(a.as_str()))
        })
        .filter_map(|a| f.handles.by_author.get(a).cloned())
        .collect();
    let by = if handle_list.is_empty() {
        String::new()
    } else {
        format!(" by {}", join(&handle_list))
    };
    let threads: Vec<&CommentFact> = f
        .comments
        .iter()
        .filter(|c| c.parent.is_none() && c.anchored)
        .collect();
    let unanchored: Vec<&CommentFact> = f
        .comments
        .iter()
        .filter(|c| c.parent.is_none() && !c.anchored)
        .collect();
    match (f.resolved, f.comments_inline) {
        (None, true) => kv(
            &mut out,
            "view: tracked",
            Some("revisions as CriticMarkup, comments inline"),
        ),
        (None, false) => kv(
            &mut out,
            "view: tracked, comments hidden",
            Some(&format!(
                "{} ({}); carrying paragraphs are marked",
                plural(threads.len(), "thread open", "threads open"),
                plural(f.comments.len(), "comment", "comments")
            )),
        ),
        (Some(accept), _) => kv(
            &mut out,
            &format!("view: {}", if accept { "accept-all" } else { "reject-all" }),
            Some(&format!(
                "{}{by} shown as {}; file unchanged",
                plural(f.changes.len(), "revision", "revisions"),
                if accept { "accepted" } else { "rejected" }
            )),
        ),
    }
    if f.tracking_on {
        kv(
            &mut out,
            "track_changes: on",
            Some("w:trackRevisions set; edits are tracked"),
        );
    } else {
        kv(
            &mut out,
            "track_changes: off",
            Some("w:trackRevisions not set; new edits are not tracked unless edit sets it"),
        );
    }
    kv(
        &mut out,
        &format!("revisions: {}", f.changes.len()),
        Some(&revisions_comment(f)),
    );
    if f.comments.is_empty() {
        kv(&mut out, "comments: 0", None);
    } else {
        let open = threads.iter().filter(|c| !f.done.contains(&c.id)).count();
        let mut key = format!("comments: {}", plural(open, "thread open", "threads open"));
        if open < threads.len() {
            key.push_str(&format!(", {} resolved", threads.len() - open));
        }
        if !unanchored.is_empty() {
            key.push_str(&format!(", {} unanchored", unanchored.len()));
        }
        // Comment paragraphs in another style than Word's: the most
        // comments' style for all (`style Normal`), and each other one's
        // (`c6 style Normal`).
        let mut counts: Vec<(&str, usize)> = Vec::new();
        for comment in &f.comments {
            match counts.iter_mut().find(|(s, _)| *s == comment.style) {
                Some((_, n)) => *n += 1,
                None => counts.push((&comment.style, 1)),
            }
        }
        let most = counts
            .iter()
            .fold(None::<(&str, usize)>, |best, &(s, n)| match best {
                Some((_, m)) if m >= n => best,
                _ => Some((s, n)),
            })
            .map_or("CommentText", |(s, _)| s);
        if most != "CommentText" {
            key.push_str(&format!(
                ", style {}",
                crate::markdown::view_notes::style_token(most)
            ));
        }
        for comment in f.comments.iter().filter(|c| c.style != most) {
            key.push_str(&format!(
                ", c{} style {}",
                comment.id,
                crate::markdown::view_notes::style_token(&comment.style)
            ));
        }
        let mut list: Vec<String> = threads
            .iter()
            .map(|t| {
                let replies: Vec<String> = f
                    .comments
                    .iter()
                    .filter(|c| c.parent.as_deref() == Some(&t.id))
                    .map(|c| format!("c{}", c.id))
                    .collect();
                match replies.len() {
                    0 => format!("c{}", t.id),
                    1 => format!("c{} (+ reply {})", t.id, replies[0]),
                    _ => format!("c{} (+ replies {})", t.id, join(&replies)),
                }
            })
            .collect();
        list.extend(unanchored.iter().map(|c| {
            format!(
                "c{} (unanchored: not in the body or a note, Word shows no balloon)",
                c.id
            )
        }));
        // A quoted style id may hold `: ` or ` #`: the value is quoted then.
        let key = match key.split_once(": ") {
            Some((name, value)) => format!("{name}: {}", scalar(value, false)),
            None => key,
        };
        kv(
            &mut out,
            &key,
            Some(&format!(
                "{}: {}",
                plural(f.comments.len(), "comment", "comments"),
                join(&list)
            )),
        );
    }
    out.push_str("authors:\n");
    match &f.owner {
        Owner::Creator(name) => kv(
            &mut out,
            &format!("  document_owner: {}", scalar(name, false)),
            Some("dc:creator"),
        ),
        Owner::LastModifiedBy(name) => kv(
            &mut out,
            &format!("  document_owner: {}", scalar(name, false)),
            Some("cp:lastModifiedBy; no dc:creator"),
        ),
        Owner::Unnamed => kv(
            &mut out,
            "  document_owner: none",
            Some("docProps/core.xml names no dc:creator or cp:lastModifiedBy"),
        ),
        Owner::None => kv(
            &mut out,
            "  document_owner: none",
            Some("no docProps/core.xml"),
        ),
    }
    for author in &f.handles.order {
        let Some(handle) = f.handles.by_author.get(author) else {
            continue;
        };
        let revisions = f
            .changes
            .iter()
            .filter(|c| c.author.as_deref() == Some(author.as_str()))
            .count();
        let comments = f
            .comments
            .iter()
            .filter(|c| c.author.as_deref() == Some(author.as_str()))
            .count();
        let mut parts = Vec::new();
        if revisions > 0 {
            parts.push(plural(revisions, "revision", "revisions"));
        }
        if comments > 0 {
            parts.push(plural(comments, "comment", "comments"));
        }
        if let Some(date) = f.handles.unique_date(author) {
            parts.push(date.to_string());
        } else if let Some(date) = f.handles.latest_date(author) {
            parts.push(format!("latest {date}"));
        }
        kv(
            &mut out,
            &format!("  {handle}: {}", scalar(author, false)),
            Some(&join(&parts)),
        );
    }
    // `p0-pN`, or nothing to name in a body without paragraphs.
    let span = f
        .paragraphs
        .checked_sub(1)
        .map_or_else(|| "no paragraphs".to_string(), |last| format!("p0-p{last}"));
    kv(
        &mut out,
        &format!(
            "body: {span}, {}, {}",
            plural(f.tables, "table", "tables"),
            plural(f.pages, "page", "pages")
        ),
        Some(match f.pages_source {
            PagesSource::Layout => "pages from layout",
            PagesSource::Cached => "pages from Word's cached layout",
            PagesSource::Estimated => "page count estimated from breaks",
        }),
    );
    if let Some(range) = &f.range {
        let of = if f.paragraphs == 0 {
            String::new()
        } else {
            format!(" of {span}")
        };
        // A header or footer change shows on the headers:/footers: lines,
        // not as a body block.
        let note = f.stories_changed.then(|| {
            if range.ends_with("(none)") {
                "no body block; header and footer text is on the headers:/footers: lines"
            } else {
                "a header or footer change too: its text is on the headers:/footers: lines"
            }
        });
        kv(&mut out, &format!("range: {range}{of}"), note);
    }
    part_two(&mut out, f);
    out.push_str("---\n");
    out
}

/// A twips-valued attribute; Strict files write the universal measure
/// (`72pt`, `1in`) where Transitional writes the integer.
fn twips(e: &Element, attr: &str) -> Option<f64> {
    e.attr(attr).and_then(|v| {
        crate::util::parse_finite_f64(v).or_else(|| crate::util::universal_measure_twips(v))
    })
}

/// The page width less the side margins of `sect`, in twips, as the
/// writer computes it (`package.rs`): what it splits a table's columns
/// over when the table line gives no widths (#1472).
pub(crate) fn text_width(sect: Option<&Element>) -> u32 {
    let size = sect.and_then(|s| s.child("pgSz"));
    let margins = sect.and_then(|s| s.child("pgMar"));
    let width = size.and_then(|s| twips(s, "w")).unwrap_or(12240.0);
    let side = |a: &str| margins.and_then(|m| twips(m, a)).unwrap_or(1440.0);
    let text = (width - side("left") - side("right")).round().max(1440.0);
    // A width that does not fit in `u32` is no page Word writes. `as`
    // would saturate, so use the Letter text width instead.
    if text.is_finite() && text <= f64::from(u32::MAX) {
        text as u32
    } else {
        9360
    }
}

/// `Letter portrait, margins 1in, header/footer 0.5in` for a `w:sectPr`.
fn page_setup(sect: &Element) -> String {
    let size = sect.child("pgSz");
    let (w, h) = (
        size.and_then(|s| twips(s, "w")).unwrap_or(12240.0),
        size.and_then(|s| twips(s, "h")).unwrap_or(15840.0),
    );
    let landscape = size.and_then(|s| s.attr("orient")) == Some("landscape") || w > h;
    let (short, long) = if w < h { (w, h) } else { (h, w) };
    // Named sizes match on the rounded twip: 210mm is the 11906 an A4
    // spells, not the 11905 a truncating cast reads (#531). The names are
    // Word's own paper list, and the writer writes the same twips back
    // for each (#561); a twip off a named size is not that size.
    let name = match WORD_PAGE_SIZES.iter().find(|&&(_, w, h)| {
        (short.round() as i64, long.round() as i64) == (i64::from(w), i64::from(h))
    }) {
        // Word's paper list names the Tabloid sheet Ledger lying
        // landscape.
        Some(&(name, _, _)) if landscape && name == "Tabloid" => "Ledger".to_string(),
        Some(&(name, _, _)) => name.to_string(),
        _ => format!(
            "{}x{}",
            super::agent::inches(w).trim_end_matches("in"),
            super::agent::inches(h)
        ),
    };
    let mut out = format!(
        "{name} {}",
        if landscape { "landscape" } else { "portrait" }
    );
    if let Some(m) = sect.child("pgMar") {
        let side = |a: &str| twips(m, a).unwrap_or(1440.0);
        let (t, r, b, l) = (side("top"), side("right"), side("bottom"), side("left"));
        let inch = super::agent::inches;
        if t == r && r == b && b == l {
            out.push_str(&format!(", margins {}", inch(t)));
        } else {
            out.push_str(&format!(
                ", margins top {}, right {}, bottom {}, left {}",
                inch(t),
                inch(r),
                inch(b),
                inch(l)
            ));
        }
        let (hd, ft) = (
            twips(m, "header").unwrap_or(720.0),
            twips(m, "footer").unwrap_or(720.0),
        );
        if hd == ft {
            out.push_str(&format!(", header/footer {}", inch(hd)));
        } else {
            out.push_str(&format!(", header {}, footer {}", inch(hd), inch(ft)));
        }
        if let Some(g) = twips(m, "gutter").filter(|&g| g > 0.0) {
            out.push_str(&format!(", gutter {}", inch(g)));
        }
    }
    // Text columns, and their gap when it is not Word's 0.5in.
    if let Some(cols) = sect.child("cols")
        && let Some(num) = cols
            .attr("num")
            .and_then(|n| n.parse::<u32>().ok())
            .filter(|&n| n > 1)
    {
        out.push_str(&format!(", columns {num}"));
        if let Some(gap) = twips(cols, "space").filter(|&g| g != 720.0) {
            out.push_str(&format!(", column gap {}", super::agent::inches(gap)));
        }
        if cols
            .attr("sep")
            .is_some_and(|v| matches!(v, "1" | "true" | "on"))
        {
            out.push_str(", column line");
        }
    }
    // The grid lines snap to; a `w:docGrid` with no type is none.
    if let Some(grid) = sect.child("docGrid")
        && let Some(kind) = match grid.attr("type") {
            Some("lines") => Some("line grid"),
            Some("linesAndChars") => Some("line and char grid"),
            Some("snapToChars") => Some("char grid"),
            _ => None,
        }
        // A character grid needs no line pitch (`snapToChars` sets only
        // the character spacing); the line grids do.
        && let Some(pitch) = match twips(grid, "linePitch").filter(|&p| p > 0.0) {
            Some(pitch) => Some(Some(pitch)),
            None => (kind == "char grid").then_some(None),
        }
    {
        match pitch {
            Some(pitch) => {
                let points = format!("{:.2}", pitch / 20.0);
                let points = points.trim_end_matches('0').trim_end_matches('.');
                out.push_str(&format!(", {kind} {points}pt"));
            }
            None => out.push_str(&format!(", {kind}")),
        }
        if kind != "line grid"
            && let Some(space) = grid
                .attr("charSpace")
                .and_then(|c| c.parse::<i64>().ok())
                .filter(|&c| c != 0)
        {
            out.push_str(&format!(", char space {space}"));
        }
    }
    // How the section starts, when its `w:sectPr` states it: `nextPage`
    // is Word's default, but a document that says so keeps saying it
    // (#528). A value outside Word's five says nothing the view can write.
    if let Some(kind) = sect.child("type").and_then(|t| t.attr("val")).filter(|v| {
        matches!(
            *v,
            "nextPage" | "continuous" | "evenPage" | "oddPage" | "nextColumn"
        )
    }) {
        out.push_str(&format!(", starts {kind}"));
    }
    out
}

/// Resolved paragraph/run properties of a style through its `basedOn`
/// chain and the document defaults.
#[derive(Default)]
struct Resolved {
    character: bool,
    font: Option<String>,
    size_half_points: Option<f64>,
    bold: bool,
    italic: bool,
    before: Option<f64>,
    after: Option<f64>,
    line: Option<(f64, String)>,
    keep_next: bool,
    keep_lines: bool,
    contextual_spacing: bool,
    /// Twips.
    left: Option<f64>,
    /// Twips.
    right: Option<f64>,
    first_line: Option<f64>,
    hanging: Option<f64>,
    align: Option<String>,
}

fn style_by_id<'a>(styles: &'a Element, id: &str) -> Option<&'a Element> {
    styles
        .children_named("style")
        .find(|s| s.attr("styleId") == Some(id))
}

fn font_of(rpr: &Element, theme: Option<&Element>) -> Option<String> {
    let fonts = rpr.child("rFonts")?;
    if let Some(name) = fonts.attr("ascii") {
        return Some(name.to_string());
    }
    let which = fonts
        .attr("asciiTheme")
        .or_else(|| fonts.attr("hAnsiTheme"))?;
    let theme = theme?;
    let mut scheme = Vec::new();
    theme.find_all(
        if which.starts_with("major") {
            "majorFont"
        } else {
            "minorFont"
        },
        &mut scheme,
    );
    scheme
        .first()?
        .child("latin")?
        .attr("typeface")
        .map(str::to_string)
}

fn apply(r: &mut Resolved, ppr: Option<&Element>, rpr: Option<&Element>, theme: Option<&Element>) {
    if let Some(rpr) = rpr {
        if r.font.is_none() {
            r.font = font_of(rpr, theme);
        }
        if r.size_half_points.is_none() {
            // `w:sz` is half-points (`ST_HpsMeasure`), not twips: a strict
            // `"11pt"` is 22, as the plain `"22"` is.
            r.size_half_points = rpr.child("sz").and_then(|s| {
                s.attr("val").and_then(|v| {
                    crate::util::parse_finite_f64(v)
                        .or_else(|| crate::util::universal_measure_half_points(v))
                })
            });
        }
        r.bold |= rpr.toggle("b").unwrap_or(false);
        r.italic |= rpr.toggle("i").unwrap_or(false);
    }
    if let Some(ppr) = ppr {
        if let Some(sp) = ppr.child("spacing") {
            if r.before.is_none() {
                r.before = twips(sp, "before");
            }
            if r.after.is_none() {
                r.after = twips(sp, "after");
            }
            if r.line.is_none()
                && let Some(line) = twips(sp, "line")
            {
                r.line = Some((line, sp.attr("lineRule").unwrap_or("auto").to_string()));
            }
        }
        r.keep_next |= ppr.child("keepNext").is_some();
        r.keep_lines |= ppr.child("keepLines").is_some();
        r.contextual_spacing |= ppr.child("contextualSpacing").is_some();
        if let Some(ind) = ppr.child("ind") {
            if r.left.is_none() {
                r.left = twips(ind, "left").or_else(|| twips(ind, "start"));
            }
            if r.right.is_none() {
                r.right = twips(ind, "right").or_else(|| twips(ind, "end"));
            }
            if r.first_line.is_none() {
                r.first_line = twips(ind, "firstLine");
            }
            if r.hanging.is_none() {
                r.hanging = twips(ind, "hanging");
            }
        }
        if r.align.is_none() {
            r.align = ppr
                .child("jc")
                .and_then(|j| j.attr("val"))
                .map(str::to_string);
        }
    }
}

fn resolve(styles: Option<&Element>, theme: Option<&Element>, id: &str) -> Resolved {
    let Some(styles) = styles else {
        return Resolved::default();
    };
    let mut r = Resolved {
        character: style_by_id(styles, id).is_some_and(|s| s.attr("type") == Some("character")),
        ..Resolved::default()
    };
    let mut current = Some(id.to_string());
    let mut hops = 0;
    while let Some(sid) = current.take() {
        hops += 1;
        if hops > 16 {
            break;
        }
        let Some(style) = style_by_id(styles, &sid) else {
            break;
        };
        apply(&mut r, style.child("pPr"), style.child("rPr"), theme);
        current = style
            .child("basedOn")
            .and_then(|b| b.attr("val"))
            .map(str::to_string);
    }
    if let Some(defaults) = styles.child("docDefaults") {
        apply(
            &mut r,
            defaults.path(&["pPrDefault", "pPr"]),
            defaults.path(&["rPrDefault", "rPr"]),
            theme,
        );
    }
    r
}

/// Whether `style` is a paragraph style: ECMA-376 `w:style` reads "If
/// this attribute is not specified, then the default value shall be
/// assumed to be paragraph" (#1485 review).
pub(crate) fn is_paragraph_style(style: &Element) -> bool {
    style.attr("type").is_none_or(|t| t == "paragraph")
}

/// Each paragraph style's text size through its `basedOn` chain and the
/// document defaults, in half-points, and the size of a paragraph with no
/// `w:pStyle` (the default paragraph style's): what a paragraph's own
/// `size` clause is measured against (#1474). Word's own default is 10pt.
pub(crate) fn paragraph_style_sizes(
    styles: Option<&Element>,
    default_style: Option<&str>,
) -> (HashMap<String, u32>, u32) {
    let size = |id: &str| {
        let half = resolve(styles, None, id)
            .size_half_points
            .filter(|h| h.is_finite())
            .unwrap_or(20.0)
            .round();
        // `as` cannot truncate: the value is clamped to ST_HpsMeasure.
        half.clamp(1.0, 3276.0) as u32
    };
    let sizes = styles
        .into_iter()
        .flat_map(|root| root.children_named("style"))
        .filter(|s| is_paragraph_style(s))
        .filter_map(|s| s.attr("styleId"))
        .map(|id| (id.to_string(), size(id)))
        .collect();
    (sizes, size(default_style.unwrap_or("")))
}

fn points(twips: f64) -> String {
    let v = format!("{:.1}", twips / 20.0);
    v.trim_end_matches('0').trim_end_matches('.').to_string()
}

fn align_word(align: Option<&str>) -> &'static str {
    match align {
        Some("center") => "center",
        Some("right" | "end") => "right",
        Some("both" | "distribute") => "justify",
        _ => "left",
    }
}

/// The default style's line prints everything; a heading line always prints
/// its font and size, then only what differs from `base` (the default
/// style), so the legend reads as deviations. Indent, keep-lines and
/// contextual spacing follow keep-next. A zero indent is named only when
/// it differs from the base.
fn describe(r: &Resolved, base: Option<&Resolved>) -> String {
    let differs = |pick: fn(&Resolved) -> String| base.is_none_or(|b| pick(b) != pick(r));
    let mut parts = Vec::new();
    let mut font = r
        .font
        .clone()
        .unwrap_or_else(|| "Times New Roman".to_string());
    if r.bold {
        font.push_str(" bold");
    }
    if r.italic {
        font.push_str(" italic");
    }
    let size = r.size_half_points.unwrap_or(20.0) / 2.0;
    let size = format!("{size:.1}");
    parts.push(format!(
        "{font} {}pt",
        size.trim_end_matches('0').trim_end_matches('.')
    ));
    // Character styles carry run properties only. Paragraph defaults
    // (including the writer template's spacing) do not describe them.
    if r.character {
        return format!("character, {}", parts.join(", "));
    }
    // An omitted space is zero and an omitted line single. The default
    // style names neither; a style based on it names a zero or a single
    // line its base does not have, or the writer would give it the base's.
    for (word, pick) in [
        (
            "before",
            (|x: &Resolved| x.before) as fn(&Resolved) -> Option<f64>,
        ),
        ("after", |x: &Resolved| x.after),
    ] {
        let space = pick(r).unwrap_or(0.0);
        let shown = match base {
            None => space > 0.0,
            Some(b) => space != pick(b).unwrap_or(0.0),
        };
        if shown {
            parts.push(format!("{word} {}pt", points(space)));
        }
    }
    let single = (240.0, "auto".to_string());
    let line = r.line.clone().unwrap_or_else(|| single.clone());
    let shown = match base {
        None => line != single,
        Some(b) => line != b.line.clone().unwrap_or(single),
    };
    if shown {
        let (line, rule) = &line;
        if rule == "auto" {
            let ratio = format!("{:.2}", line / 240.0);
            let ratio = ratio.trim_end_matches('0').trim_end_matches('.');
            if ratio != "1" || base.is_some() {
                parts.push(format!("line {ratio}"));
            }
        } else {
            parts.push(format!("line {}pt {rule}", points(*line)));
        }
    }
    if r.keep_next && differs(|x| x.keep_next.to_string()) {
        parts.push("keep-next".to_string());
    }
    if r.keep_lines && differs(|x| x.keep_lines.to_string()) {
        parts.push("keep-lines".to_string());
    }
    // Left, then first-line, hanging and right (#1489): the order the
    // writer reads back.
    if differs(|x| format!("{:?}", x.left))
        && let Some(left) = r.left
        && (base.is_some() || left != 0.0)
    {
        parts.push(format!("indent {}", super::agent::inches(left)));
    }
    if differs(|x| format!("{:?}", x.first_line))
        && let Some(first) = r.first_line
        && (base.is_some() || first != 0.0)
    {
        parts.push(format!("first-line {}", super::agent::inches(first)));
    }
    if differs(|x| format!("{:?}", x.hanging))
        && let Some(hanging) = r.hanging
        && (base.is_some() || hanging != 0.0)
    {
        parts.push(format!("hanging {}", super::agent::inches(hanging)));
    }
    if differs(|x| format!("{:?}", x.right))
        && let Some(right) = r.right
        && (base.is_some() || right != 0.0)
    {
        parts.push(format!("right {}", super::agent::inches(right)));
    }
    if r.contextual_spacing && differs(|x| x.contextual_spacing.to_string()) {
        parts.push("contextual spacing".to_string());
    }
    match base {
        None => parts.push(align_word(r.align.as_deref()).to_string()),
        Some(b) if align_word(r.align.as_deref()) != align_word(b.align.as_deref()) => {
            parts.push(align_word(r.align.as_deref()).to_string());
        }
        Some(_) => {}
    }
    parts.join(", ")
}

/// `, named Text Heading 2`: the name of style `id` when it is not the one
/// the writer would give it (`expected`).
#[doc(hidden)]
pub fn named(styles: Option<&Element>, id: &str, expected: &str) -> String {
    styles
        .and_then(|s| style_by_id(s, id))
        .and_then(|s| s.child("name"))
        .and_then(|n| n.attr("val"))
        .filter(|name| *name != expected)
        .map(|name| format!(", named {name}"))
        .unwrap_or_default()
}

/// A legend `named` value: quoted (a JSON string) when it holds a comma
/// or a quote, so the clause's `, ` separator cannot split it (#549).
fn quoted_name(name: &str) -> String {
    if name.contains(',') || name.contains('"') {
        serde_json::to_string(name).unwrap_or_else(|_| format!("\"{name}\""))
    } else {
        name.to_string()
    }
}

fn table_style_line(styles: Option<&Element>, id: &str) -> String {
    // The style's name, when it is not the one the writer would give the
    // id (`9` is named `Normal Table`, `TableGrid0` `TableGrid`, #528).
    let named = styles
        .and_then(|s| style_by_id(s, id))
        .and_then(|s| s.child("name"))
        .and_then(|n| n.attr("val"))
        .filter(|name| {
            *name
                != super::super::package::word_table_style_name(id)
                    .unwrap_or_else(|| id.to_string())
        })
        .map(|name| format!(", named {}", quoted_name(name)))
        .unwrap_or_default();
    let borders = styles
        .and_then(|s| style_by_id(s, id))
        .and_then(|s| s.path(&["tblPr", "tblBorders"]));
    let Some(borders) = borders else {
        return format!("{id}{named}");
    };
    // The strict `start`/`end` elements name the `left`/`right` borders.
    let sides = [
        &["top"][..],
        &["left", "start"][..],
        &["bottom"][..],
        &["right", "end"][..],
        &["insideH"][..],
        &["insideV"][..],
    ];
    let sizes: Vec<Option<(String, String)>> = sides
        .iter()
        .map(|names| {
            names.iter().find_map(|side| borders.child(side)).map(|b| {
                (
                    b.attr("val").unwrap_or("").to_string(),
                    b.attr("sz").unwrap_or("").to_string(),
                )
            })
        })
        .collect();
    match sizes.first().cloned().flatten() {
        Some((val, sz))
            if val == "single"
                && sizes
                    .iter()
                    .all(|s| s.as_ref() == Some(&(val.clone(), sz.clone()))) =>
        {
            let pt = crate::util::parse_finite_f64(&sz)
                .map(|s| s / 8.0)
                .filter(|pt| pt.is_finite())
                .unwrap_or(0.5);
            let pt = format!("{pt:.2}");
            format!(
                "{id}, all borders {}pt{named}",
                pt.trim_end_matches('0').trim_end_matches('.')
            )
        }
        // Word's own styles are written as Word defines them, borders
        // and all.
        _ if super::super::package::is_built_in_table_style(id) => {
            format!("{id}, borders vary{named}")
        }
        _ => {
            let sides: Vec<String> = sides
                .iter()
                .zip(super::super::view_styles::TABLE_BORDER_SIDES)
                .filter_map(|(names, side)| {
                    let b = names.iter().find_map(|name| borders.child(name))?;
                    border_side(side, b)
                })
                .collect();
            if sides.is_empty() {
                format!("{id}{named}")
            } else {
                format!("{id}, borders {}{named}", sides.join(" "))
            }
        }
    }
}

/// One side of a `borders …` clause: `bottom double 0.75pt`, with
/// `#RRGGBB` for a colour that is not `auto` and `space Npt` for a
/// spacing that is not zero. A side with no value says nothing.
fn border_side(side: &str, b: &Element) -> Option<String> {
    let val = b.attr("val").filter(|v| !v.is_empty())?;
    let mut out = format!("{side} {val}");
    if let Some(sz) = b.attr("sz").and_then(crate::util::parse_finite_f64) {
        let points = sz / 8.0;
        if !points.is_finite() {
            return Some(out);
        }
        let pt = format!("{points:.2}");
        let _ = write!(out, " {}pt", pt.trim_end_matches('0').trim_end_matches('.'));
    }
    if let Some(color) = b
        .attr("color")
        .filter(|c| c.len() == 6 && c.chars().all(|c| c.is_ascii_hexdigit()))
    {
        let _ = write!(out, " #{color}");
    }
    if let Some(space) = b
        .attr("space")
        .and_then(|s| s.parse::<u32>().ok())
        .filter(|s| *s > 0)
    {
        let _ = write!(out, " space {space}pt");
    }
    Some(out)
}

/// The style the writer gives a `header` or `footer` paragraph the view
/// names no style for: Word's own.
pub(crate) fn story_style(kind: &str) -> &'static str {
    if kind == "header" { "Header" } else { "Footer" }
}

/// A paragraph's own tab stops (`w:tabs`), each `center 4680` or
/// `right dot 9360`. A stop Word would not keep is left out.
pub(crate) fn tab_stops(tabs: &Element) -> Vec<String> {
    tabs.children_named("tab")
        .filter_map(|tab| {
            // Strict and bidirectional text say `start` and `end`.
            let val = match tab.attr("val")? {
                "start" => "left",
                "end" => "right",
                val => val,
            };
            if !crate::markdown::xml::TAB_VALS.contains(&val) {
                return None;
            }
            let pos = tab_pos(tab.attr("pos")?)?;
            let leader = tab
                .attr("leader")
                .filter(|leader| crate::markdown::xml::TAB_LEADERS.contains(leader));
            Some(match leader {
                Some(leader) => format!("{val} {leader} {pos}"),
                None => format!("{val} {pos}"),
            })
        })
        .collect()
}

fn tab_pos(raw: &str) -> Option<i64> {
    let twips =
        crate::util::parse_finite_f64(raw).or_else(|| crate::util::universal_measure_twips(raw))?;
    let twips = twips.round();
    // `as` cannot truncate: the bound is checked first, and 31680 is exact.
    (twips.is_finite() && twips.abs() <= crate::markdown::xml::TAB_POS_LIMIT as f64)
        .then_some(twips as i64)
}

/// A paragraph's own shading (`w:shd`): `val`, then `color`, then `fill`.
pub(crate) fn shading_pairs(shd: &Element) -> Vec<(&'static str, String)> {
    let mut out = Vec::new();
    if let Some(val) = shd
        .attr("val")
        .filter(|val| crate::markdown::xml::SHD_VALS.contains(val))
    {
        out.push(("val", val.to_string()));
    }
    if let Some(color) = shd
        .attr("color")
        .filter(|color| crate::markdown::xml::shading_colour(color))
    {
        out.push(("color", color.to_string()));
    }
    if let Some(fill) = shd
        .attr("fill")
        .filter(|fill| crate::markdown::xml::shading_colour(fill))
    {
        out.push(("fill", fill.to_string()));
    }
    out
}

/// A story prints paragraph by paragraph (`p0: {text: …, color: …}`) when
/// one carries its own colour, borders, frame, indent, tab stops, spacing
/// or shading, or their alignments differ.
fn by_paragraph(s: &StoryFact) -> bool {
    s.paras.iter().any(|p| {
        p.color.is_some()
            || p.border.is_some()
            || p.frame.is_some()
            || !p.indent.is_empty()
            || !p.tabs.is_empty()
            || !p.spacing.is_empty()
            || !p.shading.is_empty()
            || p.align != s.align
    })
}

/// `p0: {text: …, center, color: "595959", border: bottom single 0.5pt,
/// frame: {wrap: none, y: 1}}`, one per paragraph.
fn paragraph_entries(s: &StoryFact) -> Vec<String> {
    std::iter::once(&s.text)
        .chain(&s.more)
        .zip(&s.paras)
        .enumerate()
        .map(|(k, (text, p))| {
            let mut inner = format!("text: {}", scalar(text, true));
            if let Some(align) = p.align {
                inner.push_str(&format!(", {align}"));
            }
            if !p.indent.is_empty() {
                let sides: Vec<String> = p
                    .indent
                    .iter()
                    .map(|(side, inches)| format!("{side}: {inches}"))
                    .collect();
                inner.push_str(&format!(", indent: {{{}}}", sides.join(", ")));
            }
            if let Some(color) = &p.color {
                inner.push_str(&format!(", color: {}", scalar(color, true)));
            }
            if let Some(border) = &p.border {
                inner.push_str(&format!(", border: {}", scalar(border, true)));
            }
            if let Some(frame) = &p.frame {
                inner.push_str(&format!(", frame: {frame}"));
            }
            if !p.tabs.is_empty() {
                let items: Vec<String> = p.tabs.iter().map(|stop| scalar(stop, true)).collect();
                inner.push_str(&format!(", tabs: [{}]", items.join(", ")));
            }
            if !p.spacing.is_empty() {
                inner.push_str(&format!(
                    ", spacing: {}",
                    scalar(&p.spacing.join(", "), true)
                ));
            }
            if !p.shading.is_empty() {
                let items: Vec<String> = p
                    .shading
                    .iter()
                    .map(|(name, value)| format!("{name}: {}", scalar(value, true)))
                    .collect();
                inner.push_str(&format!(", shading: {{{}}}", items.join(", ")));
            }
            format!("p{}: {{{inner}}}", s.first + k)
        })
        .collect()
}

/// A story's entries after its text: its styles, `inactive`, its changes.
fn story_tail(s: &StoryFact) -> Vec<String> {
    let mut tail = Vec::new();
    match s.styles.as_slice() {
        [] => {}
        [style] => tail.push(format!("style: {}", scalar(style, true))),
        styles => {
            let all: Vec<String> = styles.iter().map(|s| scalar(s, true)).collect();
            tail.push(format!("styles: [{}]", all.join(", ")));
        }
    }
    if !s.active {
        tail.push("inactive".to_string());
    }
    for (key, tags) in [("rev", &s.rev), ("fmt", &s.fmt)] {
        if !tags.is_empty() {
            tail.push(format!("{key}: {}", scalar(&tags.join("; "), true)));
        }
    }
    tail
}

/// A story's entry in the first section's block: one line, or, paragraph
/// by paragraph, `key:` then its entries indented below.
fn story_kv(out: &mut String, key: &str, s: &StoryFact, comment: Option<&str>) {
    if !by_paragraph(s) {
        kv(out, &format!("{key}: {}", entry(s)), comment);
        return;
    }
    kv(out, &format!("{key}:"), comment);
    out.push_str(&format!("    id: {}\n", scalar(&s.part, true)));
    for line in paragraph_entries(s).into_iter().chain(story_tail(s)) {
        // A block mapping's flag needs a value.
        let line = if line == "inactive" {
            "inactive: true".to_string()
        } else {
            line
        };
        out.push_str(&format!("    {line}\n"));
    }
}

fn entry(s: &StoryFact) -> String {
    if by_paragraph(s) {
        let items: Vec<String> = std::iter::once(format!("id: {}", scalar(&s.part, true)))
            .chain(paragraph_entries(s))
            .chain(story_tail(s))
            .collect();
        return format!("{{{}}}", items.join(", "));
    }
    let text = if s.more.is_empty() {
        scalar(&s.text, true)
    } else {
        let all: Vec<String> = std::iter::once(&s.text)
            .chain(&s.more)
            .map(|t| scalar(t, true))
            .collect();
        format!("[{}]", all.join(", "))
    };
    let mut inner = format!("id: {}, text: {text}", scalar(&s.id, true));
    if let Some(align) = s.align {
        inner.push_str(&format!(", {align}"));
    }
    for item in story_tail(s) {
        inner.push_str(&format!(", {item}"));
    }
    format!("{{{inner}}}")
}

/// The `headers:` / `footers:` blocks of the first section.
fn first_section_stories(out: &mut String, section: &SectionFact) {
    for kind in ["header", "footer"] {
        let stories: Vec<&StoryFact> = section.stories.iter().filter(|s| s.kind == kind).collect();
        if stories.is_empty() && !section.title_page {
            continue;
        }
        out.push_str(&format!("{kind}s:\n"));
        let find = |ty: &str| stories.iter().find(|s| s.ty == ty);
        if section.title_page {
            match find("first") {
                Some(s) => story_kv(
                    out,
                    "  first",
                    s,
                    Some("page 1 only (different first page)"),
                ),
                None => kv(
                    out,
                    "  first: none",
                    Some(if kind == "footer" {
                        "page 1 shows no page number"
                    } else {
                        "page 1 shows no header"
                    }),
                ),
            }
        }
        if !section.title_page
            && let Some(s) = find("first")
        {
            story_kv(
                out,
                "  first",
                s,
                Some("defined, but different first page is off"),
            );
        }
        match find("default") {
            Some(s) => story_kv(out, "  default", s, None),
            None => kv(out, "  default: none", None),
        }
        if let Some(s) = find("even") {
            story_kv(
                out,
                "  even",
                s,
                if s.active {
                    None
                } else {
                    Some("defined, but even/odd headers are off")
                },
            );
        }
    }
}

/// `{p2-p3, page: …, columns 2, headers: {default: {…}}}`: what a later section
/// changes against the one before it (page setup against the first).
fn section_entry(
    section: &SectionFact,
    previous: &SectionFact,
    first: &SectionFact,
    handles: Option<&Handles>,
) -> String {
    let mut parts = vec![format!("p{}-p{}", section.first, section.last)];
    let setup = |s: &SectionFact| s.sect_pr.as_ref().map(page_setup);
    let earlier = changed_page(section);
    if (setup(section) != setup(first) || earlier.is_some())
        && let Some(page) = setup(section)
    {
        let mut text = format!("page: {page}");
        if let Some(earlier) = earlier {
            text.push_str(&format!("; was: {earlier}"));
        }
        parts.push(text);
    }
    if let Some(tags) = handles.and_then(|h| section_changes(section, h)) {
        parts.push(format!("fmt: {}", scalar(&tags, true)));
    }
    for kind in ["header", "footer"] {
        // w:titlePg is the section's own: a section that has it names its
        // first-page story, or `first: none`, even when inherited.
        let mut changed: Vec<String> = section
            .stories
            .iter()
            .filter(|s| s.kind == kind)
            .filter(|s| {
                (s.ty == "first" && section.title_page)
                    || !previous
                        .stories
                        .iter()
                        .any(|p| p.kind == s.kind && p.ty == s.ty && p.id == s.id)
            })
            .map(|s| format!("{}: {}", s.ty, entry(s)))
            .collect();
        if section.title_page
            && !section
                .stories
                .iter()
                .any(|s| s.kind == kind && s.ty == "first")
        {
            changed.insert(0, "first: none".to_string());
        }
        if !changed.is_empty() {
            parts.push(format!("{kind}s: {{{}}}", changed.join(", ")));
        }
    }
    format!("{{{}}}", parts.join(", "))
}

/// The page a `w:sectPrChange` recorded, when it is not the live page.
/// Reject restores it; a copy of the live page would not (#1475).
fn changed_page(section: &SectionFact) -> Option<String> {
    let sect = section.sect_pr.as_ref()?;
    let saved = sect
        .children_named("sectPrChange")
        .next()?
        .child("sectPr")?;
    let earlier = page_setup(saved);
    (earlier != page_setup(sect)).then_some(earlier)
}

/// The tracked view's tags for a section's own changes (`w:sectPrChange`):
/// `r9 @AC`.
fn section_changes(section: &SectionFact, handles: &Handles) -> Option<String> {
    let sect = section.sect_pr.as_ref()?;
    let tags: Vec<String> = sect
        .children_named("sectPrChange")
        .map(|change| super::agent::required_date_tag_of(change, handles))
        .collect();
    (!tags.is_empty()).then(|| super::agent::format_tags(&tags))
}

/// `Normal: pPr styles.r0 @AS; rPr styles.r3 @AS`: the styles part's
/// tracked changes by the style that holds them (`docDefaults` for the
/// document defaults), each tag naming the property it was read from.
fn style_changes(styles: &Element, handles: &Handles) -> Vec<(String, String)> {
    let mut found = Vec::new();
    for holder in styles.elements() {
        let name = match holder.local() {
            "docDefaults" => "docDefaults".to_string(),
            "style" => match holder.attr("styleId") {
                Some(id) => id.to_string(),
                None => continue,
            },
            _ => continue,
        };
        let mut carriers = Vec::new();
        collect_style_carriers(holder, &mut carriers);
        let mut tags: Vec<String> = Vec::new();
        for (carrier, kind) in carriers {
            let tag = format!(
                "{kind} {}",
                super::agent::format_tag(&format!(
                    "styles#{}",
                    super::agent::required_date_tag_of(carrier, handles)
                ))
            );
            if !tags.contains(&tag) {
                tags.push(tag);
            }
        }
        if !tags.is_empty() {
            found.push((name, tags.join("; ")));
        }
    }
    found
}

/// Direct property carriers, then any other id-bearing carrier. A change's
/// historical payload is not a current property.
fn collect_style_carriers<'e>(holder: &'e Element, out: &mut Vec<(&'e Element, &'static str)>) {
    if holder.local() == "docDefaults" {
        push_direct(holder.path(&["pPrDefault", "pPr"]), "pPrChange", "pPr", out);
        push_direct(holder.path(&["rPrDefault", "rPr"]), "rPrChange", "rPr", out);
    } else {
        for paragraph in holder.children_named("pPr") {
            push_direct(Some(paragraph), "pPrChange", "pPr", out);
        }
        for run in holder.children_named("rPr") {
            push_direct(Some(run), "rPrChange", "rPr", out);
        }
    }
    collect_other(holder, out);
}

fn push_direct<'e>(
    parent: Option<&'e Element>,
    change: &str,
    kind: &'static str,
    out: &mut Vec<(&'e Element, &'static str)>,
) {
    let Some(parent) = parent else {
        return;
    };
    for carrier in parent.elements() {
        if carrier.local() == change && carrier.attr("id").is_some() {
            out.push((carrier, kind));
        }
    }
}

fn collect_other<'e>(element: &'e Element, out: &mut Vec<(&'e Element, &'static str)>) {
    for child in element.elements() {
        let local = child.local();
        if (local.ends_with("Change") || matches!(local, "ins" | "del"))
            && child.attr("id").is_some()
        {
            if !out.iter().any(|(seen, _)| std::ptr::eq(*seen, child)) {
                out.push((child, "other"));
            }
            continue;
        }
        collect_other(child, out);
    }
}

fn part_two(out: &mut String, f: &Facts) {
    if let Some(first) = f.sections.first()
        && let Some(sect) = first.sect_pr.as_ref()
    {
        let mut page = page_setup(sect);
        if let Some(earlier) = changed_page(first) {
            page.push_str(&format!("; was: {earlier}"));
        }
        if f.resolved.is_none()
            && let Some(tags) = section_changes(first, f.handles)
        {
            page.push_str(&format!("; fmt {tags}"));
        }
        kv(out, &format!("page: {page}"), None);
    }
    out.push_str("styles:\n");
    let default = f.default_style.unwrap_or("Normal");
    let base = resolve(f.styles, f.theme, default);
    // A style a tracked change names but no paragraph uses still gets a
    // legend line after the used ones, so the view's own docx defines it
    // and the change has a holder there. The changed list's order is the
    // styles part's; the writer keeps it, so the next view names the same
    // order.
    let changes = if f.resolved.is_none() {
        f.styles
            .map(|styles| style_changes(styles, f.handles))
            .unwrap_or_default()
    } else {
        Vec::new()
    };
    kv(
        out,
        &format!(
            "  {}: {}",
            scalar(default, false),
            scalar(
                &format!(
                    "{}{}",
                    describe(&base, None),
                    named(f.styles, default, default)
                ),
                false
            )
        ),
        Some("default; unannotated paragraphs use it"),
    );
    for (level, style) in &f.heading_styles {
        // The writer names a `HeadingN` style `heading N`, as Word does.
        let expected = style
            .strip_prefix("Heading")
            .filter(|n| n.parse::<u32>().is_ok())
            .map_or_else(|| style.clone(), |n| format!("heading {n}"));
        kv(
            out,
            &format!(
                "  \"{}\": {}",
                "#".repeat(*level),
                scalar(
                    &format!(
                        "{style}, {}{}",
                        describe(&resolve(f.styles, f.theme, style), Some(&base)),
                        named(f.styles, style, &expected)
                    ),
                    false
                )
            ),
            None,
        );
    }
    for style in &f.other_styles {
        let source = f.note_style_sources.get(style).unwrap_or(style);
        kv(
            out,
            &format!(
                "  {}: {}",
                scalar(style, false),
                scalar(
                    &format!(
                        "{}{}",
                        describe(&resolve(f.styles, f.theme, source), Some(&base)),
                        named(f.styles, source, style)
                    ),
                    false
                )
            ),
            None,
        );
    }
    for (style, _) in &changes {
        if style.as_str() == "docDefaults"
            || style == default
            || f.heading_styles.iter().any(|(_, h)| h == style)
            || f.other_styles.iter().any(|o| o == style)
        {
            continue;
        }
        kv(
            out,
            &format!(
                "  {}: {}",
                scalar(style, false),
                scalar(
                    &format!(
                        "{}{}",
                        describe(&resolve(f.styles, f.theme, style), Some(&base)),
                        named(f.styles, style, style)
                    ),
                    false
                )
            ),
            Some("tracked changes to it"),
        );
    }
    match f.table_styles.as_slice() {
        [] => {}
        [one] if !f.tables_differ => kv(
            out,
            &format!(
                "  table: {}",
                scalar(&table_style_line(f.styles, one), false)
            ),
            None,
        ),
        many => kv(
            out,
            &format!(
                "  tables: {}",
                scalar(
                    &many
                        .iter()
                        .map(|id| table_style_line(f.styles, id))
                        .collect::<Vec<_>>()
                        .join(", "),
                    false
                )
            ),
            None,
        ),
    }
    if !changes.is_empty() {
        // Legend order: `docDefaults` leads, then the default style, then the
        // styles the body uses, then the ones only a change names. The key
        // is a pair of tiers, because `usize::MIN` is zero: one number
        // cannot put `docDefaults` ahead of the default style, which is
        // keyed 0 (#1521 review).
        let order = |id: &str| -> (u8, usize) {
            if id == "docDefaults" {
                return (0, 0);
            }
            if id == default {
                return (1, 0);
            }
            f.heading_styles
                .iter()
                .position(|(_, h)| h == id)
                .map(|i| (1, i + 1))
                .or_else(|| {
                    f.other_styles
                        .iter()
                        .position(|o| o == id)
                        .map(|i| (1, i + 1 + f.heading_styles.len()))
                })
                .unwrap_or_else(|| {
                    changes
                        .iter()
                        .position(|(holder, _)| holder == id)
                        .map_or((2, 0), |i| (2, i))
                })
        };
        let mut ordered = changes.clone();
        ordered.sort_by_key(|(holder, _)| order(holder));
        let list: Vec<String> = ordered
            .iter()
            .map(|(style, tags)| format!("{}: {}", scalar(style, true), scalar(tags, true)))
            .collect();
        let loss = ordered.iter().any(|(style, tags)| {
            style == "docDefaults" || tags.split("; ").any(|tag| tag.starts_with("other "))
        });
        let note = if loss {
            "tracked changes to the styles; docDefaults and other changes are not written back"
        } else {
            "tracked changes to the styles"
        };
        kv(
            out,
            &format!("style_changes: {{{}}}", list.join(", ")),
            Some(note),
        );
    }
    let (rev, fmt) = &f.note_changes;
    let mut clauses: Vec<String> = [("rev", rev), ("fmt", fmt)]
        .into_iter()
        .filter(|(_, tags)| !tags.is_empty())
        .map(|(key, tags)| format!("{key}: {}", scalar(&tags.join("; "), true)))
        .collect();
    let changes = !clauses.is_empty();
    if !f.empty_notes.is_empty() {
        clauses.push(format!("empty: [{}]", f.empty_notes.join(", ")));
    }
    if !clauses.is_empty() {
        kv(
            out,
            &format!("notes: {{{}}}", clauses.join(", ")),
            Some(if changes {
                "changes in notes the body does not show (separators)"
            } else {
                "notes parts that hold no note"
            }),
        );
    }
    if !f.unplaced.is_empty() {
        kv(
            out,
            &format!(
                "unplaced: [{}]",
                f.unplaced
                    .iter()
                    .map(|e| scalar(e, true))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Some("changes no other line shows (text boxes, Word's Fallback copies)"),
        );
    }
    if let Some(first) = f.sections.first() {
        first_section_stories(out, first);
        if f.sections.len() > 1 {
            out.push_str("sections:\n");
            for (i, section) in f.sections.iter().enumerate().skip(1) {
                kv(
                    out,
                    &format!(
                        "  {}: {}",
                        i + 1,
                        section_entry(
                            section,
                            &f.sections[i - 1],
                            first,
                            f.resolved.is_none().then_some(f.handles)
                        )
                    ),
                    None,
                );
            }
        }
    }
}

/// A header/footer part's paragraphs in document order, numbered as `edit`
/// numbers a story (`inspect::story_paragraph_nodes`): every `w:p` outside
/// text boxes, table cells and content controls included.
pub(crate) fn story_paragraphs(root: &Element) -> Vec<&Element> {
    super::agent::paragraphs(root)
}

/// How `story_text` reads a header or footer's tracked changes.
#[derive(Clone, Copy)]
pub(crate) enum StoryView<'a> {
    /// The agent's tracked view, with the handles and the part's stem:
    /// `{++DRAFT++}{header1.r1 @AC}`, `{--old--}{header1.r2 @AC}`;
    /// document text that reads like CriticMarkup is escaped.
    Tagged(&'a super::agent::Handles, &'a str),
    /// Every change accepted: inserted and moved-to runs count, deleted and
    /// moved-from runs do not. With the character styles that hide a run.
    Accept(&'a std::collections::HashSet<String>),
    /// Every change rejected: deleted and moved-from runs count, inserted
    /// and moved-to runs do not.
    Reject(&'a std::collections::HashSet<String>),
}

/// A header/footer paragraph's text with fields as the body prints them,
/// `{CODE}result{/}` (`{PAGE}1{/}`, `{HYPERLINK "https://…"}site{/}`), and a
/// code jubarte does not print whole as its name alone (`{XE}`), as is a
/// code holding a nested field (`{IF}`). A field nested in another's result
/// prints its result. Line breaks are newlines. Runs inside hyperlinks,
/// content controls, smart tags and custom XML count; tracked changes read
/// as `view` says.
/// [`story_text_with`] without drawing capture: the tests' view.
#[cfg(test)]
fn story_text(p: &Element, view: StoryView) -> String {
    story_text_with(p, view, &mut |_, _| None)
}

/// `story_text`, calling `draw` for each `w:drawing`, `w:pict`, `w:object`
/// and drawing-holding `mc:AlternateContent` element: its Markdown (`None`
/// prints nothing). The `bool` says the element is run content, spliced
/// inside a `w:r` (`true`) or where a `w:r` may sit (`false`, a
/// paragraph-level AlternateContent).
pub(crate) fn story_text_with(
    p: &Element,
    view: StoryView,
    draw: &mut dyn FnMut(&Element, bool) -> Option<String>,
) -> String {
    struct State<'a> {
        out: String,
        /// Open complex fields, outermost first.
        fields: Vec<Open>,
        view: StoryView<'a>,
        /// Inside deleted text the view shows.
        deleting: bool,
        /// The body's revision fold, fed the story's already-rendered pieces.
        critic: super::critic::Critic,
        /// Text already handed to the fold; field offsets stay in `out`.
        flushed: usize,
        /// How many printed fields' results the walk is in.
        in_result: usize,
    }
    /// A complex field being read.
    #[derive(Default)]
    struct Open {
        /// The instruction so far.
        instr: String,
        /// Past its `separate`: in its result.
        result: bool,
        /// Its code printed whole: `{CODE}`, its result, then `{/}`.
        printed: bool,
        /// A field nested in its instruction, which a code cannot print.
        nested: bool,
        /// Where its result starts in the text, once its code is printed.
        at: usize,
    }
    /// A printed field's end: `{/}`, or nothing when it has no result and
    /// its code is a bare name, which the writer reads as `{PAGE}`. A
    /// field in another's result always ends: `{PAGE}{NUMPAGES}{/}` would
    /// read as a bare PAGE, then NUMPAGES with no result.
    fn field_end(out: &str, at: usize, instr: &str, nested: bool) -> &'static str {
        let bare = !instr.trim().is_empty()
            && instr
                .trim()
                .bytes()
                .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit());
        if bare && !nested && out.len() == at {
            ""
        } else {
            super::FIELD_END
        }
    }
    /// `ins`/`moveTo` → `Some(true)`, `del`/`moveFrom` → `Some(false)`.
    fn inserting(local: &str) -> Option<bool> {
        match local {
            "ins" | "moveTo" => Some(true),
            "del" | "moveFrom" => Some(false),
            _ => None,
        }
    }
    fn code(instr: &str) -> String {
        let name = instr
            .split_whitespace()
            .next()
            .unwrap_or("FIELD")
            .to_uppercase();
        format!("{{{name}}}")
    }
    fn walk(
        parent: &Element,
        s: &mut State,
        draw: &mut dyn FnMut(&Element, bool) -> Option<String>,
    ) {
        for run in parent.elements() {
            match run.local() {
                "drawing" | "pict" | "object" => {
                    if let Some(markdown) = draw(run, true) {
                        s.out.push_str(&markdown);
                    }
                }
                "AlternateContent" if super::drawing::capturable_alternate(run) => {
                    if let Some(markdown) = draw(run, false) {
                        s.out.push_str(&markdown);
                    }
                }
                "AlternateContent" => {
                    if let Some(choice) = super::agent::shown_branch(run) {
                        walk(choice, s, draw);
                    }
                }
                "fldSimple" => {
                    let instr = run.attr("instr").unwrap_or("");
                    match super::printed_code(instr).filter(|_| s.fields.is_empty()) {
                        Some(code) => {
                            s.out.push_str(&code);
                            let at = s.out.len();
                            let nested = s.in_result > 0;
                            s.in_result += 1;
                            walk(run, s, draw);
                            s.in_result -= 1;
                            s.out.push_str(field_end(&s.out, at, instr, nested));
                        }
                        None if s.fields.is_empty() => s.out.push_str(&code(instr)),
                        None => walk(run, s, draw),
                    }
                }
                local if inserting(local).is_some() => {
                    let inserted = inserting(local) == Some(true);
                    let tagged = match s.view {
                        StoryView::Tagged(handles, stem) if s.fields.is_empty() => {
                            Some((handles, stem))
                        }
                        _ => None,
                    };
                    let shown = match s.view {
                        StoryView::Tagged(..) => tagged.is_some() || inserted,
                        StoryView::Accept(_) => inserted,
                        StoryView::Reject(_) => !inserted,
                    };
                    if !shown {
                        continue;
                    }
                    let mark = if inserted {
                        super::critic::Mark::Insertion
                    } else {
                        super::critic::Mark::Deletion
                    };
                    if let Some((handles, stem)) = tagged {
                        s.flush();
                        let by = format!(
                            "{}{stem}#{}",
                            super::critic::TAG,
                            super::agent::required_date_tag_of(run, handles)
                        );
                        s.critic.open(mark, Some(&by));
                    }
                    // #1134: an insertion inside a deletion still carries
                    // delText. Keep that enclosing deletion while reading it.
                    let deleting = s.deleting;
                    s.deleting |= !inserted;
                    walk(run, s, draw);
                    s.deleting = deleting;
                    if tagged.is_some() {
                        s.flush();
                        s.critic.close(mark);
                    }
                }
                "hyperlink" | "smartTag" | "customXml" => walk(run, s, draw),
                "sdt" => {
                    if let Some(content) = run.child("sdtContent") {
                        walk(content, s, draw);
                    }
                }
                "r" => {
                    // A hidden run prints nothing, as in the body.
                    let hidden = match s.view {
                        StoryView::Tagged(handles, _) => &handles.hidden_styles,
                        StoryView::Accept(hidden) | StoryView::Reject(hidden) => hidden,
                    };
                    if super::agent::hidden_run(run.child("rPr"), hidden) {
                        continue;
                    }
                    // A field's pieces print its code (`{PAGE}`, `{/}`),
                    // which marks must not wrap: the code is no text, and
                    // a wrapped separate moves the end past a result-less
                    // field's start, so it would gain `{/}`.
                    let field_piece = run.elements().any(|child| {
                        matches!(child.local(), "fldChar" | "instrText" | "delInstrText")
                    });
                    let wrap = match s.view {
                        StoryView::Tagged(..) if !field_piece => character_wrap(run),
                        _ => None,
                    };
                    let before = s.out.len();
                    for child in run.elements() {
                        run_content(child, s, draw);
                    }
                    if let Some((open, close)) = wrap
                        && s.out.len() > before
                    {
                        s.out.insert_str(before, &open);
                        s.out.push_str(&close);
                    }
                }
                _ => {}
            }
        }
    }
    /// One child of a `w:r` (or of a run-level `mc:Choice`): text, field
    /// characters, breaks, and drawings `draw` renders.
    fn run_content(
        child: &Element,
        s: &mut State,
        draw: &mut dyn FnMut(&Element, bool) -> Option<String>,
    ) {
        match child.local() {
            "drawing" | "pict" | "object" => {
                if let Some(markdown) = draw(child, true) {
                    s.out.push_str(&markdown);
                }
            }
            "AlternateContent" if super::drawing::holds_drawing(child) => {
                if let Some(markdown) = draw(child, true) {
                    s.out.push_str(&markdown);
                }
            }
            "AlternateContent" => {
                if let Some(choice) = super::agent::shown_branch(child) {
                    for inner in choice.elements() {
                        run_content(inner, s, draw);
                    }
                }
            }
            _ => {
                {
                    match child.local() {
                        "fldChar" => match child.attr("fldCharType") {
                            Some("begin") => {
                                if let Some(field) = s.fields.last_mut().filter(|f| !f.result) {
                                    field.nested = true;
                                }
                                s.fields.push(Open::default());
                            }
                            Some("separate") => {
                                let outermost = s.fields.len() == 1;
                                if let Some(field) = s.fields.last_mut() {
                                    field.result = true;
                                    if outermost
                                        && !field.nested
                                        && let Some(code) = super::printed_code(&field.instr)
                                    {
                                        field.printed = true;
                                        s.out.push_str(&code);
                                        field.at = s.out.len();
                                    }
                                }
                            }
                            Some("end") => {
                                if let Some(field) = s.fields.pop()
                                    && s.fields.is_empty()
                                {
                                    s.out.push_str(&if field.printed {
                                        field_end(&s.out, field.at, &field.instr, s.in_result > 0)
                                            .to_string()
                                    } else {
                                        code(&field.instr)
                                    });
                                }
                            }
                            _ => {}
                        },
                        "instrText" | "delInstrText" => {
                            if let Some(field) = s.fields.last_mut().filter(|f| !f.result) {
                                field.instr.push_str(&child.text());
                            }
                        }
                        // Only a printed field's result shows, and not
                        // the code of a field nested in it.
                        _ if !(s.fields.is_empty()
                            || s.fields[0].printed && s.fields.iter().all(|f| f.result)) => {}
                        "t" => s.push_text(&child.text()),
                        "delText" if s.deleting => s.push_text(&child.text()),
                        "tab" => s.out.push('\t'),
                        "br" | "cr" => s.out.push('\n'),
                        _ => {}
                    }
                }
            }
        }
    }
    impl State<'_> {
        fn flush(&mut self) {
            self.critic.raw(&self.out[self.flushed..]);
            self.flushed = self.out.len();
        }

        /// Document text; the tagged view escapes what reads like a mark,
        /// and every view text that reads like a field code (`\{PAGE}`),
        /// as the body does.
        fn push_text(&mut self, text: &str) {
            let text = escape_field_codes(text);
            match self.view {
                StoryView::Tagged(..) => self.out.push_str(&super::critic::escape(&text)),
                _ => self.out.push_str(&text),
            }
        }
    }
    let mut s = State {
        out: String::new(),
        fields: Vec::new(),
        view,
        deleting: false,
        critic: super::critic::Critic::default(),
        flushed: 0,
        in_result: 0,
    };
    walk(p, &mut s, draw);
    if matches!(view, StoryView::Tagged(..)) {
        s.flush();
        let mut text = s.critic.into_story().trim().to_string();
        if let StoryView::Tagged(handles, story) = view
            && let Some(pr) = p.path(&["pPr", "rPr"])
        {
            for mark in pr.elements().filter(|mark| mark.is("ins")) {
                let tag = super::agent::format_tag(&format!(
                    "{story}#{}",
                    super::agent::required_date_tag_of(mark, handles)
                ));
                text.push_str(&format!("¶{{{tag}}}"));
            }
        }
        text
    } else {
        s.out.trim().to_string()
    }
}

/// `text` with a backslash before each `{` the writer would read as a
/// field: one that opens what reads like a field code (`{PAGE \* roman}`),
/// a bare name (`{SELLER}`, `{1999}`) or a result's end (`{/}`), so text
/// typed in a header stays text.
fn escape_field_codes(text: &str) -> std::borrow::Cow<'_, str> {
    use crate::markdown::critic::{field_code_close, is_field_code};
    let opens = |at: usize| {
        let after = &text[at + 1..];
        after.starts_with("/}")
            || after.find('}').is_some_and(|end| {
                end > 0
                    && after[..end]
                        .bytes()
                        .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
            })
            || field_code_close(after.char_indices())
                .is_some_and(|close| is_field_code(&after[..close]))
    };
    if !text.char_indices().any(|(at, c)| c == '{' && opens(at)) {
        return std::borrow::Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len() + 2);
    for (at, c) in text.char_indices() {
        if c == '{' && opens(at) {
            out.push('\\');
        }
        out.push(c);
    }
    std::borrow::Cow::Owned(out)
}

/// The character marks a story run prints: open tags, then their closers.
/// Direct run properties only. Yellow is a bare `<mark>`; any other named
/// colour keeps `class="hl-…"`. Bold, italic, underline, strike, code and
/// vertical alignment use the same tags as the body.
fn character_wrap(run: &Element) -> Option<(String, String)> {
    let rpr = run.child("rPr")?;
    let bold = rpr.toggle("b") == Some(true);
    let italic = rpr.toggle("i") == Some(true);
    let underline = rpr.child("u").is_some_and(super::is_underlined);
    let strike = rpr.toggle("strike") == Some(true);
    let highlight = rpr
        .child("highlight")
        .and_then(|mark| mark.attr("val"))
        .and_then(super::highlight_color);
    let code = rpr.child("rStyle").and_then(|style| style.attr("val")) == Some("VerbatimChar")
        || super::font_of(rpr).is_some_and(|font| super::is_monospace(&font));
    let raised = rpr.child("vertAlign").and_then(|align| align.attr("val"));
    let sup = raised == Some("superscript");
    let sub = raised == Some("subscript");
    if !(bold || italic || underline || strike || highlight.is_some() || code || sup || sub) {
        return None;
    }
    let mut open = String::new();
    let mut close = String::new();
    let push = |open: &mut String, close: &mut String, start: &str, end: &str| {
        open.push_str(start);
        close.insert_str(0, end);
    };
    if bold {
        push(&mut open, &mut close, "<b>", "</b>");
    }
    if italic {
        push(&mut open, &mut close, "<i>", "</i>");
    }
    if underline {
        push(&mut open, &mut close, "<u>", "</u>");
    }
    match highlight {
        Some("yellow") => push(&mut open, &mut close, "<mark>", "</mark>"),
        Some(colour) => push(
            &mut open,
            &mut close,
            &format!("<mark class=\"hl-{colour}\">"),
            "</mark>",
        ),
        None => {}
    }
    if strike {
        push(&mut open, &mut close, "<s>", "</s>");
    }
    if code {
        push(&mut open, &mut close, "<code>", "</code>");
    }
    if sup {
        push(&mut open, &mut close, "<sup>", "</sup>");
    } else if sub {
        push(&mut open, &mut close, "<sub>", "</sub>");
    }
    Some((open, close))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::markdown::from_docx::ooxml::parse_xml;

    const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;

    fn ftr(inner: &str) -> Element {
        parse_xml(format!("<w:ftr {W}>{inner}</w:ftr>").as_bytes()).unwrap()
    }

    const PAGE_RUNS: &str = r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>"#;

    /// Review t09-15: header and footer ids must number paragraphs exactly as
    /// `edit` resolves them, so the two walks are checked against each other.
    #[test]
    fn story_paragraphs_agree_with_the_paragraphs_edit_resolves() {
        let xml = format!(
            r#"<w:ftr {W}><w:p/><w:tbl><w:tr><w:tc><w:p/><w:tbl><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl></w:tc></w:tr></w:tbl><w:sdt><w:sdtContent><w:p/></w:sdtContent></w:sdt><w:p><w:r><w:pict><v:shape xmlns:v="urn:schemas-microsoft-com:vml"><v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:p><w:customXml><w:p/></w:customXml></w:ftr>"#
        );
        let ours = story_paragraphs(&parse_xml(xml.as_bytes()).unwrap()).len();
        let mut dom = crate::xmllinq::Dom::new();
        let document = dom.parse_xdocument(&xml);
        let root = dom.root(document).unwrap();
        let edits = crate::inspect::story_paragraph_nodes(&dom, root).len();
        assert_eq!(ours, edits);
        assert_eq!(ours, 6);
    }

    #[test]
    fn a_section_s_universal_measures_read_as_twips() {
        // Strict packages write `595.3pt` where Transitional writes `11906`;
        // none of these are the fallback defaults, so a lost decode says so.
        let strict = parse_xml(
            format!(
                r#"<w:sectPr {W}><w:pgSz w:w="595.3pt" w:h="841.9pt"/><w:pgMar w:top="54pt" w:right="0.75in" w:bottom="54pt" w:left="0.75in" w:header="54pt" w:footer="54pt"/></w:sectPr>"#
            )
            .as_bytes(),
        )
        .unwrap();
        let transitional = parse_xml(
            format!(
                r#"<w:sectPr {W}><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1080" w:right="1080" w:bottom="1080" w:left="1080" w:header="1080" w:footer="1080"/></w:sectPr>"#
            )
            .as_bytes(),
        )
        .unwrap();
        assert_eq!(
            page_setup(&strict),
            "A4 portrait, margins 0.75in, header/footer 0.75in"
        );
        assert_eq!(page_setup(&strict), page_setup(&transitional));
    }

    /// An mm-spelled page is the page its twips twin names: 210mm x 297mm
    /// is A4 once rounded to the twips it is (11905.5 → 11906), not the
    /// `8.268x11.693in` a truncating cast reads from any producer whose
    /// spelling is not Word's own `595.3pt` (#531 review defect 6).
    #[test]
    fn an_mm_spelled_page_is_the_page_its_twips_twin_names() {
        let mm = parse_xml(
            format!(r#"<w:sectPr {W}><w:pgSz w:w="210mm" w:h="297mm"/></w:sectPr>"#).as_bytes(),
        )
        .unwrap();
        let twin = parse_xml(
            format!(r#"<w:sectPr {W}><w:pgSz w:w="11906" w:h="16838"/></w:sectPr>"#).as_bytes(),
        )
        .unwrap();
        assert_eq!(page_setup(&mm), "A4 portrait");
        assert_eq!(page_setup(&mm), page_setup(&twin));
    }

    /// Word's paper list: every size Word names and the writer writes
    /// back exactly is named by the rounded twips Word spells it in — the
    /// short side first, whatever way the sheet lies (#561 review defect
    /// 4). Tabloid is the sheet Word's list names Ledger lying landscape.
    #[test]
    fn word_s_paper_list_names_its_sizes() {
        let cases = [
            (12_240, 15_840, "", "Letter portrait"),
            (12_240, 20_160, "", "Legal portrait"),
            (10_440, 15_120, "", "Executive portrait"),
            (15_840, 24_480, "", "Tabloid portrait"),
            (
                24_480,
                15_840,
                r#" w:orient="landscape""#,
                "Ledger landscape",
            ),
            (16_838, 23_811, "", "A3 portrait"),
            (11_906, 16_838, "", "A4 portrait"),
            (8_391, 11_906, "", "A5 portrait"),
            (14_570, 20_636, "", "B4 (JIS) portrait"),
            (10_318, 14_570, "", "B5 (JIS) portrait"),
        ];
        for (w, h, orient, expected) in cases {
            let sect = parse_xml(
                format!(r#"<w:sectPr {W}><w:pgSz w:w="{w}" w:h="{h}"{orient}/></w:sectPr>"#)
                    .as_bytes(),
            )
            .unwrap();
            assert_eq!(page_setup(&sect), expected, "{w}x{h}");
        }
        // A twip off the named size is not the named size: the rounded
        // match is exact, so an unnamed sheet keeps its inches.
        let off = parse_xml(
            format!(r#"<w:sectPr {W}><w:pgSz w:w="8392" w:h="11906"/></w:sectPr>"#).as_bytes(),
        )
        .unwrap();
        assert_eq!(page_setup(&off), "5.828x8.268in portrait");
    }

    /// A strict table style names its side borders `start`/`end`: the
    /// legend reads them as the `left`/`right` they name, and one side a
    /// twip apart still varies.
    #[test]
    fn a_table_style_s_start_end_borders_read_as_left_right() {
        let borders = |sides: &str| {
            parse_xml(
                format!(
                    r#"<w:styles {W}><w:style w:type="table" w:styleId="T"><w:tblPr><w:tblBorders>{sides}</w:tblBorders></w:tblPr></w:style></w:styles>"#
                )
                .as_bytes(),
            )
            .unwrap()
        };
        let strict = borders(
            r#"<w:top w:val="single" w:sz="4"/><w:start w:val="single" w:sz="4"/><w:bottom w:val="single" w:sz="4"/><w:end w:val="single" w:sz="4"/><w:insideH w:val="single" w:sz="4"/><w:insideV w:val="single" w:sz="4"/>"#,
        );
        let transitional = borders(
            r#"<w:top w:val="single" w:sz="4"/><w:left w:val="single" w:sz="4"/><w:bottom w:val="single" w:sz="4"/><w:right w:val="single" w:sz="4"/><w:insideH w:val="single" w:sz="4"/><w:insideV w:val="single" w:sz="4"/>"#,
        );
        assert_eq!(table_style_line(Some(&strict), "T"), "T, all borders 0.5pt");
        assert_eq!(
            table_style_line(Some(&transitional), "T"),
            table_style_line(Some(&strict), "T")
        );
        let varied = borders(
            r#"<w:top w:val="single" w:sz="4"/><w:start w:val="single" w:sz="8"/><w:bottom w:val="single" w:sz="4"/><w:end w:val="single" w:sz="4"/><w:insideH w:val="single" w:sz="4"/><w:insideV w:val="single" w:sz="4"/>"#,
        );
        assert_eq!(
            table_style_line(Some(&varied), "T"),
            "T, borders top single 0.5pt left single 1pt bottom single 0.5pt right single 0.5pt insideH single 0.5pt insideV single 0.5pt"
        );
    }

    #[test]
    fn a_long_value_aligns_by_characters_not_bytes() {
        let mut ascii = String::new();
        // 32 characters (35 bytes): the padded branch.
        kv(
            &mut ascii,
            "  document_owner: Jorgen Osterbo",
            Some("dc:creator"),
        );
        let mut accented = String::new();
        kv(
            &mut accented,
            "  document_owner: Jørgen Østerbø",
            Some("dc:creator"),
        );
        assert_eq!(
            ascii.find('#'),
            accented.chars().position(|c| c == '#'),
            "{ascii}{accented}"
        );
    }

    #[test]
    fn an_empty_comment_leaves_no_hash() {
        let mut out = String::new();
        kv(&mut out, "  AC: Ann Counsel", Some(""));
        assert_eq!(out, "  AC: Ann Counsel\n");
    }

    #[test]
    fn a_story_field_prints_its_whole_code_and_its_result() {
        // As in the body: `{CODE}result{/}`, so a link's target and text
        // and a field's switches survive the round trip.
        let root = ftr(&format!(
            r#"<w:p><w:r><w:t>Page </w:t></w:r>{PAGE_RUNS}<w:r><w:t> · </w:t></w:r><w:fldSimple w:instr=" HYPERLINK &quot;https://x.example&quot; "><w:r><w:t>site</w:t></w:r></w:fldSimple></w:p>"#
        ));
        assert_eq!(
            story_text(
                story_paragraphs(&root)[0],
                StoryView::Accept(&Default::default())
            ),
            r#"Page {PAGE}1{/} · {HYPERLINK "https://x.example"}site{/}"#
        );
    }

    #[test]
    fn a_story_field_without_a_result_prints_its_bare_code() {
        // The writer's `{PAGE}`: no result, so none is printed; a field
        // with switches keeps the coded form.
        let root = ftr(
            r#"<w:p><w:fldSimple w:instr=" PAGE "/><w:r><w:t> of </w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> NUMPAGES </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t> </w:t></w:r><w:fldSimple w:instr=" PAGE \* roman "/></w:p>"#,
        );
        assert_eq!(
            story_text(
                story_paragraphs(&root)[0],
                StoryView::Accept(&Default::default())
            ),
            r#"{PAGE} of {NUMPAGES} {PAGE \* roman}{/}"#
        );
    }

    #[test]
    fn a_page_field_in_a_block_content_control_is_found() {
        let root = ftr(&format!(
            "<w:sdt><w:sdtPr/><w:sdtContent><w:p>{PAGE_RUNS}</w:p></w:sdtContent></w:sdt><w:p/>"
        ));
        let paragraphs = story_paragraphs(&root);
        assert_eq!(paragraphs.len(), 2);
        assert_eq!(
            story_text(paragraphs[0], StoryView::Accept(&Default::default())),
            "{PAGE}1{/}"
        );
        assert_eq!(
            story_text(paragraphs[1], StoryView::Accept(&Default::default())),
            ""
        );
    }

    #[test]
    fn runs_inside_inline_wrappers_count_and_deletions_do_not() {
        let root = ftr(&format!(
            r#"<w:p><w:hyperlink><w:r><w:t>Page </w:t></w:r></w:hyperlink><w:sdt><w:sdtContent>{PAGE_RUNS}</w:sdtContent></w:sdt><w:ins><w:r><w:t> of </w:t></w:r></w:ins><w:del><w:r><w:delText>gone</w:delText></w:r></w:del><w:fldSimple w:instr=" numpages "><w:r><w:t>3</w:t></w:r></w:fldSimple></w:p>"#
        ));
        assert_eq!(
            story_text(
                story_paragraphs(&root)[0],
                StoryView::Accept(&Default::default())
            ),
            "Page {PAGE}1{/} of {numpages}3{/}"
        );
    }

    #[test]
    fn paragraphs_number_as_edit_does_tables_in_and_text_boxes_out() {
        // edit numbers a story's every w:p outside text boxes, table cells
        // included, so `footer1.p1` here is the paragraph edit numbers 1.
        let root = ftr(
            r#"<w:tbl><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl><w:p><w:r><w:pict><w:txbxContent><w:p><w:r><w:t>boxed</w:t></w:r></w:p></w:txbxContent></w:pict></w:r><w:r><w:t>body</w:t></w:r></w:p>"#,
        );
        let paragraphs = story_paragraphs(&root);
        assert_eq!(paragraphs.len(), 2);
        assert_eq!(
            story_text(paragraphs[0], StoryView::Accept(&Default::default())),
            ""
        );
        assert_eq!(
            story_text(paragraphs[1], StoryView::Accept(&Default::default())),
            "body"
        );
    }

    /// pi review r392 F1/F6: values a YAML 1.1 or 1.2 reader takes as a
    /// number, a time or a date are quoted; prose that starts with a digit
    /// stays plain.
    #[test]
    fn number_and_time_like_values_are_quoted() {
        for value in [
            "0x2A",
            "0o17",
            "+.inf",
            ".Inf",
            "12:30",
            "1:30:45",
            "1_000",
            "2026-10-01",
            "42",
            "1e5",
            "+1",
        ] {
            assert_eq!(scalar(value, false), format!("\"{value}\""), "{value}");
        }
        for value in ["1. Introduction", "3 survive", "Page 2", "x0x2A"] {
            assert_eq!(scalar(value, true), value, "{value}");
        }
    }

    /// pi review av2 F18: a line break inside a header paragraph is a line
    /// break in its text, not two words glued together.
    #[test]
    fn a_break_in_a_header_line_is_a_newline() {
        let root = ftr(
            r#"<w:p><w:r><w:t>line one</w:t><w:br/><w:t>line two</w:t><w:cr/><w:t>three</w:t></w:r></w:p>"#,
        );
        assert_eq!(
            story_text(
                story_paragraphs(&root)[0],
                StoryView::Accept(&Default::default())
            ),
            "line one\nline two\nthree"
        );
    }

    /// pi review av2 F18: a field nested in another's instruction does not
    /// replace it; the outer field names the code, its result stays hidden.
    #[test]
    fn a_nested_field_keeps_the_outer_code() {
        let root = ftr(&format!(
            r#"<w:p><w:r><w:t>Page </w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> IF </w:instrText></w:r>{PAGE_RUNS}<w:r><w:instrText xml:space="preserve"> > 1 "more" "" </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>more</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t> end</w:t></w:r></w:p>"#
        ));
        assert_eq!(
            story_text(
                story_paragraphs(&root)[0],
                StoryView::Accept(&Default::default())
            ),
            "Page {IF} end"
        );
    }

    /// A paragraph indent, contextual spacing and keep-lines are named;
    /// a style with none of them keeps today's line.
    #[test]
    fn the_legend_names_an_indent_contextual_spacing_and_keep_lines() {
        let xml = format!(
            r#"<w:styles {W}><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/><w:sz w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="160" w:line="259" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:styleId="Heading1"><w:basedOn w:val="Normal"/><w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before="240" w:after="80"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/></w:rPr></w:style><w:style w:styleId="HeadingPlain"><w:basedOn w:val="Normal"/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="80"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/></w:rPr></w:style><w:style w:styleId="ListParagraph"><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="720"/><w:contextualSpacing/></w:pPr></w:style><w:style w:styleId="First"><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="720" w:firstLine="360"/></w:pPr></w:style><w:style w:styleId="Hang"><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:style><w:style w:styleId="Both"><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="2520" w:hanging="2520"/></w:pPr></w:style><w:style w:styleId="Zero"><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="0"/></w:pPr></w:style><w:style w:styleId="Plain"><w:basedOn w:val="Normal"/></w:style></w:styles>"#
        );
        let styles = parse_xml(xml.as_bytes()).unwrap();
        let base = resolve(Some(&styles), None, "Normal");
        let line = |id: &str| describe(&resolve(Some(&styles), None, id), Some(&base));
        assert_eq!(
            describe(&base, None),
            "Calibri 11pt, after 8pt, line 1.08, left"
        );
        assert_eq!(
            line("ListParagraph"),
            "Calibri 11pt, indent 0.5in, contextual spacing"
        );
        assert_eq!(
            line("Heading1"),
            "Calibri bold 16pt, before 12pt, after 4pt, keep-next, keep-lines"
        );
        assert_eq!(
            line("HeadingPlain"),
            "Calibri bold 16pt, before 12pt, after 4pt, keep-next"
        );
        assert_eq!(
            line("First"),
            "Calibri 11pt, indent 0.5in, first-line 0.25in"
        );
        assert_eq!(line("Hang"), "Calibri 11pt, indent 0.5in, hanging 0.25in");
        assert_eq!(line("Both"), "Calibri 11pt, indent 1.75in, hanging 1.75in");
        assert_eq!(line("Zero"), "Calibri 11pt, indent 0in");
        assert_eq!(line("Plain"), "Calibri 11pt");
        let flat = Resolved {
            font: Some("Calibri".to_string()),
            size_half_points: Some(22.0),
            left: Some(0.0),
            ..Resolved::default()
        };
        assert_eq!(describe(&flat, None), "Calibri 11pt, left");
    }

    /// A style's right indent is named, as `right 0.5in` (the id line's
    /// word): the legend dropped it, and the written text ran wider (#1489).
    /// It inherits through `basedOn` as the left indent does, and Strict's
    /// `w:end` reads as `w:right`.
    #[test]
    fn the_legend_names_a_right_indent() {
        let xml = format!(
            r#"<w:styles {W}><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/><w:sz w:val="22"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:styleId="Quote"><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="720" w:right="720"/></w:pPr></w:style><w:style w:styleId="Inherits"><w:basedOn w:val="Quote"/></w:style><w:style w:styleId="Reset"><w:basedOn w:val="Quote"/><w:pPr><w:ind w:right="0"/></w:pPr></w:style><w:style w:styleId="End"><w:basedOn w:val="Normal"/><w:pPr><w:ind w:end="1440"/></w:pPr></w:style><w:style w:styleId="Hang"><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="2520" w:right="720" w:hanging="2520"/></w:pPr></w:style></w:styles>"#
        );
        let styles = parse_xml(xml.as_bytes()).unwrap();
        let base = resolve(Some(&styles), None, "Normal");
        let line = |id: &str| describe(&resolve(Some(&styles), None, id), Some(&base));
        assert_eq!(describe(&base, None), "Calibri 11pt, left");
        assert_eq!(line("Quote"), "Calibri 11pt, indent 0.5in, right 0.5in");
        assert_eq!(line("Inherits"), "Calibri 11pt, indent 0.5in, right 0.5in");
        assert_eq!(line("Reset"), "Calibri 11pt, indent 0.5in, right 0in");
        assert_eq!(line("End"), "Calibri 11pt, right 1in");
        assert_eq!(
            line("Hang"),
            "Calibri 11pt, indent 1.75in, hanging 1.75in, right 0.5in"
        );
        let flat = Resolved {
            font: Some("Calibri".to_string()),
            size_half_points: Some(22.0),
            right: Some(0.0),
            ..Resolved::default()
        };
        assert_eq!(describe(&flat, None), "Calibri 11pt, left");
    }

    /// A strict style carries its measures as universal measures (`11pt`,
    /// `1in`) and its font size in half-points either way: the legend reads
    /// the same as the transitional integers.
    #[test]
    fn a_zero_space_or_a_single_line_apart_from_the_base_is_named() {
        let xml = format!(
            r#"<w:styles {W}><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/><w:sz w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="200" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:styleId="Heading1"><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:before="480" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr><w:b/><w:sz w:val="28"/></w:rPr></w:style><w:style w:styleId="Same"><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:before="0" w:after="200"/></w:pPr></w:style><w:style w:styleId="Alone"><w:pPr><w:spacing w:before="120"/></w:pPr></w:style></w:styles>"#
        );
        let styles = parse_xml(xml.as_bytes()).unwrap();
        let base = resolve(Some(&styles), None, "Normal");
        let line = |id: &str| describe(&resolve(Some(&styles), None, id), Some(&base));
        assert_eq!(
            describe(&base, None),
            "Calibri 11pt, after 10pt, line 1.15, left"
        );
        // Written back on a style based on the default, an omitted zero
        // would take the default's space.
        assert_eq!(
            line("Heading1"),
            "Calibri bold 14pt, before 24pt, after 0pt, line 1"
        );
        // A zero the base has too is no deviation.
        assert_eq!(line("Same"), "Calibri 11pt");
        assert_eq!(line("Alone"), "Calibri 11pt, before 6pt");
        // The default style omits them: an omitted space is zero, and an
        // omitted line single.
        let flat = Resolved {
            font: Some("Calibri".to_string()),
            size_half_points: Some(22.0),
            before: Some(0.0),
            after: Some(0.0),
            line: Some((240.0, "auto".to_string())),
            ..Resolved::default()
        };
        assert_eq!(describe(&flat, None), "Calibri 11pt, left");
    }

    #[test]
    fn a_style_s_universal_measures_read_as_their_integers() {
        let legend = |rpr: &str, ppr: &str| {
            let xml = format!(
                r#"<w:styles {W}><w:style w:type="paragraph" w:styleId="S"><w:name w:val="S"/><w:pPr>{ppr}</w:pPr><w:rPr>{rpr}</w:rPr></w:style></w:styles>"#
            );
            let styles = parse_xml(xml.as_bytes()).unwrap();
            describe(&resolve(Some(&styles), None, "S"), None)
        };
        assert_eq!(
            legend(
                r#"<w:rFonts w:ascii="Calibri"/><w:sz w:val="16pt"/>"#,
                r#"<w:spacing w:before="10pt" w:after="5pt" w:line="12.95pt" w:lineRule="auto"/><w:ind w:start="0.25in"/>"#
            ),
            legend(
                r#"<w:rFonts w:ascii="Calibri"/><w:sz w:val="32"/>"#,
                r#"<w:spacing w:before="200" w:after="100" w:line="259" w:lineRule="auto"/><w:ind w:left="360"/>"#
            )
        );
    }
}