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
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0
//! The agent view: numbering that matches `inspect` and `edit`, revision
//! tags, author handles and timestamps, comment threads, id lines, table
//! lines and block selection.

use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::rc::Rc;

use super::ooxml::{Element, Node};
use crate::markdown::{Pick, Select};

// The stamps start with U+E000, which no XML name can hold, so a file
// cannot forge them.
/// Attribute stamped on every numbered `w:p`: its `pN` index.
pub(crate) const INDEX: &str = "\u{E000}jubarteIndex";
/// Attribute stamped on every top-level `w:tbl`: its `t{N}` number.
pub(crate) const TABLE: &str = "\u{E000}jubarteTable";
/// Attribute stamped on a `w:p` that holds revisions: `kind:tag` entries
/// separated by spaces (`ins:0@AC sub:1+2@AC fmt:3@JD mark-ins:4@AC`),
/// recorded before resolution.
pub(crate) const REVS: &str = "\u{E000}jubarteRevs";

/// Author handles, order and timestamps for tags, notes and the header.
#[derive(Debug, Default, Clone)]
pub(crate) struct Handles {
    /// Author name as stored → handle (`Ann Counsel` → `AC`).
    pub by_author: HashMap<String, String>,
    /// Authors in first-appearance order: revision authors in document
    /// order, then comment-only authors in part order, then authors only the
    /// styles' changes name.
    pub order: Vec<String>,
    /// Author → every timestamp on their marks and comments.
    pub dates: HashMap<String, BTreeSet<String>>,
    /// Authors with at least one undated mark or comment: no header date
    /// may stand in for their individual timestamps.
    undated: HashSet<String>,
    /// Comment ids whose ranges the view prints (`{==…==}`) and bookmark
    /// names it prints (`<a id>`): either one between two marks keeps them
    /// apart, as the text shows them.
    pub shown_ranges: HashSet<String>,
    pub shown_bookmarks: HashSet<String>,
    /// Character styles whose runs are hidden (`w:vanish`): such a run
    /// prints nothing, as a directly hidden one.
    pub hidden_styles: HashSet<String>,
}

impl Handles {
    pub(crate) fn of(&self, author: Option<&str>) -> Option<&str> {
        author
            .and_then(|a| self.by_author.get(a))
            .map(String::as_str)
    }

    /// The one timestamp all of the author's marks and comments share.
    pub(crate) fn unique_date(&self, author: &str) -> Option<&str> {
        if self.undated.contains(author) {
            return None;
        }
        let dates = self.dates.get(author)?;
        let first = dates.iter().next()?;
        dates
            .iter()
            .all(|date| {
                date == first
                    || crate::util::datetime::timestamp_order_key(date).is_some_and(|key| {
                        Some(key) == crate::util::datetime::timestamp_order_key(first)
                    })
            })
            .then_some(first.as_str())
    }

    /// The latest whole timestamp of an author with several timestamps.
    pub(crate) fn latest_date(&self, author: &str) -> Option<&str> {
        if self.undated.contains(author) {
            return None;
        }
        let dates = self.dates.get(author)?;
        (self.unique_date(author).is_none())
            .then(|| {
                dates
                    .iter()
                    .max_by_key(|date| crate::util::datetime::timestamp_order_key(date))
                    .map(String::as_str)
            })
            .flatten()
    }

    /// Undated marks make each dated note's timestamp necessary even without
    /// `--dates`: an absent timestamp must keep meaning undated on writeback.
    pub(crate) fn needs_date(&self, author: Option<&str>, dates: bool) -> bool {
        // A shared instant can have different local offsets or precision.
        // Its individual spellings still belong in --dates notes.
        author.is_some_and(|a| {
            self.undated.contains(a)
                || (dates && self.dates.get(a).is_some_and(|dates| dates.len() > 1))
        })
    }
}

/// One logical revision as the paragraph id line groups it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RevTag {
    /// `ins`, `del`, `sub`, `mark` (paragraph mark), `row`, `cell`.
    pub kind: &'static str,
    /// Internal form: `0@AC`, `1+2@AC`, `1@AC|2@JD`.
    pub tag: String,
    pub author: Option<String>,
    pub date: Option<String>,
}

fn is_revision(local: &str) -> bool {
    matches!(
        local,
        "ins" | "del" | "moveTo" | "moveFrom" | "cellIns" | "cellDel"
    )
}

fn kind_of(local: &str) -> Option<&'static str> {
    match local {
        "ins" | "moveTo" => Some("ins"),
        "del" | "moveFrom" => Some("del"),
        _ => None,
    }
}

/// A change mark that holds no text (`<w:ins/>`, or runs of formatting
/// only): the view shows nothing for it, so it neither joins nor splits.
fn hollow(e: &Element) -> bool {
    kind_of(e.local()).is_some()
        && e.elements()
            .all(|r| r.local() == "r" && r.elements().all(|c| c.local() == "rPr"))
}

/// A run the text prints nothing for: vanished, or holding only empty
/// text and page breaks (the page break is the paragraph's id line). It
/// keeps no two marks apart, as in the text.
fn silent_run(e: &Element, handles: &Handles) -> bool {
    if e.local() != "r" {
        return false;
    }
    if hidden_run(e.child("rPr"), &handles.hidden_styles) {
        return true;
    }
    e.elements().all(|c| match c.local() {
        // The text prints no soft hyphen and no symbol font's glyph.
        "rPr" | "lastRenderedPageBreak" | "softHyphen" | "sym" => true,
        "t" | "delText" => c.text().is_empty(),
        "br" | "cr" => c.attr("type") == Some("page"),
        _ => false,
    })
}

/// Whether a run of properties `rpr` is hidden: its own `w:vanish`, else
/// its character style's (one of `hidden`).
pub(crate) fn hidden_run(rpr: Option<&Element>, hidden: &HashSet<String>) -> bool {
    rpr.and_then(|r| r.toggle("vanish")).unwrap_or_else(|| {
        rpr.and_then(|r| r.child("rStyle"))
            .and_then(|s| s.attr("val"))
            .is_some_and(|id| hidden.contains(id))
    })
}

/// Whether `mark` holds the start of a shown comment range that ends past
/// it, and the end of one that starts before it.
fn half_ranges(mark: &Element, handles: &Handles) -> (bool, bool) {
    fn walk(e: &Element, handles: &Handles, starts: &mut Vec<String>, ends: &mut Vec<String>) {
        for child in e.elements() {
            let shown = || {
                child
                    .attr("id")
                    .filter(|id| handles.shown_ranges.contains(*id))
                    .map(str::to_string)
            };
            match child.local() {
                "commentRangeStart" => starts.extend(shown()),
                "commentRangeEnd" => ends.extend(shown()),
                _ => walk(child, handles, starts, ends),
            }
        }
    }
    let (mut starts, mut ends) = (Vec::new(), Vec::new());
    walk(mark, handles, &mut starts, &mut ends);
    (
        starts.iter().any(|id| !ends.contains(id)),
        ends.iter().any(|id| !starts.contains(id)),
    )
}

/// `12@AC`: the element's `w:id` and its author's handle (`??` for an
/// author the legend does not know: a malformed file, or Word's
/// `w:tblGridChange`, which has no author).
pub(crate) fn tag_of(element: &Element, handles: &Handles) -> String {
    let id = element.attr("id").map_or_else(|| "?".to_string(), tag_id);
    let handle = handles.of(element.attr("author")).unwrap_or("??");
    format!("{id}@{handle}")
}

/// A tag being printed rather than stamped internally. When an author's
/// undated marks forbid a header timestamp, keep this mark's date on its note.
pub(crate) fn required_date_tag_of(element: &Element, handles: &Handles) -> String {
    let mut tag = tag_of(element, handles);
    if handles.needs_date(element.attr("author"), false)
        && let Some(date) = element.revision_date()
    {
        tag.push(' ');
        tag.push_str(&date);
    }
    tag
}

/// `12@Ana%20Lima%20(2026-…)` for the plain view: the element's `w:id` and
/// its `Author (date)` note in place of a handle, spelled ([`tag_id`],
/// spaces too) so that tags split on none of it.
pub(crate) fn plain_tag_of(element: &Element, note: &str) -> String {
    let id = element.attr("id").map_or_else(|| "?".to_string(), tag_id);
    format!("{id}@{}", tag_id(note).replace(' ', "%20"))
}

/// A `w:id` as an internal tag holds it: the characters tags join and
/// split on (`+`, `|`, `@`, `#`, `?`) and `%` itself spelled `%XX`, so a
/// malformed id such as `1+2` stays one id. [`untag_id`] reverses it.
fn tag_id(id: &str) -> String {
    let mut out = String::with_capacity(id.len());
    for c in id.chars() {
        if matches!(c, '+' | '|' | '@' | '#' | '?' | '%') {
            out.push_str(&format!("%{:02X}", u32::from(c)));
        } else {
            out.push(c);
        }
    }
    out
}

/// The `w:id` one piece of an internal tag spells ([`tag_id`]).
fn untag_id(piece: &str) -> String {
    let mut out = String::with_capacity(piece.len());
    let mut rest = piece;
    while let Some(at) = rest.find('%') {
        out.push_str(&rest[..at]);
        match rest
            .get(at + 1..at + 3)
            .and_then(|hex| u8::from_str_radix(hex, 16).ok())
        {
            Some(byte) => {
                out.push(char::from(byte));
                rest = &rest[at + 3..];
            }
            None => {
                out.push('%');
                rest = &rest[at + 1..];
            }
        }
    }
    out.push_str(rest);
    out
}

/// One internal tag's parts: `header1#1+2@AC` → (`Some("header1")`,
/// `1+2`, `AC`). The story is absent in the body's tags. Internal only:
/// [`format_tag`] prints it.
pub(crate) fn split_tag(one: &str) -> (Option<&str>, &str, &str) {
    let (head, handle) = one.rsplit_once('@').unwrap_or((one, "??"));
    // The range name is not the author. [`join_tags`] copies it back.
    let handle = handle.split(super::critic::MOVE).next().unwrap_or(handle);
    match head.split_once('#') {
        Some((story, ids)) => (Some(story), ids, handle),
        None => (None, head, handle),
    }
}

/// The range name stamped after [`super::critic::MOVE`] on `tag`, when it
/// is a move. Empty is a move whose range has no name.
fn move_payload(tag: &str) -> Option<&str> {
    let handle = tag.rsplit_once('@')?.1;
    let rest = handle.split_once(super::critic::MOVE)?.1;
    Some(rest.split([' ', '\u{E002}']).next().unwrap_or(rest))
}

/// The handle of a one-author tag (`1+2@AC` → `AC`); `None` for several.
pub(crate) fn handle_of(tag: &str) -> Option<&str> {
    if tag.contains('|') {
        return None;
    }
    Some(split_tag(tag).2)
}

/// Joins the tags of one logical change: `1@AC` + `2@AC` is `1+2@AC`,
/// `1@AC` + `2@JD` is `1@AC|2@JD`, `1+2@AC` + `3@AC` is `1+2+3@AC`. Tags
/// join only within one story and one handle.
pub(crate) fn join_tags(parts: &[String]) -> String {
    if parts.is_empty() {
        return String::new();
    }
    let keys: Vec<Option<(Option<&str>, &str)>> = parts
        .iter()
        .map(|p| {
            (!p.contains('|')).then(|| {
                let (story, _, handle) = split_tag(p);
                (story, handle)
            })
        })
        .collect();
    match keys[0] {
        Some((story, handle)) if keys.iter().all(|k| *k == keys[0]) => {
            let ids: Vec<&str> = parts.iter().map(|p| split_tag(p).1).collect();
            let story = story.map_or(String::new(), |s| format!("{s}#"));
            let mut joined = format!("{story}{}@{handle}", ids.join("+"));
            let payloads: Vec<Option<&str>> = parts.iter().map(|p| move_payload(p)).collect();
            if let Some(name) = payloads.iter().find_map(|payload| *payload)
                && payloads
                    .iter()
                    .all(|payload| payload.is_none_or(|payload| payload == name))
            {
                joined.push(super::critic::MOVE);
                joined.push_str(name);
            }
            joined
        }
        _ => parts.join("|"),
    }
}

/// `0@AC` → `r0 @AC`; `1+2@AC` → `r1+2 @AC`; `header1#2@JD` →
/// `header1.r2 @JD`; `1@AC|2@JD` → `r1 @AC; r2 @JD`. An id the short form
/// cannot spell prints its long id, one per id: every printed id is one
/// `accept --id` takes. A mark without a `w:id` (only a malformed file has
/// one) prints `noid`: it names no change, and no id parser reads it.
pub(crate) fn format_tag(tag: &str) -> String {
    format_tag_by(tag, |handle| format!(" @{handle}"))
}

/// Whether two internal tags print the same ids: two marks of one
/// logical change do (`3@B` and `4@B` both print `r3+4`).
pub(crate) fn same_change(a: &str, b: &str) -> bool {
    let ids = |tag: &str| format_tag_by(tag, |_| String::new());
    ids(a) == ids(b)
}

/// Whether a deletion and the insertion after it are one replacement, as
/// `changes` lists it: they print the same ids, a joined one among them
/// (`r3+4`). The same single id on both is a file repeating a `w:id`:
/// `changes` lists two changes, so the view prints two.
pub(crate) fn one_replacement(del: &str, ins: &str) -> bool {
    let ids = |tag: &str| format_tag_by(tag, |_| String::new());
    let (a, b) = (ids(del), ids(ins));
    a == b && a.split("; ").any(|id| id.contains('+'))
}

/// A plain-view tag ([`plain_tag_of`]) as its note prints it: the ids,
/// then the `Author (date)` note when there is one (`r1+2 Ana Lima
/// (2026-09-29T14:05:00Z)`, `r7`).
pub(crate) fn format_plain_tag(tag: &str) -> String {
    format_tag_by(tag, |note| match untag_id(note) {
        note if note.is_empty() => note,
        note => format!(" {note}"),
    })
}

/// [`format_tag`] with `by` spelling what follows the ids.
fn format_tag_by(tag: &str, by: impl Fn(&str) -> String) -> String {
    tag.split('|')
        .map(|one| {
            let (story, ids, handle) = split_tag(one);
            if ids.split('+').any(|w| w == "?") {
                let story = story.map_or(String::new(), |s| format!("{s}."));
                return format!("{story}noid{}", by(handle));
            }
            whole_changes(
                ids.split('+')
                    .map(|w| crate::ids::ChangeId::new(story.unwrap_or("body"), untag_id(w)))
                    .collect(),
            )
            .iter()
            .map(|changes| {
                let short: Vec<String> = changes.iter().map(crate::ids::ChangeId::short).collect();
                if short.iter().all(|s| !s.contains(":rev:")) {
                    let numbers: Vec<&str> = changes.iter().map(|c| c.wid.as_str()).collect();
                    let head = short[0]
                        .strip_suffix(changes[0].wid.as_str())
                        .unwrap_or("r");
                    format!("{head}{}{}", numbers.join("+"), by(handle))
                } else {
                    short
                        .iter()
                        .map(|s| format!("{s}{}", by(handle)))
                        .collect::<Vec<_>>()
                        .join("; ")
                }
            })
            .collect::<Vec<_>>()
            .join("; ")
        })
        .collect::<Vec<_>>()
        .join("; ")
}

// Each mark's logical change while a view prints (#1261): the marks Word
// wrote for one edit print the whole change's id. Set for the length of
// one conversion ([`with_wholes`]), so every tag the view prints, in
// notes, on id lines and in the header, names what `changes` lists.
thread_local! {
    static WHOLES: RefCell<Rc<Wholes>> = RefCell::new(Rc::default());
    // The logical changes themselves, for the header's count; `None` when
    // the listing could not read the package.
    static LOGICAL: RefCell<Rc<Option<Vec<crate::changes::Change>>>> =
        RefCell::new(Rc::default());
}

/// Runs `print` with `changes` as the logical changes the header counts
/// ([`shown_changes`]).
pub(crate) fn with_logical<T>(
    changes: Option<Vec<crate::changes::Change>>,
    print: impl FnOnce() -> T,
) -> T {
    struct Restore(Rc<Option<Vec<crate::changes::Change>>>);
    impl Drop for Restore {
        fn drop(&mut self) {
            let previous = std::mem::take(&mut self.0);
            LOGICAL.with(|logical| *logical.borrow_mut() = previous);
        }
    }
    let previous = LOGICAL.with(|l| l.replace(Rc::new(changes)));
    let _restore = Restore(previous);
    print()
}

/// What the view shows its body's changes as: one entry per change
/// `jubarte changes` lists for the body, by the kind it gives it (#1356).
/// So a change printed only as a parent (`re r7 @B`) counts, a single id
/// printed in every cell of an inserted row counts once, as that row, and
/// a change the header lists (`unplaced:`) counts too. A view of some
/// blocks (`whole` false) counts the changes whose ids its blocks print.
/// Without the listing, the count reads the printed tags
/// ([`collect_revisions`]).
pub(crate) fn shown_changes(shown: &str, whole: bool) -> Vec<&'static str> {
    use crate::changes::ChangeKind;
    let logical = LOGICAL.with(|logical| Rc::clone(&logical.borrow()));
    let Some(changes) = logical.as_ref() else {
        return collect_revisions(shown);
    };
    let printed = if whole {
        HashSet::new()
    } else {
        printed_change_ids("", shown)
    };
    changes
        .iter()
        .filter(|c| {
            c.kind != ChangeKind::Formatting
                && crate::ids::parse_change_ids(&c.id).map_or(!c.id.contains('.'), |ids| {
                    ids.iter().all(|id| id.story == "body")
                })
        })
        .filter(|c| {
            whole
                || if c.members.is_empty() {
                    printed.contains(&c.id)
                } else {
                    c.members.iter().any(|m| printed.contains(&m.id))
                }
        })
        .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()
}

/// How many changes each story other than the body and `styles` holds,
/// as `jubarte changes` lists them (#1353 review): a header's
/// `header1.r2+3` counts once. `None` without the listing.
pub(crate) fn story_changes() -> Option<HashMap<String, usize>> {
    let logical = LOGICAL.with(|logical| Rc::clone(&logical.borrow()));
    let changes = logical.as_ref().as_ref()?;
    let mut counts = HashMap::new();
    for c in changes {
        let story = crate::ids::parse_change_ids(&c.id)
            .ok()
            .and_then(|ids| ids.into_iter().next())
            .map_or_else(|| "body".to_string(), |id| id.story);
        if !matches!(story.as_str(), "body" | "styles") {
            *counts.entry(story).or_default() += 1;
        }
    }
    Some(counts)
}

/// The marks of each logical change of several marks: by a mark's short
/// id (`r8`, `header1.r2`), the `w:id`s of all its change's marks in
/// reading order (`7 8 9 10`).
pub(crate) type Wholes = HashMap<String, Vec<String>>;

/// Restores the logical changes an enclosing conversion set.
struct Restore(Rc<Wholes>);

impl Drop for Restore {
    fn drop(&mut self) {
        let previous = std::mem::take(&mut self.0);
        WHOLES.with(|wholes| *wholes.borrow_mut() = previous);
    }
}

/// Runs `print` with `wholes` as the logical changes the tags it prints
/// name ([`format_tag`]).
pub(crate) fn with_wholes<T>(wholes: Wholes, print: impl FnOnce() -> T) -> T {
    let previous = WHOLES.with(|w| w.replace(Rc::new(wholes)));
    let _restore = Restore(previous);
    print()
}

/// The logical changes of a package, as [`with_wholes`] takes them.
pub(crate) fn wholes_of(changes: &[crate::changes::Change]) -> Wholes {
    let mut out = Wholes::new();
    for change in changes.iter().filter(|c| !c.members.is_empty()) {
        let wids: Vec<String> = change
            .members
            .iter()
            .filter_map(|m| crate::ids::change_id(&m.id).map(|id| id.wid))
            .collect();
        for member in &change.members {
            out.insert(member.id.clone(), wids.clone());
        }
    }
    out
}

/// `changes` as the logical changes they are marks of, each a tag of its
/// own: a mark of a change of several marks stands for the whole change,
/// named once (the substitution `4+1` of the replacement `r3+4+1+2` prints
/// `r3+4+1+2`), and a mark of none keeps its own id. Marks of no such
/// change stay one tag, repeats too (`r43+43`).
fn whole_changes(changes: Vec<crate::ids::ChangeId>) -> Vec<Vec<crate::ids::ChangeId>> {
    WHOLES.with(|wholes| {
        let wholes = wholes.borrow();
        if !changes
            .iter()
            .any(|change| wholes.contains_key(&change.short()))
        {
            return vec![changes];
        }
        let mut out = Vec::new();
        let mut named: Vec<&Vec<String>> = Vec::new();
        for change in changes {
            match wholes.get(&change.short()) {
                Some(wids) if named.contains(&wids) => {}
                Some(wids) => {
                    named.push(wids);
                    out.push(
                        wids.iter()
                            .map(|wid| crate::ids::ChangeId::new(change.story.clone(), wid.clone()))
                            .collect(),
                    );
                }
                None => out.push(vec![change]),
            }
        }
        out
    })
}

/// A list of tags for an id line: `r0 @AC; r1+2 @AC`.
pub(crate) fn format_tags(tags: &[String]) -> String {
    tags.iter()
        .map(|t| format_tag(t))
        .collect::<Vec<_>>()
        .join("; ")
}

