jubarte-doc 0.20.0

The document operations of the jubarte engine above compare: changes, comments, validation, audit, scrub, append, fields and the debug views
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
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! Tracked changes one at a time: list each with an id, accept or reject a
//! selection and keep the rest tracked, as Word's Accept/Reject This Change
//! does.
//!
//! A change is one revision element (`w:ins`, `w:del`, `w:moveFrom`,
//! `w:moveTo`, `w:cellIns`, `w:cellDel`, `w:*PrChange`, ...), named
//! by its short id: `r12` in the body, `header1.r1`, `footnotes.r1`,
//! `comments.r9` or `styles.r0` in another story, the story being a header,
//! footer, notes or comments part's file stem (`header1`, `footnotes`,
//! `comments`, as `jubarte read` names them)
//! ([`crate::ids::ChangeId::short`]). Resolving some changes never renumbers the rest, so an
//! id listed before stays valid after. Word moves text as one change:
//! selecting either side of a move selects both sides and their range
//! markers. A revision inside a comment body (`word/comments.xml`) is
//! `comments.rN`, the same id accept and reject select (#1706).

use std::collections::{HashMap, HashSet};
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::namespaces::{MC, W};
use crate::opc::PartFs;
use crate::revision_processor::{FROZEN_NS, Resolution, resolve_package, revision_bearing_parts};
use crate::xmllinq::{Dom, NodeId, XName};

mod logical;

/// What a change does.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChangeKind {
    /// Inserted text, paragraph mark, row or cell.
    Insertion,
    /// Deleted text, paragraph mark, row or cell.
    Deletion,
    /// One side of a move.
    Move,
    /// Changed run, paragraph, section, table, row or cell properties.
    Formatting,
    /// One author's deletion and the insertion right after it, listed as
    /// one change ([`list_logical_changes`]). No single element has this
    /// kind, so a filter of it is refused ([`ChangeFilter::normalized`]).
    Replacement,
}

/// Which side of a move a change is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MoveSide {
    /// Where the text was moved from (`w:moveFrom`): accepting removes it.
    From,
    /// Where the text was moved to (`w:moveTo`): rejecting removes it.
    To,
}

/// One tracked change.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Change {
    /// The short id: `r12` in the body, `header1.r1` in another story
    /// ([`crate::ids::ChangeId::short`]).
    pub id: String,
    /// The same id as [`Self::id`].
    #[serde(rename = "ref")]
    pub r#ref: String,
    /// What the change does.
    pub kind: ChangeKind,
    /// What it applies to: `text`, `paragraph_mark`, `table_row`,
    /// `table_cell` or `properties`.
    pub target: &'static str,
    /// Revision author.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// The valid UTC instant, written in the author's local offset when both
    /// times record a whole-minute difference within ±14:00; otherwise `Z`.
    /// Without a valid `w16du:dateUtc`, `w:date` as stored.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,
    /// The text the change covers: inserted, deleted or moved text, or the
    /// text of the run or paragraph whose properties changed.
    pub text: String,
    /// The paragraph the change sits in (`p12`, `header1.p2`): the
    /// nearest listed paragraph around it, or a row's, cell's or table's
    /// first. `None` in `styles` and outside any paragraph.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub paragraph: Option<String>,
    /// The move's name, shared by both of its sides.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub move_name: Option<String>,
    /// The side of the move, for a move.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub move_side: Option<MoveSide>,
    /// The change whose content holds this one: an inserted, deleted or
    /// moved run, row or cell around it, or the mark of the paragraph whose
    /// properties it changes. Resolving that change so its content goes
    /// (accepting a deletion or the moved-from side, rejecting an insertion
    /// or the moved-to side) takes this one along.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inside: Option<String>,
    /// The comments (`c4`, and a reply's `c5`) whose reference mark this
    /// change holds: resolving it so its content goes (as for
    /// [`Self::inside`]) removes their threads, as Word does (#1159).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub holds_comments: Vec<String>,
    /// The marks of a logical change ([`list_logical_changes`]) that Word
    /// wrote as several elements, in reading order: empty for one element.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub members: Vec<ChangeMember>,
}

impl Change {
    /// The ids of the elements this change is made of, in reading order:
    /// its [`Self::members`]', or its own for a change of one element.
    pub fn element_ids(&self) -> impl Iterator<Item = &str> {
        let own = self.members.is_empty().then_some(self.id.as_str());
        own.into_iter()
            .chain(self.members.iter().map(|m| m.id.as_str()))
    }
}

/// One mark of a logical change: an element Word wrote for it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ChangeMember {
    /// The element's own id (`r7`), as [`list_changes`] lists it.
    pub id: String,
    /// What the element does: an insertion or a deletion.
    pub kind: ChangeKind,
    /// `text` or `paragraph_mark`.
    pub target: &'static str,
    /// The element's own date, as [`Change::date`] reports it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,
    /// The text it covers (empty for a paragraph mark).
    pub text: String,
}

/// Private audit view: public `Change` serialization stays unchanged.
pub(crate) struct AuditStory {
    pub part: String,
    pub paragraphs: Vec<(String, String)>,
    /// What [`run_characters`] counts in each paragraph, in order.
    pub contents: Vec<String>,
    pub changes: Vec<AuditChange>,
    pub markers: Vec<AuditMarker>,
}

/// A carrier omitted from the change listing. Only its own cursor slot can
/// disappear transparently; any visible descendants keep their positions.
pub(crate) struct AuditMarker {
    pub kind: String,
    pub paragraph: Option<usize>,
    pub owner: String,
    pub start: usize,
}

pub(crate) struct AuditChange {
    pub change: Change,
    pub owner: String,
    /// Document positions the change covers. A run's formatting history
    /// covers its run, so the touching fragments of one record, after an
    /// edit split the run, cover continuous text (#1656).
    pub start: usize,
    pub end: usize,
    /// The old properties a formatting change recorded
    /// ([`recorded_properties`]); `None` for every other change.
    pub payload: Option<String>,
    /// The characters a run formatting change's run covers in its
    /// paragraph ([`run_characters`]); `None` for every other change.
    pub characters: Option<(usize, usize)>,
}

/// Read paragraph text including deletions, and document positions for the
/// same carriers as `list_changes`. Positions count visible atoms and every
/// revision, including carriers omitted from the public listing.
pub(crate) fn audit_stories(docx: &[u8]) -> Result<Vec<AuditStory>, ChangeError> {
    let pkg = open(docx)?;
    let main = main_part(&pkg);
    let mut stories = Vec::new();
    for (part, _) in revision_bearing_parts(&pkg) {
        let Some(xml) = pkg.part_string(&part) else {
            continue;
        };
        let mut dom = Dom::new();
        let document = dom.parse_xdocument(&xml);
        let Some(root) = dom.root(document) else {
            continue;
        };
        let story = story_id(&main, &part);
        let found = carriers(&dom, root, &story);
        let revision_nodes: HashSet<_> = found.iter().map(|c| c.node).collect();
        let mut spans = HashMap::new();
        let mut cursor = 0;
        let mut pending = vec![(root, false)];
        while let Some((node, closing)) = pending.pop() {
            if closing {
                if let Some(span) = spans.get_mut(&node) {
                    let (_, end): &mut (usize, usize) = span;
                    *end = cursor;
                }
                continue;
            }
            spans.insert(node, (cursor, cursor));
            let visible = dom.name(node).is_some_and(|name| {
                name.namespace_name() == W::URI
                    && matches!(
                        name.local_name(),
                        "t" | "delText"
                            | "instrText"
                            | "delInstrText"
                            | "tab"
                            | "br"
                            | "cr"
                            | "drawing"
                            | "pict"
                            | "object"
                            | "sym"
                            | "noBreakHyphen"
                            | "softHyphen"
                            | "footnoteReference"
                            | "endnoteReference"
                    )
            });
            let empty_text = dom.name(node).is_some_and(|name| {
                matches!(
                    name.local_name(),
                    "t" | "delText" | "instrText" | "delInstrText"
                )
            }) && dom.value(node).is_empty();
            if revision_nodes.contains(&node) || (visible && !empty_text) {
                cursor += 1;
            }
            pending.push((node, true));
            for index in (0..dom.child_count(node)).rev() {
                pending.push((dom.child_at(node, index), false));
            }
        }
        let paragraphs = crate::inspect::story_paragraph_nodes(&dom, root)
            .into_iter()
            .enumerate()
            .map(|(index, node)| (crate::ids::paragraph_id(&story, index), text_of(&dom, node)))
            .collect();
        let paragraph_nodes = paragraph_index(&dom, root);
        let (characters, contents) = run_characters(&dom, root, &HashSet::new());
        let markers = found
            .iter()
            .filter(|carrier| carrier.change.is_none())
            .map(|carrier| {
                let paragraph = paragraph_of(&dom, carrier.node, &paragraph_nodes);
                AuditMarker {
                    kind: dom.name(carrier.node).unwrap().local_name().to_string(),
                    paragraph,
                    owner: if paragraph.is_none() {
                        audit_owner(&dom, carrier.node)
                    } else {
                        String::new()
                    },
                    start: spans[&carrier.node].0,
                }
            })
            .collect();
        let changes = found
            .into_iter()
            .filter_map(|carrier| {
                let change = carrier.change?;
                let owner = if change.paragraph.is_none() {
                    audit_owner(&dom, carrier.node)
                } else {
                    String::new()
                };
                let run = formatted_run(&dom, carrier.node);
                let (start, end) = spans[&run.unwrap_or(carrier.node)];
                let payload = (change.kind == ChangeKind::Formatting)
                    .then(|| recorded_properties(&dom, carrier.node));
                Some(AuditChange {
                    change,
                    owner,
                    start,
                    end,
                    payload,
                    characters: run.and_then(|run| characters.get(&run).copied()),
                })
            })
            .collect();
        stories.push(AuditStory {
            part,
            paragraphs,
            contents,
            changes,
            markers,
        });
    }
    Ok(stories)
}

/// The run a `w:r/w:rPr/w:rPrChange` formats; `None` for any other
/// record, a paragraph mark's or a style's included.
fn formatted_run(dom: &Dom, record: NodeId) -> Option<NodeId> {
    if !dom.name_is(record, &W::r_pr_change()) {
        return None;
    }
    let rpr = dom.parent(record).filter(|&n| dom.name_is(n, &W::r_pr()))?;
    dom.parent(rpr).filter(|&n| dom.name_is(n, &W::r()))
}

/// The properties a formatting record kept, spelled without revision ids
/// or namespace prefixes: its own attributes past id, author and date, then
/// each element as `{namespace}local`, its attributes
/// `{namespace}local="value"` sorted, its children in document order (the
/// first matching `mc:Choice` wins) and a leaf's text. A value that lists
/// prefixes (`Requires`, `mc:Ignorable`, …) lists their namespaces, and an
/// on/off `w:val` is spelled one way. Two records with the same payload
/// recorded the same old formatting.
pub(crate) fn recorded_properties(dom: &Dom, record: NodeId) -> String {
    fn attributes(dom: &Dom, node: NodeId, skip: &[XName]) -> String {
        let Some(name) = dom.name(node) else {
            return String::new();
        };
        let mut attributes: Vec<String> = dom
            .attributes(node)
            .into_iter()
            .filter(|(attribute, _)| {
                !dom.is_namespace_declaration(attribute) && !skip.contains(attribute)
            })
            .filter_map(|(attribute, value)| {
                let value =
                    if crate::xmllinq::serialize::is_namespace_prefix_list(&name, &attribute) {
                        value
                            .split_whitespace()
                            .map(|prefix| {
                                crate::validate::namespace_in_scope(dom, node, prefix).map_or_else(
                                    || format!("{prefix}:"),
                                    |uri| format!("{{{uri}}}"),
                                )
                            })
                            .collect::<Vec<_>>()
                            .join(" ")
                    } else if attribute == W::val() && on_off(&name) {
                        match value.as_str() {
                            // `<w:b/>` and `<w:b w:val="true"/>` are both on.
                            "1" | "true" | "on" => return None,
                            "0" | "false" | "off" => "0".to_string(),
                            _ => value,
                        }
                    } else {
                        value
                    };
                Some(format!(
                    "{{{}}}{}={value:?}",
                    attribute.namespace_name(),
                    attribute.local_name()
                ))
            })
            .collect();
        attributes.sort();
        attributes.join(",")
    }
    fn canonical(dom: &Dom, node: NodeId) -> String {
        let Some(name) = dom.name(node) else {
            return String::new();
        };
        let children: Vec<String> = dom
            .elements(node, None)
            .into_iter()
            .map(|child| canonical(dom, child))
            .collect();
        let text = if children.is_empty() {
            dom.value(node)
        } else {
            String::new()
        };
        format!(
            "{{{}}}{}[{}]({}){text:?}",
            name.namespace_name(),
            name.local_name(),
            attributes(dom, node, &[W::id()]),
            children.join(",")
        )
    }
    let own = attributes(dom, record, &[W::id(), W::author(), W::date()]);
    let children: Vec<String> = dom
        .elements(record, None)
        .into_iter()
        .map(|child| canonical(dom, child))
        .collect();
    format!("[{own}]({})", children.join(","))
}

/// A `CT_OnOff` property: its `w:val` is on when absent.
fn on_off(name: &XName) -> bool {
    name.namespace_name() == W::URI
        && matches!(
            name.local_name(),
            "b" | "bCs"
                | "i"
                | "iCs"
                | "caps"
                | "smallCaps"
                | "strike"
                | "dstrike"
                | "outline"
                | "shadow"
                | "emboss"
                | "imprint"
                | "noProof"
                | "snapToGrid"
                | "vanish"
                | "webHidden"
                | "specVanish"
                | "rtl"
                | "cs"
                | "oMath"
                | "keepNext"
                | "keepLines"
                | "pageBreakBefore"
                | "widowControl"
                | "suppressLineNumbers"
                | "suppressAutoHyphens"
                | "kinsoku"
                | "wordWrap"
                | "overflowPunct"
                | "topLinePunct"
                | "autoSpaceDE"
                | "autoSpaceDN"
                | "bidi"
                | "adjustRightInd"
                | "contextualSpacing"
                | "mirrorIndents"
                | "suppressOverlap"
                | "titlePg"
                | "rtlGutter"
                | "noEndnote"
                | "formProt"
                | "bidiVisual"
                | "hidden"
                | "cantSplit"
                | "tblHeader"
                | "noWrap"
                | "tcFitText"
                | "hideMark"
        )
}

/// A properties element (`w:pPr`, `w:rPr`, …): no content lives in it.
fn properties(name: &XName) -> bool {
    name.namespace_name() == W::URI
        && matches!(
            name.local_name(),
            "pPr" | "rPr" | "sectPr" | "tblPr" | "tblPrEx" | "tblGrid" | "trPr" | "tcPr" | "sdtPr"
        )
}

/// One character per visible element that is not text: what a run holding
/// a tab, a break or a drawing covers.
#[doc(hidden)]
pub fn atom(name: &XName) -> Option<char> {
    if name.namespace_name() != W::URI {
        return None;
    }
    Some(match name.local_name() {
        "tab" | "ptab" => '\t',
        "br" | "cr" => '\n',
        "drawing" | "pict" | "object" => '\u{FFFC}',
        "sym" => '\u{FFFD}',
        "noBreakHyphen" => '\u{2011}',
        "softHyphen" => '\u{AD}',
        "footnoteReference" | "endnoteReference" => '\u{E000}',
        "instrText" | "delInstrText" => '\u{E001}',
        _ => return None,
    })
}

/// Whether `run` covers any character [`run_characters`] counts: text
/// outside its properties, or an atom ([`atom`]).
#[doc(hidden)]
pub fn run_has_characters(dom: &Dom, run: NodeId) -> bool {
    let (t, del_text) = (W::t(), W::del_text());
    let mut pending: Vec<NodeId> = dom.elements(run, None);
    while let Some(node) = pending.pop() {
        let Some(name) = dom.name(node) else {
            continue;
        };
        if properties(&name) {
            continue;
        }
        if dom.name_is(node, &t) || dom.name_is(node, &del_text) {
            if !dom.value(node).is_empty() {
                return true;
            }
        } else if atom(&name).is_some() {
            return true;
        }
        pending.extend(dom.elements(node, None));
    }
    false
}

/// What each run covers in its story paragraph: the characters of its
/// `w:t` and `w:delText`, one more per tab, break, drawing or other atom
/// ([`atom`]), a text box's runs at their place; and each paragraph's
/// counted content, in order. Content under a `skipped` element counts for
/// nothing, and a paragraph whose inserted mark is `skipped` continues into
/// the next, as rejecting that mark joins them.
fn run_characters(
    dom: &Dom,
    root: NodeId,
    skipped: &HashSet<NodeId>,
) -> (HashMap<NodeId, (usize, usize)>, Vec<String>) {
    let (r, t, del_text) = (W::r(), W::t(), W::del_text());
    let mut spans = HashMap::new();
    let mut contents = Vec::new();
    let mut cursor = 0;
    for paragraph in crate::inspect::story_paragraph_nodes(dom, root) {
        let mut content = String::new();
        let mut pending = vec![(paragraph, false, false)];
        while let Some((node, closing, skipping)) = pending.pop() {
            if closing {
                if let Some(span) = spans.get_mut(&node) {
                    let (_, end): &mut (usize, usize) = span;
                    *end = cursor;
                }
                continue;
            }
            let skipping = skipping || skipped.contains(&node);
            // Properties hold no content (a `w:tabs/w:tab` is a tab stop).
            if node != paragraph && dom.name(node).is_some_and(|name| properties(&name)) {
                continue;
            }
            if dom.name_is(node, &r) {
                spans.insert(node, (cursor, cursor));
            } else if !skipping {
                if dom.name_is(node, &t) || dom.name_is(node, &del_text) {
                    let text = dom.value(node);
                    cursor += text.chars().count();
                    content.push_str(&text);
                } else if let Some(atom) = dom.name(node).and_then(|name| atom(&name)) {
                    cursor += 1;
                    content.push(atom);
                }
            }
            pending.push((node, true, skipping));
            for index in (0..dom.child_count(node)).rev() {
                pending.push((dom.child_at(node, index), false, skipping));
            }
        }
        contents.push(content);
        let joined = dom
            .element(paragraph, &W::p_pr())
            .and_then(|p_pr| dom.element(p_pr, &W::r_pr()))
            .and_then(|r_pr| dom.element(r_pr, &W::ins()))
            .is_some_and(|mark| skipped.contains(&mark));
        if !joined {
            cursor = 0;
        }
    }
    (spans, contents)
}

/// A formatting change: the old properties it recorded
/// ([`recorded_properties`]) and, a run's, the characters it covers
/// ([`run_characters`]).
#[derive(Clone, Debug, PartialEq, Eq)]
#[doc(hidden)]
pub struct Recorded {
    pub payload: String,
    pub characters: Option<(usize, usize)>,
}

/// Each formatting change's [`Recorded`], under the story-scoped id
/// [`list_changes`] gives it (`r3`, `styles.r3`). A `w:id` repeated in one
/// story keeps every record, in document order.
pub(crate) type Records = HashMap<String, Vec<Recorded>>;

/// The comments of a package's comments part: each comment's `w:id`, and
/// for each comment-body change (`comments.r9`, as [`list_changes`] names
/// it) the `w:id` of the comment that holds it, `None` when the change's
/// id repeats in two comments. A comment an edit removes takes its body's
/// changes with it (#1706).
#[derive(Debug, Default)]
#[doc(hidden)]
pub struct CommentBodies {
    pub comments: HashSet<String>,
    pub owners: HashMap<String, Option<String>>,
}

/// [`CommentBodies`] of `docx`; empty when it has no comments part.
#[doc(hidden)]
pub fn comment_bodies(docx: &[u8]) -> Result<CommentBodies, ChangeError> {
    let pkg = open(docx)?;
    let mut bodies = CommentBodies::default();
    let Some(part) = crate::revision_processor::comments_part(&pkg) else {
        return Ok(bodies);
    };
    let story = story_id(&main_part(&pkg), &part);
    let comment = W::comment();
    let id = W::id();
    for_each_story(&pkg, |dom, root, name| {
        if name != story {
            return;
        }
        dom.for_each_descendant_element(root, Some(&comment), |c| {
            if let Some(val) = dom.attribute(c, &id) {
                bodies.comments.insert(val.to_string());
            }
        });
        for carrier in carriers(dom, root, name) {
            let Some(change) = carrier.change else {
                continue;
            };
            // The nearest comment with an id that holds the carrier, walked up without a Vec.
            let mut holder = None;
            let mut node = dom.parent(carrier.node);
            while let Some(n) = node {
                if dom.name_is(n, &comment)
                    && let Some(val) = dom.attribute(n, &id)
                {
                    holder = Some(val.to_string());
                    break;
                }
                node = dom.parent(n);
            }
            if let Some(holder) = holder {
                bodies
                    .owners
                    .entry(change.id)
                    .and_modify(|owner| {
                        if owner.as_ref() != Some(&holder) {
                            *owner = None;
                        }
                    })
                    .or_insert(Some(holder));
            }
        }
    });
    Ok(bodies)
}