/// The revisions among a paragraph's direct children, in order. Distinct
/// ids remain separate. Only a deletion followed by a live insertion of
/// one change pairs as a substitution, greedily left to right (#1363).
/// A run, comment range or printed bookmark breaks adjacency; proofing
/// markers, unprinted bookmarks and empty runs do not. Revisions inside
/// links, content controls and simple fields count.
#[doc(hidden)]
pub fn revision_tags(p: &Element, handles: &Handles) -> Vec<RevTag> {
    // One slot per child: a revision, or `None` for anything else that
    // breaks adjacency.
    // Links, content controls, smart tags, custom XML and simple fields are
    // transparent: the renderer prints their runs inline, so their
    // revisions count and neighbour the ones around them.
    fn flatten<'a>(parent: &'a Element, out: &mut Vec<&'a Element>) {
        for e in parent.elements() {
            match e.local() {
                "hyperlink" | "smartTag" | "customXml" | "fldSimple" | "bdo" | "dir" => {
                    flatten(e, out);
                }
                "sdt" => {
                    if let Some(content) = e.child("sdtContent") {
                        flatten(content, out);
                    }
                }
                _ => out.push(e),
            }
        }
    }
    let mut children = Vec::new();
    flatten(p, &mut children);
    let mut slots: Vec<Option<RevTag>> = Vec::new();
    for e in children {
        // A range or a bookmark the text prints sits between the marks.
        let shown = match e.local() {
            "commentRangeStart" | "commentRangeEnd" => e
                .attr("id")
                .is_some_and(|id| handles.shown_ranges.contains(id)),
            "bookmarkStart" => e
                .attr("name")
                .is_some_and(|name| handles.shown_bookmarks.contains(name)),
            _ => false,
        };
        if shown {
            slots.push(None);
            continue;
        }
        if matches!(
            e.local(),
            "bookmarkStart"
                | "bookmarkEnd"
                | "proofErr"
                | "commentRangeStart"
                | "commentRangeEnd"
                | "moveFromRangeStart"
                | "moveFromRangeEnd"
                | "moveToRangeStart"
                | "moveToRangeEnd"
                | "permStart"
                | "permEnd"
                | "customXmlInsRangeStart"
                | "customXmlInsRangeEnd"
                | "customXmlDelRangeStart"
                | "customXmlDelRangeEnd"
                | "customXmlMoveFromRangeStart"
                | "customXmlMoveFromRangeEnd"
                | "customXmlMoveToRangeStart"
                | "customXmlMoveToRangeEnd"
        ) || hollow(e)
            || silent_run(e, handles)
        {
            continue;
        }
        // A mark holding one end of a shown comment range: the text
        // prints the range across its edge, which parts it from the mark
        // on that side.
        let (opens, closes) = if kind_of(e.local()).is_some() {
            half_ranges(e, handles)
        } else {
            (false, false)
        };
        if closes {
            slots.push(None);
        }
        slots.push(kind_of(e.local()).map(|kind| RevTag {
            kind,
            tag: tag_of(e, handles),
            author: e.attr("author").map(str::to_string),
            date: e.revision_date(),
        }));
        if opens {
            slots.push(None);
        }
    }
    // Each XML carrier keeps its own mark, even when its id repeats.
    let mut joined = slots;
    // 2. Pair a deletion with the insertion after it.
    let mut out = Vec::new();
    let mut i = 0;
    while i < joined.len() {
        let Some(current) = joined[i].take() else {
            i += 1;
            continue;
        };
        let next_kind = joined.get(i + 1).and_then(|n| n.as_ref()).map(|n| n.kind);
        // The replacement spelling follows source order: deletion, then
        // insertion of one change (#1363). The reverse order stays separate.
        let pair = matches!((current.kind, next_kind), ("del", Some("ins")))
            && joined[i + 1].as_ref().is_some_and(|next| {
                current.author == next.author
                    && current.date == next.date
                    && one_replacement(&current.tag, &next.tag)
            });
        if pair {
            let next = joined[i + 1].take().expect("checked above");
            let (old, new) = if current.kind == "del" {
                (current, next)
            } else {
                (next, current)
            };
            out.push(RevTag {
                kind: "sub",
                tag: join_tags(&[old.tag, new.tag]),
                author: old.author,
                date: old.date,
            });
            i += 2;
        } else {
            out.push(current);
            i += 1;
        }
    }
    out
}

/// Tracked paragraph mark: the `w:ins` / `w:del` under `w:pPr/w:rPr`.
pub(crate) fn mark_tags(p: &Element, handles: &Handles) -> (Vec<String>, Vec<String>) {
    mark_tags_by(p, handles, tag_of)
}

fn mark_tags_by(
    p: &Element,
    handles: &Handles,
    tag: fn(&Element, &Handles) -> String,
) -> (Vec<String>, Vec<String>) {
    let mut ins = Vec::new();
    let mut del = Vec::new();
    if let Some(rpr) = p.path(&["pPr", "rPr"]) {
        for e in rpr.elements() {
            match kind_of(e.local()) {
                Some("ins") => ins.push(tag(e, handles)),
                Some("del") => del.push(tag(e, handles)),
                _ => {}
            }
        }
    }
    (ins, del)
}

/// Tags of the formatting changes recorded in a paragraph (its runs' and
/// its own properties, its list number), a text box Word stores twice read
/// once.
pub(crate) fn format_change_tags(p: &Element, handles: &Handles) -> Vec<String> {
    format_change_nests(p, handles, tag_of)
        .into_iter()
        .map(|(own, _)| own)
        .collect()
}

/// Each formatting change in `p`, with the insertion, deletion or move
/// that encloses it when one does. The change's own tag stays first.
fn format_change_nests(
    p: &Element,
    handles: &Handles,
    tag: fn(&Element, &Handles) -> String,
) -> Vec<(String, Option<String>)> {
    fn walk(
        e: &Element,
        handles: &Handles,
        tag: fn(&Element, &Handles) -> String,
        parent: &Option<String>,
        out: &mut Vec<(String, Option<String>)>,
    ) {
        for child in shown_children(e) {
            if child.is("rPrChange") || child.is("pPrChange") || child.is("numberingChange") {
                out.push((tag(child, handles), parent.clone()));
            } else if matches!(child.local(), "ins" | "del" | "moveFrom" | "moveTo") {
                walk(child, handles, tag, &Some(tag(child, handles)), out);
            } else {
                walk(child, handles, tag, parent, out);
            }
        }
    }
    let mut found = Vec::new();
    walk(p, handles, tag, &None, &mut found);
    found
}

/// One formatting tag, then ` re ` and the change it sits in.
fn format_one_nest(own: &str, parent: Option<&str>) -> String {
    let mut out = format_tag(own);
    if let Some(parent) = parent {
        out.push_str(" re ");
        out.push_str(&parent_label(&format_tag(parent)));
    }
    out
}

/// A printed parent tag kept inside its one `fmt` entry: the reader splits
/// the clause on `; `, so a parent printing several tags (two marks, a
/// spelled id) joins them with `, ` instead. The reader drops the parent.
fn parent_label(printed: &str) -> String {
    printed.replace("; ", ", ")
}

fn format_nested_tags(tags: &[(String, Option<String>)]) -> String {
    let mut out = String::new();
    for (index, (own, parent)) in tags.iter().enumerate() {
        if index > 0 {
            out.push_str("; ");
        }
        out.push_str(&format_one_nest(own, parent.as_deref()));
    }
    out
}

struct Counter {
    p: usize,
    t: usize,
}

/// Numbers every `w:p` under `body` as `inspect::body_paragraph_nodes`
/// does (document order, text boxes excluded), numbers top-level tables,
/// and records each paragraph's revision tags. Returns (paragraphs, tables).
pub(crate) fn stamp(body: &mut Element, handles: &Handles) -> (usize, usize) {
    let mut counter = Counter { p: 0, t: 0 };
    stamp_in(body, &mut counter, handles, false);
    (counter.p, counter.t)
}

fn stamp_in(element: &mut Element, c: &mut Counter, handles: &Handles, in_cell: bool) {
    if element.is("p") {
        // Content revisions, then formatting changes, then the paragraph
        // mark: everything resolution may strip.
        let (mark_ins, mark_del) = mark_tags(element, handles);
        let revs: Vec<String> = revision_tags(element, handles)
            .into_iter()
            .map(|t| format!("{}:{}", t.kind, t.tag))
            .chain(
                format_change_tags(element, handles)
                    .into_iter()
                    .map(|t| format!("fmt:{t}")),
            )
            .chain(mark_ins.into_iter().map(|t| format!("mark-ins:{t}")))
            .chain(mark_del.into_iter().map(|t| format!("mark-del:{t}")))
            .collect();
        element.attrs.push((INDEX.to_string(), c.p.to_string()));
        c.p += 1;
        if !revs.is_empty() {
            element.attrs.push((REVS.to_string(), revs.join(" ")));
        }
    }
    // Row and cell revisions, which resolution strips with the `trPr` and
    // `tcPr` markers: the table line names them by row and cell.
    let held = match element.local() {
        "tr" => element.child("trPr").map(|pr| ("row", pr)),
        "tc" => element.child("tcPr").map(|pr| ("cell", pr)),
        _ => None,
    };
    if let Some((kind, pr)) = held {
        let revs: Vec<String> = pr
            .elements()
            .filter(|m| matches!(m.local(), "ins" | "del" | "cellIns" | "cellDel"))
            .map(|m| format!("{kind}:{}", tag_of(m, handles)))
            .collect();
        if !revs.is_empty() {
            element.attrs.push((REVS.to_string(), revs.join(" ")));
        }
    }
    if element.is("tbl") && !in_cell {
        element.attrs.push((TABLE.to_string(), c.t.to_string()));
        c.t += 1;
    }
    // AC's raw tables are not rendered as blocks. Keep numbering their
    // paragraphs, but do not consume a tN in either compatibility branch.
    let in_cell = in_cell || element.is("tc") || element.is("AlternateContent");
    for child in element.children.iter_mut() {
        if let Node::Element(child) = child {
            if child.is("txbxContent") {
                continue;
            }
            stamp_in(child, c, handles, in_cell);
        }
    }
}

/// The tags a resolved view's id line names for `p`'s marks: each mark
/// prints its change's id, so a change of several marks is named once
/// (#1261).
fn resolved_tags(p: &Element) -> Vec<String> {
    let mut tags: Vec<String> = Vec::new();
    for (_, tag) in stamped_revs(p) {
        let tag = format_tag(&tag);
        let joined = tag
            .split_whitespace()
            .next()
            .is_some_and(|id| id.contains('+'));
        if !(joined && tags.contains(&tag)) {
            tags.push(tag);
        }
    }
    tags
}

/// The `kind:tag` entries stamped on a paragraph, row or cell, as (kind,
/// tag).
pub(crate) fn stamped_revs(element: &Element) -> Vec<(String, String)> {
    element
        .attr(REVS)
        .map(|revs| {
            revs.split(' ')
                .filter_map(|r| {
                    r.split_once(':')
                        .map(|(k, t)| (k.to_string(), t.to_string()))
                })
                .collect()
        })
        .unwrap_or_default()
}

/// Whether `e` holds a tracked change, by the author `by` names when given:
/// a resolved `@AC` handle, or a full name.
pub(crate) fn revised_by(e: &Element, by: Option<&str>, handles: &Handles) -> bool {
    e.elements().any(|c| {
        let revision = matches!(
            c.local(),
            "ins" | "del" | "moveFrom" | "moveTo" | "cellIns" | "cellDel" | "cellMerge"
        ) || c.local().ends_with("PrChange")
            || c.local() == "tblGridChange";
        let author = c.attr("author");
        (revision
            && by.is_none_or(|by| match by.strip_prefix('@') {
                Some(handle) => handles.of(author) == Some(handle),
                None => author == Some(by),
            }))
            || revised_by(c, by, handles)
    })
}

/// The comment ids a range or a reference under `e` anchors.
pub(crate) fn comment_anchors(e: &Element, out: &mut HashSet<String>) {
    for c in e.elements() {
        if matches!(c.local(), "commentRangeStart" | "commentReference")
            && let Some(id) = c.attr("id")
        {
            out.insert(id.to_string());
        }
        comment_anchors(c, out);
    }
}

/// The children of `e` the view renders: of an `mc:AlternateContent`, only
/// the `mc:Choice` (else the `mc:Fallback`), so a text box Word stores twice
/// counts once.
pub(super) fn shown_children(e: &Element) -> Vec<&Element> {
    if e.is("AlternateContent") {
        shown_branch(e).into_iter().collect()
    } else {
        e.elements().collect()
    }
}

/// The branch Word shows. A Choice whose Requires names a namespace Word
/// does not know is passed over for a later Choice, then the Fallback.
pub(super) fn shown_branch(alternate: &Element) -> Option<&Element> {
    alternate
        .elements()
        .find(|child| child.is("Choice") && requires_understood(child))
        .or_else(|| alternate.child("Fallback"))
}

fn requires_understood(choice: &Element) -> bool {
    crate::markup_simplifier::requires_list_understood(choice.attr("Requires"), |prefix| {
        choice
            .namespaces
            .get(prefix)
            .is_some_and(|uri| crate::markup_simplifier::word_understands_namespace(uri))
    })
}

/// Whether a cell's own text (not a nested table's) is inside changes of
/// its own: a cell's insertion or deletion then stays on the table line,
/// as a row's does.
pub(crate) fn text_marked(e: &Element) -> bool {
    e.elements().any(|c| {
        (is_revision(c.local()) && shows_text(c)) || (c.local() != "tbl" && text_marked(c))
    })
}

/// Whether `e` holds a tracked change inside a tracked change: CriticMarkup
/// cannot nest one, so a container's mark merged into the nest's outer
/// change would lose it — the text keeps its own marks instead, as the
/// agent view's marked text does.
pub(crate) fn nested_marked(e: &Element) -> bool {
    e.elements().any(|c| {
        (is_revision(c.local()) && any_revision(c)) || (c.local() != "tbl" && nested_marked(c))
    })
}

/// Whether any element below `e` is a tracked change.
fn any_revision(e: &Element) -> bool {
    e.elements()
        .any(|c| is_revision(c.local()) || any_revision(c))
}

/// Whether `e` holds text the view shows. Word's Fallback copy of a text
/// box is not shown.
fn shows_text(e: &Element) -> bool {
    shown_children(e).into_iter().any(|c| {
        matches!(c.local(), "t" | "delText" | "instrText" | "delInstrText") || shows_text(c)
    })
}

fn walk_revision_authors(
    e: &Element,
    out: &mut Vec<String>,
    dates: &mut HashMap<String, BTreeSet<String>>,
    undated: &mut HashSet<String>,
) {
    // Every kind `jubarte changes` lists: marks, cell merges, and
    // formatting (`*PrChange`, `numberingChange`, `tblGridChange`).
    if (is_revision(e.local()) || e.local() == "cellMerge" || e.local().ends_with("Change"))
        && let Some(author) = e.attr("author")
    {
        if !out.iter().any(|a| a == author) {
            out.push(author.to_string());
        }
        if let Some(date) = e.revision_date() {
            dates.entry(author.to_string()).or_default().insert(date);
        } else {
            undated.insert(author.to_string());
        }
    }
    // Every child, a text box's `mc:Fallback` copy too: `jubarte changes`
    // lists a change only the Fallback holds, so its author needs a handle.
    // A Fallback twin repeats the Choice's authors, already in `out`.
    for child in e.elements() {
        walk_revision_authors(child, out, dates, undated);
    }
}

/// Authors of revisions (document order, then the other stories: footnotes,
/// endnotes, headers and footers) then of comments (comment order), then of
/// the styles' changes, each with a handle: the comment `w:initials` that author wrote, else the
/// uppercase initials of the name's words; a collision appends 2, 3, ….
pub(crate) fn handles(
    document: &Element,
    stories: &[&Element],
    comments: Option<&Element>,
    styles: Option<&Element>,
) -> Handles {
    let mut order = Vec::new();
    let mut dates: HashMap<String, BTreeSet<String>> = HashMap::new();
    let mut undated = HashSet::new();
    walk_revision_authors(document, &mut order, &mut dates, &mut undated);
    for root in stories {
        walk_revision_authors(root, &mut order, &mut dates, &mut undated);
    }
    let mut initials: HashMap<String, String> = HashMap::new();
    if let Some(comments) = comments {
        for c in comments.children_named("comment") {
            let Some(author) = c.attr("author") else {
                continue;
            };
            if !order.iter().any(|a| a == author) {
                order.push(author.to_string());
            }
            if let Some(date) = c.comment_date() {
                dates
                    .entry(author.to_string())
                    .or_default()
                    .insert(date.to_string());
            } else {
                undated.insert(author.to_string());
            }
            if let Some(i) = c.attr("initials").map(str::trim).filter(|i| !i.is_empty()) {
                initials
                    .entry(author.to_string())
                    .or_insert_with(|| i.to_string());
            }
        }
    }
    if let Some(styles) = styles {
        walk_revision_authors(styles, &mut order, &mut dates, &mut undated);
    }
    let mut by_author = HashMap::new();
    let mut taken: HashSet<String> = HashSet::new();
    // A handle is letters and digits only: it sits inside tags (`1+2@AC`,
    // `1@AC|2@JD`), space-separated stamps and `{>>…<<}` notes.
    let clean = |s: &str| -> String { s.chars().filter(|c| c.is_alphanumeric()).collect() };
    for author in &order {
        let base = initials
            .get(author)
            .map(|i| clean(i))
            .filter(|i| !i.is_empty())
            .unwrap_or_else(|| {
                let letters = clean(
                    &author
                        .split_whitespace()
                        .filter_map(|w| w.chars().find(|c| c.is_alphanumeric()))
                        .collect::<String>()
                        .to_uppercase(),
                );
                if letters.is_empty() {
                    "??".to_string()
                } else {
                    letters
                }
            });
        let mut handle = base.clone();
        let mut n = 2;
        while !taken.insert(handle.clone()) {
            handle = format!("{base}{n}");
            n += 1;
        }
        by_author.insert(author.clone(), handle);
    }
    Handles {
        by_author,
        order,
        dates,
        undated,
        shown_ranges: HashSet::new(),
        shown_bookmarks: HashSet::new(),
        hidden_styles: HashSet::new(),
    }
}

/// Consecutive runs of sorted indices: `[3,4,5,9]` → `[(3,5),(9,9)]`.
pub(crate) fn runs(indices: &[usize]) -> Vec<(usize, usize)> {
    let mut out: Vec<(usize, usize)> = Vec::new();
    for &i in indices {
        match out.last_mut() {
            Some((_, end)) if *end + 1 == i => *end = i,
            _ => out.push((i, i)),
        }
    }
    out
}

/// What the id line of a paragraph says beyond its index.
pub(crate) struct LineFacts<'a> {
    pub index: usize,
    pub style: Option<&'a str>,
    pub heading: Option<usize>,
    /// The list marker the converter computed (`1.`, `(a)`, `-`).
    pub marker: Option<&'a str>,
    /// The list level Word gives the paragraph (`ilvl`): `level 1`. The
    /// view prints no list indentation, since each id line ends the
    /// Markdown list.
    pub level: usize,
    /// The paragraph's own `w:outlineLvl`, when no style carries the
    /// level (`outline 2`): the `#` count alone would give the writer's
    /// `HeadingN`. Levels 7-9, which no `#` reaches, are carried by the
    /// clause alone.
    pub outline: Option<usize>,
    pub page_break: bool,
    /// Accept-all or reject-all view: print the `rev` tags.
    pub resolved: bool,
    /// Comment ids to list (comments hidden).
    pub comments: &'a [String],
    /// Comment threads whose range runs on past this paragraph, inline or
    /// hidden: `in c5`.
    pub spans: &'a [String],
    /// Comment events a revision holds that the rendered note does not
    /// already place (`holds del r70 c0 start`).
    pub holds: &'a [String],
    /// The paragraph has no text but keeps its own line for its marks,
    /// revisions or comments: `<!-- p4 -->` followed by `¶{r3 @AC}`.
    pub empty: bool,
    /// The size is the runs', and the mark states none (`mark style`).
    pub mark_inherits: bool,
    /// Tracked view: the printed tags of the paragraph's changes its text
    /// prints no tag for, `true` for an insertion (see [`unshown_tags`]).
    pub unshown: &'a [(bool, String)],
    /// The text size the paragraph states and its style does not give
    /// (`size 9pt`), in half-points: see [`own_size`].
    pub size: Option<u32>,
}