/// [`list_changes`] and its formatting changes' [`Records`], from one
/// parse of each story. The content of a change `skip` names, and the
/// paragraph mark it inserts, count for nothing in the characters.
#[doc(hidden)]
pub fn changes_and_records(
    docx: &[u8],
    skip: &dyn Fn(&Change) -> bool,
) -> Result<(Vec<Change>, Records), ChangeError> {
    let pkg = open(docx)?;
    let mut changes = Vec::new();
    let mut records = Records::new();
    for_each_story(&pkg, |dom, root, story| {
        let found = carriers(dom, root, story);
        let formatting = |carrier: &Carrier| {
            carrier
                .change
                .as_ref()
                .is_some_and(|c| c.kind == ChangeKind::Formatting)
        };
        if found.iter().any(formatting) {
            let skipped: HashSet<_> = found
                .iter()
                .filter(|carrier| carrier.change.as_ref().is_some_and(skip))
                .map(|carrier| carrier.node)
                .collect();
            let (characters, _) = run_characters(dom, root, &skipped);
            for carrier in found.iter().filter(|carrier| formatting(carrier)) {
                let Some(change) = &carrier.change else {
                    continue;
                };
                records
                    .entry(change.id.clone())
                    .or_default()
                    .push(Recorded {
                        payload: recorded_properties(dom, carrier.node),
                        characters: formatted_run(dom, carrier.node)
                            .and_then(|run| characters.get(&run).copied()),
                    });
            }
        }
        changes.extend(found.into_iter().filter_map(|c| c.change));
    });
    Ok((changes, records))
}

/// Owner paths use semantic ids where OOXML defines them, otherwise the
/// element's ordinal among same-named siblings. Revision ids never enter it.
fn audit_owner(dom: &Dom, node: NodeId) -> String {
    let mut path = Vec::new();
    for ancestor in dom.ancestors(node, None).into_iter().rev() {
        let Some(name) = dom.name(ancestor) else {
            continue;
        };
        let local = name.local_name();
        let identity = ["styleId", "abstractNumId", "numId", "ilvl", "id"]
            .into_iter()
            .find_map(|attr| {
                dom.attribute(ancestor, &W::name(attr))
                    .map(|id| format!("{attr}={id}"))
            })
            .unwrap_or_else(|| {
                let ordinal = dom
                    .nodes_before_self(ancestor)
                    .into_iter()
                    .filter(|&sibling| dom.name(sibling).as_ref() == Some(&name))
                    .count();
                ordinal.to_string()
            });
        path.push(format!("{local}[{identity}]"));
    }
    path.join("/")
}

/// Which changes to resolve. A change is selected when it matches every
/// list given; a list left out matches any change, so the default filter
/// selects every change, and an empty list selects none.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ChangeFilter {
    /// Change ids (`r12`, `header1.r1`); an id not in the document is an
    /// error.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ids: Option<Vec<String>>,
    /// Revision authors.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authors: Option<Vec<String>>,
    /// Change kinds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kinds: Option<Vec<ChangeKind>>,
}

impl ChangeFilter {
    /// Build a filter that selects the changes `ids` names (`r12`,
    /// `header1.r1`, `r1+2`).
    pub fn ids<I: IntoIterator<Item = S>, S: Into<String>>(ids: I) -> Self {
        Self {
            ids: Some(ids.into_iter().map(Into::into).collect()),
            ..Self::default()
        }
    }

    /// The filter with every id in its settled short spelling, the form
    /// [`Change::id`] holds and [`Self::check`] and [`Self::matches`]
    /// compare: `r12`, `header1.r1`, a pair `r1+2` as its two ids, each
    /// once. Only settled ids parse ([`crate::ids::parse_change_ids`]):
    /// `12`, 0.12's `#12` and the expired `body:rev:12` are
    /// [`ChangeError::InvalidId`], naming the spelling to use.
    ///
    /// # Errors
    ///
    /// [`ChangeError::InvalidId`] for an id that does not parse, and for
    /// the kind [`ChangeKind::Replacement`], which no element has: it would
    /// select nothing.
    pub fn normalized(&self) -> Result<Self, ChangeError> {
        if self
            .kinds
            .as_ref()
            .is_some_and(|kinds| kinds.contains(&ChangeKind::Replacement))
        {
            return Err(ChangeError::InvalidId(
                "the kind replacement names a logical change, not its marks: select a replacement by its id (r3+4), or its marks by kind (deletion, insertion)".into(),
            ));
        }
        let Some(ids) = &self.ids else {
            return Ok(self.clone());
        };
        let mut out: Vec<String> = Vec::with_capacity(ids.len());
        for id in ids {
            let parsed = crate::ids::parse_change_ids(id)
                .map_err(|e| ChangeError::InvalidId(e.to_string()))?;
            for one in parsed {
                let one = one.short();
                if !out.contains(&one) {
                    out.push(one);
                }
            }
        }
        Ok(Self {
            ids: Some(out),
            ..self.clone()
        })
    }

    /// The first error the filter's ids meet in `listed`: an id that names
    /// no change, or one that names several. Expects a [`Self::normalized`]
    /// filter.
    ///
    /// # Errors
    ///
    /// [`ChangeError::UnknownChange`] when an id is not in `listed`;
    /// [`ChangeError::Ambiguous`] when an id names more than one change.
    pub fn check(&self, listed: &[Change]) -> Result<(), ChangeError> {
        for id in self.ids.iter().flatten() {
            let named: Vec<&Change> = listed.iter().filter(|c| &c.id == id).collect();
            match named.len() {
                0 => return Err(ChangeError::UnknownChange(id.clone())),
                1 => {}
                _ => {
                    return Err(ChangeError::Ambiguous {
                        id: id.clone(),
                        candidates: named.into_iter().cloned().collect(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Whether `change` is selected.
    pub fn matches(&self, change: &Change) -> bool {
        self.ids.as_ref().is_none_or(|ids| ids.contains(&change.id))
            && self
                .authors
                .as_ref()
                .is_none_or(|authors| change.author.as_ref().is_some_and(|a| authors.contains(a)))
            && self
                .kinds
                .as_ref()
                .is_none_or(|kinds| kinds.contains(&change.kind))
    }
}

/// Why changes could not be listed or resolved.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChangeError {
    /// The package could not be read or written.
    Package(String),
    /// A filter id names no change in the document.
    UnknownChange(String),
    /// A filter id is not a change id ([`crate::ids::parse_change_ids`]),
    /// or a filter kind is one no element has ([`ChangeFilter::normalized`]).
    InvalidId(String),
    /// A filter id names more than one listed change: a
    /// duplicate `w:id` in one story.
    Ambiguous {
        /// The id.
        id: String,
        /// The changes it names, in document order.
        candidates: Vec<Change>,
    },
    /// The filter's ids name only some of the marks of one logical change
    /// ([`list_logical_changes`]), or only part of one side of a
    /// replacement.
    PartOfChange {
        /// The marks named, as one id (`r7+8`).
        named: String,
        /// The whole change (`r7+8+9+10`).
        whole: String,
        /// For part of one side of a replacement: the side (`r20+21`) and
        /// its kind.
        side: Option<(String, ChangeKind)>,
    },
    /// Settling the selection would leave `w:ins` or `w:del` on a
    /// container's final paragraph mark. The mark was not already that
    /// container's final mark. A cell in this shape hangs Word's Accept
    /// All and Reject All (#1669, #1693). No document is returned.
    ExposedFinalMark {
        /// `cell`, `body`, `header`, `footer`, `note`, `textbox`, or
        /// `comment`.
        container: &'static str,
        /// Path of the container (`w:body[0]/w:tbl[0]/w:tr[0]/w:tc[1]`).
        path: String,
        /// Path of the paragraph that would keep the mark.
        paragraph: String,
        /// The remaining mark's short id (`r1`, `header1.r1`), or
        /// `(no w:id)` for a mark without one.
        revision: String,
        /// `ins` or `del`.
        kind: &'static str,
    },
}

impl fmt::Display for ChangeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ChangeError::Package(m) => write!(f, "invalid package: {m}"),
            ChangeError::UnknownChange(id) => write!(f, "no tracked change {id}"),
            ChangeError::InvalidId(message) => f.write_str(message),
            ChangeError::Ambiguous { id, candidates } => {
                // Only these elements' ids are renumbered by validate --repair.
                let repairable = candidates.iter().all(|c| {
                    matches!(
                        c.kind,
                        ChangeKind::Insertion | ChangeKind::Deletion | ChangeKind::Move
                    ) && c.target != "table_cell"
                });
                write!(f, "{id} names {} changes", candidates.len())?;
                if repairable {
                    f.write_str(" (duplicate w:id; validate --repair renumbers them)")?;
                }
                let listed: Vec<String> = candidates
                    .iter()
                    .map(|c| {
                        let place = c
                            .paragraph
                            .as_deref()
                            .map(|p| format!(" in {p}"))
                            .unwrap_or_default();
                        format!("{id} {} {:?}{place}", kind_name(c.kind), c.text)
                    })
                    .collect();
                write!(f, ": {}", listed.join("; "))
            }
            ChangeError::PartOfChange {
                named,
                whole,
                side: None,
            } => write!(
                f,
                "{named} is part of {whole}; name the whole change ({whole})"
            ),
            ChangeError::PartOfChange {
                named,
                whole,
                side: Some((side, kind)),
            } => {
                let kind = if *kind == ChangeKind::Deletion {
                    "deleted"
                } else {
                    "inserted"
                };
                write!(
                    f,
                    "{named} is part of {side}, the {kind} side of {whole}; name that side ({side}) or the whole change ({whole})"
                )
            }
            ChangeError::ExposedFinalMark {
                container,
                path,
                paragraph,
                revision,
                kind,
            } => write!(
                f,
                "refusing to leave {kind} {revision} on the final mark of {container} {path} at paragraph {paragraph}"
            ),
        }
    }
}

impl std::error::Error for ChangeError {}

fn kind_name(kind: ChangeKind) -> &'static str {
    match kind {
        ChangeKind::Insertion => "insertion",
        ChangeKind::Deletion => "deletion",
        ChangeKind::Move => "move",
        ChangeKind::Formatting => "formatting",
        ChangeKind::Replacement => "replacement",
    }
}

/// `jubarte changes`' listing: one line per change, `{ref}\t{kind}\t{target}
/// \t{author}\t{paragraph}\t{text}[\t({n} elements)][\tinside {ref}][\tholds
/// comment {c}'s mark]` (`-` for an absent author or paragraph; the text
/// quoted, its first 60 characters; `({n} elements)` for a logical change
/// Word wrote as several; `holds comment marks {c}, {c}` for several), then
/// `{n} change(s)`. A row has six fields, and one more for each suffix.
pub fn changes_text(changes: &[Change]) -> String {
    let mut out = String::new();
    for c in changes {
        let preview: String = c.text.chars().take(60).collect();
        let paragraph = c.paragraph.as_deref().unwrap_or("-");
        let elements = match c.members.len() {
            0 => String::new(),
            n => format!("\t({n} elements)"),
        };
        let inside = c
            .inside
            .as_deref()
            .map(|id| format!("\tinside {id}"))
            .unwrap_or_default();
        let holds = match c.holds_comments.as_slice() {
            [] => String::new(),
            [one] => format!("\tholds comment {one}'s mark"),
            many => format!("\tholds comment marks {}", many.join(", ")),
        };
        out.push_str(&format!(
            "{}\t{}\t{}\t{}\t{paragraph}\t{preview:?}{elements}{inside}{holds}\n",
            c.r#ref,
            kind_name(c.kind),
            c.target,
            c.author.as_deref().unwrap_or("-"),
        ));
    }
    out.push_str(&format!("{} change(s)\n", changes.len()));
    out
}

/// Every tracked change, story by story (body, headers, footers, endnotes,
/// footnotes, comments, styles), in document order. A revision inside a
/// comment body is `comments.r9` (#1706).
///
/// # Errors
///
/// [`ChangeError::Package`] when the package is not a readable zip.
pub fn list_changes(docx: &[u8]) -> Result<Vec<Change>, ChangeError> {
    Ok(changes_in(&open(docx)?))
}

/// Every logical change, story by story, in document order: the changes
/// `jubarte changes` lists. One author's touching insertions, or touching
/// deletions, are one change with a composite id (`r7+8+9+10`) and
/// [`Change::members`]; a deletion run followed by the same author's
/// insertion run is one [`ChangeKind::Replacement`] (module `logical`
/// has the rule). Every other element is listed as [`list_changes`]
/// lists it.
///
/// # Errors
///
/// [`ChangeError::Package`] when the package is not a readable zip.
pub fn list_logical_changes(docx: &[u8]) -> Result<Vec<Change>, ChangeError> {
    Ok(logical_changes_in(&open(docx)?))
}

/// The id of the marks `ids` names together, in their order: `r7+8`,
/// `header1.r1+2`. One mark keeps its own id, whatever its spelling.
#[doc(hidden)]
pub fn composite_id(ids: &[String]) -> String {
    match ids {
        [one] => one.clone(),
        _ => logical::joined(ids.iter().map(String::as_str)),
    }
}

/// The changes `authors` wrote, matched as [`ChangeFilter::authors`]
/// matches them (exact names); every change when `authors` is empty. A
/// logical change has one author, so it is kept or left whole: the filter
/// `jubarte changes --author` applies (#1690).
pub fn by_authors(changes: Vec<Change>, authors: &[String]) -> Vec<Change> {
    if authors.is_empty() {
        return changes;
    }
    let filter = ChangeFilter {
        authors: Some(authors.to_vec()),
        ..ChangeFilter::default()
    };
    changes.into_iter().filter(|c| filter.matches(c)).collect()
}

/// The logical changes of an opened package ([`list_logical_changes`]).
#[doc(hidden)]
pub fn logical_changes_in(pkg: &PartFs) -> Vec<Change> {
    let mut out = Vec::new();
    for_each_story(pkg, |dom, root, story| {
        out.extend(logical::logical(dom, root, &carriers(dom, root, story)));
    });
    out
}

/// Refuse ids that name only some marks of a logical change
/// ([`ChangeError::PartOfChange`]): the check `accept` and `reject` make,
/// for an edit plan's `resolve_revisions` and the edit flags to make on
/// their source before they resolve anything.
#[doc(hidden)]
pub fn check_whole_changes(docx: &[u8], filter: &ChangeFilter) -> Result<(), ChangeError> {
    let filter = filter.normalized()?;
    if filter.ids.is_none() {
        return Ok(());
    }
    logical::check_whole(&filter, &logical_changes_in(&open(docx)?))
}

/// [`list_changes`] for a view that already renders the package: no
/// admission, and a part that does not parse lists nothing, so the view's
/// count fails only where the package itself does.
#[doc(hidden)]
pub fn list_changes_tolerant(docx: &[u8]) -> Result<Vec<Change>, ChangeError> {
    Ok(changes_in(&tolerant(docx)?))
}

/// [`list_logical_changes`] as [`list_changes_tolerant`] lists the marks:
/// the changes a view's tags name.
#[doc(hidden)]
pub fn list_logical_changes_tolerant(docx: &[u8]) -> Result<Vec<Change>, ChangeError> {
    Ok(logical_changes_in(&tolerant(docx)?))
}

/// The package a view reads, opened without admission. Its parts parse
/// permissively, so one nesting deeper than the view reads is refused
/// before the parser recurses into it (#1353 review).
fn tolerant(docx: &[u8]) -> Result<PartFs, ChangeError> {
    use crate::xmllinq::parse::{PERMISSIVE_MAX_DEPTH, nests_deeper};

    let normalized = crate::strict_translation::strict_to_transitional_docx(docx)
        .map_err(|e| ChangeError::Package(e.to_string()))?;
    let pkg = PartFs::open(&normalized).map_err(|e| ChangeError::Package(e.to_string()))?;
    for (part, _) in revision_bearing_parts(&pkg) {
        if pkg
            .part_string(&part)
            .is_some_and(|xml| nests_deeper(&xml, PERMISSIVE_MAX_DEPTH))
        {
            return Err(ChangeError::Package(format!(
                "{part}: XML nesting too deep"
            )));
        }
    }
    Ok(pkg)
}

/// The changes of an opened (transitional) package, as [`list_changes`]
/// lists them. A comment-body revision is `comments.rN` (#1706).
#[doc(hidden)]
pub fn changes_in(pkg: &PartFs) -> Vec<Change> {
    let mut out = Vec::new();
    for_each_story(pkg, |dom, root, story| {
        out.extend(
            carriers(dom, root, story)
                .into_iter()
                .filter_map(|c| c.change),
        );
    });
    out
}

/// Each listed story's parsed part, in [`list_changes`] order: every
/// revision-bearing part, including comment bodies (`comments.rN`).
fn for_each_story(pkg: &PartFs, mut each: impl FnMut(&Dom, NodeId, &str)) {
    let main = main_part(pkg);
    for (part, _) in revision_bearing_parts(pkg) {
        let Some(xml) = pkg.part_string(&part) else {
            continue;
        };
        let mut dom = Dom::new();
        let doc = dom.parse_xdocument(&xml);
        let Some(root) = dom.root(doc) else {
            continue;
        };
        each(&dom, root, &story_id(&main, &part));
    }
}

/// Accept the changes `filter` selects; the others stay tracked. A Strict
/// package is written back transitional, as the comparer writes it; with
/// nothing selected the bytes come back untouched.
///
/// # Errors
///
/// [`ChangeError::InvalidId`] for an id `filter` accepts that is not a
/// change id; [`ChangeError::UnknownChange`] for an id not present in the
/// document; [`ChangeError::Ambiguous`] for an id that names more than one
/// listed change; [`ChangeError::PartOfChange`] when the ids name only some
/// of the marks of a logical change ([`list_logical_changes`]), so that it
/// would be half settled ([`accept_elements`] settles marks one by one);
/// [`ChangeError::Package`] when the package cannot be read or rewritten;
/// [`ChangeError::ExposedFinalMark`] when settling the selection would
/// leave `w:ins` or `w:del` on a container's final paragraph mark that
/// was not already final (#1693).
pub fn accept_changes(docx: &[u8], filter: &ChangeFilter) -> Result<Vec<u8>, ChangeError> {
    resolve(docx, filter, Resolution::Accept).map(|(document, _, _)| document)
}

/// Reject the changes `filter` selects; the others stay tracked. A Strict
/// package is written back transitional, as [`accept_changes`] writes it.
///
/// # Errors
///
/// As [`accept_changes`].
pub fn reject_changes(docx: &[u8], filter: &ChangeFilter) -> Result<Vec<u8>, ChangeError> {
    resolve(docx, filter, Resolution::Reject).map(|(document, _, _)| document)
}

/// A resolved document and the comments removed with its revisions.
#[derive(Clone, Debug)]
pub struct ResolvedChanges {
    /// The document after resolving the selected changes.
    pub document: Vec<u8>,
    /// Removed comments, including replies, with their original ids and text.
    /// Surviving comments keep their ids in `document` (#1264).
    pub removed_comments: Vec<crate::comments::CommentRecord>,
    /// Why each of `removed_comments` went, in its order: `anchor removed
    /// by accepting r13`, naming the change that held its mark, or its
    /// thread root's (#1159).
    pub removed_why: Vec<String>,
    /// Tracked changes still inside comment bodies after the resolution.
    /// An id, author or kind selection names them as `comments.rN`; one
    /// that does not name them leaves them tracked (#1706, #1223).
    pub comment_changes_left: usize,
    /// Threads rescued onto empty anchors, in source comment ids; the CLI's
    /// `--keep-nested-comment` opt-in (#1279). Empty when settlement
    /// removed the threads (Word's behaviour, and the default).
    pub kept_comments: Vec<crate::comment_settlement::KeptComment>,
}

/// `anchor removed by accepting r13`: the verb of `resolution`, and the
/// change of `changes` (the source's) that held the reference mark of a
/// comment of `thread` (the root's first, then each reply's). The change
/// must be one the verb removes the content of (a deletion or moved-from
/// side accepted, an insertion or moved-to side rejected) and one the pass
/// settled: an id of `settled`, or the other side of a move it holds, which
/// it names as `settled` does; `None` settled every change. Of changes
/// nested in one another the innermost is named. A thread also goes when
/// the changes resolved remove all its range's text, its mark outside them
/// (Word prunes a dead range): that names no change.
pub(crate) fn why_removed(
    changes: &[Change],
    thread: &[String],
    resolution: Resolution,
    settled: Option<&[String]>,
    wholes: &HashMap<String, String>,
) -> String {
    let (verb, kind, side) = match resolution {
        Resolution::Accept => ("accepting", ChangeKind::Deletion, MoveSide::From),
        Resolution::Reject => ("rejecting", ChangeKind::Insertion, MoveSide::To),
    };
    let removes = |ch: &Change| {
        ch.kind == kind || (ch.kind == ChangeKind::Move && ch.move_side == Some(side))
    };
    // The id the pass selected for `ch`: its own, or its move's other side.
    let named = |ch: &Change| -> Option<String> {
        let Some(settled) = settled else {
            return Some(ch.id.clone());
        };
        if settled.contains(&ch.id) {
            return Some(ch.id.clone());
        }
        let name = ch.move_name.as_ref()?;
        changes
            .iter()
            .find(|other| {
                other.id != ch.id
                    && other.move_name.as_ref() == Some(name)
                    && settled.contains(&other.id)
            })
            .map(|other| other.id.clone())
    };
    let holder = thread.iter().find_map(|c| {
        let held: Vec<&Change> = changes
            .iter()
            .filter(|ch| ch.holds_comments.contains(c) && removes(ch) && named(ch).is_some())
            .collect();
        held.iter()
            .find(|ch| {
                !held
                    .iter()
                    .any(|inner| inner.inside.as_ref() == Some(&ch.id))
            })
            .and_then(|ch| named(ch))
    });
    match holder {
        Some(change) => format!(
            "anchor removed by {verb} {}",
            wholes.get(&change).unwrap_or(&change)
        ),
        None => format!("anchor removed by {verb} the changes that held all its text"),
    }
}

/// Each mark of a change of several marks, by its id, with the id of that
/// change: a removed comment's reason names the whole change, as `changes`
/// lists it and a selection names it (#1261).
pub(crate) fn member_wholes(docx: &[u8]) -> Result<HashMap<String, String>, ChangeError> {
    Ok(list_logical_changes_tolerant(docx)?
        .into_iter()
        .flat_map(|change| {
            change
                .members
                .into_iter()
                .map(move |member| (member.id, change.id.clone()))
        })
        .collect())
}

/// Accept selected changes and report comments that disappeared with them.
///
/// # Errors
/// As [`accept_changes`], or when the removed comments cannot be read.
pub fn accept_changes_with_report(
    docx: &[u8],
    filter: &ChangeFilter,
) -> Result<ResolvedChanges, ChangeError> {
    resolve_with_report(docx, filter, Resolution::Accept)
}

/// Reject selected changes and report comments that disappeared with them.
///
/// # Errors
/// As [`reject_changes`], or when the removed comments cannot be read.
pub fn reject_changes_with_report(
    docx: &[u8],
    filter: &ChangeFilter,
) -> Result<ResolvedChanges, ChangeError> {
    resolve_with_report(docx, filter, Resolution::Reject)
}

/// Accept selected changes, keeping wholly removed comment threads on
/// empty anchors (#1279). The CLI's `--keep-nested-comment` opt-in; the
/// default removes them, as Word does.
///
/// # Errors
/// As [`accept_changes_with_report`].
pub fn accept_changes_keeping_comments(
    docx: &[u8],
    filter: &ChangeFilter,
) -> Result<ResolvedChanges, ChangeError> {
    resolve_keeping_comments(docx, filter, Resolution::Accept)
}

/// Reject selected changes, keeping wholly removed comment threads on
/// empty anchors (#1279). The CLI's `--keep-nested-comment` opt-in; the
/// default removes them, as Word does.
///
/// # Errors
/// As [`reject_changes_with_report`].
pub fn reject_changes_keeping_comments(
    docx: &[u8],
    filter: &ChangeFilter,
) -> Result<ResolvedChanges, ChangeError> {
    resolve_keeping_comments(docx, filter, Resolution::Reject)
}

fn resolve_with_report(
    docx: &[u8],
    filter: &ChangeFilter,
    resolution: Resolution,
) -> Result<ResolvedChanges, ChangeError> {
    let (document, removed, comment_changes_left) = resolve(docx, filter, resolution)?;
    let (removed_comments, removed_why) = if removed.is_empty() {
        (Vec::new(), Vec::new())
    } else {
        removed_comment_report(docx, &removed, filter, resolution)?
    };
    Ok(ResolvedChanges {
        document,
        removed_comments,
        removed_why,
        comment_changes_left,
        kept_comments: Vec::new(),
    })
}

/// The `removed_comments` / `removed_why` pair for the comment ids
/// `removed`: each record (replies included) beside the reason its thread
/// went, naming the selected change that held it.
fn removed_comment_report(
    docx: &[u8],
    removed: &[String],
    filter: &ChangeFilter,
    resolution: Resolution,
) -> Result<(Vec<crate::comments::CommentRecord>, Vec<String>), ChangeError> {
    let comments =
        crate::comments::list_comments_within(docx, crate::admission::InputLimits::compare())
            .map_err(|e| ChangeError::Package(e.to_string()))?;
    let listed = list_changes_tolerant(docx)?;
    let wholes = member_wholes(docx)?;
    let filter = filter.normalized()?;
    let settled: Vec<String> = listed
        .iter()
        .filter(|c| filter.matches(c))
        .map(|c| c.id.clone())
        .collect();
    // `removed` keeps each `w:id` as written (`0005`). The reader parsed that
    // same id to a number, so match the number, not the spelling.
    let removed_ids: HashSet<u32> = removed.iter().filter_map(|id| id.parse().ok()).collect();
    let removed_comments: Vec<crate::comments::CommentRecord> = comments
        .iter()
        .filter(|c| removed_ids.contains(&c.id))
        .cloned()
        .collect();
    // A reply's thread: itself, then each comment it replies to.
    let removed_why = removed_comments
        .iter()
        .map(|c| {
            let mut thread = vec![format!("c{}", c.id)];
            let mut parent = c.parent;
            while let Some(id) = parent.filter(|id| !thread.contains(&format!("c{id}"))) {
                thread.push(format!("c{id}"));
                parent = comments.iter().find(|p| p.id == id).and_then(|p| p.parent);
            }
            why_removed(&listed, &thread, resolution, Some(&settled), &wholes)
        })
        .collect();
    Ok((removed_comments, removed_why))
}

fn resolve(
    docx: &[u8],
    filter: &ChangeFilter,
    resolution: Resolution,
) -> Result<(Vec<u8>, Vec<String>, usize), ChangeError> {
    resolve_for_edit_or_cli(docx, filter, resolution, None, true)
        .map(|out| (out.document, out.removed, out.comment_left))
}

fn resolve_keeping_comments(
    docx: &[u8],
    filter: &ChangeFilter,
    resolution: Resolution,
) -> Result<ResolvedChanges, ChangeError> {
    let out = resolve_for_edit_or_cli(docx, filter, resolution, Some(true), true)?;
    let document = if out.kept.is_empty() {
        out.document
    } else {
        // Publish the rescued threads on the lowest free comment ids; the
        // receipt keeps the source ids (#1279).
        let mut pkg = open(&out.document)?;
        crate::revision_processor::renumber_rescued_comments(&mut pkg, &out.kept);
        pkg.to_zip()
            .map_err(|e| ChangeError::Package(e.to_string()))?
    };
    let (removed_comments, removed_why) = if out.removed.is_empty() {
        (Vec::new(), Vec::new())
    } else {
        removed_comment_report(docx, &out.removed, filter, resolution)?
    };
    let mut anchors = crate::comment_settlement::AnchorChanges::default();
    anchors.extend(Vec::new(), out.kept, resolution, None);
    let (_removed_records, kept_comments) = anchors
        .records(docx)
        .map_err(|e| ChangeError::Package(e.to_string()))?;
    Ok(ResolvedChanges {
        document,
        removed_comments,
        removed_why,
        comment_changes_left: out.comment_left,
        kept_comments,
    })
}

/// Accept the elements `filter` selects, each `w:ins`, `w:del` or other
/// mark by its own id ([`list_changes`]), even when it is only part of a
/// logical change: for tools that work mark by mark, such as a comparison
/// with Word's own handling of each element. [`accept_changes`] refuses
/// such a selection.
///
/// # Errors
///
/// As [`accept_changes`], but never [`ChangeError::PartOfChange`].
pub fn accept_elements(docx: &[u8], filter: &ChangeFilter) -> Result<Vec<u8>, ChangeError> {
    resolve_for_edit_or_cli(docx, filter, Resolution::Accept, None, false).map(|out| out.document)
}

/// Reject the elements `filter` selects, as [`accept_elements`] accepts
/// them.
///
/// # Errors
///
/// As [`accept_elements`].
pub fn reject_elements(docx: &[u8], filter: &ChangeFilter) -> Result<Vec<u8>, ChangeError> {
    resolve_for_edit_or_cli(docx, filter, Resolution::Reject, None, false).map(|out| out.document)
}

/// Serialized document, pruned comment ids, and rescued comment ids.
type CommentResolution = (Vec<u8>, Vec<String>, Vec<String>);

/// Settlement driven by an edit plan, with stable comment ids and opt-in
/// empty anchors. Removed ids come directly from package pruning.
#[doc(hidden)]
pub fn resolve_for_edit(
    docx: &[u8],
    filter: &ChangeFilter,
    resolution: Resolution,
    keep_comments: bool,
) -> Result<CommentResolution, ChangeError> {
    // The plan's own selection was checked on its source
    // ([`check_whole_changes`]); what is left after its accepts may group
    // differently.
    resolve_for_edit_or_cli(docx, filter, resolution, Some(keep_comments), false)
        .map(|out| (out.document, out.removed, out.kept))
}

fn resolve_for_edit_or_cli(
    docx: &[u8],
    filter: &ChangeFilter,
    resolution: Resolution,
    edit: Option<bool>,
    whole: bool,
) -> Result<ResolutionOutcome, ChangeError> {
    let filter = &filter.normalized()?;
    let mut pkg = open(docx)?;
    let listed = changes_in(&pkg);
    filter.check(&listed)?;
    if whole && filter.ids.is_some() {
        logical::check_whole(filter, &logical_changes_in(&pkg))?;
    }
    // Comment-body revisions are listed as `comments.rN` and selected like
    // every other story (#1706). This count is what a selection leaves in
    // the comments part, including when the part is the only story.
    let comment_changes = comment_changes_in(&pkg);
    // Nothing selected: nothing to resolve, and nothing else to touch.
    if !listed
        .iter()
        .chain(comment_changes.iter())
        .any(|c| filter.matches(c))
    {
        return Ok(ResolutionOutcome {
            document: docx.to_vec(),
            removed: Vec::new(),
            kept: Vec::new(),
            comment_left: comment_changes.len(),
        });
    }
    let main = main_part(&pkg);
    // An edit plan settles accepts, rejects and its global policy in
    // several passes; it judges exposure once, on the settled document
    // ([`check_exposed_final_marks`]).
    let before_marks = edit.is_none().then(|| exposed_final_marks(&pkg, &main));
    let freeze = |part: &str, dom: &mut Dom, root: NodeId| {
        let found = carriers(dom, root, &story_id(&main, part));
        let selected: HashSet<&Group> = found
            .iter()
            .filter(|c| c.change.as_ref().is_some_and(|ch| filter.matches(ch)))
            .map(|c| &c.group)
            .collect();
        let with_rows: HashSet<NodeId> = found
            .iter()
            .filter(|c| selected.contains(&c.group))
            .flat_map(|c| final_marks_of_row(dom, c.node))
            .collect();
        let keep: Vec<NodeId> = found
            .iter()
            .filter(|c| !selected.contains(&c.group) && !with_rows.contains(&c.node))
            .flat_map(|c| {
                std::iter::once(c.node)
                    .chain(deleted_text(dom, c.node))
                    .chain(recorded_marks(dom, c.node))
            })
            .collect();
        for node in keep {
            if let Some(name) = dom.name(node) {
                dom.set_name(node, XName::get(name.local_name(), FROZEN_NS));
            }
        }
    };
    let (removed, kept) = match edit {
        Some(keep) => crate::revision_processor::resolve_package_for_edit(
            &mut pkg,
            resolution,
            Some(&freeze),
            keep,
        ),
        None => (
            resolve_package(&mut pkg, resolution, Some(&freeze)),
            Vec::new(),
        ),
    };
    move_words_past_deleted_tables(&mut pkg, &main);
    if let Some(before) = before_marks {
        newly_exposed(before, exposed_final_marks(&pkg, &main))?;
    }
    // The comment-body revisions a selection left tracked (#1223). The
    // part may be gone when every comment went.
    let comment_left = comment_changes_in(&pkg).len();
    let document = pkg
        .to_zip()
        .map_err(|e| ChangeError::Package(e.to_string()))?;
    Ok(ResolutionOutcome {
        document,
        removed,
        kept,
        comment_left,
    })
}

/// The same revision on the final marks of the cells `carrier` inserts or
/// deletes, when it is a row's (`w:trPr/w:ins`, `w:trPr/w:del`) or a cell's
/// (`w:cellIns`, `w:cellDel`), nested tables' cells included. Word writes a
/// cell's final mark inserted or deleted only with its row, and a row
/// resolved without it leaves the revision on the mark, where Accept All or
/// Reject All never returns (#1669): the two resolve together.
fn final_marks_of_row(dom: &Dom, carrier: NodeId) -> Vec<NodeId> {
    let Some(name) = dom.name(carrier) else {
        return Vec::new();
    };
    let Some(parent) = dom.parent(carrier) else {
        return Vec::new();
    };
    let (kind, top) = match name.local_name() {
        kind @ ("ins" | "del") if dom.name_is(parent, &W::tr_pr()) => (kind, dom.parent(parent)),
        "cellIns" | "cellDel" if dom.name_is(parent, &W::tc_pr()) => (
            if name.local_name() == "cellIns" {
                "ins"
            } else {
                "del"
            },
            dom.parent(parent),
        ),
        _ => return Vec::new(),
    };
    let Some(top) = top else {
        return Vec::new();
    };
    // The cells under `top`, nested tables' too, that no row or cell
    // between them and `top` covers by itself (#1684): `top`'s revision is
    // the one that covers them. A cell of `top` itself that carries the
    // revision (`w:cellIns`, `w:cellDel`) covers its own mark
    // (#1680, round 11).
    let cell_kind = if kind == "ins" {
        W::cell_ins()
    } else {
        W::cell_del()
    };
    let covered_below = |cell: NodeId| {
        let mut cell = cell;
        loop {
            if cell == top {
                return false;
            }
            let Some(&row) = dom.ancestors(cell, Some(&W::tr())).first() else {
                return false;
            };
            if row == top {
                return dom
                    .element(cell, &W::tc_pr())
                    .is_some_and(|pr| dom.element(pr, &cell_kind).is_some());
            }
            if crate::validate_dom::row_revised(dom, row, cell, kind) {
                return true;
            }
            let Some(&outer) = dom.ancestors(row, Some(&W::tc())).first() else {
                return false;
            };
            cell = outer;
        }
    };
    dom.descendants_and_self(top, Some(&W::tc()))
        .into_iter()
        .filter(|&cell| !covered_below(cell))
        .filter_map(|cell| crate::validate_dom::last_block_paragraph(dom, cell))
        .filter_map(|p| dom.element(p, &W::p_pr()))
        .filter_map(|ppr| dom.element(ppr, &W::r_pr()))
        .filter_map(|rpr| dom.element(rpr, &crate::validate_dom::revision_name(kind)))
        .collect()
}

/// Refuse `after` when it holds a final `w:ins` / `w:del` paragraph mark
/// that `before` did not: the check an edit plan runs once its accepts,
/// rejects and global policy have all settled (#1693, #2096).
///
/// # Errors
///
/// [`ChangeError::ExposedFinalMark`] for the first newly exposed mark;
/// [`ChangeError::Package`] when either package cannot be read.
#[doc(hidden)]
pub fn check_exposed_final_marks(before: &[u8], after: &[u8]) -> Result<(), ChangeError> {
    let before = open(before)?;
    let after = open(after)?;
    newly_exposed(
        exposed_final_marks(&before, &main_part(&before)),
        exposed_final_marks(&after, &main_part(&after)),
    )
}

/// The first of `after` that `before` does not account for. Marks are
/// compared as counted keys, not as a set: two cells may carry one `w:id`
/// (or none), and one already final must not hide another newly so.
fn newly_exposed(before: Vec<ExposedMark>, after: Vec<ExposedMark>) -> Result<(), ChangeError> {
    let mut had: HashMap<String, usize> = HashMap::new();
    for mark in before {
        *had.entry(mark.key).or_default() += 1;
    }
    for mark in after {
        match had.get_mut(&mark.key) {
            Some(left) if *left > 0 => *left -= 1,
            _ => {
                return Err(ChangeError::ExposedFinalMark {
                    container: mark.container,
                    path: mark.path,
                    paragraph: mark.paragraph,
                    revision: mark.revision,
                    kind: mark.kind,
                });
            }
        }
    }
    Ok(())
}

/// A final paragraph mark carrying `w:ins` or `w:del` that no row covers.
struct ExposedMark {
    key: String,
    container: &'static str,
    path: String,
    paragraph: String,
    revision: String,
    kind: &'static str,
}

/// Final `w:ins` / `w:del` marks in `pkg`, one per container that ends on
/// them. A cell counts only when its row does not carry the same revision
/// ([`crate::validate_dom::uncovered_final_marks`]). The body's, a header's or
/// footer's, a note's, a text box's and a comment's last paragraph count
/// on their own: Word resolves a body's final mark, so validate does not
/// flag it, and a selective pass still must not create one (#1693). Both
/// branches of an `mc:AlternateContent` are walked. A final `moveTo` or
/// `moveFrom` is not a mark here, and a container whose last block is a
/// table has no final paragraph mark.
fn exposed_final_marks(pkg: &PartFs, main: &str) -> Vec<ExposedMark> {
    let mut out = Vec::new();
    for (part, styles) in revision_bearing_parts(pkg) {
        if styles {
            continue;
        }
        let Some(xml) = pkg.part_string(&part) else {
            continue;
        };
        let mut dom = Dom::new();
        let doc = dom.parse_xdocument(&xml);
        let Some(root) = dom.root(doc) else {
            continue;
        };
        let story = story_id(main, &part);
        let site = |container: &'static str, node: NodeId| MarkSite {
            part: &part,
            story: &story,
            container,
            node,
        };
        dom.for_each_descendant_element(root, Some(&W::tc()), |cell| {
            for (paragraph, kind) in crate::validate_dom::uncovered_final_marks(&dom, cell) {
                record_exposed_mark(&mut out, &dom, &site("cell", cell), paragraph, kind);
            }
        });
        if let Some(body) = dom.element(root, &W::body()) {
            record_container_mark(&mut out, &dom, &site("body", body));
        } else if dom.name_is(root, &W::hdr()) {
            record_container_mark(&mut out, &dom, &site("header", root));
        } else if dom.name_is(root, &W::ftr()) {
            record_container_mark(&mut out, &dom, &site("footer", root));
        }
        for name in [W::footnote(), W::endnote()] {
            dom.for_each_descendant_element(root, Some(&name), |note| {
                // Separators and the continuation notice are not content
                // notes; the story enumeration skips them too.
                let structural = dom.attribute(note, &W::type_()).is_some_and(|kind| {
                    matches!(
                        kind,
                        "separator" | "continuationSeparator" | "continuationNotice"
                    )
                });
                if !structural {
                    record_container_mark(&mut out, &dom, &site("note", note));
                }
            });
        }
        for name in crate::inspect::text_box_names() {
            dom.for_each_descendant_element(root, Some(&name), |text_box| {
                record_container_mark(&mut out, &dom, &site("textbox", text_box));
            });
        }
        dom.for_each_descendant_element(root, Some(&W::comment()), |comment| {
            record_container_mark(&mut out, &dom, &site("comment", comment));
        });
    }
    out
}

/// Where a final mark sits: the part, its story, and the container node.
struct MarkSite<'a> {
    part: &'a str,
    story: &'a str,
    container: &'static str,
    node: NodeId,
}