/// The one `w:sz` every shown run of paragraph `p` states (#1474), or,
/// with none, its mark's, in half-points: `None` when a run states none or
/// another. A shown run holds text, a tab or a line break, all of which
/// the writer gives the clause's size; a hidden run (`hidden` names the
/// hidden character styles) prints nothing. A run whose `w:szCs` differs
/// from its `w:sz` states no one size: the writer gives both the clause's.
/// A text box sits inside a run, math holds runs of its own, and of an
/// `mc:AlternateContent` only the branch Word shows counts.
pub(crate) fn own_size(p: &Element, hidden: &HashSet<String>) -> Option<u32> {
    fn half_points(value: &str) -> Option<u32> {
        let half = crate::util::parse_finite_f64(value)
            .or_else(|| crate::util::universal_measure_half_points(value))?
            .round();
        // `as` cannot truncate: the range is checked first.
        (half.is_finite() && (1.0..=3276.0).contains(&half)).then_some(half as u32)
    }
    fn size(rpr: Option<&Element>) -> Option<u32> {
        let rpr = rpr?;
        let sz = half_points(rpr.child("sz")?.attr("val")?)?;
        match rpr.child("szCs").and_then(|cs| cs.attr("val")) {
            Some(cs) if half_points(cs) != Some(sz) => None,
            _ => Some(sz),
        }
    }
    fn shown(run: &Element) -> bool {
        run.elements().any(|c| match c.local() {
            "t" | "delText" | "tab" | "noBreakHyphen" => true,
            // A page break is the paragraph's id line, not a line.
            "br" | "cr" => c.attr("type") != Some("page"),
            _ => false,
        })
    }
    fn walk(element: &Element, hidden: &HashSet<String>, sizes: &mut Vec<Option<u32>>) {
        for child in element.elements() {
            match child.local() {
                "pPr" | "oMath" | "oMathPara" => {}
                "AlternateContent" => {
                    if let Some(branch) = shown_branch(child) {
                        walk(branch, hidden, sizes);
                    }
                }
                "r" => {
                    if shown(child) && !hidden_run(child.child("rPr"), hidden) {
                        sizes.push(size(child.child("rPr")));
                    }
                }
                _ => walk(child, hidden, sizes),
            }
        }
    }
    let mut sizes = Vec::new();
    walk(p, hidden, &mut sizes);
    match sizes.split_first() {
        None => size(p.path(&["pPr", "rPr"])),
        Some((first, rest)) => first.filter(|_| rest.iter().all(|s| s == first)),
    }
}

/// `size 9pt`, `size 10.5pt`: the clause of a text size in half-points.
pub(crate) fn size_clause(half_points: u32) -> String {
    match half_points % 2 {
        0 => format!("size {}pt", half_points / 2),
        _ => format!("size {}.5pt", half_points / 2),
    }
}

/// The mark states no `w:sz`, so a size the runs share stays off it.
pub(crate) fn mark_keeps_style(p: &Element) -> bool {
    p.path(&["pPr", "rPr"])
        .and_then(|rpr| rpr.child("sz"))
        .is_none()
}

/// The tags of the insertions, deletions and moves in paragraph `p` whose
/// id no note in `shown` (the paragraph's rendered text) prints: a deleted
/// object, break, field character or empty mark has no text to wrap. The
/// tracked view's id line names them (`rev r12 @AC`, a deletion `rev-del
/// r13 @AC`), so every change reads from the view. The paragraph mark's
/// own changes (`¶{rN @X}`, `break-del`) and formatting (`fmt`) have
/// their own clauses; a text box renders its own blocks, and Word's
/// Fallback copy is the Choice's twin. Each entry is a printed tag
/// ([`unshown_sides`]), its `bool` saying the mark inserts (`ins`,
/// `moveTo`) rather than deletes (`del`, `moveFrom`).
pub(crate) fn unshown_tags(p: &Element, shown: &str, handles: &Handles) -> Vec<(bool, String)> {
    fn walk(e: &Element, handles: &Handles, out: &mut Vec<(bool, String, String)>) {
        for child in shown_children(e) {
            match child.local() {
                "pPr" | "txbxContent" => {}
                // A formatting change's own history (`w:rPrChange/w:rPr/w:del`)
                // is no change `jubarte changes` lists.
                local if local.ends_with("PrChange") => {}
                local @ ("ins" | "del" | "moveFrom" | "moveTo") => {
                    if let Some(id) = child.attr("id") {
                        let inserted = matches!(local, "ins" | "moveTo");
                        out.push((
                            inserted,
                            id.to_string(),
                            required_date_tag_of(child, handles),
                        ));
                    }
                    walk(child, handles, out);
                }
                _ => walk(child, handles, out),
            }
        }
    }
    let mut carriers = Vec::new();
    walk(p, handles, &mut carriers);
    if carriers.is_empty() {
        return Vec::new();
    }
    let printed = printed_wids(shown, "body");
    unshown_sides(
        carriers
            .into_iter()
            .filter(|(_, id, _)| !printed.contains(id))
            .map(|(inserted, _, tag)| (inserted, tag)),
    )
}

/// The printed tags of the unshown marks `carriers` (each its side, `true`
/// inserting, and internal tag), one per side of each change, in reading
/// order. The marks of one joined change print its tag (`r3+4`) once,
/// unless neither side has text to wrap: a field deleted and another put
/// in its place. Then each side names its own marks (`rev r4 @D, rev-del
/// r3 @D`), so the writer brings each back on its side, and `accept --id`
/// settles either side alone (#1353 review).
fn unshown_sides(carriers: impl IntoIterator<Item = (bool, String)>) -> Vec<(bool, String)> {
    let mut sides: Vec<(bool, String, Vec<String>)> = Vec::new();
    for (inserted, tag) in carriers {
        let whole = format_tag(&tag);
        match sides
            .iter_mut()
            .find(|(side, named, _)| *side == inserted && *named == whole)
        {
            Some((_, _, own)) => own.push(tag),
            None => sides.push((inserted, whole, vec![tag])),
        }
    }
    sides
        .iter()
        .map(|(inserted, whole, own)| {
            let both = sides
                .iter()
                .any(|(side, named, _)| side != inserted && named == whole);
            let tag = if both {
                // Its own marks, not their whole change's.
                with_wholes(Wholes::new(), || format_tag(&join_tags(own)))
            } else {
                whole.clone()
            };
            (*inserted, tag)
        })
        .collect()
}

/// The `w:id`s of `story`'s changes the tag notes in `shown` print
/// (`{r12 @AC}`, `{header1.r1+2 @AC}`); a comment's note holds the
/// author's words and no tag.
fn printed_wids(shown: &str, story: &str) -> HashSet<String> {
    let mut printed = HashSet::new();
    for (_, note) in crate::markdown::critic::attributed_notes(shown) {
        for tag in note.split(" re ").flat_map(|part| part.split("; ")) {
            let token = tag.split(' ').next().unwrap_or("");
            if let Ok(ids) = crate::ids::parse_change_ids(token) {
                printed.extend(
                    ids.into_iter()
                        .filter(|id| id.story == story)
                        .map(|id| id.wid),
                );
            }
        }
    }
    printed
}

/// `holds` clauses for comment events that sit in an insertion or a deletion
/// and that the rendered note does not already place. A note inside `{--`,
/// `{++` or `{~~` carries its events. `in rN` carries the reference. A range
/// start is named only when the revision's id is not printed in the text.
pub(crate) fn held_comment_clauses(p: &Element, shown: &str) -> Vec<String> {
    struct Event {
        inserted: bool,
        revision: u32,
        comment: u32,
        kind: u8,
    }
    fn walk(
        e: &Element,
        stack: &mut Vec<(bool, u32)>,
        seen: &mut HashSet<(u32, u8)>,
        out: &mut Vec<Event>,
    ) {
        for child in shown_children(e) {
            let local = child.local();
            if local == "pPr"
                || local == "rPr"
                || local.ends_with("PrChange")
                || local == "txbxContent"
            {
                continue;
            }
            if local == "ins" || local == "del" {
                let id = child.attr("id").and_then(|id| id.parse::<u32>().ok());
                if let Some(id) = id {
                    stack.push((local == "ins", id));
                }
                walk(child, stack, seen, out);
                if id.is_some() {
                    stack.pop();
                }
                continue;
            }
            if let Some(&(inserted, revision)) = stack.last()
                && let Some(kind) = match local {
                    "commentRangeStart" => Some(0),
                    "commentRangeEnd" => Some(1),
                    "commentReference" => Some(2),
                    _ => None,
                }
                && let Some(comment) = child.attr("id").and_then(|id| id.parse().ok())
                && seen.insert((comment, kind))
            {
                out.push(Event {
                    inserted,
                    revision,
                    comment,
                    kind,
                });
            }
            walk(child, stack, seen, out);
        }
    }
    let mut events = Vec::new();
    walk(p, &mut Vec::new(), &mut HashSet::new(), &mut events);
    if events.is_empty() {
        return Vec::new();
    }
    let (inside, held_refs) = comment_note_places(shown);
    let printed = printed_wids(shown, "body");
    // A note printed inside a change places its events where the view's
    // marks fall, inside the spans printed there. A range start a revision
    // holds that prints nothing has no span to fall in: it keeps its clause.
    events.retain(|event| {
        if let Some(&reply) = inside.get(&event.comment) {
            return match event.kind {
                0 => !printed.contains(&event.revision.to_string()),
                1 => reply,
                _ => false,
            };
        }
        match event.kind {
            0 => !printed.contains(&event.revision.to_string()),
            2 => !held_refs
                .get(&event.comment)
                .is_some_and(|ids| ids.contains(&event.revision)),
            _ => true,
        }
    });
    // A clause names a set of events, not their order: start, end, then
    // reference, each kind in document order, so the clause reads the same
    // after a round trip that writes one comment's end and reference
    // together.
    events.sort_by_key(|event| event.kind);
    let mut groups: Vec<(bool, u32, String)> = Vec::new();
    for event in events {
        let word = match event.kind {
            0 => "start",
            1 => "end",
            _ => "ref",
        };
        let piece = format!("c{} {word}", event.comment);
        match groups.iter_mut().find(|(inserted, revision, _)| {
            *inserted == event.inserted && *revision == event.revision
        }) {
            Some((_, _, pieces)) => {
                pieces.push(' ');
                pieces.push_str(&piece);
            }
            None => groups.push((event.inserted, event.revision, piece)),
        }
    }
    groups
        .into_iter()
        .map(|(inserted, revision, pieces)| {
            let kind = if inserted { "ins" } else { "del" };
            format!("holds {kind} r{revision} {pieces}")
        })
        .collect()
}

/// Comments whose `{>>cN` sits inside an open critic span, and the revisions
/// a note head names with `in rN`.
fn comment_note_places(shown: &str) -> (HashMap<u32, bool>, HashMap<u32, Vec<u32>>) {
    let (mut inside, mut held) = (HashMap::new(), HashMap::new());
    let (mut del, mut ins, mut sub) = (0usize, 0usize, 0usize);
    let mut at = 0;
    while at < shown.len() {
        let rest = &shown[at..];
        if let Some(next) = critic_span(rest) {
            match next {
                ("{--", 3) => del += 1,
                ("--}", 3) => del = del.saturating_sub(1),
                ("{++", 3) => ins += 1,
                ("++}", 3) => ins = ins.saturating_sub(1),
                ("{~~", 3) => sub += 1,
                ("~~}", 3) => sub = sub.saturating_sub(1),
                _ => {}
            }
            at += 3;
            continue;
        }
        if let Some(body) = rest.strip_prefix("{>>") {
            let head_end = body
                .find(": ")
                .or_else(|| body.find("<<}"))
                .unwrap_or(body.len());
            let head = &body[..head_end];
            if let Some(comment) = head
                .split_whitespace()
                .next()
                .and_then(|word| crate::ids::parse_comment_id(word).ok())
            {
                // A reply (`re c0`) prints no scope of its own, so its range
                // end has no `==}` to fall in: only its reference is placed.
                let reply = head.split_whitespace().any(|word| word == "re");
                if del + ins + sub > 0 {
                    inside.insert(comment, reply);
                }
                if let Some(ids) = head_held_revisions(head) {
                    held.insert(comment, ids);
                }
            }
            at += rest.find("<<}").map_or(3, |end| end + 3);
            continue;
        }
        at += rest.chars().next().map_or(1, char::len_utf8);
    }
    (inside, held)
}

/// The critic opener or closer `rest` begins with, when it begins with one.
fn critic_span(rest: &str) -> Option<(&'static str, usize)> {
    for marker in ["{--", "--}", "{++", "++}", "{~~", "~~}"] {
        if rest.starts_with(marker) {
            return Some((marker, marker.len()));
        }
    }
    None
}

/// The body revision ids at the end of a note head (`c0 @B in r13`).
fn head_held_revisions(head: &str) -> Option<Vec<u32>> {
    let words: Vec<&str> = head.split_whitespace().collect();
    let [.., "in", change] = words.as_slice() else {
        return None;
    };
    let ids = crate::ids::parse_change_ids(change).ok()?;
    Some(
        ids.into_iter()
            .filter_map(|id| id.wid.parse().ok())
            .collect(),
    )
}

/// The ids (`r12`, `header1.r1`) of every change the view prints a tag for:
/// an id, or ids joined by `+`, followed by an `@` handle. Only where the
/// writer prints tags: the body's attribution braces (not a comment's note, which
/// holds the author's words) and `<!-- … -->` lines, and the header without
/// its headers' and footers' `text:` values. Document text that reads like
/// a tag (`ping r5 @ops`) prints no change.
pub(crate) fn printed_change_ids(head: &str, body: &str) -> HashSet<String> {
    let mut spans: Vec<String> = Vec::new();
    tag_spans(body, true, &mut spans);
    let mut authors = false;
    for line in head.lines() {
        // The author legend, the title, the source path and the owner are
        // free text: a name or title that reads like a tag prints nothing.
        if line == "authors:" {
            authors = true;
            continue;
        }
        if authors && line.starts_with("  ") {
            continue;
        }
        authors = false;
        if line.starts_with("source: ") || line.starts_with("title: ") {
            continue;
        }
        let (rest, texts) = split_story_text(line);
        spans.extend(tag_fields(&rest));
        for text in texts {
            tag_spans(&text, false, &mut spans);
        }
    }
    let mut printed = HashSet::new();
    for span in &spans {
        let words: Vec<&str> = span
            .split(|c: char| c.is_whitespace() || ",;{}<>()[]\"".contains(c))
            .filter(|w| !w.is_empty())
            .collect();
        printed.extend(
            words
                .windows(2)
                .filter(|pair| pair[1].len() > 1 && pair[1].starts_with('@'))
                .filter_map(|pair| crate::ids::parse_change_ids(pair[0]).ok())
                .flatten()
                .map(|id| id.short()),
        );
    }
    printed
}

/// The values of a header line's tag fields: the `style_changes:` map
/// whole, else each `rev:` and `fmt:` value and a page's `; fmt` tail. A
/// quoted value runs to its closing quote, a plain one to the next `,` or
/// `}`, the page's tail to the line's end.
fn tag_fields(line: &str) -> Vec<String> {
    if let Some(map) = line.strip_prefix("style_changes: ") {
        return vec![map.to_string()];
    }
    let mut out = Vec::new();
    if let Some((_, tail)) = line.split_once("; fmt ") {
        out.push(tail.to_string());
    }
    for key in ["rev: ", "fmt: "] {
        let mut rest = line;
        while let Some(at) = rest.find(key) {
            let value = &rest[at + key.len()..];
            let end = match value.strip_prefix('"') {
                Some(quoted) => 1 + quoted.find('"').map_or(quoted.len(), |i| i + 1),
                None => value.find([',', '}']).unwrap_or(value.len()),
            };
            out.push(value[..end].to_string());
            rest = &value[end..];
        }
    }
    out
}

/// Ranges of fenced code, in bytes. A line of three or more backticks or
/// tildes, indented less than four columns, opens a fence, and a later bare
/// line of at least that many of the same character closes it. An opening
/// line may name a language; a backtick one names none holding a backtick.
fn code_fenced(text: &str) -> Vec<std::ops::Range<usize>> {
    let mut open: Option<(char, usize, usize)> = None;
    let mut ranges = Vec::new();
    let mut offset = 0usize;
    for line in text.split_inclusive('\n') {
        // Four columns of indent make indented code, not a fence.
        let mut indent = 0usize;
        for c in line.chars() {
            match c {
                ' ' => indent += 1,
                '\t' => indent += 4 - indent % 4,
                _ => break,
            }
        }
        let trimmed = line.trim();
        if indent < 4
            && let Some((ch, len, bare)) = fence_mark(trimmed)
        {
            match open {
                Some((och, olen, start)) if ch == och && bare && len >= olen => {
                    ranges.push(start..offset + line.len());
                    open = None;
                }
                // A backtick opener's info string holds no backtick
                // (`` ```a``` `` is inline code).
                None if ch != '`' || !trimmed[len..].contains('`') => {
                    open = Some((ch, len, offset));
                }
                _ => {}
            }
        }
        offset += line.len();
    }
    if let Some((_, _, start)) = open {
        ranges.push(start..text.len());
    }
    ranges
}

/// Fenced ranges asked about positions in increasing order: a cursor
/// walks the sorted ranges once, so a text with many fences and many
/// lines stays linear.
struct Fences<'a> {
    ranges: &'a [std::ops::Range<usize>],
    next: usize,
}

impl<'a> Fences<'a> {
    fn new(ranges: &'a [std::ops::Range<usize>]) -> Self {
        Self { ranges, next: 0 }
    }

    /// Whether `at` sits in a fence; `at` never goes back.
    fn holds(&mut self, at: usize) -> bool {
        while self
            .ranges
            .get(self.next)
            .is_some_and(|range| range.end <= at)
        {
            self.next += 1;
        }
        self.ranges
            .get(self.next)
            .is_some_and(|range| range.contains(&at))
    }
}

/// A fence marker: its character, how many, and whether nothing else is on
/// the line, which is what closes a fence.
fn fence_mark(trimmed: &str) -> Option<(char, usize, bool)> {
    let ch = trimmed.chars().next().filter(|c| matches!(c, '`' | '~'))?;
    let len = trimmed.chars().take_while(|&c| c == ch).count();
    (len >= 3).then(|| (ch, len, trimmed.chars().skip(len).all(char::is_whitespace)))
}

/// The attribution braces (`{r5 @AC}`, comments skipped) in `text`, and with
/// `lines` its `<!-- … -->` lines' contents. A comment inside a code fence
/// is the fence's text.
fn tag_spans(text: &str, lines: bool, out: &mut Vec<String>) {
    out.extend(
        crate::markdown::critic::attributed_notes(text)
            .into_iter()
            .map(|(_, note)| note),
    );
    if lines {
        let ranges = code_fenced(text);
        let mut fenced = Fences::new(&ranges);
        let mut rest = text;
        let mut base = 0usize;
        while let Some(at) = rest.find("<!-- ") {
            let after = &rest[at + 5..];
            let end = after.find(" -->").unwrap_or(after.len());
            if !fenced.holds(base + at) {
                out.push(after[..end].to_string());
            }
            base += at + 5 + end;
            rest = &after[end..];
        }
    }
}

/// A header line without its `text: …` values (a header's or footer's own
/// words, which keep their tag notes), and those values: a plain value runs
/// to the next `,` or `}`, a quoted one to its closing quote, a list (a
/// story of several paragraphs) to its `]` outside quotes.
fn split_story_text(line: &str) -> (String, Vec<String>) {
    let mut out = String::with_capacity(line.len());
    let mut texts = Vec::new();
    let mut rest = line;
    while let Some(at) = rest.find("text: ") {
        out.push_str(&rest[..at]);
        let value = &rest[at + "text: ".len()..];
        // The end of the quoted values in `s`, scanning past them, at the
        // first `stop` outside quotes.
        let past_quotes = |s: &str, stop: char| {
            let (mut quoted, mut escaped) = (false, false);
            s.char_indices()
                .find(|&(_, c)| {
                    let done = c == stop && !quoted;
                    if quoted {
                        quoted = c != '"' || escaped;
                        escaped = c == '\\' && !escaped;
                    } else {
                        quoted = c == '"';
                    }
                    done
                })
                .map_or(s.len(), |(i, _)| i + 1)
        };
        let end = if let Some(quoted) = value.strip_prefix('"') {
            let mut escaped = false;
            let close = quoted
                .char_indices()
                .find(|&(_, c)| {
                    let done = c == '"' && !escaped;
                    escaped = c == '\\' && !escaped;
                    done
                })
                .map_or(quoted.len(), |(i, _)| i + 1);
            1 + close
        } else if let Some(list) = value.strip_prefix('[') {
            1 + past_quotes(list, ']')
        } else {
            value.find([',', '}']).unwrap_or(value.len())
        };
        texts.push(value[..end].to_string());
        rest = &value[end..];
    }
    out.push_str(rest);
    (out, texts)
}