/// The last block of `site`, when it is a paragraph whose mark is inserted
/// or deleted. A container that ends in a table has no final mark.
fn record_container_mark(out: &mut Vec<ExposedMark>, dom: &Dom, site: &MarkSite<'_>) {
    let Some(&paragraph) = crate::validate_dom::container_blocks(dom, site.node).last() else {
        return;
    };
    if !dom.name_is(paragraph, &W::p()) {
        return;
    }
    for kind in ["ins", "del"] {
        record_exposed_mark(out, dom, site, paragraph, kind);
    }
}

/// Record `paragraph`'s `kind` mark, with or without a `w:id`.
fn record_exposed_mark(
    out: &mut Vec<ExposedMark>,
    dom: &Dom,
    site: &MarkSite<'_>,
    paragraph: NodeId,
    kind: &'static str,
) {
    let Some(revision) = dom
        .element(paragraph, &W::p_pr())
        .and_then(|ppr| dom.element(ppr, &W::r_pr()))
        .and_then(|rpr| dom.element(rpr, &crate::validate_dom::revision_name(kind)))
    else {
        return;
    };
    let wid = dom.attribute(revision, &W::id());
    out.push(ExposedMark {
        key: format!(
            "{}\u{0}{}\u{0}{kind}\u{0}{}",
            site.part,
            site.container,
            wid.unwrap_or_default()
        ),
        container: site.container,
        path: crate::validate::element_path(dom, site.node),
        paragraph: crate::validate::element_path(dom, paragraph),
        revision: wid.map_or_else(
            || "(no w:id)".to_string(),
            |wid| crate::ids::ChangeId::new(site.story, wid).short(),
        ),
        kind,
    });
}

/// The listed changes of the comments part only (empty when the package
/// has none). The same changes are in `changes_in` as `comments.rN`.
pub fn comment_changes_in(pkg: &PartFs) -> Vec<Change> {
    let Some(part) = crate::revision_processor::comments_part(pkg) else {
        return Vec::new();
    };
    let Some(xml) = pkg.part_string(&part) else {
        return Vec::new();
    };
    let mut dom = Dom::new();
    let doc = dom.parse_xdocument(&xml);
    let Some(root) = dom.root(doc) else {
        return Vec::new();
    };
    carriers(&dom, root, "comments")
        .into_iter()
        .filter_map(|c| c.change)
        .collect()
}

/// Serialized document, pruned comment ids, rescued comment ids, and the
/// comment-body revisions a selection left tracked.
struct ResolutionOutcome {
    document: Vec<u8>,
    removed: Vec<String>,
    kept: Vec<String>,
    comment_left: usize,
}

/// The package, Strict normalized to transitional as `inspect` reads it.
#[doc(hidden)]
pub fn open(docx: &[u8]) -> Result<PartFs, ChangeError> {
    crate::admission::admit_package(docx).map_err(|e| ChangeError::Package(e.to_string()))?;
    let normalized = crate::strict_translation::strict_to_transitional_docx(docx)
        .map_err(|e| ChangeError::Package(e.to_string()))?;
    PartFs::open(&normalized).map_err(|e| ChangeError::Package(e.to_string()))
}