/// A change on the header's `unplaced:` line: `del r3 @AC in p0`, the
/// kind first so the writer gives the mark the same (`ins` by omission).
pub(crate) fn unplaced_entry(change: &crate::changes::Change, handles: &Handles) -> String {
    let handle = handles.of(change.author.as_deref()).unwrap_or("??");
    let date = change
        .date
        .as_deref()
        .filter(|_| handles.needs_date(change.author.as_deref(), false))
        .map_or(String::new(), |date| format!(" {date}"));
    let kind = match change.kind {
        crate::changes::ChangeKind::Deletion => "del ",
        crate::changes::ChangeKind::Move
            if change.move_side == Some(crate::changes::MoveSide::From) =>
        {
            "del "
        }
        crate::changes::ChangeKind::Formatting => "fmt ",
        _ => "ins ",
    };
    match change.paragraph.as_deref() {
        Some(p) => format!(
            "{kind}{} @{handle}{date} in {}",
            change.r#ref,
            crate::ids::short_paragraph(p)
        ),
        None => format!("{kind}{} @{handle}{date}", change.r#ref),
    }
}

/// The header's `unplaced:` entries: each change no other line shows, and,
/// for a row or cell, one more entry at every later paragraph a change
/// inside it sits in. The later entry is the same mark. The reader keeps
/// the first paragraph only.
pub(crate) fn unplaced_entries(
    changes: &[crate::changes::Change],
    printed: &HashSet<String>,
    handles: &Handles,
) -> Vec<String> {
    let mut out = Vec::new();
    for change in changes.iter().filter(|c| !printed.contains(&c.id)) {
        out.push(unplaced_entry(change, handles));
        if !matches!(change.target, "table_row" | "table_cell") {
            continue;
        }
        let Some(home) = change.paragraph.as_deref() else {
            continue;
        };
        let mut more: Vec<&str> = changes
            .iter()
            .filter(|inner| inner.inside.as_deref() == Some(change.id.as_str()))
            .filter_map(|inner| inner.paragraph.as_deref())
            .filter(|paragraph| *paragraph != home)
            .collect();
        more.sort_unstable();
        more.dedup();
        for paragraph in more {
            let mut continued = change.clone();
            continued.paragraph = Some(paragraph.to_string());
            out.push(unplaced_entry(&continued, handles));
        }
    }
    out
}

/// A whole story part's changes (a header, a footer, one note) whose id
/// `shown` prints no tag for, as printed tags: insertions, deletions and
/// moves, each `true` for an insertion (`rev`/`rev-del`), then formatting
/// (`fmt`), each with its paragraph when one holds it (`in footer1.p1`).
/// The view shows a header by one paragraph and a note by its text, so
/// these name the rest.
/// A change `story_unshown` names: whether it inserts, and its tag.
pub(crate) type StoryRev = (bool, String);
/// A formatting change `story_unshown` names: its paragraph when one
/// holds it, and its tag.
pub(crate) type StoryFmt = (Option<usize>, String);

pub(crate) fn story_unshown(
    root: &Element,
    story: &str,
    shown: &str,
    skip: &HashSet<String>,
    handles: &Handles,
) -> (Vec<StoryRev>, Vec<StoryFmt>) {
    // `at` is the carrier's paragraph, counted as [`paragraphs`] does, so a
    // formatting change lands on the paragraph it is in (`in footer1.p1`).
    struct Carrier<'e> {
        at: Option<usize>,
        formatting: bool,
        inserted: bool,
        element: &'e Element,
        parent: Option<&'e Element>,
    }
    fn walk<'e>(
        e: &'e Element,
        at: Option<usize>,
        counted: bool,
        parent: Option<&'e Element>,
        next: &mut usize,
        out: &mut Vec<Carrier<'e>>,
    ) {
        for child in shown_children(e) {
            let local = child.local();
            if local == "p" && counted {
                let index = *next;
                *next += 1;
                walk(child, Some(index), counted, parent, next, out);
                continue;
            }
            let revision = matches!(local, "ins" | "del" | "moveFrom" | "moveTo");
            let formatting =
                local.ends_with("PrChange") || matches!(local, "tblGridChange" | "numberingChange");
            let cell = matches!(local, "cellIns" | "cellDel" | "cellMerge");
            if revision || formatting || cell {
                let inserted = if revision {
                    matches!(local, "ins" | "moveTo")
                } else {
                    !cell || local == "cellIns"
                };
                out.push(Carrier {
                    at,
                    formatting,
                    inserted,
                    element: child,
                    parent,
                });
            }
            if formatting {
                continue;
            }
            let nearer = if revision { Some(child) } else { parent };
            walk(
                child,
                at,
                counted && local != "txbxContent",
                nearer,
                next,
                out,
            );
        }
    }
    let mut carriers = Vec::new();
    walk(root, None, true, None, &mut 0, &mut carriers);
    let printed = printed_wids(shown, story);
    let (mut rev, mut fmt) = (Vec::new(), Vec::new());
    for carrier in carriers {
        let Some(id) = carrier.element.attr("id") else {
            continue;
        };
        if printed.contains(id) || skip.contains(id) {
            continue;
        }
        let tag = format!("{story}#{}", required_date_tag_of(carrier.element, handles));
        if carrier.formatting {
            let mut tag = format_tag(&tag);
            if let Some(parent) = carrier.parent {
                tag.push_str(" re ");
                tag.push_str(&parent_label(&format_tag(&format!(
                    "{story}#{}",
                    required_date_tag_of(parent, handles)
                ))));
            }
            if !fmt.iter().any(|(_, t)| *t == tag) {
                fmt.push((carrier.at, tag));
            }
        } else {
            rev.push((carrier.inserted, tag));
        }
    }
    (unshown_sides(rev), fmt)
}

/// A header's or footer's paragraph marks that are tracked: `break-del
/// footer1.r25 @BC in footer1.p1` each, and their `w:id`s.
pub(crate) fn story_paragraph_marks(
    root: &Element,
    story: &str,
    handles: &Handles,
) -> (Vec<String>, HashSet<String>) {
    let mut entries = Vec::new();
    let mut ids = HashSet::new();
    for (index, p) in paragraphs(root).into_iter().enumerate() {
        for mark in p
            .path(&["pPr", "rPr"])
            .into_iter()
            .flat_map(Element::elements)
        {
            let word = match mark.local() {
                "ins" => {
                    if let Some(id) = mark.attr("id") {
                        ids.insert(id.to_string());
                    }
                    continue;
                }
                "del" => "break-del",
                _ => continue,
            };
            let Some(id) = mark.attr("id") else { continue };
            ids.insert(id.to_string());
            let tag = format_tag(&format!("{story}#{}", required_date_tag_of(mark, handles)));
            let at = crate::ids::short_paragraph(&format!("{story}:p:{index}"));
            entries.push(format!("{word} {tag} in {at}"));
        }
    }
    (entries, ids)
}

/// An empty paragraph that still says something the `pN empty` run would
/// lose: a tracked mark, a formatting change or, resolved, a revision.
pub(crate) fn holds_revision_facts(p: &Element, resolved: bool, handles: &Handles) -> bool {
    let (ins, del) = mark_tags_by(p, handles, required_date_tag_of);
    !ins.is_empty()
        || !del.is_empty()
        || !format_change_tags(p, handles).is_empty()
        || (resolved && !stamped_revs(p).is_empty())
}

/// The comment ids a paragraph's ranges and references name, in document
/// order, each once.
pub(crate) fn comment_ids(p: &Element) -> Vec<String> {
    fn walk(e: &Element, out: &mut Vec<String>) {
        for child in e.elements() {
            if child.is("commentRangeStart") || child.is("commentReference") {
                if let Some(id) = child.attr("id")
                    && !out.iter().any(|c| c == id)
                {
                    out.push(id.to_string());
                }
            } else {
                walk(child, out);
            }
        }
    }
    let mut out = Vec::new();
    walk(p, &mut out);
    out
}

/// Character-unit sides of `w:ind` (`w:firstLineChars` and the rest), in
/// the id lines' order. Each value is hundredths of a character (`200` is
/// `2ch`). Strict `startChars` and `endChars` count only when `leftChars`
/// and `rightChars` are absent.
fn char_indent_clauses(ind: &Element) -> Vec<(&'static str, String)> {
    [
        (&["firstLineChars"][..], "first-line"),
        (&["hangingChars"][..], "hanging"),
        (&["leftChars", "startChars"][..], "left"),
        (&["rightChars", "endChars"][..], "right"),
    ]
    .into_iter()
    .filter_map(|(attrs, name)| {
        let v = attrs.iter().find_map(|attr| ind.attr(attr))?;
        let hundredths = crate::util::parse_finite_f64(v)?;
        Some((name, crate::markdown::xml::char_units(hundredths)))
    })
    .collect()
}

/// A paragraph's own indent (`w:ind`), one clause per side in the id
/// lines' order: `first-line`, `hanging`, `left`, `right`, each in inches,
/// then the same sides in characters (`first-line 2ch`). The strict
/// `start`/`end` count only when the transitional `left`/`right` is
/// absent, as the layout reads them.
pub(crate) fn indent_clauses(ind: &Element) -> Vec<(&'static str, String)> {
    [
        (&["firstLine"][..], "first-line"),
        (&["hanging"][..], "hanging"),
        (&["left", "start"][..], "left"),
        (&["right", "end"][..], "right"),
    ]
    .into_iter()
    .filter_map(|(attrs, name)| {
        let v = attrs.iter().find_map(|attr| ind.attr(attr))?;
        let twips =
            crate::util::parse_finite_f64(v).or_else(|| crate::util::universal_measure_twips(v))?;
        Some((name, inches(twips)))
    })
    .chain(char_indent_clauses(ind))
    .collect()
}

/// A paragraph's own spacing (`w:spacing`, #1473) in the styles legend's
/// words, each value exact: `before 6pt`, `after 10.05pt`, `line 1.5` (a
/// multiple of a single line) or `line 8.65pt exact` / `atLeast`. A Strict
/// package's universal measures (`12.95pt`) read as the nearest twip, as
/// Word stores them. `before auto` is Word's automatic space
/// (`w:beforeAutospacing`), which Word puts in place of `w:before`.
pub(crate) fn spacing_clauses(spacing: &Element) -> Vec<String> {
    let twips = |attr: &str| {
        let v = spacing.attr(attr)?;
        crate::util::parse_finite_f64(v)
            .or_else(|| crate::util::universal_measure_twips(v))
            .filter(|t| t.is_finite() && *t >= 0.0)
    };
    let mut out = Vec::new();
    for word in ["before", "after"] {
        let auto = spacing
            .attr(&format!("{word}Autospacing"))
            .is_some_and(|v| matches!(v, "1" | "true" | "on"));
        if auto {
            out.push(format!("{word} auto"));
        } else if let Some(t) = twips(word) {
            out.push(format!("{word} {}", exact_points(t)));
        }
        if let Some(raw) = spacing.attr(&format!("{word}Lines"))
            && let Some(count) = line_count(raw)
        {
            out.push(format!("{word} {count} lines"));
        }
    }
    if let Some(line) = twips("line") {
        match spacing.attr("lineRule").unwrap_or("auto") {
            rule @ ("exact" | "atLeast") => {
                out.push(format!("line {} {rule}", exact_points(line)));
            }
            _ => out.push(format!("line {}", line_ratio(line))),
        }
    }
    out
}

/// Twips as points with no more decimals than they need (`120` → `6pt`,
/// `173` → `8.65pt`): a twip is a twentieth of a point, so two are always
/// enough.
fn exact_points(twips: f64) -> String {
    let value = format!("{:.2}", twips.round() / 20.0);
    let value = value.trim_end_matches('0').trim_end_matches('.');
    format!("{value}pt")
}

/// An `auto` line (240ths of a line) as a multiple of a line with the
/// fewest decimals (two at least, four at most) that read back to it:
/// `360` → `1.5`, `249` → `1.038`.
fn line_ratio(line: f64) -> String {
    let ratio = line / 240.0;
    let value = (2..=4)
        .map(|places| format!("{ratio:.places$}"))
        .find(|text| {
            text.parse::<f64>()
                .is_ok_and(|v| (v * 240.0).round() == line.round())
        })
        .unwrap_or_else(|| format!("{ratio:.4}"));
    value
        .trim_end_matches('0')
        .trim_end_matches('.')
        .to_string()
}

/// `w:beforeLines` / `w:afterLines` (hundredths of a line) with the fewest
/// decimals that read back to the same count: `150` → `1.5`, `100` → `1`.
fn line_count(raw: &str) -> Option<String> {
    let n = crate::util::parse_finite_f64(raw)?;
    if !(n.is_finite() && n >= 0.0) {
        return None;
    }
    let hundredths = n.round();
    let count = hundredths / 100.0;
    let value = (0..=2)
        .map(|places| format!("{count:.places$}"))
        .find(|text| {
            text.parse::<f64>()
                .is_ok_and(|v| (v * 100.0).round() == hundredths)
        })
        .unwrap_or_else(|| format!("{count:.2}"));
    // Only a fraction's trailing zeros go: `10` stays ten lines.
    Some(if value.contains('.') {
        value
            .trim_end_matches('0')
            .trim_end_matches('.')
            .to_string()
    } else {
        value
    })
}

/// Twips as inches with the fewest decimals (two at least, four at most)
/// that read back to the same twips: `720` → `0.5in`, `1440` → `1in`,
/// `1134` (2cm) → `0.7875in`. Four decimals are always enough: they are off
/// by 0.072 twips at most.
pub(crate) fn inches(twips: f64) -> String {
    let inches = twips / 1440.0;
    let value = (2..=4)
        .map(|places| format!("{inches:.places$}"))
        .find(|text| {
            text.parse::<f64>()
                .is_ok_and(|v| (v * 1440.0).round() == twips.round())
        })
        .unwrap_or_else(|| format!("{inches:.4}"));
    let value = value.trim_end_matches('0').trim_end_matches('.');
    format!("{value}in")
}

/// Whether a descendant of `e` outside text boxes matches `hit`: a break
/// inside a text box turns no page of the body.
fn holds(e: &Element, hit: &dyn Fn(&Element) -> bool) -> bool {
    e.elements()
        .any(|c| !c.is("txbxContent") && (hit(c) || holds(c, hit)))
}

/// How many elements under `e` (text boxes excluded) `hit` matches.
fn count(e: &Element, hit: &dyn Fn(&Element) -> bool) -> usize {
    e.elements()
        .filter(|c| !c.is("txbxContent"))
        .map(|c| usize::from(hit(c)) + count(c, hit))
        .sum()
}