/// A selection can leave a paragraph's inserted words right before a
/// deleted table: resolving the deleted mark between them joins the two
/// paragraphs. Word 16.115 crashes opening that shape (#1851), so the words
/// start the paragraph Accept All joins them to, as compare writes them.
/// The story is rewritten only when it holds the shape.
fn move_words_past_deleted_tables(pkg: &mut PartFs, main: &str) {
    let Some(xml) = pkg.part_string(main) else {
        return;
    };
    let mut dom = Dom::new();
    let doc = dom.parse_xdocument(&xml);
    let Some(root) = dom.root(doc) else {
        return;
    };
    let shaped = dom.element(root, &W::body()).is_some_and(|body| {
        !crate::validate_dom::inserted_text_before_deleted_tables(&dom, body).is_empty()
    });
    if shaped {
        crate::comparer::deleted_tables::move_inserted_text_past_deleted_tables(&mut dom, root);
        pkg.set_part(main, dom.serialize_document(doc).into_bytes());
    }
}

fn main_part(pkg: &PartFs) -> String {
    pkg.main_document_part()
        .unwrap_or_else(|| "word/document.xml".to_string())
}

/// `body` for the main part, else the part's file stem (`header1`,
/// `footnotes`, `comments`, `styles`).
fn story_id(main: &str, part: &str) -> String {
    if part.trim_start_matches('/') == main.trim_start_matches('/') {
        return "body".to_string();
    }
    crate::ids::part_story(part)
}

/// The revisions that resolve together: a move's sides and range markers,
/// or one element on its own.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Group {
    Move(String),
    Own(NodeId),
}

/// A revision element: a listed change, or a move range marker.
struct Carrier {
    node: NodeId,
    group: Group,
    change: Option<Change>,
}

/// Formatting changes: each records the properties it replaced.
#[doc(hidden)]
pub const FORMATTING: &[&str] = &[
    "rPrChange",
    "pPrChange",
    "sectPrChange",
    "tblPrChange",
    "tblPrExChange",
    "tblGridChange",
    "trPrChange",
    "tcPrChange",
    "numberingChange",
    "cellMerge",
];

use crate::util::datetime::revision_date;

/// The revision elements under `root`, in document order.
fn carriers(dom: &Dom, root: NodeId, story: &str) -> Vec<Carrier> {
    let id_attr = W::id();
    let name_attr = W::name("name");
    // Open move ranges, innermost last: (range id, move name).
    let mut open_from: Vec<(String, String)> = Vec::new();
    let mut open_to: Vec<(String, String)> = Vec::new();
    let mut out = Vec::new();
    for e in dom.descendants(root, None) {
        let Some(name) = dom.name(e) else {
            continue;
        };
        if name.namespace_name() != W::URI {
            continue;
        }
        let local = name.local_name();
        let id = dom.attribute(e, &id_attr).unwrap_or("").to_string();
        let kind = match local {
            "moveFromRangeStart" | "moveToRangeStart" => {
                let move_name = dom
                    .attribute(e, &name_attr)
                    .map_or_else(|| format!("#{id}"), str::to_string);
                let open = if local == "moveFromRangeStart" {
                    &mut open_from
                } else {
                    &mut open_to
                };
                open.push((id, move_name.clone()));
                out.push(Carrier {
                    node: e,
                    group: Group::Move(move_name),
                    change: None,
                });
                continue;
            }
            "moveFromRangeEnd" | "moveToRangeEnd" => {
                let open = if local == "moveFromRangeEnd" {
                    &mut open_from
                } else {
                    &mut open_to
                };
                let group = match open.iter().rposition(|(i, _)| *i == id) {
                    Some(at) => Group::Move(open.remove(at).1),
                    None => Group::Own(e),
                };
                out.push(Carrier {
                    node: e,
                    group,
                    change: None,
                });
                continue;
            }
            _ if in_recorded_properties(dom, e) => continue,
            "ins" | "cellIns" => ChangeKind::Insertion,
            "del" | "cellDel" => ChangeKind::Deletion,
            "moveFrom" | "moveTo" => ChangeKind::Move,
            l if FORMATTING.contains(&l) => ChangeKind::Formatting,
            _ => continue,
        };
        let target = target(dom, e, local);
        let open = match local {
            "moveFrom" => Some((&open_from, "moveFromRangeStart")),
            "moveTo" => Some((&open_to, "moveToRangeStart")),
            _ => None,
        };
        let move_name = open.and_then(|(open, start)| {
            let enclosing = open.last().map(|(_, n)| n.clone());
            if target == "paragraph_mark" {
                paragraph_move(dom, e, start).or(enclosing)
            } else {
                enclosing
            }
        });
        let text = match target {
            "paragraph_mark" => String::new(),
            "properties" => owner_text(dom, e),
            _ => text_of(dom, e),
        };
        out.push(Carrier {
            node: e,
            group: move_name.clone().map_or(Group::Own(e), Group::Move),
            change: Some(Change {
                id: crate::ids::ChangeId::new(story, id.as_str()).short(),
                r#ref: crate::ids::ChangeId::new(story, id.as_str()).short(),
                kind,
                target,
                author: dom.attribute(e, &W::author()).map(str::to_string),
                date: revision_date(|ns, local| dom.attribute(e, &XName::get(local, ns))),
                text,
                paragraph: None,
                move_name,
                move_side: match local {
                    "moveFrom" => Some(MoveSide::From),
                    "moveTo" => Some(MoveSide::To),
                    _ => None,
                },
                inside: None,
                holds_comments: Vec::new(),
                members: Vec::new(),
            }),
        });
    }
    fold_twins(dom, &mut out);
    fold_style_pairs(dom, &mut out);
    let ids: HashMap<NodeId, String> = out
        .iter()
        .filter_map(|c| Some((c.node, c.change.as_ref()?.id.clone())))
        .collect();
    let paragraphs = (story != "styles").then(|| paragraph_index(dom, root));
    for c in &mut out {
        if let Some(change) = &mut c.change {
            change.holds_comments = held_comment_marks(dom, c.node, change.target);
            change.inside = holder(dom, c.node, &ids);
            change.paragraph = paragraphs
                .as_ref()
                .and_then(|index| paragraph_of(dom, c.node, index))
                .map(|n| crate::ids::paragraph_id(story, n));
        }
    }
    out
}

/// The comments whose reference mark the content of change `e` holds
/// (`c4`, `c5`), in document order: what resolving the change so its
/// content goes removes. A paragraph mark's or formatting change removes
/// no content; a row's or cell's change removes the row's or cell's.
fn held_comment_marks(dom: &Dom, e: NodeId, target: &str) -> Vec<String> {
    let content = match target {
        "text" => Some(e),
        "table_row" => dom.ancestors(e, Some(&W::tr())).first().copied(),
        "table_cell" => dom.ancestors(e, Some(&W::tc())).first().copied(),
        _ => None,
    };
    let mut held = Vec::new();
    for mark in content
        .map(|c| dom.descendants(c, Some(&W::comment_reference())))
        .unwrap_or_default()
    {
        if let Some(id) = dom.attribute(mark, &W::id()) {
            // The comment's own id, as the comment list reads it: a padded
            // `w:id` (`0005`) is comment `c5`.
            let id = match id.parse::<u32>() {
                Ok(number) => format!("c{number}"),
                Err(_) => format!("c{id}"),
            };
            if !held.contains(&id) {
                held.push(id);
            }
        }
    }
    held
}

/// Word stores a text box twice, in an `mc:AlternateContent`'s `mc:Choice`
/// and its `mc:Fallback`, and gives the Fallback copy of each change its own
/// consecutive `w:id`. Each Fallback's carriers pair, in order, with the
/// Choice's still-listed carriers of the same kind, target and text (a
/// carrier the Choice lacks is skipped, not mispaired): the Choice copy (the
/// one the view shows) is listed, and the twin joins its group unlisted, so
/// resolving the change resolves both copies. Inner `mc:AlternateContent`s
/// pair first, so an outer Fallback meets one listed copy of each nested
/// change. A carrier without a partner stays listed.
fn fold_twins(dom: &Dom, carriers: &mut [Carrier]) {
    let (choice, fallback) = (MC::name("Choice"), MC::name("Fallback"));
    // Each listed carrier's mc:Choice / mc:Fallback ancestors.
    let branches: Vec<(usize, Vec<NodeId>)> = carriers
        .iter()
        .enumerate()
        .filter(|(_, c)| c.change.is_some())
        .map(|(i, c)| {
            let mut found = dom.ancestors(c.node, Some(&choice));
            found.extend(dom.ancestors(c.node, Some(&fallback)));
            (i, found)
        })
        .filter(|(_, found)| !found.is_empty())
        .collect();
    let mut fallbacks: Vec<NodeId> = Vec::new();
    for (_, found) in &branches {
        for &b in found {
            if dom.name_is(b, &fallback) && !fallbacks.contains(&b) {
                fallbacks.push(b);
            }
        }
    }
    // Innermost first.
    fallbacks.sort_by_key(|&f| std::cmp::Reverse(dom.ancestors(f, None).len()));
    let key = |c: &Carrier| {
        c.change
            .as_ref()
            .map(|ch| (ch.kind, ch.target, ch.text.clone()))
    };
    for f in fallbacks {
        let Some(partner) = dom.parent(f).and_then(|ac| dom.element(ac, &choice)) else {
            continue;
        };
        let under = |b: NodeId, carriers: &[Carrier]| -> Vec<usize> {
            branches
                .iter()
                .filter(|(i, found)| found.contains(&b) && carriers[*i].change.is_some())
                .map(|(i, _)| *i)
                .collect()
        };
        let originals = under(partner, carriers);
        let mut next = 0;
        for twin in under(f, carriers) {
            let Some(at) = originals[next..]
                .iter()
                .position(|&o| key(&carriers[o]) == key(&carriers[twin]))
            else {
                continue;
            };
            let original = originals[next + at];
            next += at + 1;
            carriers[twin].group = carriers[original].group.clone();
            carriers[twin].change = None;
        }
    }
}

/// Word records a style's paragraph and run formatting changes
/// (`w:style/w:pPr/w:pPrChange`, `w:style/w:rPr/w:rPrChange`) under one
/// `w:id`: one change. The first is listed; the other joins its group
/// unlisted, so resolving it resolves both. Any other record sharing the
/// id (a `w:tblStylePr`'s) stays a change of its own.
fn fold_style_pairs(dom: &Dom, carriers: &mut [Carrier]) {
    let style = W::name("style");
    // The style whose own pPr/rPr holds `node`, a pPrChange or rPrChange.
    let own_style = |node: NodeId| {
        let block = dom.parent(node)?;
        let owner = dom.parent(block)?;
        let pair = [("pPrChange", "pPr"), ("rPrChange", "rPr")];
        let (name, block_name) = (dom.name(node)?, dom.name(block)?);
        let shape = (name.local_name(), block_name.local_name());
        (pair.contains(&shape) && dom.name_is(owner, &style)).then_some(owner)
    };
    let mut first: HashMap<(NodeId, String), Group> = HashMap::new();
    for c in carriers.iter_mut() {
        let Some(change) = &c.change else { continue };
        if change.kind != ChangeKind::Formatting {
            continue;
        }
        let Some(owner) = own_style(c.node) else {
            continue;
        };
        let wid = crate::ids::change_id(&change.id).map_or_else(String::new, |c| c.wid);
        match first.get(&(owner, wid.clone())) {
            Some(group) => {
                c.group = group.clone();
                c.change = None;
            }
            None => {
                first.insert((owner, wid), c.group.clone());
            }
        }
    }
}

/// Each listed paragraph of the story under `root` (the body's or a
/// header's, footer's or notes part's, as `inspect` numbers them) by node.
fn paragraph_index(dom: &Dom, root: NodeId) -> HashMap<NodeId, usize> {
    crate::inspect::story_paragraph_nodes(dom, root)
        .into_iter()
        .enumerate()
        .map(|(i, p)| (p, i))
        .collect()
}

/// The paragraph a revision element sits in: the nearest listed paragraph
/// around it (a text box's paragraphs are not listed, so its anchor's), or
/// the first listed paragraph of the row, cell or table around it.
fn paragraph_of(dom: &Dom, e: NodeId, index: &HashMap<NodeId, usize>) -> Option<usize> {
    let ancestors = dom.ancestors(e, None);
    if let Some(n) = ancestors.iter().find_map(|a| index.get(a)) {
        return Some(*n);
    }
    let holders = [W::tc(), W::tr(), W::tbl()];
    std::iter::once(e)
        .chain(ancestors)
        .filter(|&a| dom.name(a).is_some_and(|n| holders.contains(&n)))
        .find_map(|a| {
            dom.descendants(a, Some(&W::p()))
                .into_iter()
                .find_map(|p| index.get(&p).copied())
        })
}

/// True when `e` sits in the properties a formatting change records: a mark
/// there is history, part of that change.
fn in_recorded_properties(dom: &Dom, e: NodeId) -> bool {
    dom.ancestors(e, None).into_iter().any(|a| {
        dom.name(a)
            .is_some_and(|n| n.namespace_name() == W::URI && FORMATTING.contains(&n.local_name()))
    })
}

/// What a formatting change `e` records: the revision marks inside it (a
/// cell's `w:cellIns`, `w:cellDel` or `w:cellMerge` in its `w:tcPrChange`)
/// and the one formatting history the schema allows there, a list's
/// `w:numberingChange` in its `w:pPrChange`. They sit out with it when it
/// stays tracked, or resolving another change would find them live and drop
/// or apply them.
fn recorded_marks(dom: &Dom, e: NodeId) -> Vec<NodeId> {
    if !dom
        .name(e)
        .is_some_and(|n| FORMATTING.contains(&n.local_name()))
    {
        return Vec::new();
    }
    dom.descendants(e, None)
        .into_iter()
        .filter(|&d| {
            dom.name(d).is_some_and(|n| {
                n.namespace_name() == W::URI
                    && (matches!(
                        n.local_name(),
                        "ins" | "del" | "moveFrom" | "moveTo" | "cellIns" | "cellDel"
                    ) || FORMATTING.contains(&n.local_name()))
            })
        })
        .collect()
}

/// The move a paragraph mark `e` belongs to: the last range of its side
/// (`start`) opening inside its paragraph. Word writes the mark in the
/// `pPr`, ahead of the range start of the paragraph it ends.
fn paragraph_move(dom: &Dom, e: NodeId, start: &str) -> Option<String> {
    let p = dom.ancestors(e, Some(&W::p())).into_iter().next()?;
    dom.descendants(p, Some(&W::name(start)))
        .into_iter()
        .rev()
        .find_map(|r| dom.attribute(r, &W::name("name")).map(str::to_string))
}

/// The id of the innermost change around `e` whose content holds it: an
/// ancestor revision element, the row or cell an ancestor `w:tr` / `w:tc`
/// marks inserted or deleted, or the mark of the paragraph whose `pPr`
/// holds `e` (the paragraph's properties go with its mark).
fn holder(dom: &Dom, e: NodeId, ids: &HashMap<NodeId, String>) -> Option<String> {
    let (tr, tc, p_pr) = (W::tr(), W::tc(), W::p_pr());
    dom.ancestors(e, None).into_iter().find_map(|a| {
        if let Some(id) = ids.get(&a) {
            return Some(id.clone());
        }
        let name = dom.name(a)?;
        let (props, marks): (XName, &[&str]) = if name == tr {
            (W::tr_pr(), &["ins", "del"])
        } else if name == tc {
            (W::tc_pr(), &["cellIns", "cellDel"])
        } else if name == p_pr {
            (W::r_pr(), &["ins", "del", "moveFrom", "moveTo"])
        } else {
            return None;
        };
        let props = dom.element(a, &props)?;
        dom.elements(props, None)
            .into_iter()
            .filter(|&m| m != e)
            .filter(|&m| dom.name(m).is_some_and(|n| marks.contains(&n.local_name())))
            .find_map(|m| ids.get(&m).cloned())
    })
}

fn target(dom: &Dom, e: NodeId, local: &str) -> &'static str {
    if local.starts_with("cell") {
        return "table_cell";
    }
    if FORMATTING.contains(&local) {
        return "properties";
    }
    let parent = dom.parent(e).and_then(|p| dom.name(p));
    let grandparent = dom
        .parent(e)
        .and_then(|p| dom.parent(p))
        .and_then(|g| dom.name(g));
    if parent == Some(W::tr_pr()) {
        "table_row"
    } else if parent == Some(W::r_pr()) && grandparent == Some(W::p_pr()) {
        "paragraph_mark"
    } else {
        "text"
    }
}

/// The `w:delText` / `w:delInstrText` a `w:del` holds itself (not through a
/// nested `w:del`): the resolution rewrites deleted text wherever it sits,
/// so a kept deletion keeps its text only when that text sits out too.
fn deleted_text(dom: &Dom, e: NodeId) -> Vec<NodeId> {
    let del = W::del();
    if dom.name(e).as_ref() != Some(&del) {
        return Vec::new();
    }
    let (text, instr) = (W::del_text(), W::del_instr_text());
    dom.descendants(e, None)
        .into_iter()
        .filter(|&d| dom.name(d).is_some_and(|n| n == text || n == instr))
        .filter(|&d| dom.ancestors(d, Some(&del)).first() == Some(&e))
        .collect()
}

/// Inserted, deleted or moved text under `e`. A tab is `\t` and a break
/// is `\n`, in the same order as the text nodes around them. Only a run's
/// own `w:tab` and `w:br` count: a tab stop (`w:pPr/w:tabs/w:tab`) is
/// layout, not text.
fn text_of(dom: &Dom, e: NodeId) -> String {
    let (t, del, tab, br, run) = (W::t(), W::del_text(), W::name("tab"), W::name("br"), W::r());
    let mut out = String::new();
    dom.for_each_descendant_element(e, None, |node| {
        let Some(name) = dom.name(node) else {
            return;
        };
        let in_run = || dom.parent(node).is_some_and(|p| dom.name_is(p, &run));
        if name == t || name == del {
            out.push_str(&dom.value(node));
        } else if name == tab && in_run() {
            out.push('\t');
        } else if name == br && in_run() {
            out.push('\n');
        }
    });
    out
}

/// The text of the run or paragraph whose properties a change records.
fn owner_text(dom: &Dom, change: NodeId) -> String {
    dom.parent(change)
        .and_then(|props| dom.parent(props))
        .filter(|&owner| dom.name(owner).is_some_and(|n| n == W::r() || n == W::p()))
        .map(|owner| text_of(dom, owner))
        .unwrap_or_default()
}

/// Accept every revision through the processor, rescuing wholly removed
/// comment threads onto empty anchors (#1279). The CLI's
/// `--keep-nested-comment` opt-in on `convert --track-changes accept`.
/// Lives here in the doc layer with the settlement it drives; the
/// facade's `document_comparer` module composes it back.
///
/// # Errors
/// Refused input, an unreadable package or unreadable comment records.
pub fn accept_revisions_keeping_comments(docx: &[u8]) -> Result<ResolvedChanges, ChangeError> {
    accept_changes_keeping_comments(docx, &ChangeFilter::default())
}

/// Reject every revision through the processor, rescuing wholly removed
/// comment threads onto empty anchors (#1279). The CLI's
/// `--keep-nested-comment` opt-in on `convert --track-changes reject`.
///
/// # Errors
/// As [`accept_revisions_keeping_comments`].
pub fn reject_revisions_keeping_comments(docx: &[u8]) -> Result<ResolvedChanges, ChangeError> {
    reject_changes_keeping_comments(docx, &ChangeFilter::default())
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod run_character_tests {
    use super::*;

    fn run(inner: &str) -> bool {
        let xml = format!(
            "<w:r xmlns:w=\"{}\" xmlns:x=\"urn:x\">{inner}</w:r>",
            W::URI
        );
        let mut dom = Dom::new();
        let doc = dom.parse_xdocument(&xml);
        let root = dom.root(doc).unwrap();
        run_has_characters(&dom, root)
    }

    #[test]
    fn a_run_has_characters_only_outside_its_properties() {
        assert!(!run(""));
        assert!(!run("<w:rPr><w:t>hidden</w:t></w:rPr>"));
        assert!(!run("<w:t></w:t><w:delText></w:delText>"));
        assert!(run("<w:delText>x</w:delText>"));
        assert!(run("<w:tab/>"));
        // A foreign wrapper is looked into; a foreign rPr is not properties.
        assert!(run("<x:wrap><w:t>x</w:t></x:wrap>"));
        assert!(run("<x:rPr><w:t>x</w:t></x:rPr>"));
        assert!(!run("<w:lastRenderedPageBreak/>"));
        assert_eq!(atom(&XName::get("tab", "urn:x")), None);
        assert_eq!(atom(&W::name("sym")), Some('\u{FFFD}'));
    }
}