/// The first page break of `p` inside an insertion or deletion: the
/// change's kind (`ins`, `del`; a move as its side) and tag.
fn tracked_page_break(p: &Element, handles: &Handles) -> Option<(&'static str, String)> {
    fn walk(
        e: &Element,
        within: Option<(&'static str, &Element)>,
        handles: &Handles,
    ) -> Option<(&'static str, String)> {
        for child in shown_children(e) {
            if child.is("pPr") || child.is("txbxContent") || child.local().ends_with("PrChange") {
                continue;
            }
            if is_page_break(child) {
                if let Some((kind, change)) = within {
                    return Some((kind, required_date_tag_of(change, handles)));
                }
                continue;
            }
            let within = kind_of(child.local()).map_or(within, |kind| Some((kind, child)));
            if let Some(found) = walk(child, within, handles) {
                return Some(found);
            }
        }
        None
    }
    walk(p, None, handles)
}

fn is_page_break(e: &Element) -> bool {
    e.is("br") && e.attr("type") == Some("page")
}

/// A run whose only content is a page break.
fn page_break_only(run: &Element) -> bool {
    run.local() == "r"
        && run.elements().any(is_page_break)
        && run.elements().all(|child| {
            matches!(child.local(), "rPr" | "lastRenderedPageBreak") || is_page_break(child)
        })
}

/// Text the view prints: a later one means a page break is not the
/// paragraph's last content.
fn shown_leaf(element: &Element) -> bool {
    match element.local() {
        "t" | "delText" => !element.text().is_empty(),
        "tab" | "ptab" | "noBreakHyphen" => true,
        "br" | "cr" => element.attr("type") != Some("page"),
        // The view prints a symbol in place, `<sym …/>` (#1365).
        "sym" => ["font", "char"]
            .iter()
            .all(|name| element.attr(name).is_some_and(|value| !value.is_empty())),
        _ => false,
    }
}

/// Page-break runs of `paragraph` that have text after them. The view
/// prints each in place (`<br type="page"/>`); a break that ends the
/// paragraph stays on its id line.
pub(crate) fn mid_paragraph_page_breaks(paragraph: &Element) -> Vec<*const Element> {
    let mut order = Vec::new();
    fn walk<'a>(element: &'a Element, depth: usize, order: &mut Vec<(usize, &'a Element)>) {
        order.push((depth, element));
        for child in element.elements() {
            walk(child, depth + 1, order);
        }
    }
    walk(paragraph, 0, &mut order);
    let mut breaks = Vec::new();
    for (index, (depth, element)) in order.iter().enumerate() {
        if !page_break_only(element) {
            continue;
        }
        let mut rest = order[index + 1..]
            .iter()
            .skip_while(|(later, _)| *later > *depth);
        if rest.any(|(_, later)| shown_leaf(later)) {
            breaks.push(std::ptr::from_ref(*element));
        }
    }
    breaks
}

pub(crate) fn has_page_break(p: &Element) -> bool {
    holds(p, &is_page_break)
}

pub(crate) fn has_rendered_page_break(p: &Element) -> bool {
    holds(p, &|e| e.is("lastRenderedPageBreak"))
}

/// The hard page breaks in `p`: a paragraph can hold several.
pub(crate) fn page_breaks(p: &Element) -> usize {
    count(p, &is_page_break)
}

/// The cached page breaks in `p`: a paragraph that runs over three pages
/// holds two.
pub(crate) fn rendered_page_breaks(p: &Element) -> usize {
    count(p, &|e| e.is("lastRenderedPageBreak"))
}

/// Backslash-escapes the characters CommonMark would act on inside a run of
/// document text, so literal `*`, `` ` ``, `~~`, `==`, `\`, `[^` and
/// tag-like `<` read back as themselves. `_` is escaped only at a word edge
/// (`a_b` stays; `_x_` becomes `\_x\_`); `=` only beside its twin; `~`
/// and `^` beside their twin or at a word edge (`H~2~O` stays). CriticMarkup delimiters are `critic::escape`'s job, after this.
pub(crate) fn escape_markdown(text: &str) -> String {
    let chars: Vec<char> = text.chars().collect();
    let at = |i: usize| chars.get(i).copied();
    let before = |i: usize| i.checked_sub(1).and_then(at);
    let mut out = String::with_capacity(text.len() + 8);
    for (i, &c) in chars.iter().enumerate() {
        let next = at(i + 1);
        let escape = match c {
            '\\' | '*' | '`' => true,
            '_' => {
                !(before(i).is_some_and(char::is_alphanumeric)
                    && next.is_some_and(char::is_alphanumeric))
            }
            '=' => before(i) == Some(c) || next == Some(c),
            // One `~` or `^` marks subscript or superscript at a word
            // edge; inside a word, or between spaces, it opens nothing.
            '~' | '^' if before(i) == Some('[') => false,
            '~' | '^' => {
                let word = |c: Option<char>| c.is_some_and(char::is_alphanumeric);
                let space = |c: Option<char>| c.is_none_or(char::is_whitespace);
                before(i) == Some(c)
                    || next == Some(c)
                    || !((word(before(i)) && word(next)) || (space(before(i)) && space(next)))
            }
            '<' => next.is_some_and(|n| n.is_ascii_alphabetic() || n == '/' || n == '!'),
            '[' => next == Some('^'),
            // A `]` before `(`, `[` or `:` would close a link, an image, a
            // reference or a reference definition.
            ']' => matches!(next, Some('(' | '[' | ':')),
            '&' => entity_follows(&chars[i + 1..]),
            // A literal `{/}`, or `{` before a field code and `}`, would
            // read back as a field.
            '{' => field_follows(&chars[i + 1..]),
            _ => false,
        };
        if escape {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// Whether `rest` (the text after a `{`) is `/}` or a field code then `}`,
/// which the writer reads as a body field.
fn field_follows(rest: &[char]) -> bool {
    use crate::markdown::critic::{field_code_close, is_field_code};
    field_code_close(rest.iter().copied().enumerate()).is_some_and(|close| {
        let code: String = rest[..close].iter().collect();
        code == "/" || is_field_code(&code)
    })
}

/// Whether `rest` (the text after a `&`) reads as an entity or character
/// reference (`copy;`, `#35;`, `#x23;`), which would decode on the way back.
/// A name HTML does not define (`foo;`) is text to CommonMark: the parser
/// itself says which names decode.
fn entity_follows(rest: &[char]) -> bool {
    let numeric = rest.first() == Some(&'#');
    let body = if numeric { &rest[1..] } else { rest };
    let name = body
        .iter()
        .take_while(|c| c.is_ascii_alphanumeric())
        .count();
    if name == 0 || body.get(name) != Some(&';') {
        return false;
    }
    if numeric {
        return true;
    }
    let reference: String = std::iter::once('&')
        .chain(body[..=name].iter().copied())
        .collect();
    let read: String = pulldown_cmark::Parser::new(&reference)
        .filter_map(|event| match event {
            pulldown_cmark::Event::Text(text) => Some(text.into_string()),
            _ => None,
        })
        .collect();
    read != reference
}

/// A heading's text with a trailing run of `#` escaped: CommonMark reads a
/// run of `#` at the end of an ATX heading, after a space or alone, as a
/// closing sequence and drops it.
pub(crate) fn escape_closing_hashes(text: &str) -> String {
    let trimmed = text.trim_end();
    let body = trimmed.trim_end_matches('#');
    if body.len() == trimmed.len() || !(body.is_empty() || body.ends_with([' ', '\t'])) {
        return text.to_string();
    }
    format!("{body}\\{}", &text[body.len()..])
}

/// Escapes a block-opening mark at the start of one line of a paragraph:
/// `#` (one to six, then a space or the end), `>`, `|`, a list bullet (`-`
/// or `+` then a space), an ordered marker (digits then `.` or `)` then a
/// space or the end), or a line of dashes or of `=` (a setext underline or a
/// rule).
/// A leading `*` is already `\*` from `escape_markdown`.
pub(crate) fn escape_block_start(line: &str) -> String {
    let bytes = line.as_bytes();
    // A block opener may sit after up to three spaces; four open an indented
    // code block, whose text shows as written. Paragraph lines arrive trimmed
    // (`tidy_inline`), so this guards callers that keep their indent.
    let indent = bytes.iter().take_while(|&&b| b == b' ').count();
    if (1..=3).contains(&indent) {
        let (spaces, rest) = line.split_at(indent);
        return format!("{spaces}{}", escape_block_start(rest));
    }
    let hashes = bytes.iter().take_while(|&&b| b == b'#').count();
    let opens = ((1..=6).contains(&hashes) && bytes.get(hashes).is_none_or(|&b| b == b' '))
        || matches!(bytes.first(), Some(b'>' | b'|'))
        || (matches!(bytes.first(), Some(b'-' | b'+')) && bytes.get(1).is_none_or(|&b| b == b' '))
        || (bytes.first() == Some(&b'-') && line.trim_end().bytes().all(|b| b == b'-'))
        || (bytes.first() == Some(&b'=') && line.trim_end().bytes().all(|b| b == b'='));
    if opens {
        return format!("\\{line}");
    }
    let digits = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
    if (1..=9).contains(&digits)
        && matches!(bytes.get(digits), Some(b'.' | b')'))
        && bytes.get(digits + 1).is_none_or(|&b| b == b' ')
    {
        return format!("{}\\{}", &line[..digits], &line[digits..]);
    }
    line.to_string()
}

/// `escape_block_start` on every line: after a hard break an ATX heading or
/// a list item can interrupt a paragraph.
pub(crate) fn escape_line_starts(text: &str) -> String {
    text.split('\n')
        .map(escape_block_start)
        .collect::<Vec<_>>()
        .join("\n")
}

/// The tables under `e` in document order, text boxes excluded.
pub(crate) fn tables(e: &Element) -> Vec<&Element> {
    fn walk<'a>(e: &'a Element, out: &mut Vec<&'a Element>) {
        for c in e
            .elements()
            .filter(|c| !c.is("txbxContent") && !c.is("AlternateContent"))
        {
            if c.is("tbl") {
                out.push(c);
            }
            walk(c, out);
        }
    }
    let mut out = Vec::new();
    walk(e, &mut out);
    out
}

/// The paragraphs under `e` in document order, text boxes excluded.
pub(crate) fn paragraphs(e: &Element) -> Vec<&Element> {
    fn walk<'a>(e: &'a Element, out: &mut Vec<&'a Element>) {
        for c in e.elements() {
            if c.is("p") {
                out.push(c);
            }
            if !c.is("txbxContent") {
                walk(c, out);
            }
        }
    }
    let mut out = Vec::new();
    walk(e, &mut out);
    out
}

/// Every paragraph under `e` in document order, a text box's too: a
/// paragraph, then the paragraphs of the boxes it anchors.
pub(crate) fn paragraphs_and_boxes(e: &Element) -> Vec<&Element> {
    fn walk<'a>(e: &'a Element, out: &mut Vec<&'a Element>) {
        for c in e.elements() {
            if c.is("p") {
                out.push(c);
            }
            walk(c, out);
        }
    }
    let mut out = Vec::new();
    walk(e, &mut out);
    out
}

/// Indices of the paragraphs whose section break starts a new page: the
/// section after them is not `continuous` or `nextColumn` (a section's
/// `w:type` says how that section starts).
pub(crate) fn page_sections(body: &Element) -> HashSet<usize> {
    let ends: Vec<(usize, &Element)> = paragraphs(body)
        .into_iter()
        .filter_map(|p| Some((p.attr(INDEX)?.parse().ok()?, p.path(&["pPr", "sectPr"])?)))
        .collect();
    let last = body.child("sectPr");
    ends.iter()
        .enumerate()
        .filter(|(k, _)| {
            let next = ends.get(k + 1).map(|(_, s)| *s).or(last);
            !next
                .and_then(|s| s.path(&["type"]))
                .and_then(|t| t.attr("val"))
                .is_some_and(|v| v == "continuous" || v == "nextColumn")
        })
        .map(|(_, (index, _))| *index)
        .collect()
}

/// A table's cached page breaks: whether its first paragraph opens a page,
/// and how many more pages its other paragraphs turn (named at the next
/// block, since a marker cannot go inside a table).
pub(crate) fn table_breaks(tbl: &Element, cached: bool) -> (bool, usize) {
    let ps = paragraphs(tbl);
    if cached {
        let first = ps.first().is_some_and(|p| has_rendered_page_break(p));
        let all: usize = ps.iter().map(|p| rendered_page_breaks(p)).sum();
        (first, all - usize::from(first))
    } else {
        (false, ps.iter().map(|p| page_breaks(p)).sum())
    }
}

pub(crate) fn has_section_break(p: &Element) -> bool {
    p.path(&["pPr", "sectPr"]).is_some()
}

/// `<!-- head -->` or `<!-- head clause, clause -->`.
pub(crate) fn line(head: &str, clauses: &[String]) -> String {
    if clauses.is_empty() {
        format!("<!-- {head} -->")
    } else {
        format!("<!-- {head} {} -->", clauses.join(", "))
    }
}

/// `<!-- p3 justify, first-line 0.5in, comments c5 -->` (the plan's grammar).
/// A paragraph that states a style names it, the default too: the statement
/// is the document's own, not the view's to drop (#528). A heading's own
/// `HeadingN` with text needs no name, the `#` count says it; an empty
/// paragraph has no `#`, so even that one is named.
pub(crate) fn id_line(p: &Element, f: &LineFacts, handles: &Handles) -> String {
    let mut head = format!("p{}", f.index);
    if let Some(style) = f.style {
        let implied = !f.empty
            && f.heading
                .is_some_and(|level| style == format!("Heading{level}"));
        if !implied {
            head.push(' ');
            head.push_str(&crate::markdown::view_notes::style_token(style));
        }
    }
    let ppr = p.child("pPr");
    let mut clauses: Vec<String> = Vec::new();
    if let Some(outline) = f.outline {
        clauses.push(format!("outline {outline}"));
    }
    if f.empty {
        clauses.push("empty".to_string());
    }
    if let Some(jc) = ppr
        .and_then(|pr| pr.child("jc"))
        .and_then(|j| j.attr("val"))
    {
        clauses.push(
            match jc {
                "center" => "center",
                "right" | "end" => "right",
                "both" | "distribute" => "justify",
                _ => "left",
            }
            .to_string(),
        );
    }
    if let Some(ind) = ppr.and_then(|pr| pr.child("ind")) {
        for (name, value) in indent_clauses(ind) {
            clauses.push(format!("{name} {value}"));
        }
    }
    if let Some(spacing) = ppr.and_then(|pr| pr.child("spacing")) {
        clauses.extend(spacing_clauses(spacing));
    }
    if let Some(size) = f.size {
        clauses.push(size_clause(size));
        if f.mark_inherits {
            clauses.push("mark style".to_string());
        }
    }
    match f.marker {
        Some("-") => clauses.push("bullet".to_string()),
        // `\` and `"` escaped, so the quoted label always parses.
        Some(label) => clauses.push(format!(
            "num \"{}\"",
            label.replace('\\', "\\\\").replace('"', "\\\"")
        )),
        None => {}
    }
    if f.marker.is_some() && f.level > 0 {
        clauses.push(format!("level {}", f.level));
    }
    // A page break in a tracked change names it: `rev` would say only
    // that some change shows no text, not that it is the break's.
    let tracked_break = (!f.resolved && f.page_break)
        .then(|| tracked_page_break(p, handles))
        .flatten();
    match &tracked_break {
        Some((kind, tag)) => clauses.push(format!("page-break-{kind} {}", format_tag(tag))),
        None if f.page_break => clauses.push("page-break".to_string()),
        None => {}
    }
    if has_section_break(p) {
        clauses.push("section-break".to_string());
    }
    let (_, del) = mark_tags_by(p, handles, required_date_tag_of);
    if !del.is_empty() {
        clauses.push(format!("break-del {}", format_tags(&del)));
    }
    let fmt = format_change_nests(p, handles, required_date_tag_of);
    if !fmt.is_empty() {
        clauses.push(format!("fmt {}", format_nested_tags(&fmt)));
    }
    let unshown: Vec<&(bool, String)> = f
        .unshown
        .iter()
        .filter(|(_, tag)| {
            tracked_break
                .as_ref()
                .is_none_or(|(_, b)| format_tag(b) != *tag)
        })
        .collect();
    if !f.resolved {
        for inserted in [true, false] {
            let tags: Vec<&str> = unshown
                .iter()
                .filter(|(ins, _)| *ins == inserted)
                .map(|(_, tag)| tag.as_str())
                .collect();
            if !tags.is_empty() {
                let word = if inserted { "rev" } else { "rev-del" };
                clauses.push(format!("{word} {}", tags.join("; ")));
            }
        }
    }
    if f.resolved {
        let tags = resolved_tags(p);
        if !tags.is_empty() {
            clauses.push(format!("rev {}", tags.join("; ")));
        }
    }
    if !f.comments.is_empty() {
        let ids: Vec<String> = f.comments.iter().map(|c| format!("c{c}")).collect();
        clauses.push(format!("comments {}", ids.join(" ")));
    }
    if !f.spans.is_empty() {
        let ids: Vec<String> = f.spans.iter().map(|c| format!("c{c}")).collect();
        clauses.push(format!("in {}", ids.join(" ")));
    }
    if !f.resolved {
        clauses.extend(f.holds.iter().cloned());
    }
    line(&head, &clauses)
}

/// `<!-- p19 empty -->` / `<!-- p19-p23 empty -->` lines for pending empties.
pub(crate) fn empty_lines(indices: &[usize]) -> Vec<String> {
    runs(indices)
        .into_iter()
        .map(|(a, b)| {
            if a == b {
                format!("<!-- p{a} empty -->")
            } else {
                format!("<!-- p{a}-p{b} empty -->")
            }
        })
        .collect()
}

/// The page marker `paginate` writes, for the cached-break fallback.
pub(crate) fn page_marker(page: usize, total: usize) -> String {
    format!("<!-- page {page} of {total} -->")
}

/// Paragraphs (text boxes excluded) holding `w:lastRenderedPageBreak`, and
/// hard page breaks plus section breaks that start a page, for the
/// cached-break page count.
pub(crate) fn page_counts(body: &Element) -> (usize, usize) {
    let ps = paragraphs(body);
    let rendered = ps.iter().map(|p| rendered_page_breaks(p)).sum();
    let hard = ps.iter().map(|p| page_breaks(p)).sum::<usize>() + page_sections(body).len();
    (rendered, hard)
}

/// The table line's merged cells, row by row: `t0.row0.cell1 across 2`
/// for a cell spanning two grid columns, `t0.row0.cell0 down 3` for a
/// vertical merge starting there and covering three rows (Word's
/// `gridSpan` and `vMerge`). `grid` holds each row's cells as grid column,
/// columns spanned and vertical merge.
fn merged_cells(t: &str, grid: &[Vec<(usize, usize, Option<bool>)>]) -> Vec<String> {
    let mut out = Vec::new();
    for (r, cells) in grid.iter().enumerate() {
        for (c, &(column, span, vertical)) in cells.iter().enumerate() {
            let mut said = Vec::new();
            if span > 1 {
                said.push(format!("across {span}"));
            }
            if vertical == Some(true) {
                let down = 1 + grid[r + 1..]
                    .iter()
                    .take_while(|row| {
                        row.iter()
                            .any(|&(at, _, v)| at == column && v == Some(false))
                    })
                    .count();
                if down > 1 {
                    said.push(format!("down {down}"));
                }
            }
            if !said.is_empty() {
                out.push(format!("t{t}.row{r}.cell{c} {}", said.join(" ")));
            }
        }
    }
    out
}

/// The sides `props` (`w:tblBorders`, `w:tcBorders`, `w:pBdr`) names among
/// `all`, in schema order.
pub(super) fn own_borders(
    props: Option<&Element>,
    all: &[&'static str],
) -> crate::markdown::borders::Sides {
    use crate::markdown::borders;
    let found: Vec<_> = props
        .into_iter()
        .flat_map(|e| e.elements())
        .filter_map(|side| {
            let name = borders::side(side.local(), all)?;
            let border = borders::Border::new(
                side.attr("val")?,
                side.attr("sz"),
                side.attr("color"),
                side.attr("space"),
            )
            .with_theme(
                side.attr("themeColor"),
                side.attr("themeTint"),
                side.attr("themeShade"),
            )
            .with_effects(side.attr("shadow"), side.attr("frame"));
            Some((name, border))
        })
        .collect();
    borders::ordered(&found, all)
}

/// The borders `tbl` and its cells carry themselves, as its line prints them
/// (`borders single 0.5pt 000000`, `cell-borders bottom single 1pt in
/// t0.row0`): what Word passes comes back as it was.
fn border_clauses(tbl: &Element, t: &str, rows: &[&Element]) -> Vec<String> {
    use crate::markdown::borders::{self, CELL_SIDES, TABLE_SIDES};
    let read = own_borders;
    let mut clauses = Vec::new();
    let own = read(tbl.path(&["tblPr", "tblBorders"]), &TABLE_SIDES);
    if !own.is_empty() {
        clauses.push(format!("borders {}", borders::describe(&own, &TABLE_SIDES)));
    }
    // A row's own table borders (`w:tblPrEx/w:tblBorders`), the rows that
    // share one in one group: `row-borders top double 0.5pt in t0.row1`.
    let mut row_groups: Vec<(String, Vec<String>)> = Vec::new();
    for (r, tr) in rows.iter().enumerate() {
        let sides = read(tr.path(&["tblPrEx", "tblBorders"]), &TABLE_SIDES);
        if sides.is_empty() {
            continue;
        }
        let text = borders::describe(&sides, &TABLE_SIDES);
        let at = format!("t{t}.row{r}");
        match row_groups.iter_mut().find(|(g, _)| *g == text) {
            Some((_, rows)) => rows.push(at),
            None => row_groups.push((text, vec![at])),
        }
    }
    if !row_groups.is_empty() {
        let groups: Vec<String> = row_groups
            .iter()
            .map(|(text, at)| format!("{text} in {}", at.join(" ")))
            .collect();
        clauses.push(format!("row-borders {}", groups.join("; ")));
    }
    // Each cell's borders, as text, by row; the cells that share one print
    // as one group, a whole row as the row, every cell as `all`.
    let cells: Vec<Vec<String>> = rows
        .iter()
        .map(|tr| {
            super::row_cells(tr)
                .map(|tc| {
                    let sides = read(tc.path(&["tcPr", "tcBorders"]), &CELL_SIDES);
                    borders::describe(&sides, &CELL_SIDES)
                })
                .collect()
        })
        .collect();
    let mut texts: Vec<&String> = Vec::new();
    for text in cells.iter().flatten().filter(|t| !t.is_empty()) {
        if !texts.contains(&text) {
            texts.push(text);
        }
    }
    let groups: Vec<String> = texts
        .iter()
        .map(|text| {
            if cells.iter().flatten().all(|c| c == *text) {
                return format!("{text} in all");
            }
            let mut at = Vec::new();
            for (r, row) in cells.iter().enumerate() {
                if !row.is_empty() && row.iter().all(|c| c == *text) {
                    at.push(format!("t{t}.row{r}"));
                    continue;
                }
                for (c, cell) in row.iter().enumerate() {
                    if cell == *text {
                        at.push(format!("t{t}.row{r}.cell{c}"));
                    }
                }
            }
            format!("{text} in {}", at.join(" "))
        })
        .collect();
    if !groups.is_empty() {
        clauses.push(format!("cell-borders {}", groups.join("; ")));
    }
    clauses
}

/// `widths 2.1424in 0.985in`, `width auto`, `indent 0.25in`, `layout
/// fixed`: the table's geometry where it is not what the writer writes by
/// itself (#1472), columns that split `text_width` evenly over 100% of it,
/// no indent and an autofit layout. A grid column with no width, or one
/// past Word's 22in, prints no widths at all: the writer would read them
/// as another grid.
pub(crate) fn geometry_clauses(tbl: &Element, text_width: u32) -> Vec<String> {
    // The reader's bounds (`xml.rs`): 22in, and 600% of the text width.
    const MOST: f64 = 31_680.0;
    const MOST_PERCENT: f64 = 600.0;
    let twips = |e: &Element, attr: &str| -> Option<f64> {
        let v = e.attr(attr)?;
        crate::util::parse_finite_f64(v)
            .or_else(|| crate::util::universal_measure_twips(v))
            .filter(|t| t.is_finite())
    };
    let mut out = Vec::new();
    let widths: Option<Vec<f64>> = tbl.child("tblGrid").and_then(|grid| {
        grid.children_named("gridCol")
            .map(|col| twips(col, "w").filter(|w| (0.0..=MOST).contains(&w.round())))
            .collect()
    });
    if let Some(widths) = widths.filter(|w| !w.is_empty()) {
        let count = u32::try_from(widths.len()).unwrap_or(u32::MAX);
        let even = f64::from(text_width / count.max(1));
        if widths.iter().any(|w| w.round() != even) {
            let listed: Vec<String> = widths.iter().map(|&w| inches(w)).collect();
            out.push(format!("widths {}", listed.join(" ")));
        }
    }
    let properties = tbl.child("tblPr");
    // No `w:tblW`, or `nil`, is Word's auto; `w:type` left out is `dxa`.
    let width = properties.and_then(|p| p.child("tblW"));
    match width.and_then(|w| w.attr("type")).unwrap_or(match width {
        Some(_) => "dxa",
        None => "auto",
    }) {
        "pct" => {
            // `5000` fiftieths of a percent, or `100%`.
            let fiftieths =
                width
                    .and_then(|w| w.attr("w"))
                    .and_then(|v| match v.strip_suffix('%') {
                        Some(percent) => crate::util::parse_finite_f64(percent).map(|p| p * 50.0),
                        None => crate::util::parse_finite_f64(v),
                    });
            // No width, or 0, is no preference: Word lays the table out
            // as auto. Past 600% the reader refuses the clause, so the
            // view prints none (#1483 review).
            match fiftieths.filter(|f| f.is_finite() && *f >= 0.0) {
                None if width.and_then(|w| w.attr("w")).is_none() => {
                    out.push("width auto".to_string());
                }
                Some(f) if f.round() == 0.0 => out.push("width auto".to_string()),
                Some(f) if f.round() != 5000.0 && f.round() <= MOST_PERCENT * 50.0 => {
                    let percent = format!("{:.2}", f.round() / 50.0);
                    let percent = percent.trim_end_matches('0').trim_end_matches('.');
                    out.push(format!("width {percent}%"));
                }
                _ => {}
            }
        }
        "dxa" => match width.and_then(|w| twips(w, "w")) {
            None if width.and_then(|w| w.attr("w")).is_none() => {
                out.push("width auto".to_string());
            }
            Some(w) if w.round() == 0.0 => out.push("width auto".to_string()),
            Some(w) if (0.0..=MOST).contains(&w.round()) => {
                out.push(format!("width {}", inches(w)));
            }
            _ => {}
        },
        _ => out.push("width auto".to_string()),
    }
    if let Some(indent) = properties
        .and_then(|p| p.child("tblInd"))
        .filter(|i| i.attr("type").is_none_or(|t| t == "dxa"))
        .and_then(|i| twips(i, "w"))
        .filter(|w| w.round() != 0.0 && w.round().abs() <= MOST)
    {
        out.push(format!("indent {}", inches(indent)));
    }
    if properties
        .and_then(|p| p.child("tblLayout"))
        .and_then(|l| l.attr("type"))
        == Some("fixed")
    {
        out.push("layout fixed".to_string());
    }
    out
}

/// `<!-- t0 center 3x3, cells p8-p16 by row, p9 center, header row repeats -->`
/// (`aligned`: the cell paragraphs aligned against their column);
/// `None` for a nested table (not numbered). With `comments` (comments
/// hidden) the cells' comment ids print as `comments c9 in p3`; `spans`
/// are the comment threads whose range runs through the table (`in c5`).
pub(crate) fn table_line(
    tbl: &Element,
    style: Option<&str>,
    aligned: &[String],
    resolved: bool,
    comments: Option<&HashMap<String, Element>>,
    spans: &[String],
    handles: &Handles,
) -> Option<String> {
    let t = tbl.attr(TABLE)?;
    let rows: Vec<&Element> = super::table_rows(tbl);
    let cols = tbl
        .child("tblGrid")
        .map(|g| g.children_named("gridCol").count())
        .filter(|&c| c > 0)
        .unwrap_or_else(|| {
            rows.iter()
                .map(|r| super::row_cells(r).count())
                .max()
                .unwrap_or(0)
        });
    let mut head = format!("t{t}");
    if let Some(jc) = tbl.path(&["tblPr", "jc"]).and_then(|j| j.attr("val")) {
        match jc {
            "center" => head.push_str(" center"),
            "right" | "end" => head.push_str(" right"),
            _ => {}
        }
    }
    // The size opens the clauses: `t0 center 3x3, cells …`.
    let mut clauses: Vec<String> = vec![format!("{}x{}", rows.len(), cols)];
    let mut per_row: Vec<(usize, usize)> = Vec::new();
    let mut uniform = true;
    // Each row's cells: grid column, columns spanned, and vertical merge
    // (`Some(true)` where one starts, `Some(false)` where one continues).
    let mut grid: Vec<Vec<(usize, usize, Option<bool>)>> = Vec::new();
    let mut break_ins: Vec<String> = Vec::new();
    let mut break_del: Vec<String> = Vec::new();
    let mut revs: Vec<String> = Vec::new();
    // A row's or cell's own deletion and a cell's merge: `rev` alone is an
    // insertion.
    let mut rev_del: Vec<String> = Vec::new();
    let mut rev_merge: Vec<String> = Vec::new();
    let mut fmt: Vec<String> = Vec::new();
    let mut held: Vec<String> = Vec::new();
    let mut held_ids: Vec<String> = Vec::new();
    let mut gaps: Vec<String> = Vec::new();
    // The tracked view names the table's own property changes (Word's
    // `tblPrChange`, `tblGridChange`, `trPrChange`, `tblPrExChange`,
    // `tcPrChange`) and its cell insertions, deletions and merges, where
    // they sit: the cells' text shows none of them.
    let changes_in = |props: Option<&Element>, at: &str, out: &mut Vec<String>| {
        for change in props
            .into_iter()
            .flat_map(|e| e.elements())
            .filter(|c| c.local().ends_with("Change"))
        {
            out.push(format!(
                "{}{at}",
                format_tag(&required_date_tag_of(change, handles))
            ));
        }
    };
    if !resolved {
        changes_in(tbl.child("tblPr"), "", &mut fmt);
        changes_in(tbl.child("tblGrid"), "", &mut fmt);
    }
    for (r, tr) in rows.iter().enumerate() {
        let mut range: Option<(usize, usize)> = None;
        if resolved {
            revs.extend(
                stamped_revs(tr)
                    .into_iter()
                    .map(|(_, tag)| format!("{} in t{t}.row{r}", format_tag(&tag))),
            );
        } else {
            let at = format!(" in t{t}.row{r}");
            changes_in(tr.child("trPr"), &at, &mut fmt);
            changes_in(tr.child("tblPrEx"), &at, &mut fmt);
            // A row's own insertion or deletion is named here. Cell text
            // with no marks of its own still shows the row's tag; the
            // writer puts the mark back on the row from this clause.
            for mark in tr
                .child("trPr")
                .into_iter()
                .flat_map(|e| e.elements())
                .filter(|e| matches!(e.local(), "ins" | "del"))
            {
                let tag = format!("{}{at}", format_tag(&required_date_tag_of(mark, handles)));
                if mark.local() == "del" {
                    rev_del.push(tag);
                } else {
                    revs.push(tag);
                }
            }
        }
        let grid_skip = |name: &str| {
            tr.path(&["trPr", name])
                .and_then(|g| g.attr("val"))
                .and_then(|v| v.parse::<usize>().ok())
                .unwrap_or(0)
        };
        let mut column = grid_skip("gridBefore");
        // Grid columns a row leaves out before or after its cells: the
        // view prints them as empty cells, which are no cells. A row whose
        // cells stop short of the grid without `gridAfter` leaves the rest
        // out the same way.
        let filled: usize = super::row_cells(tr)
            .map(|tc| {
                tc.path(&["tcPr", "gridSpan"])
                    .and_then(|g| g.attr("val"))
                    .and_then(|v| v.parse::<usize>().ok())
                    .unwrap_or(1)
                    .clamp(1, 64)
            })
            .sum();
        let after = grid_skip("gridAfter");
        // A row whose cells and gaps take more grid columns than the grid
        // has, with a cell that prints nothing, holds a cell the view
        // cannot tell from its padding: its paragraph count, per row,
        // brings it back. Cells that all print text place themselves.
        if column + filled + after > cols && super::row_cells(tr).any(|tc| !shows_text(tc)) {
            uniform = false;
        }
        let after = after.max(cols.saturating_sub(column + filled));
        let mut gap = Vec::new();
        if column > 0 {
            gap.push(format!("before {column}"));
        }
        if after > 0 {
            gap.push(format!("after {after}"));
        }
        if !gap.is_empty() {
            gaps.push(format!("t{t}.row{r} {}", gap.join(" ")));
        }
        let mut cells = Vec::new();
        for (c, tc) in super::row_cells(tr).enumerate() {
            let span = tc
                .path(&["tcPr", "gridSpan"])
                .and_then(|g| g.attr("val"))
                .and_then(|v| v.parse::<usize>().ok())
                .unwrap_or(1)
                .clamp(1, 64);
            let vertical = tc
                .path(&["tcPr", "vMerge"])
                .map(|v| v.attr("val") == Some("restart"));
            cells.push((column, span, vertical));
            column += span;
            if resolved {
                revs.extend(
                    stamped_revs(tc)
                        .into_iter()
                        .map(|(_, tag)| format!("{} in t{t}.row{r}.cell{c}", format_tag(&tag))),
                );
            } else {
                let at = format!(" in t{t}.row{r}.cell{c}");
                let props = tc.child("tcPr");
                changes_in(props, &at, &mut fmt);
                // Word's own cell mark is `w:ins`/`w:del` in `w:tcPr` as
                // often as `w:cellIns`/`w:cellDel` (both read); a merge is
                // `w:cellMerge`.
                for cell_change in props.into_iter().flat_map(|e| e.elements()).filter(|e| {
                    matches!(
                        e.local(),
                        "ins" | "del" | "cellIns" | "cellDel" | "cellMerge"
                    )
                }) {
                    let tag = format!(
                        "{}{at}",
                        format_tag(&required_date_tag_of(cell_change, handles))
                    );
                    match cell_change.local() {
                        "del" | "cellDel" => rev_del.push(tag),
                        "cellMerge" => rev_merge.push(tag),
                        _ => revs.push(tag),
                    }
                }
            }
            let mut ps = Vec::new();
            tc.find_all("p", &mut ps);
            let idx: Vec<usize> = ps
                .iter()
                .filter_map(|p| p.attr(INDEX)?.parse().ok())
                .collect();
            if idx.len() != 1 {
                uniform = false;
            }
            for p in &ps {
                let Some(i) = p.attr(INDEX) else { continue };
                let (ins, del) = mark_tags_by(p, handles, required_date_tag_of);
                break_ins.extend(ins.iter().map(|t| format!("{} in p{i}", format_tag(t))));
                break_del.extend(del.iter().map(|t| format!("{} in p{i}", format_tag(t))));
                if resolved {
                    revs.extend(
                        resolved_tags(p)
                            .into_iter()
                            .map(|tag| format!("{tag} in p{i}")),
                    );
                } else {
                    // A cell's paragraph has no id line to carry its own
                    // formatting changes.
                    fmt.extend(
                        format_change_nests(p, handles, required_date_tag_of)
                            .iter()
                            .map(|(own, parent)| {
                                format!("{} in p{i}", format_one_nest(own, parent.as_deref()))
                            }),
                    );
                }
                let ids: Vec<String> = comments.map_or_else(Vec::new, |known| {
                    comment_ids(p)
                        .into_iter()
                        .filter(|id| known.contains_key(id))
                        .collect()
                });
                if !ids.is_empty() {
                    held_ids.extend(ids.iter().cloned());
                    let ids: Vec<String> = ids.iter().map(|c| format!("c{c}")).collect();
                    held.push(format!("{} in p{i}", ids.join(" ")));
                }
            }
            if let (Some(&a), Some(&b)) = (idx.first(), idx.last()) {
                range = Some(match range {
                    None => (a, b),
                    Some((start, _)) => (start, b),
                });
            }
        }
        if let Some(r) = range {
            per_row.push(r);
        }
        grid.push(cells);
    }
    if uniform {
        if let (Some(&(a, _)), Some(&(_, b))) = (per_row.first(), per_row.last()) {
            clauses.push(format!("cells p{a}-p{b} by row"));
        }
    } else {
        let rows: Vec<String> = per_row
            .iter()
            .enumerate()
            .map(|(i, (a, b))| {
                if a == b {
                    format!("t{t}.row{i} p{a}")
                } else {
                    format!("t{t}.row{i} p{a}-p{b}")
                }
            })
            .collect();
        clauses.push(format!("cells {}", rows.join(" ")));
    }
    clauses.extend(aligned.iter().cloned());
    if rows
        .first()
        .is_some_and(|tr| tr.path(&["trPr", "tblHeader"]).is_some())
    {
        clauses.push("header row repeats".to_string());
    }
    if let Some(style) = style {
        clauses.push(format!(
            "style {}",
            crate::markdown::view_notes::style_token(style)
        ));
    }
    clauses.extend(border_clauses(tbl, t, &rows));
    let merged = merged_cells(t, &grid);
    if !merged.is_empty() {
        clauses.push(format!("merged {}", merged.join("; ")));
    }
    if !gaps.is_empty() {
        clauses.push(format!("gaps {}", gaps.join("; ")));
    }
    if !break_ins.is_empty() {
        clauses.push(format!("break-ins {}", break_ins.join("; ")));
    }
    if !break_del.is_empty() {
        clauses.push(format!("break-del {}", break_del.join("; ")));
    }
    if !revs.is_empty() {
        clauses.push(format!("rev {}", revs.join("; ")));
    }
    if !rev_del.is_empty() {
        clauses.push(format!("rev-del {}", rev_del.join("; ")));
    }
    if !rev_merge.is_empty() {
        clauses.push(format!("rev-merge {}", rev_merge.join("; ")));
    }
    if !fmt.is_empty() {
        clauses.push(format!("fmt {}", fmt.join("; ")));
    }
    if !held.is_empty() {
        clauses.push(format!("comments {}", held.join("; ")));
    }
    // A comment a cell holds is named once, where it is held.
    let ids: Vec<String> = spans
        .iter()
        .filter(|c| !held_ids.contains(c))
        .map(|c| format!("c{c}"))
        .collect();
    if !ids.is_empty() {
        clauses.push(format!("in {}", ids.join(" ")));
    }
    Some(line(&head, &clauses))
}

/// Comment threads from `commentsExtended.xml`.
#[derive(Debug, Default, Clone)]
pub(crate) struct Threads {
    /// Reply id → root id (`w15:paraIdParent`; Word threads are flat).
    pub reply_of: HashMap<String, String>,
    /// Ids marked `w15:done="1"`.
    pub done: HashSet<String>,
}

/// `commentEx` names a comment by the `w14:paraId` of its last paragraph.
pub(crate) fn threads(comments: Option<&Element>, extended: Option<&Element>) -> Threads {
    let mut t = Threads::default();
    let (Some(comments), Some(extended)) = (comments, extended) else {
        return t;
    };
    let by_para: HashMap<String, String> = comments
        .children_named("comment")
        .filter_map(|c| {
            let id = c.attr("id")?;
            let para = c.children_named("p").last()?.attr("paraId")?;
            Some((para.to_string(), id.to_string()))
        })
        .collect();
    for ex in extended.children_named("commentEx") {
        let Some(id) = ex.attr("paraId").and_then(|p| by_para.get(p)) else {
            continue;
        };
        if ex.attr("done").is_some_and(|d| d == "1" || d == "true") {
            t.done.insert(id.clone());
        }
        if let Some(parent) = ex.attr("paraIdParent").and_then(|p| by_para.get(p)) {
            t.reply_of.insert(id.clone(), parent.clone());
        }
    }
    t
}

/// `c5 @AC: `, `c5 @AC resolved: `, `c6 @AS re c5: `, or `c5: ` with
/// no author. `date` is the inline timestamp, when wanted; `held`, the
/// change whose mark holds the comment's reference when the note prints
/// outside it (`c5 @AC in r13: `).
pub(crate) fn comment_head(
    id: &str,
    author: Option<&str>,
    date: Option<&str>,
    handles: &Handles,
    threads: &Threads,
    held: Option<u32>,
) -> String {
    let mut head = format!("c{id}");
    if let Some(handle) = handles.of(author) {
        head.push_str(&format!(" @{handle}"));
    }
    if let Some(date) = date {
        head.push(' ');
        head.push_str(date);
    }
    if let Some(root) = threads.reply_of.get(id) {
        head.push_str(&format!(" re c{root}"));
    } else if threads.done.contains(id) {
        head.push_str(" resolved");
    }
    if let Some(change) = held {
        head.push_str(&format!(" in r{change}"));
    }
    head.push_str(": ");
    head
}

/// The changes the body actually prints, after nesting, neighbouring marks,
/// substitutions and selection have been rendered. Each attributed span is
/// one change; ids joined by `+` and parents named by `re` add no changes.
/// Inserted paragraph marks count inline; other structural marks count
/// where their id-line clauses print them.
pub(crate) fn collect_revisions(shown: &str) -> Vec<&'static str> {
    use crate::markdown::view_notes;

    // A change of several marks once, however many pieces print its joined
    // id (#1261); a span of one mark counts each time it prints, but for a
    // piece the view split from it around a change nested in it
    // (`{++a++}{r7 @B}{--x--}{r9 @A re r7 @B}{++b++}{r7 @B}`: one
    // insertion, as `changes` lists it).
    let mut out: Vec<(Vec<Vec<u32>>, &'static str)> = Vec::new();
    let mut add = |tags: &[&view_notes::Tag], kind: &'static str| {
        let ids: Vec<Vec<u32>> = tags.iter().map(|tag| tag.ids.clone()).collect();
        let joined = ids.iter().all(|ids| !ids.is_empty()) && ids.iter().any(|ids| ids.len() > 1);
        match out.iter_mut().find(|(other, _)| joined && *other == ids) {
            Some((_, was)) => *was = joined_kind(was, kind),
            None => out.push((ids, kind)),
        }
    };
    // The one-mark piece read last, while the changes touching it are
    // nested in it, and whether one has been: two pieces of one id that
    // touch with no nest between are two marks (a file repeating an id),
    // as `changes` lists them.
    let mut split: Option<((Vec<u32>, &'static str), bool)> = None;
    for (token, note, touches) in crate::markdown::critic::touching_notes(shown) {
        let (own, parents) = note.split_once(" re ").unwrap_or((note.as_str(), ""));
        let Some(tags) = view_notes::revision_tags(own) else {
            split = None;
            continue;
        };
        if own.split("; ").any(|tag| {
            tag.split_whitespace().next().is_none_or(|id| {
                id != "noid"
                    && crate::ids::parse_change_ids(id)
                        .map_or(true, |ids| ids.iter().any(|id| id.story != "body"))
            })
        }) {
            split = None;
            continue;
        }
        use crate::markdown::critic::Token;
        // An inline paragraph mark is an inserted one: a deleted mark
        // prints on its paragraph's id line.
        let kind = match token {
            Token::InsertEnd => "ins",
            Token::DeleteEnd => "del",
            Token::SubstituteEnd => "sub",
            _ => INSERTED_MARK,
        };
        let piece = match tags.as_slice() {
            [tag] if tag.ids.len() == 1 => Some((tag.ids.clone(), kind)),
            _ => None,
        };
        let nested_in = |ids: &[u32]| {
            parents.split(" re ").any(|parent| {
                view_notes::revision_tags(parent)
                    .is_some_and(|tags| tags.iter().any(|tag| tag.ids == ids))
            })
        };
        match &mut split {
            Some((was, nest)) if *nest && touches && piece.as_ref() == Some(was) => {
                *nest = false;
                continue;
            }
            Some(((ids, _), nest)) if touches && nested_in(ids) => *nest = true,
            _ => split = piece.map(|piece| (piece, false)),
        }
        match (kind, tags.as_slice()) {
            // A substitution of two tags is two changes, its deleted side's
            // and its inserted side's (`{r3 @A; r5+6 @B}`); a joined one
            // counts once with its other pieces (`¶{r5+6 @B}`, #1356).
            ("sub", [old, new]) => {
                add(&[old], "del");
                add(&[new], "ins");
            }
            _ => add(&tags.iter().collect::<Vec<_>>(), kind),
        }
    }
    let ranges = code_fenced(shown);
    let mut fenced = Fences::new(&ranges);
    let mut offset = 0usize;
    for line in shown.split_inclusive('\n') {
        let at = offset;
        offset += line.len();
        if fenced.holds(at) {
            continue;
        }
        let line = line.trim_end_matches(['\n', '\r']);
        if let Some(p) = view_notes::id_line(line) {
            if let Some(tag) = &p.break_ins {
                add(&[tag], INSERTED_MARK);
            }
            if let Some(tag) = &p.break_del {
                add(&[tag], DELETED_MARK);
            }
            if let Some((ins, tag)) = &p.page_break_change {
                add(&[tag], if *ins { "ins" } else { "del" });
            }
            for (inserted, tag) in &p.rev {
                add(&[tag], if *inserted { "ins" } else { "del" });
            }
        } else if let Some(t) = view_notes::table_line(line) {
            for (inserted, tag) in t.marks.values().flatten() {
                add(
                    &[tag],
                    if *inserted {
                        INSERTED_MARK
                    } else {
                        DELETED_MARK
                    },
                );
            }
            for (_, tag) in t.row_marks.values() {
                add(&[tag], "row");
            }
            for (_, tag) in t.cell_marks.values() {
                add(&[tag], "cell");
            }
        }
    }
    out.into_iter()
        .map(|(_, kind)| match kind {
            INSERTED_MARK | DELETED_MARK => "mark",
            kind => kind,
        })
        .collect()
}

/// A paragraph mark's piece of a change, by its side: alone, either counts
/// as a paragraph mark.
const INSERTED_MARK: &str = "mark+";
const DELETED_MARK: &str = "mark-";

/// What one change shows as when its pieces show as `was` and `kind`: a
/// deletion with an insertion is a substitution, and so is text with a
/// paragraph mark of the other side (#1362); a mark goes with its own
/// side's text.
fn joined_kind(was: &'static str, kind: &'static str) -> &'static str {
    match (was, kind) {
        (a, b) if a == b => a,
        ("sub", _) | (_, "sub") | ("ins", "del") | ("del", "ins") => "sub",
        (INSERTED_MARK, "del")
        | ("del", INSERTED_MARK)
        | (DELETED_MARK, "ins")
        | ("ins", DELETED_MARK) => "sub",
        (INSERTED_MARK | DELETED_MARK, other) | (other, INSERTED_MARK | DELETED_MARK) => other,
        (a, _) => a,
    }
}

/// One block of the rendered body: its lines, the paragraph span it covers
/// and, for a table, its number.
struct Block {
    text: String,
    span: Option<(usize, usize)>,
    table: Option<usize>,
    /// The `<!-- page N of M -->` line that preceded it, if any.
    page: Option<String>,
}

/// Every `pN` in a table or empty-run line, for its span.
fn numbers_after(line: &str, key: &str) -> Vec<usize> {
    let Some(at) = line.find(key) else {
        return Vec::new();
    };
    line[at + key.len()..]
        .split(|c: char| !c.is_ascii_digit() && c != 'p')
        .filter_map(|piece| piece.strip_prefix('p')?.parse().ok())
        .collect()
}

/// The lines around the branch of a block-level `mc:AlternateContent`
/// that Word shows: read-only text, no edit address.
pub(crate) const ALTERNATE_START: &str = "<!-- alternate -->";
pub(crate) const ALTERNATE_END: &str = "<!-- /alternate -->";

/// Splits a rendered body on blank lines into blocks keyed by their id
/// lines; a page marker attaches to the block after it; a block with no id
/// line (notes, footnote definitions) attaches to the block before it. An
/// `<!-- alternate -->` region is a block of its own with no span, so it
/// never rides along with the paragraph before it.
fn blocks_of(body: &str) -> Vec<Block> {
    let mut blocks: Vec<Block> = Vec::new();
    let mut page: Option<String> = None;
    let mut in_alternate = false;
    for chunk in body.split("\n\n").filter(|c| !c.trim().is_empty()) {
        // A nested list item's id line, and a page marker between nested
        // items, are indented with the item.
        let first = chunk.lines().next().unwrap_or("").trim_start();
        if in_alternate {
            in_alternate = first != ALTERNATE_END;
            if let Some(last) = blocks.last_mut() {
                last.text.push_str("\n\n");
                last.text.push_str(chunk);
            }
            continue;
        }
        if first == ALTERNATE_START {
            in_alternate = true;
            blocks.push(Block {
                text: chunk.to_string(),
                span: None,
                table: None,
                page: page.take(),
            });
            continue;
        }
        if first.starts_with("<!-- page ") {
            page = Some(first.to_string());
            continue;
        }
        let head = first.strip_prefix("<!-- ").unwrap_or("");
        if let Some(rest) = head.strip_prefix('p') {
            let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
            if let Ok(start) = digits.parse::<usize>() {
                let end = rest
                    .strip_prefix(&digits)
                    .and_then(|r| r.strip_prefix("-p"))
                    .map(|r| {
                        r.chars()
                            .take_while(char::is_ascii_digit)
                            .collect::<String>()
                    })
                    .and_then(|d| d.parse::<usize>().ok())
                    .unwrap_or(start);
                blocks.push(Block {
                    text: chunk.to_string(),
                    span: Some((start, end)),
                    table: None,
                    page: page.take(),
                });
                continue;
            }
        }
        if let Some(rest) = head.strip_prefix('t') {
            let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
            if let Ok(table) = digits.parse::<usize>() {
                let cells = numbers_after(first, "cells ");
                let span = match (cells.iter().min(), cells.iter().max()) {
                    (Some(&a), Some(&b)) => Some((a, b)),
                    _ => None,
                };
                blocks.push(Block {
                    text: chunk.to_string(),
                    span,
                    table: Some(table),
                    page: page.take(),
                });
                continue;
            }
        }
        match blocks.last_mut() {
            Some(last) => {
                last.text.push_str("\n\n");
                last.text.push_str(chunk);
            }
            None => blocks.push(Block {
                text: chunk.to_string(),
                span: None,
                table: None,
                page: page.take(),
            }),
        }
    }
    blocks
}

fn span_text(a: usize, b: usize) -> String {
    if a == b {
        format!("p{a}")
    } else {
        format!("p{a}-p{b}")
    }
}

/// `@HH` in `text` where the handle ends (the next char is not
/// alphanumeric).
fn names_handle(text: &str, handle: &str) -> bool {
    let key = format!("@{handle}");
    text.match_indices(&key).any(|(at, _)| {
        text[at + key.len()..]
            .chars()
            .next()
            .is_none_or(|c| !c.is_alphanumeric())
    })
}

/// The id line a block opens with (`<!-- p3 … -->`, `<!-- t0 … -->`), or
/// `""` for a block that opens with document text. A nested list item's
/// id line is indented with its item.
fn id_line_of(block: &str) -> &str {
    block
        .lines()
        .next()
        .map(str::trim_start)
        .filter(|line| line.starts_with("<!-- "))
        .unwrap_or("")
}

/// The number a comment word names: `c5`, or the 0.12 spelling `#c5`.
fn comment_word(word: &str) -> Option<&str> {
    let id = word.strip_prefix('#').unwrap_or(word).strip_prefix('c')?;
    (!id.is_empty() && id.bytes().all(|b| b.is_ascii_digit())).then_some(id)
}

/// Whether a block holds a mark of `handle`: on its id or table line, in the
/// attribution brace (`{r4 @AC}`) or comment (`{>>c6 @AS re c5: …<<}`; the comment text
/// after the colon is the author's words, not a tag), or as the author of a
/// hidden comment its line names. Document text never counts: the view
/// escapes any `{>>` in it.
fn has_handle(block: &str, handle: &str, comment_handles: &HashMap<String, String>) -> bool {
    let first = id_line_of(block);
    if names_handle(first, handle) {
        return true;
    }
    let hidden = first
        .split(|c: char| c.is_whitespace() || c == ',' || c == ';')
        .filter_map(comment_word)
        .any(|id| comment_handles.get(id).is_some_and(|h| h == handle));
    hidden
        || crate::markdown::critic::attributed_notes(block)
            .iter()
            .any(|(_, tag)| names_handle(tag, handle))
        || block.match_indices("{>>").any(|(at, _)| {
            let note = &block[at + 3..];
            let end = note.find("}").unwrap_or(note.len());
            let tag = note[..end].split(':').next().unwrap_or("");
            names_handle(tag, handle)
        })
}

/// Whether a block of the agent view carries a tracked change or a comment:
/// an attribution brace or comment in its text, or a mark clause on its id
/// or table line (`in c5` for a block inside a comment range whose note is
/// elsewhere).
fn is_marked(block: &str) -> bool {
    !crate::markdown::critic::attributed_notes(block).is_empty()
        || block.contains("{>>")
        || has_mark_clause(id_line_of(block))
}

/// Whether an id or table line holds a mark clause: `rev` (`rev-del`,
/// `rev-merge`), `fmt`, `break-ins` or `break-del` followed by a tag (`r3 @AC`), or `comments`
/// or `in` followed by a comment id (`c5`). A style or a list label that
/// reads `rev` is not one.
fn has_mark_clause(line: &str) -> bool {
    let words: Vec<&str> = line.split_whitespace().collect();
    words.windows(3).any(|w| {
        matches!(
            w[0],
            "rev" | "rev-del" | "rev-merge" | "fmt" | "break-ins" | "break-del"
        ) && w[2].starts_with('@')
    }) || words.windows(2).any(|w| {
        matches!(w[0], "comments" | "in")
            && comment_word(w[1].trim_end_matches([',', ';'])).is_some()
    })
}

/// The selected blocks of `body` joined back, the `range:` text, and the
/// body paragraphs the kept blocks span (`pN` numbers, ascending). A
/// `Select::Changed` author arrives resolved: `@AC` for a known handle, the
/// text as given otherwise (no block holds an unknown author's marks).
/// `notes` (the `[^1]: …` definitions) keeps those the kept blocks cite,
/// and under `Select::Changed` those holding a selected mark, named in the
/// range by their label.
pub(crate) fn select_blocks(
    body: &str,
    notes: &mut Vec<String>,
    select: &Select,
    last: Option<usize>,
    comment_handles: &HashMap<String, String>,
) -> Result<(String, String, Vec<usize>), String> {
    let blocks = blocks_of(body);
    let keep: Vec<bool>;
    let mut changed_notes: Vec<String> = Vec::new();
    let range: String = match select {
        Select::Head(n) | Select::Tail(n) if *n == 0 => {
            return Err(format!(
                "{} needs a count above 0",
                if matches!(select, Select::Head(_)) {
                    "head"
                } else {
                    "tail"
                }
            ));
        }
        Select::Head(n) => {
            keep = (0..blocks.len()).map(|i| i < *n).collect();
            let spans: Vec<(usize, usize)> =
                blocks.iter().take(*n).filter_map(|b| b.span).collect();
            format!(
                "head {n} ({})",
                span_text(
                    spans.first().map_or(0, |s| s.0),
                    spans.last().map_or(0, |s| s.1)
                )
            )
        }
        Select::Tail(n) => {
            let skip = blocks.len().saturating_sub(*n);
            keep = (0..blocks.len()).map(|i| i >= skip).collect();
            let spans: Vec<(usize, usize)> =
                blocks.iter().skip(skip).filter_map(|b| b.span).collect();
            format!(
                "tail {n} ({})",
                span_text(
                    spans.first().map_or(0, |s| s.0),
                    spans.last().map_or(0, |s| s.1)
                )
            )
        }
        Select::Changed { by } => {
            let handle = by.as_deref().map(|by| by.strip_prefix('@'));
            let selected = |text: &str| {
                is_marked(text)
                    && match handle {
                        None => true,
                        Some(Some(handle)) => has_handle(text, handle, comment_handles),
                        Some(None) => false,
                    }
            };
            keep = blocks.iter().map(|block| selected(&block.text)).collect();
            for note in notes.iter().filter(|note| selected(note)) {
                if let Some(label) = note_label(note) {
                    changed_notes.push(label.to_string());
                }
            }
            let names: Vec<String> = blocks
                .iter()
                .zip(&keep)
                .filter(|(_, keep)| **keep)
                .filter_map(|(block, _)| match (block.table, block.span) {
                    (Some(t), _) => Some(format!("t{t}")),
                    (None, Some((a, z))) => Some(span_text(a, z)),
                    _ => None,
                })
                .chain(changed_notes.iter().map(|label| format!("[^{label}]")))
                .collect();
            format!(
                "changed{} ({})",
                by.as_deref()
                    .map_or(String::new(), |by| format!(" by {by}")),
                if names.is_empty() {
                    "none".to_string()
                } else {
                    names.join(", ")
                }
            )
        }
        Select::Picks(picks) => {
            let mut wanted: Vec<(usize, usize)> = Vec::new();
            let mut tables: Vec<usize> = Vec::new();
            let mut names: Vec<(usize, String)> = Vec::new();
            for pick in picks {
                match pick {
                    Pick::Paragraphs { from, to } => {
                        let Some(last) = last else {
                            return Err("the body has no paragraphs".to_string());
                        };
                        let to = to.unwrap_or(last);
                        for n in [*from, to] {
                            if n > last {
                                return Err(format!("p{n} is past the last paragraph p{last}"));
                            }
                        }
                        wanted.push((*from, to));
                        names.push((*from, span_text(*from, to)));
                    }
                    Pick::Table(t) => {
                        let Some(block) = blocks.iter().find(|b| b.table == Some(*t)) else {
                            return Err(format!("t{t} is not a table of this document"));
                        };
                        tables.push(*t);
                        names.push((block.span.map_or(0, |s| s.0), format!("t{t}")));
                    }
                }
            }
            // Accepting or rejecting can join a paragraph into the one
            // before it, which then holds its index.
            for &(from, to) in &wanted {
                let found = blocks
                    .iter()
                    .any(|b| b.span.is_some_and(|(a, z)| a <= to && from <= z));
                if !found
                    && let Some((a, _)) = blocks
                        .iter()
                        .filter_map(|b| b.span)
                        .filter(|&(a, _)| a < from)
                        .max_by_key(|&(a, _)| a)
                {
                    return Err(format!(
                        "p{from} is part of p{a} in this view (accepting or rejecting joined them); pick p{a}, or read the tracked view"
                    ));
                }
            }
            keep = blocks
                .iter()
                .map(|b| {
                    b.table.is_some_and(|t| tables.contains(&t))
                        || b.span.is_some_and(|(a, z)| {
                            wanted.iter().any(|&(from, to)| a <= to && from <= z)
                        })
                })
                .collect();
            names.sort_by_key(|(at, _)| *at);
            names
                .into_iter()
                .map(|(_, name)| name)
                .collect::<Vec<_>>()
                .join(", ")
        }
    };
    let mut out = String::new();
    let mut page_due: Option<&str> = None;
    let mut page_written: Option<&str> = None;
    for (block, keep) in blocks.iter().zip(&keep) {
        if let Some(page) = &block.page {
            page_due = Some(page.as_str());
        }
        if !keep {
            continue;
        }
        if let Some(page) = page_due.take()
            && page_written != Some(page)
        {
            out.push_str(page);
            out.push_str("\n\n");
            page_written = Some(page);
        }
        out.push_str(&block.text);
        out.push_str("\n\n");
    }
    // `convert` ends the Markdown with its newline.
    out.truncate(out.trim_end_matches('\n').len());
    notes.retain(|note| {
        note_label(note).is_some_and(|label| {
            changed_notes.iter().any(|l| l == label) || out.contains(&format!("[^{label}]"))
        })
    });
    let mut paragraphs: Vec<usize> = blocks
        .iter()
        .zip(&keep)
        .filter(|(_, keep)| **keep)
        .filter_map(|(block, _)| block.span)
        .flat_map(|(a, z)| a..=z)
        .collect();
    paragraphs.sort_unstable();
    paragraphs.dedup();
    Ok((out, range, paragraphs))
}

/// The label of a note definition, `1` for `[^1]: …`. A note inserted or
/// deleted with its reference carries its label inside the mark
/// (`{++[^1]: …++}`).
pub(crate) fn note_label(note: &str) -> Option<&str> {
    let note = ["{++", "{--"]
        .into_iter()
        .find_map(|mark| note.strip_prefix(mark))
        .unwrap_or(note);
    note.strip_prefix("[^")?
        .split_once("]:")
        .map(|(label, _)| label)
}

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

    /// Review 4504980747, 4504980748: a parent that prints as several
    /// tags (two marks, or a spelled id) stays inside its one `fmt` entry,
    /// so the reader finds only the formatting change itself.
    #[test]
    fn a_parent_printing_several_tags_stays_in_one_fmt_entry() {
        let line = format_nested_tags(&[
            ("95@TL".to_string(), Some("96@RC|97@SD".to_string())),
            ("98@TL".to_string(), None),
        ]);
        let tags = crate::markdown::view_notes::formatting_tags(&line).expect("the clause reads");
        let ids: Vec<Vec<u32>> = tags.iter().map(|tag| tag.ids.clone()).collect();
        assert_eq!(ids, [vec![95], vec![98]], "{line}");
        assert!(tags.iter().all(|tag| tag.handle == "TL"), "{line}");
    }

    /// empryo review of #476: a nested item's indented id line opens its
    /// own block, and an indented page marker still attaches to the block
    /// after it, so `-p`, `--head`, `--tail` and `--changed` see the item.
    #[test]
    fn an_indented_id_line_opens_its_own_block() {
        let body = "<!-- p0 ListParagraph num \"1.\" -->\n1. One.\n\n\
                    \x20  <!-- page 2 of 2 -->\n\n\
                    \x20  <!-- p1 bullet -->\n   - Sub.\n\n<!-- p2 -->\nTwo.";
        let blocks = blocks_of(body);
        let spans: Vec<_> = blocks.iter().map(|block| block.span).collect();
        assert_eq!(spans, [Some((0, 0)), Some((1, 1)), Some((2, 2))]);
        assert_eq!(blocks[1].page.as_deref(), Some("<!-- page 2 of 2 -->"));
    }

    /// A nested list item's id line is indented with its item; its mark
    /// clause and its handle still select the block.
    #[test]
    fn an_indented_id_line_still_marks_its_block() {
        let block = "   <!-- p5 ListParagraph bullet, break-ins r3 @AS -->\n   - Sub.";
        assert!(is_marked(block));
        assert!(has_handle(block, "AS", &HashMap::new()));
        assert!(!has_handle(block, "AC", &HashMap::new()));
    }

    /// pi review of Task 5 F4: a clause key is a mark only with its tag or
    /// comment id after it, so a style or list label reading `rev` keeps no
    /// block under `--changed`.
    #[test]
    fn mark_clauses_need_a_tag_or_a_comment_id() {
        for marked in [
            "<!-- p0 rev r1 @AC -->",
            "<!-- p3 Quote, fmt r5 @AC; r6 @AC -->",
            "<!-- p5 comments c5 c6 -->",
            "<!-- p1 comments #c5 -->",
            "<!-- p2 in c9 -->",
            "<!-- p4 empty, break-ins r3 @AC -->",
            "<!-- t0 2x2, cells p0-p3 by row, fmt r12 @AS in t0.row1 -->",
            "<!-- t0 1x2, cells p0-p1 by row, comments c9 in p1 -->",
        ] {
            assert!(has_mark_clause(marked), "{marked}");
        }
        for plain in [
            "<!-- p0 rev -->",
            "<!-- p0 fmt, justify -->",
            "<!-- p0 comments -->",
            "<!-- p0 num \"See rev 3\" -->",
            "<!-- p0 in -->",
            "<!-- t0 1x1, cells p0-p0 by row -->",
        ] {
            assert!(!has_mark_clause(plain), "{plain}");
        }
    }

    /// #392: a note inserted or deleted with its reference
    /// carries its label inside the mark.
    #[test]
    fn note_label_reads_through_the_mark_around_an_inserted_or_deleted_note() {
        assert_eq!(note_label("[^1]: text"), Some("1"));
        assert_eq!(note_label("{++[^2]: added++}{r5 @AC}"), Some("2"));
        assert_eq!(note_label("{--[^3]: gone--}{r6 @AC}"), Some("3"));
        assert_eq!(note_label("text [^4]: not a definition"), None);
    }

    #[test]
    fn escape_markdown_escapes_only_what_commonmark_acts_on() {
        for (text, escaped) in [
            ("a_b snake_case", "a_b snake_case"),
            ("_x_", "\\_x\\_"),
            ("x < y <br> </u> <!--", "x < y \\<br> \\</u> \\<!--"),
            ("2*3 `t` \\", "2\\*3 \\`t\\` \\\\"),
            ("~~a~~ ~x == y = z", "\\~\\~a\\~\\~ \\~x \\=\\= y = z"),
            ("a ^b^ c ~d~ e", "a \\^b\\^ c \\~d\\~ e"),
            ("H~2~O 2^10 x^2^ a ~ b ^", "H~2~O 2^10 x^2\\^ a ~ b ^"),
            ("[^1] [x]", "\\[^1] [x]"),
            // An entity reference would decode on the way back; a name
            // HTML does not define (`&foo;`, `AT&T;`) stays as it is.
            (
                "&copy; &#35; &#x23; AT&T & co &; &foo; AT&T; &amp;",
                "\\&copy; \\&#35; \\&#x23; AT&T & co &; &foo; AT&T; \\&amp;",
            ),
            // A `]` right before `(`, `[` or `:` would close a link, an
            // image, a reference or a reference definition.
            (
                "[a](b) ![i](p.png) [r]: /u [c][d]",
                "[a\\](b) ![i\\](p.png) [r\\]: /u [c\\][d]",
            ),
            ("[sic] (a) x]", "[sic] (a) x]"),
        ] {
            assert_eq!(escape_markdown(text), escaped, "{text}");
        }
    }

    #[test]
    fn escape_closing_hashes_escapes_a_closing_sequence_only() {
        for (text, escaped) in [
            ("C #", "C \\#"),
            ("#", "\\#"),
            ("C ##", "C \\##"),
            ("C#", "C#"),
            ("C# x", "C# x"),
            ("plain", "plain"),
        ] {
            assert_eq!(escape_closing_hashes(text), escaped, "{text}");
        }
    }

    #[test]
    fn escape_block_start_escapes_block_openers_only() {
        for (line, escaped) in [
            ("# x", "\\# x"),
            ("###### x", "\\###### x"),
            ("####### x", "####### x"),
            ("#tag", "#tag"),
            ("> q", "\\> q"),
            ("| a |", "\\| a |"),
            ("- x", "\\- x"),
            ("+ x", "\\+ x"),
            ("-x", "-x"),
            ("---", "\\---"),
            ("-", "\\-"),
            ("1. one", "1\\. one"),
            ("10) ten", "10\\) ten"),
            ("1.5 litres", "1.5 litres"),
            ("1.", "1\\."),
            ("plain", "plain"),
            // CommonMark lets a block opener sit after up to three spaces.
            ("   =", "   \\="),
            ("  # Fees", "  \\# Fees"),
            (" > q", " \\> q"),
            ("   - x", "   \\- x"),
            ("  1. one", "  1\\. one"),
            // Four spaces (or a tab) inside a paragraph are plain text.
            ("    # x", "    # x"),
            ("\t- x", "\t- x"),
        ] {
            assert_eq!(escape_block_start(line), escaped, "{line}");
        }
        assert_eq!(escape_line_starts("a  \n# b"), "a  \n\\# b");
    }

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

    #[test]
    fn own_size_reads_the_branch_word_shows() {
        let paragraph = |requires: &str| {
            parse_xml(format!(r#"<w:p {W} xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:zz="urn:example:future"><w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:t>a</w:t></w:r><mc:AlternateContent><mc:Choice Requires="{requires}"><w:r><w:rPr><w:sz w:val="40"/></w:rPr><w:t>b</w:t></w:r></mc:Choice><mc:Fallback><w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:t>b</w:t></w:r></mc:Fallback></mc:AlternateContent></w:p>"#).as_bytes()).unwrap()
        };
        let hidden = HashSet::new();
        // Word does not know `zz`: it shows the Fallback, so every run is 10pt.
        assert_eq!(own_size(&paragraph("zz"), &hidden), Some(20));
        // Word knows `wps`: it shows the Choice's 20pt run beside a 10pt one.
        assert_eq!(own_size(&paragraph("wps"), &hidden), None);
    }

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

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

    fn indices(e: &Element, out: &mut Vec<String>) {
        if e.is("p") {
            out.push(e.attr(INDEX).unwrap_or("-").to_string());
        }
        for child in e.elements() {
            indices(child, out);
        }
    }

    #[test]
    fn stamps_paragraphs_in_document_order_cells_included_text_boxes_excluded() {
        let mut body = body(
            r#"<w:p/><w:tbl><w:tr><w:tc><w:p/><w:p/></w:tc></w:tr></w:tbl><w:p><w:r><w:pict><w:txbxContent><w:p/></w:txbxContent></w:pict></w:r></w:p><w:sdt><w:sdtContent><w:p/></w:sdtContent></w:sdt>"#,
        );
        let (paragraphs, tables) = stamp(&mut body, &Handles::default());
        assert_eq!((paragraphs, tables), (5, 1));
        let mut seen = Vec::new();
        indices(&body, &mut seen);
        assert_eq!(seen, ["0", "1", "2", "3", "-", "4"]);
        assert_eq!(body.child("tbl").unwrap().attr(TABLE), Some("0"));
    }

    /// A strict `w:ind` writes universal measures (`72pt`, `1in`) where
    /// Transitional writes twips; the clause prints the same inches.
    #[test]
    fn a_universal_measure_indent_on_the_id_line_reads_as_twips() {
        let p = body(
            r#"<w:p><w:pPr><w:ind w:start="72pt" w:end="36pt" w:firstLine="18pt"/></w:pPr><w:r><w:t>x</w:t></w:r></w:p>"#,
        );
        let p = p.child("p").unwrap();
        let facts = LineFacts {
            index: 0,
            style: None,
            outline: None,
            heading: None,
            marker: None,
            level: 0,
            page_break: false,
            resolved: false,
            comments: &[],
            spans: &[],
            empty: false,
            mark_inherits: false,
            unshown: &[],
            size: None,
            holds: &[],
        };
        let line = id_line(p, &facts, &Handles::default());
        assert_eq!(line, "<!-- p0 first-line 0.25in, left 1in, right 0.5in -->");
    }

    /// A parsable-but-absurd measure is not a measure the schema spells
    /// (`1e300pt`, `nanpt`): the clause drops, as it did before the Strict
    /// reader, instead of printing 250-digit inches or `NaNin`
    /// (#531 review defect 5).
    #[test]
    fn an_absurd_measure_indent_drops_its_clause() {
        for start in ["1e300pt", "nanpt", "999999999999999999999999999in"] {
            let p = body(&format!(
                r#"<w:p><w:pPr><w:ind w:start="{start}" w:end="36pt"/></w:pPr><w:r><w:t>x</w:t></w:r></w:p>"#
            ));
            let p = p.child("p").unwrap();
            let facts = LineFacts {
                index: 0,
                style: None,
                outline: None,
                heading: None,
                marker: None,
                level: 0,
                page_break: false,
                resolved: false,
                comments: &[],
                spans: &[],
                empty: false,
                mark_inherits: false,
                unshown: &[],
                size: None,
                holds: &[],
            };
            let line = id_line(p, &facts, &Handles::default());
            assert_eq!(line, "<!-- p0 right 0.5in -->", "{start}: {line}");
        }
    }

    #[test]
    fn nested_tables_are_not_numbered() {
        let mut body = body(
            r#"<w:tbl><w:tr><w:tc><w:tbl><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl></w:tc></w:tr></w:tbl><w:tbl><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl>"#,
        );
        let (_, tables) = stamp(&mut body, &Handles::default());
        assert_eq!(tables, 2);
        // `find_all` stops at a match; nested tables need a full walk.
        fn all_tables<'a>(e: &'a Element, out: &mut Vec<&'a Element>) {
            if e.is("tbl") {
                out.push(e);
            }
            for child in e.elements() {
                all_tables(child, out);
            }
        }
        let mut all = Vec::new();
        all_tables(&body, &mut all);
        let numbered: Vec<Option<&str>> = all.iter().map(|t| t.attr(TABLE)).collect();
        assert_eq!(numbered, [Some("0"), None, Some("1")]);
    }

    /// A cell paragraph's mark names an insertion and a deletion at once
    /// (`w:pPr/w:rPr` holds both `w:ins` and `w:del`), and the header
    /// counts each mark the change list names.
    #[test]
    fn a_cell_paragraph_mark_named_twice_counts_twice() {
        let line = "<!-- t0 1x1, cells p1-p1 by row, break-ins r3 @AC in p1, \
                    break-del r4 @AC in p1 -->";
        assert_eq!(collect_revisions(line), ["mark", "mark"]);
    }

    /// A code fence keeps a line that looks like an id line as text, so the
    /// fallback count and a selection skip it. A cell paragraph that names
    /// an insertion and a deletion still counts as two marks.
    #[test]
    fn a_fenced_id_line_does_not_count_and_both_cell_marks_do() {
        let fenced = "```\n<!-- p3 rev r4 @AC -->\n```\n";
        let fallback = with_logical(None, || shown_changes(fenced, true));
        assert!(
            fallback.is_empty(),
            "fenced id line counted in the fallback: {fallback:?}"
        );
        let selected = with_logical(Some(vec![change("r4")]), || shown_changes(fenced, false));
        assert!(
            selected.is_empty(),
            "fenced id line counted in a selection: {selected:?}"
        );
        let marks = "<!-- t0 1x1, cells p5-p5 by row, break-ins r1 @A in p5, \
                     break-del r2 @A in p5 -->";
        assert_eq!(collect_revisions(marks), ["mark", "mark"]);
        assert_eq!(
            with_logical(None, || shown_changes("<!-- p3 rev r4 @AC -->", true)),
            ["ins"]
        );
        assert_eq!(
            with_logical(Some(vec![change("r9")]), || shown_changes(fenced, true)),
            ["ins"]
        );
    }

    /// Four spaces before backticks make indented code, not a fence (as in
    /// CommonMark and the reader's own literal scan): the id line after it
    /// still counts, and a line of three spaces still opens one.
    #[test]
    fn an_indented_backtick_line_is_no_fence() {
        let indented = "    ```\n<!-- p3 rev r4 @AC -->\n";
        assert_eq!(
            with_logical(None, || shown_changes(indented, true)),
            ["ins"]
        );
        assert!(code_fenced(indented).is_empty());
        let fenced = "   ```\n<!-- p3 rev r4 @AC -->\n   ```\n";
        assert_eq!(code_fenced(fenced).len(), 1);
        let inline = "```a```\n<!-- p3 rev r4 @AC -->\n";
        assert!(code_fenced(inline).is_empty());
    }

    /// Positions asked in order walk the ranges once and still answer as a
    /// scan of every range would.
    #[test]
    fn fences_answer_positions_in_order() {
        let text = "a\n```\nb\n```\nc\n~~~\nd\n~~~\ne\n";
        let ranges = code_fenced(text);
        let mut fences = Fences::new(&ranges);
        for at in 0..text.len() {
            assert_eq!(
                fences.holds(at),
                ranges.iter().any(|range| range.contains(&at)),
                "{at}"
            );
        }
    }

    fn change(id: &str) -> crate::changes::Change {
        crate::changes::Change {
            id: id.to_string(),
            r#ref: id.to_string(),
            kind: crate::changes::ChangeKind::Insertion,
            target: "text",
            author: None,
            date: None,
            text: String::new(),
            paragraph: None,
            move_name: None,
            move_side: None,
            inside: None,
            holds_comments: Vec::new(),
            members: Vec::new(),
        }
    }

    /// A mark with no `w:id` prints `noid`, so one author's inserted and
    /// deleted unshown marks are the same tag: each keeps the kind its own
    /// clause gave it, as two changes the header lists as one of each.
    #[test]
    fn anonymous_unshown_marks_keep_the_kind_their_clause_gave_them() {
        let body = "<!-- p1 rev noid @AC, rev-del noid @AC -->";
        assert_eq!(collect_revisions(body), ["ins", "del"]);
    }

    #[test]
    fn review_3_revision_tags_keep_unequal_source_dates_separate() {
        for new_date in ["", r#" w:date="2026-10-02T10:00:00Z""#] {
            let d = doc(&format!(
                r#"<w:p><w:del w:id="1" w:author="Alice" w:date="2026-10-01T09:00:00Z"><w:r><w:delText>old</w:delText></w:r></w:del><w:ins w:id="2" w:author="Alice"{new_date}><w:r><w:t>new</w:t></w:r></w:ins></w:p>"#
            ));
            let handles = handles(&d, &[], None, None);
            let p = d.child("body").unwrap().child("p").unwrap();
            let tags = revision_tags(p, &handles)
                .into_iter()
                .map(|tag| format!("{}:{}", tag.kind, tag.tag))
                .collect::<Vec<_>>();
            assert_eq!(tags, ["del:1@A", "ins:2@A"]);
        }
    }

    #[test]
    fn revision_tags_keep_distinct_ids_and_pair_a_deletion_with_the_insertion_after_it() {
        // Distinct adjacent ids stay separate. A deletion followed by an
        // insertion of one change forms a substitution (#1363): `changes`
        // groups the touching deletion 4 and insertion 5.
        let d = doc(
            r#"<w:p><w:ins w:id="0" w:author="Ann Counsel"><w:r><w:t>x</w:t></w:r></w:ins><w:r><w:t> t </w:t></w:r><w:ins w:id="2" w:author="Ann Counsel"><w:r><w:t>b</w:t></w:r></w:ins><w:bookmarkStart w:id="9" w:name="_b"/><w:del w:id="1" w:author="Ann Counsel"><w:r><w:delText>a</w:delText></w:r></w:del><w:r><w:t> u </w:t></w:r><w:ins w:id="7" w:author="Ann Counsel"><w:r><w:t>d</w:t></w:r></w:ins><w:ins w:id="8" w:author="Ann Counsel"><w:r><w:t>e</w:t></w:r></w:ins><w:del w:id="3" w:author="Ann Counsel"><w:r><w:delText>c</w:delText></w:r></w:del><w:r><w:t> v </w:t></w:r><w:del w:id="4" w:author="Ann Counsel"><w:r><w:delText>f</w:delText></w:r></w:del><w:ins w:id="5" w:author="Ann Counsel"><w:r><w:t>g</w:t></w:r></w:ins></w:p>"#,
        );
        let handles = handles(&d, &[], None, None);
        let p = d.child("body").unwrap().child("p").unwrap();
        let tags = |wholes: Wholes| -> Vec<String> {
            with_wholes(wholes, || {
                revision_tags(p, &handles)
                    .into_iter()
                    .map(|t| format!("{}:{}", t.kind, t.tag))
                    .collect()
            })
        };
        let one = ["4", "5"].map(String::from).to_vec();
        let pair = Wholes::from([("r4".to_string(), one.clone()), ("r5".to_string(), one)]);
        assert_eq!(
            tags(pair),
            [
                "ins:0@AC",
                "ins:2@AC",
                "del:1@AC",
                "ins:7@AC",
                "ins:8@AC",
                "del:3@AC",
                "sub:4+5@AC"
            ]
        );
        // Two changes, as `changes` would list them with content between.
        assert_eq!(
            &tags(Wholes::new())[5..],
            ["del:3@AC", "del:4@AC", "ins:5@AC"]
        );
    }

    #[test]
    fn revision_tags_pass_over_empty_marks_wherever_they_sit() {
        // An empty mark shows nothing: the id line's `rev` clause names it,
        // and it neither joins nor splits the changes around it.
        let d = doc(
            r#"<w:p><w:r><w:t>Empty </w:t></w:r><w:ins w:id="8" w:author="Ann Counsel"><w:r><w:t>a</w:t></w:r></w:ins><w:ins w:id="9" w:author="Ann Counsel"/><w:r><w:t> end.</w:t></w:r><w:ins w:id="10" w:author="Ann Counsel"><w:r><w:rPr><w:b/></w:rPr></w:r></w:ins><w:del w:id="11" w:author="Ann Counsel"><w:r><w:delText>b</w:delText></w:r></w:del><w:ins w:id="12" w:author="Ann Counsel"/><w:del w:id="13" w:author="Ann Counsel"><w:r><w:delText>c</w:delText></w:r></w:del></w:p>"#,
        );
        let handles = handles(&d, &[], None, None);
        let p = d.child("body").unwrap().child("p").unwrap();
        let tags: Vec<String> = revision_tags(p, &handles)
            .into_iter()
            .map(|t| format!("{}:{}", t.kind, t.tag))
            .collect();
        assert_eq!(tags, ["ins:8@AC", "del:11@AC", "del:13@AC"]);
    }

    #[test]
    fn inches_read_back_to_the_same_twips() {
        // 2cm margins are 1134 twips: `0.79in` came back as 1138.
        assert_eq!(inches(1134.0), "0.7875in");
        assert_eq!(inches(1417.0), "0.984in");
        assert_eq!(inches(720.0), "0.5in");
        assert_eq!(inches(1440.0), "1in");
        for twips in 0..=31_680u32 {
            let text = inches(f64::from(twips));
            let back: f64 = text.strip_suffix("in").unwrap().parse().unwrap();
            assert_eq!((back * 1440.0).round(), f64::from(twips), "{text}");
        }
    }

    #[test]
    fn a_shown_range_or_bookmark_between_marks_keeps_them_apart() {
        // The text prints `{++a++}{=={--b--}==}{>>c0<<}`: two changes, not
        // a substitution, and `{++a++}<a id="m"></a>{++b++}` two insertions.
        // A range or bookmark the view does not print joins as before.
        let d = doc(
            r#"<w:p><w:ins w:id="1" w:author="Ann Counsel"><w:r><w:t>a</w:t></w:r></w:ins><w:commentRangeStart w:id="0"/><w:del w:id="2" w:author="Ann Counsel"><w:r><w:delText>b</w:delText></w:r></w:del><w:commentRangeEnd w:id="0"/><w:r><w:t> </w:t></w:r><w:ins w:id="3" w:author="Ann Counsel"><w:r><w:t>c</w:t></w:r></w:ins><w:bookmarkStart w:id="0" w:name="m"/><w:ins w:id="4" w:author="Ann Counsel"><w:r><w:t>d</w:t></w:r></w:ins><w:r><w:t> </w:t></w:r><w:ins w:id="5" w:author="Ann Counsel"><w:r><w:t>e</w:t></w:r></w:ins><w:commentRangeStart w:id="7"/><w:bookmarkStart w:id="1" w:name="n"/><w:del w:id="6" w:author="Ann Counsel"><w:r><w:delText>f</w:delText></w:r></w:del></w:p>"#,
        );
        let mut handles = handles(&d, &[], None, None);
        let p = d.child("body").unwrap().child("p").unwrap();
        let tags = |handles: &Handles| -> Vec<String> {
            revision_tags(p, handles)
                .into_iter()
                .map(|t| format!("{}:{}", t.kind, t.tag))
                .collect()
        };
        assert_eq!(
            tags(&handles),
            [
                "ins:1@AC", "del:2@AC", "ins:3@AC", "ins:4@AC", "ins:5@AC", "del:6@AC"
            ]
        );
        handles.shown_ranges.insert("0".into());
        handles.shown_bookmarks.insert("m".into());
        assert_eq!(
            tags(&handles),
            [
                "ins:1@AC", "del:2@AC", "ins:3@AC", "ins:4@AC", "ins:5@AC", "del:6@AC"
            ]
        );
    }

    #[test]
    fn tags_always_carry_the_handle_and_format_for_printing() {
        let d = doc(
            r#"<w:p><w:ins w:id="0" w:author="Ann Counsel"><w:r><w:t>a</w:t></w:r></w:ins><w:r><w:t> </w:t></w:r><w:del w:id="1" w:author="John Doe"><w:r><w:delText>b</w:delText></w:r></w:del></w:p>"#,
        );
        let handles = handles(&d, &[], None, None);
        assert_eq!(handles.by_author["Ann Counsel"], "AC");
        assert_eq!(handles.by_author["John Doe"], "JD");
        let p = d.child("body").unwrap().child("p").unwrap();
        let tags: Vec<String> = revision_tags(p, &handles)
            .into_iter()
            .map(|t| t.tag)
            .collect();
        assert_eq!(tags, ["0@AC", "1@JD"]);
        assert_eq!(join_tags(&["1@AC".into(), "2@AC".into()]), "1+2@AC");
        assert_eq!(join_tags(&["1@AC".into(), "2@JD".into()]), "1@AC|2@JD");
        assert_eq!(join_tags(&["1+2@AC".into(), "3@AC".into()]), "1+2+3@AC");
        assert_eq!(format_tag("0@AC"), "r0 @AC");
        assert_eq!(format_tag("1+2@AC"), "r1+2 @AC");
        assert_eq!(format_tag("1@AC|2@JD"), "r1 @AC; r2 @JD");
        assert_eq!(format_tag("footnotes#1+2@AC"), "footnotes.r1+2 @AC");
        assert_eq!(format_tag("1@AC|header1#2@JD"), "r1 @AC; header1.r2 @JD");
        // An id the short form cannot spell prints its long id.
        assert_eq!(format_tag("007@AC"), "body:rev:007 @AC");
        assert_eq!(
            format_tag("Header_1#4+5@AC"),
            "Header_1:rev:4 @AC; Header_1:rev:5 @AC"
        );
        assert_eq!(format_tag("?@??"), "noid @??");
        assert_eq!(format_tag("footnotes#?@AC"), "footnotes.noid @AC");
        assert!(crate::ids::parse_change_ids("noid").is_err());
        assert_eq!(handle_of("1+2@AC"), Some("AC"));
        assert_eq!(handle_of("header1#1@AC"), Some("AC"));
        assert_eq!(
            join_tags(&["header1#1@AC".into(), "header1#2@AC".into()]),
            "header1#1+2@AC"
        );
        assert_eq!(
            join_tags(&["1@AC".into(), "header1#2@AC".into()]),
            "1@AC|header1#2@AC"
        );
    }

    #[test]
    fn handles_prefer_comment_initials_disambiguate_collisions_and_collect_timestamps() {
        let d = doc(
            r#"<w:p><w:ins w:id="0" w:author="Ann Counsel" w:date="2026-10-01T09:00:00Z"/><w:ins w:id="1" w:author="Al Cooper" w:date="2026-10-02T08:00:00Z"/><w:ins w:id="2" w:author="Al Cooper" w:date="2026-10-03T08:30:00Z"/></w:p>"#,
        );
        let comments = parse_xml(format!(r#"<w:comments {W}><w:comment w:id="5" w:author="Arthur Souza Rodrigues" w:initials="AS" w:date="2026-10-09T16:13:00Z"/><w:comment w:id="6" w:author="Ann Counsel" w:date="2026-10-01T09:00:00Z"/></w:comments>"#).as_bytes()).unwrap();
        let handles = handles(&d, &[], Some(&comments), None);
        assert_eq!(
            handles.order,
            ["Ann Counsel", "Al Cooper", "Arthur Souza Rodrigues"]
        );
        assert_eq!(handles.by_author["Ann Counsel"], "AC");
        assert_eq!(handles.by_author["Al Cooper"], "AC2");
        assert_eq!(handles.by_author["Arthur Souza Rodrigues"], "AS");
        assert_eq!(
            handles.unique_date("Ann Counsel"),
            Some("2026-10-01T09:00:00Z")
        );
        assert_eq!(handles.unique_date("Al Cooper"), None);
        assert_eq!(
            handles.latest_date("Al Cooper"),
            Some("2026-10-03T08:30:00Z")
        );
        assert_eq!(handles.unique_date("Nobody"), None);
        assert_eq!(handles.latest_date("Ann Counsel"), None);
        assert_eq!(handles.latest_date("Nobody"), None);
    }

    #[test]
    fn latest_date_orders_positive_offsets_by_instant() {
        let handles = Handles {
            dates: HashMap::from([(
                "Ann Lee".into(),
                BTreeSet::from([
                    "2026-03-04T05:00:00+02:00".into(),
                    "2026-03-04T04:00:00Z".into(),
                ]),
            )]),
            ..Handles::default()
        };
        assert_eq!(handles.latest_date("Ann Lee"), Some("2026-03-04T04:00:00Z"));
    }

    #[test]
    fn latest_date_orders_negative_offsets_by_instant() {
        let handles = Handles {
            dates: HashMap::from([(
                "Ann Lee".into(),
                BTreeSet::from([
                    "2026-03-04T03:00:00-02:00".into(),
                    "2026-03-04T04:00:00Z".into(),
                ]),
            )]),
            ..Handles::default()
        };
        assert_eq!(
            handles.latest_date("Ann Lee"),
            Some("2026-03-04T03:00:00-02:00")
        );
    }

    #[test]
    fn latest_date_compares_fractions_across_days_and_missing_offsets() {
        for (earlier, later) in [
            ("2026-01-01T00:30:00+01:00", "2025-12-31T23:45:00Z"),
            ("2024-03-01T00:30:00+01:00", "2024-02-29T23:45:00Z"),
            ("2026-03-04T05:00:00.100+02:00", "2026-03-04T03:00:00.11Z"),
            ("2026-03-04T05:00:00+02:00", "2026-03-04T04:00:00"),
        ] {
            let handles = Handles {
                dates: HashMap::from([(
                    "Ann Lee".into(),
                    BTreeSet::from([earlier.into(), later.into()]),
                )]),
                ..Handles::default()
            };
            assert_eq!(handles.latest_date("Ann Lee"), Some(later), "{earlier}");
        }
    }

    #[test]
    fn range_markers_do_not_break_a_move_or_a_substitution() {
        let d = doc(
            r#"<w:p><w:moveToRangeStart w:id="21" w:name="m"/><w:moveTo w:id="2" w:author="Ann Counsel"><w:r><w:t>b</w:t></w:r></w:moveTo><w:moveToRangeEnd w:id="21"/><w:permStart w:id="30"/><w:moveFromRangeStart w:id="20" w:name="m"/><w:moveFrom w:id="1" w:author="Ann Counsel"><w:r><w:delText>a</w:delText></w:r></w:moveFrom><w:moveFromRangeEnd w:id="20"/><w:permEnd w:id="30"/></w:p>"#,
        );
        let handles = handles(&d, &[], None, None);
        let p = d.child("body").unwrap().child("p").unwrap();
        let tags: Vec<String> = revision_tags(p, &handles)
            .into_iter()
            .map(|t| format!("{}:{}", t.kind, t.tag))
            .collect();
        assert_eq!(tags, ["ins:2@AC", "del:1@AC"]);
    }

    #[test]
    fn joining_no_tags_is_empty() {
        assert_eq!(join_tags(&[]), "");
    }

    #[test]
    fn format_changes_list_in_document_order() {
        let d = doc(
            r#"<w:p><w:pPr><w:pPrChange w:id="1" w:author="Ann Counsel"><w:pPr/></w:pPrChange></w:pPr><w:r><w:rPr><w:b/><w:rPrChange w:id="2" w:author="Ann Counsel"><w:rPr/></w:rPrChange></w:rPr><w:t>x</w:t></w:r></w:p>"#,
        );
        let handles = handles(&d, &[], None, None);
        let p = d.child("body").unwrap().child("p").unwrap();
        assert_eq!(format_change_tags(p, &handles), ["1@AC", "2@AC"]);
    }

    #[test]
    fn a_stamp_cannot_be_forged_by_the_file() {
        let mut body = body(r#"<w:p w:jubarteIndex="99"/>"#);
        stamp(&mut body, &Handles::default());
        assert_eq!(body.child("p").unwrap().attr(INDEX), Some("0"));
    }

    #[test]
    fn index_runs_collapse_consecutive_indices() {
        assert_eq!(runs(&[3, 4, 5, 9, 11, 12]), [(3, 5), (9, 9), (11, 12)]);
        assert!(runs(&[]).is_empty());
    }

    /// Whole line counts keep their zeros: `0` is no lines, `1000` is ten
    /// (#2130 review).
    #[test]
    fn line_counts_keep_the_zeros_of_whole_counts() {
        for (raw, want) in [
            ("0", "0"),
            ("100", "1"),
            ("1000", "10"),
            ("2000", "20"),
            ("150", "1.5"),
            ("1050", "10.5"),
            ("125", "1.25"),
            ("10", "0.1"),
        ] {
            assert_eq!(line_count(raw).as_deref(), Some(want), "{raw}");
        }
    }
}