jubarte-markdown 0.20.0

Markdown in and out of Word documents for the jubarte engine: CriticMarkup as tracked changes, the agent view, and .doc reading
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! The style legend an agent view's YAML header prints, read back:
//!
//! ```yaml
//! styles:
//!   Normal: Times New Roman 11pt, after 6pt, line 12pt atLeast, left  # default; …
//!   "#": Heading1, Times New Roman bold 24pt, before 24pt, keep-next
//! ```
//!
//! The default paragraph style's line gives its whole look: font, bold and
//! italic, size, spacing before and after (none printed is none), line
//! spacing (none printed is single), keep-next, keep-lines, a paragraph
//! indent (`indent 0.5in`, and `first-line`, `hanging` or `right` when set),
//! contextual spacing and alignment. A heading's line names its style, its
//! font, size, bold and italic, and only the spacing, keep-next, keep-lines,
//! indent, contextual spacing and alignment that differ from the default
//! style's, which it is based on. Every other paragraph style the body uses
//! follows, keyed by its id, described like a heading (`TOC2: Arial 12pt,
//! after 6pt`). A line ends `, named Text Heading 2` when the style's name
//! is not its id (for a heading `HeadingN`, not `heading N`). A character
//! style a story paragraph names leads with `character` (`LineNumber:
//! character, Calibri 11pt, named line number`), and the writer rebuilds a
//! `w:type="character"` style for it.
//!
//! The writer sets a property only when the legend's value differs from
//! what the style already inherits: document defaults for the default and
//! character styles, and the default paragraph style for other paragraph styles.
//! The default style's spacing is written as the document default itself
//! (`w:pPrDefault`), where Word keeps it.

use std::fmt::Write as _;

use super::from_docx::Element;
use super::xml::{FormatMark, StyleChangeKind, escape};

/// `styles` with one tracked change per property the view's
/// `style_changes:` names. A paragraph tag writes `w:pPrChange` and a run
/// tag writes `w:rPrChange`; the first tag of each kind wins, and an
/// existing carrier of that kind is replaced. `docDefaults` and `other`
/// are not written: the schema has no slot for them. Each written carrier
/// holds empty previous properties, because the view names no payload. A
/// holder the part has no style of is left out. When nothing is written
/// the part's bytes stay as they were.
pub(super) fn with_style_changes(
    styles: &str,
    changes: &[(String, Vec<(StyleChangeKind, FormatMark)>)],
) -> String {
    let mut out = styles.to_string();
    for (holder, marks) in changes {
        if holder == "docDefaults" {
            continue;
        }
        let paragraph = marks
            .iter()
            .find(|(kind, _)| *kind == StyleChangeKind::Paragraph)
            .map(|(_, mark)| mark);
        let run = marks
            .iter()
            .find(|(kind, _)| *kind == StyleChangeKind::Run)
            .map(|(_, mark)| mark);
        if paragraph.is_none() && run.is_none() {
            continue;
        }
        let key = format!("w:styleId=\"{}\"", escape(holder));
        let Some(at) = out.find(&key) else {
            continue;
        };
        let Some(end) = out[at..].find("</w:style>").map(|i| at + i) else {
            continue;
        };
        let mut block = out[at..end].to_string();
        // The style's own `w:pPr` and `w:rPr`: the `w:rPr` a `w:pPr`
        // holds is the paragraph mark's (`CT_ParaRPr`), and `CT_Style`
        // puts the style's own after the `w:pPr`.
        if let Some(mark) = paragraph {
            place(&mut block, "pPr", &carrier(mark, "pPr"));
        }
        if let Some(mark) = run {
            place(&mut block, "rPr", &carrier(mark, "rPr"));
        }
        out.replace_range(at..end, &block);
    }
    out
}

/// Warnings for the marks the writer drops: extra tags of one kind, an
/// `other` tag, a legacy tag with no kind, and every `docDefaults` tag.
pub(super) fn style_change_warnings(
    changes: &[(String, Vec<(StyleChangeKind, FormatMark)>)],
    legacy: &[(String, Vec<String>)],
) -> Vec<String> {
    let mut out = Vec::new();
    for (holder, tags) in legacy {
        // The defaults are never written; their own warning below says so.
        if tags.is_empty() || holder == "docDefaults" {
            continue;
        }
        let verb = if tags.len() == 1 { "has" } else { "have" };
        out.push(format!(
            "style_changes: {holder}: {} {verb} no kind; written as rPr",
            tags.join("; ")
        ));
    }
    for (holder, marks) in changes {
        if holder == "docDefaults" {
            let count = marks.len();
            if count == 1 {
                out.push(
                    "style_changes: docDefaults: the document defaults have no change slot; 1 change is not written"
                        .to_string(),
                );
            } else if count > 1 {
                out.push(format!(
                    "style_changes: docDefaults: the document defaults have no change slot; {count} changes are not written"
                ));
            }
            continue;
        }
        let paragraph = marks
            .iter()
            .filter(|(kind, _)| *kind == StyleChangeKind::Paragraph)
            .count();
        let run = marks
            .iter()
            .filter(|(kind, _)| *kind == StyleChangeKind::Run)
            .count();
        let other = marks
            .iter()
            .filter(|(kind, _)| *kind == StyleChangeKind::Other)
            .count();
        if paragraph > 1 {
            out.push(format!(
                "style_changes: {holder}: {paragraph} pPr changes for one slot; the rest are not written"
            ));
        }
        if run > 1 {
            out.push(format!(
                "style_changes: {holder}: {run} rPr changes for one slot; the rest are not written"
            ));
        }
        if other == 1 {
            out.push(format!(
                "style_changes: {holder}: 1 other change is not written"
            ));
        } else if other > 1 {
            out.push(format!(
                "style_changes: {holder}: {other} other changes are not written"
            ));
        }
    }
    out
}

fn carrier(mark: &FormatMark, inner: &str) -> String {
    let date = super::xml::date_attribute(&mark.date);
    let id = mark
        .id
        .map_or_else(String::new, |id| format!(" w:id=\"{id}\""));
    format!(
        "<w:{inner}Change{id} w:author=\"{}\"{date}><w:{inner}/></w:{inner}Change>",
        escape(&mark.author)
    )
}

/// One carrier, last in the style's own property element. An existing
/// direct carrier of that kind is replaced, nested closes and all. A
/// missing `w:pPr` is created before the style's `w:rPr`.
fn place(block: &mut String, property: &str, change: &str) {
    match if property == "pPr" {
        own_ppr(block)
    } else {
        own_rpr(block)
    } {
        Some(own) if own.empty() => {
            block.replace_range(
                own.start..own.end,
                &format!("<w:{property}>{change}</w:{property}>"),
            );
        }
        Some(own) => {
            if let Some(span) = direct_child_span(block, &own, &format!("{property}Change")) {
                block.replace_range(span, change);
            } else if let Some(close) = own.close {
                block.insert_str(close, change);
            }
        }
        None if property == "pPr" => {
            let at = own_rpr(block).map_or(block.len(), |run| run.start);
            block.insert_str(at, &format!("<w:pPr>{change}</w:pPr>"));
        }
        None => block.push_str(&format!("<w:rPr>{change}</w:rPr>")),
    }
}

/// Where an element's start tag lies.
struct OpenTag {
    start: usize,
    /// Just past its `>`.
    end: usize,
    /// `<w:name/>`, which holds nothing.
    empty: bool,
}

/// The first `<w:name …>` start tag in `range` of `xml`, attributes and
/// all; `<w:nameMore` is another element.
fn open_tag(xml: &str, name: &str, range: std::ops::Range<usize>) -> Option<OpenTag> {
    let tag = format!("<w:{name}");
    let mut from = range.start;
    while let Some(at) = xml[from..range.end].find(&tag).map(|i| from + i) {
        let after = at + tag.len();
        if xml[after..].starts_with([' ', '>', '/', '\t', '\n', '\r']) {
            let end = after + xml[after..].find('>')? + 1;
            return Some(OpenTag {
                start: at,
                end,
                empty: xml[..end - 1].ends_with('/'),
            });
        }
        from = after;
    }
    None
}

/// One element of a style the view writes a change into, and where that
/// change goes: before the element's close tag, which is where each
/// schema puts its change (`w:pPrChange` last in `CT_PPr`, `w:rPrChange`
/// last in `CT_RPr`).
struct Own {
    start: usize,
    end: usize,
    /// The close tag's own start; `None` for `<w:name/>`, which a change
    /// replaces whole.
    close: Option<usize>,
}

impl Own {
    /// Whether the change replaces the element rather than joining it.
    fn empty(&self) -> bool {
        self.close.is_none()
    }
}

/// The first `<w:name>` element in `block` from `from`, with where its
/// change goes. The element nests: a `w:pPrChange` holds the previous
/// properties in a `w:pPr` of their own.
fn own(block: &str, name: &str, from: usize) -> Option<Own> {
    let open = open_tag(block, name, from..block.len())?;
    if open.empty {
        return Some(Own {
            start: open.start,
            end: open.end,
            close: None,
        });
    }
    let close = close_at(block, name, open.end)?;
    let tag = format!("</w:{name}>");
    Some(Own {
        start: open.start,
        end: close + tag.len(),
        close: Some(close),
    })
}

/// Where the `<w:name>` element that opens just before `open_end` closes:
/// the closes nest, so every open before a close counts unless it is an
/// empty element, which holds nothing.
fn close_at(block: &str, name: &str, open_end: usize) -> Option<usize> {
    let tag = format!("</w:{name}>");
    let mut depth = 1usize;
    let mut at = open_end;
    while let Some(close) = block[at..].find(&tag).map(|i| i + at) {
        depth += usize::from(open_tag(block, name, at..close).is_some_and(|open| !open.empty));
        depth = depth.checked_sub(1)?;
        if depth == 0 {
            return Some(close);
        }
        at = close + tag.len();
    }
    None
}

/// The style's own `w:pPr`: the first one, never the previous properties a
/// `w:pPrChange` holds.
fn own_ppr(block: &str) -> Option<Own> {
    own(block, "pPr", 0)
}

/// The style's own `w:rPr`: `CT_Style` puts it after the `w:pPr`, and the
/// `w:rPr` a `w:pPr` holds is the paragraph mark's (`CT_ParaRPr`), not
/// the style's (#1595 review).
fn own_rpr(block: &str) -> Option<Own> {
    own(block, "rPr", own_ppr(block).map_or(0, |ppr| ppr.end))
}

/// The first direct child named `local` inside `own`, including a nested
/// payload. A carrier inside that payload is not this child.
fn direct_child_span(block: &str, own: &Own, local: &str) -> Option<std::ops::Range<usize>> {
    let open_end = own.start + block[own.start..].find('>')? + 1;
    let close = own.close?;
    let mut at = open_end;
    while at < close {
        let rest = &block[at..close];
        let Some(rel) = rest.find('<') else {
            break;
        };
        let start = at + rel;
        if block.as_bytes().get(start + 1) == Some(&b'/') {
            break;
        }
        let tag_end = start + block[start..close].find('>')?;
        let raw = &block[start + 1..tag_end];
        let empty = raw.ends_with('/');
        let token = raw.trim_end_matches('/').split_whitespace().next()?;
        let name = token.rsplit(':').next().unwrap_or(token);
        let element_end = if empty {
            tag_end + 1
        } else {
            let close_at = close_at(block, name, tag_end + 1)?;
            close_at + format!("</w:{name}>").len()
        };
        if name == local {
            return Some(start..element_end);
        }
        at = element_end;
    }
    None
}

/// One style the legend describes.
#[derive(Clone, Debug, PartialEq)]
#[doc(hidden)]
pub struct StyleSpec {
    pub id: String,
    /// The style's name, when the legend gives one (`, named …`).
    pub name: Option<String>,
    /// A character style: the legend's first clause names the kind
    /// (`LineNumber: character, Calibri 11pt`).
    pub character: bool,
    /// The `#` count for a heading.
    pub heading: Option<u32>,
    /// The default paragraph style, which other paragraph styles are based on.
    pub default: bool,
    pub font: String,
    pub bold: bool,
    pub italic: bool,
    /// Half points.
    pub size: u32,
    /// Twips.
    pub before: Option<u32>,
    pub after: Option<u32>,
    /// Twips with `exact` or `atLeast`, or 240ths of a line with `auto`.
    pub line: Option<(u32, &'static str)>,
    pub keep_next: bool,
    pub keep_lines: bool,
    /// Left indent, twips.
    pub left: Option<i64>,
    /// Right indent, twips.
    pub right: Option<i64>,
    /// First-line indent, twips.
    pub first_line: Option<i64>,
    /// Hanging indent, twips.
    pub hanging: Option<i64>,
    pub contextual_spacing: bool,
    pub align: Option<&'static str>,
}

/// The largest font size and spacing the legend can set: Word's 1638pt.
const MOST_POINTS: f64 = 1638.0;

fn points(value: &str, scale: f64) -> Option<u32> {
    let n: f64 = value.strip_suffix("pt")?.parse().ok()?;
    // `as` cannot overflow: the bound is checked first.
    (n.is_finite() && (0.0..=MOST_POINTS).contains(&n)).then(|| (n * scale).round() as u32)
}

/// `0.5in` as twips. Word's indent is at most 22in (31680 twips) either way.
pub(super) fn twips_in(value: &str) -> Option<i64> {
    let n: f64 = value.strip_suffix("in")?.parse().ok()?;
    if !n.is_finite() {
        return None;
    }
    let twips = (n * 1440.0).round();
    // `as` cannot overflow: the bound is checked first.
    (twips.is_finite() && twips.abs() <= 31680.0).then_some(twips as i64)
}

/// `Times New Roman bold italic 11pt`: the font, bold, italic and size.
fn font_clause(clause: &str) -> Option<(String, bool, bool, u32)> {
    let (rest, size) = clause.rsplit_once(' ')?;
    let size = points(size, 2.0)?;
    let mut rest = rest;
    let mut italic = false;
    let mut bold = false;
    if let Some(r) = rest.strip_suffix(" italic") {
        italic = true;
        rest = r;
    }
    if let Some(r) = rest.strip_suffix(" bold") {
        bold = true;
        rest = r;
    }
    (!rest.is_empty()).then(|| (rest.to_string(), bold, italic, size))
}

/// The style a legend value describes; `heading` is the `#` count.
fn spec(id: &str, heading: Option<u32>, default: bool, value: &str) -> Option<StyleSpec> {
    let (value, name) = match value.rsplit_once(", named ") {
        Some((value, name)) => (value, Some(name.to_string())),
        None => (value, None),
    };
    let mut clauses = value.split(", ").peekable();
    // A character style leads with its kind, before the look. The default
    // style is a paragraph one: for it, `character` is no clause we know.
    let character = !default && clauses.next_if(|c| *c == "character").is_some();
    let (font, bold, italic, size) = font_clause(clauses.next()?)?;
    let mut spec = StyleSpec {
        id: id.to_string(),
        name,
        character,
        heading,
        default,
        font,
        bold,
        italic,
        size,
        before: None,
        after: None,
        line: None,
        keep_next: false,
        keep_lines: false,
        left: None,
        right: None,
        first_line: None,
        hanging: None,
        contextual_spacing: false,
        align: None,
    };
    for clause in clauses {
        match clause.split_once(' ') {
            Some(("before", v)) => spec.before = Some(points(v, 20.0)?),
            Some(("after", v)) => spec.after = Some(points(v, 20.0)?),
            Some(("indent", v)) => spec.left = Some(twips_in(v)?),
            // `right` alone is the alignment; with a value, the indent.
            Some(("right", v)) => spec.right = Some(twips_in(v)?),
            Some(("first-line", v)) => spec.first_line = Some(twips_in(v)?),
            Some(("hanging", v)) => spec.hanging = Some(twips_in(v)?),
            Some(("contextual", "spacing")) => spec.contextual_spacing = true,
            Some(("line", v)) => {
                spec.line = Some(match v.split_once(' ') {
                    Some((height, "exact")) => (points(height, 20.0)?, "exact"),
                    Some((height, "atLeast")) => (points(height, 20.0)?, "atLeast"),
                    Some(_) => return None,
                    None => {
                        let ratio: f64 = v.parse().ok()?;
                        if !(ratio.is_finite() && (0.0..=132.0).contains(&ratio)) {
                            return None;
                        }
                        // `as` cannot overflow: the bound is checked first.
                        ((ratio * 240.0).round() as u32, "auto")
                    }
                });
            }
            None if clause == "keep-next" => spec.keep_next = true,
            None if clause == "keep-lines" => spec.keep_lines = true,
            None => {
                spec.align = Some(match clause {
                    "left" => "left",
                    "center" => "center",
                    "right" => "right",
                    "justify" => "both",
                    _ => return None,
                });
            }
            Some(_) => return None,
        }
    }
    Some(spec)
}

/// `line` without the comment the view prints after a value: a `#` after
/// two spaces, outside a quoted string (`text: "ACME  #1"` keeps its
/// `#`; so does `title: Issue #5`).
pub(super) fn without_comment(line: &str) -> &str {
    let mut quoted = false;
    let mut escaped = false;
    let mut spaces = 0;
    for (at, c) in line.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' if quoted => escaped = true,
            '"' => quoted = !quoted,
            '#' if spaces >= 2 && !quoted => return &line[..at],
            _ => {}
        }
        spaces = if c == ' ' { spaces + 1 } else { 0 };
    }
    line
}

/// A YAML scalar as the legend prints it: plain, or a JSON string.
fn unquote(value: &str) -> Option<String> {
    if value.starts_with('"') {
        serde_json::from_str(value).ok()
    } else {
        Some(value.to_string())
    }
}

/// A table style's borders as its legend entry states them.
#[derive(Clone, Debug, PartialEq)]
#[doc(hidden)]
pub enum TableBorders {
    /// `all borders 0.5pt`: every side one single line of this size, in
    /// eighths of a point.
    All(u32),
    /// `borders bottom double 0.75pt`: each side the style sets, in Word's
    /// order (top, left, bottom, right, insideH, insideV).
    Sides(Vec<BorderSide>),
}

/// One side of a `borders …` clause: `top single 1.5pt #FF0000 space 2pt`.
#[derive(Clone, Debug, PartialEq)]
#[doc(hidden)]
pub struct BorderSide {
    /// `top`, `left`, `bottom`, `right`, `insideH` or `insideV`.
    pub side: String,
    /// The `w:val`: `single`, `double`, `nil`, …
    pub val: String,
    /// The `w:sz`, in eighths of a point.
    pub size: Option<u32>,
    /// The `w:color` when it is not `auto`.
    pub color: Option<String>,
    /// The `w:space`, in points, when it is not zero.
    pub space: Option<u32>,
}

/// The sides a table style's `w:tblBorders` holds, in the order Word's
/// schema puts them.
pub(crate) const TABLE_BORDER_SIDES: [&str; 6] =
    ["top", "left", "bottom", "right", "insideH", "insideV"];

/// A `borders …` clause's sides (`borders bottom double 0.75pt`): a side
/// name, its value, then a size in points, a `#RRGGBB` colour and a
/// `space Npt`, each optional. A side the grammar does not know, or one
/// named twice, reads as no clause.
fn border_sides(clause: &str) -> Option<Vec<BorderSide>> {
    let mut tokens = clause.strip_prefix("borders ")?.split(' ').peekable();
    let mut sides: Vec<BorderSide> = Vec::new();
    while let Some(side) = tokens.next() {
        if !TABLE_BORDER_SIDES.contains(&side) || sides.iter().any(|s| s.side == side) {
            return None;
        }
        let val = tokens
            .next()
            .filter(|v| !v.is_empty() && v.chars().all(|c| c.is_ascii_alphanumeric()))?;
        let mut border = BorderSide {
            side: side.to_string(),
            val: val.to_string(),
            size: None,
            color: None,
            space: None,
        };
        while let Some(&token) = tokens.peek() {
            if TABLE_BORDER_SIDES.contains(&token) {
                break;
            }
            tokens.next();
            if let Some(pt) = token.strip_suffix("pt").filter(|_| border.size.is_none()) {
                let pt = pt
                    .parse::<f64>()
                    .ok()
                    .filter(|pt| (0.0..=255.0).contains(pt))?;
                border.size = Some((pt * 8.0).round() as u32);
            } else if let Some(hex) = token.strip_prefix('#').filter(|_| border.color.is_none()) {
                (hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit())).then_some(())?;
                border.color = Some(hex.to_string());
            } else if token == "space" && border.space.is_none() {
                let pt = tokens.next()?.strip_suffix("pt")?.parse::<u32>().ok()?;
                border.space = Some(pt);
            } else {
                return None;
            }
        }
        sides.push(border);
    }
    (!sides.is_empty()).then_some(sides)
}

/// The legend's `table:` style, which every table takes: its id, the
/// borders its entry states and the name it gives the style.
pub(super) fn table_style(yaml: &str) -> Option<(String, Option<TableBorders>, Option<String>)> {
    legend_line(yaml, "table: ")
        .as_deref()
        .and_then(table_style_entry)
        .map(|(entry, _)| entry)
}

/// The `tables:` legend's entries, keyed by their style id: the styles of
/// a document whose tables differ, each with the border and the name its
/// entry states.
pub(super) fn table_legend(
    yaml: &str,
) -> std::collections::BTreeMap<String, (Option<TableBorders>, Option<String>)> {
    let mut out = std::collections::BTreeMap::new();
    let Some(value) = legend_line(yaml, "tables: ") else {
        return out;
    };
    let mut rest = value.as_str();
    while let Some(((id, border, name), next)) = table_style_entry(rest) {
        out.insert(id, (border, name));
        rest = next;
    }
    out
}

/// The `styles:` block's `key: ` line's value, unwrapped from its YAML
/// quoting: `table: X, named My X`'s, `tables: …`'s.
fn legend_line(yaml: &str, key: &str) -> Option<String> {
    let mut inside = false;
    for line in yaml.lines() {
        if !line.starts_with(' ') {
            inside = line.trim_end() == "styles:";
            continue;
        }
        if let Some(value) = without_comment(line)
            .trim()
            .strip_prefix(key)
            .filter(|_| inside)
            .and_then(|v| unquote(v.trim()))
        {
            return Some(value);
        }
    }
    None
}

/// One `table:`/`tables:` entry — `X, all borders 0.5pt, named My X` —
/// its id, the border it states and the name it gives the style, with
/// the rest of the line after it (the `tables:` legend holds one entry
/// per style). A clause that is none of the grammar's ends the entry.
type TableStyleEntry = (String, Option<TableBorders>, Option<String>);

fn table_style_entry(value: &str) -> Option<(TableStyleEntry, &str)> {
    let (id, mut rest) = take_clause(value);
    let id = unquote(id.trim()).filter(|id| !id.is_empty())?;
    let mut border = None;
    let mut name = None;
    while !rest.is_empty() {
        let (clause, next) = take_clause(rest);
        if border.is_none()
            && let Some(pt) = clause
                .strip_prefix("all borders ")
                .and_then(|pt| pt.strip_suffix("pt"))
                .and_then(|pt| pt.parse::<f64>().ok())
                .filter(|pt| (0.25..=6.0).contains(pt))
        {
            border = Some(TableBorders::All((pt * 8.0).round() as u32));
        } else if border.is_none()
            && let Some(sides) = border_sides(&clause)
        {
            border = Some(TableBorders::Sides(sides));
        } else if name.is_none()
            && let Some(named) = clause
                .strip_prefix("named ")
                .and_then(|named| unquote(named.trim()))
        {
            name = Some(named);
        } else if clause != "borders vary" {
            return Some(((id, border, name), rest));
        }
        rest = next;
    }
    Some(((id, border, name), ""))
}

/// The value's first `, `-separated clause, a quoted one whole (a `"`
/// opens a JSON string, whose `, ` is the name's own), and what follows
/// the separator.
fn take_clause(value: &str) -> (String, &str) {
    let (mut quoted, mut escaped) = (false, false);
    for (i, c) in value.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' if quoted => escaped = true,
            '"' => quoted = !quoted,
            ',' if !quoted && value[i + 1..].starts_with(' ') => {
                return (value[..i].to_string(), &value[i + 2..]);
            }
            _ => {}
        }
    }
    (value.to_string(), "")
}

pub(super) fn legend(yaml: &str) -> Vec<StyleSpec> {
    let mut specs = Vec::new();
    let mut inside = false;
    for line in yaml.lines() {
        if !line.starts_with(' ') {
            inside = line.trim_end() == "styles:";
            continue;
        }
        if !inside {
            continue;
        }
        // A YAML comment (`  # …`) is no part of the value.
        let line = without_comment(line).trim();
        let Some((key, value)) = line.split_once(": ") else {
            continue;
        };
        let (Some(key), Some(value)) = (unquote(key), unquote(value.trim())) else {
            continue;
        };
        let spec = if key.bytes().all(|b| b == b'#') {
            let level = u32::try_from(key.len())
                .ok()
                .filter(|n| (1..=6).contains(n));
            level.and_then(|level| {
                let (id, rest) = value.split_once(", ")?;
                spec(&unquote(id)?, Some(level), false, rest)
            })
        } else if matches!(key.as_str(), "table" | "tables" | "changes") {
            None
        } else {
            let default = !specs.iter().any(|s: &StyleSpec| s.default);
            spec(&key, None, default, &value)
        };
        specs.extend(spec);
    }
    specs
}

/// `styles` (a styles part) with each style of `specs` defined as the
/// legend describes it, in place of its own definition. A default style
/// other than `Normal` takes the default from the part's own.
pub(super) fn apply(styles: &str, specs: &[StyleSpec]) -> String {
    let mut defaults = document_defaults(styles);
    let mut out = styles.to_string();
    let base = specs.iter().find(|s| s.default);
    let from_base = base.map(effective);
    if let Some(look) = &from_base {
        out = out.replace(
            "w:type=\"paragraph\" w:default=\"1\"",
            "w:type=\"paragraph\"",
        );
        // The default style's spacing is the document's default, as Word
        // keeps it: a table style's own spacing wins over `docDefaults` in
        // its cells, and would not over the default style's (ISO/IEC 29500
        // style precedence).
        with_default_spacing(&mut out, look);
        defaults.before = look.before;
        defaults.after = look.after;
        defaults.line_twips = look.line_twips;
        defaults.line_rule.clone_from(&look.line_rule);
    }
    for spec in specs {
        out = without_style(&out, &spec.id);
        let inherited = if spec.default || spec.character {
            &defaults
        } else {
            from_base.as_ref().unwrap_or(&defaults)
        };
        // Word ignores a basedOn that names a different kind of style
        // (ISO/IEC 29500, basedOn). Character styles therefore use
        // docDefaults and write their run properties against those.
        let parent = base.filter(|_| !spec.character).map(|b| b.id.as_str());
        let definition = definition(spec, parent, inherited);
        if let Some(at) = out.rfind("</w:styles>") {
            out.insert_str(at, &definition);
        }
    }
    out
}

/// The `w:pPr` children CT_PPrBase puts after `w:spacing`.
const AFTER_SPACING: [&str; 11] = [
    "ind",
    "contextualSpacing",
    "mirrorIndents",
    "suppressOverlap",
    "jc",
    "textDirection",
    "textAlignment",
    "textboxTightWrap",
    "outlineLvl",
    "divId",
    "cnfStyle",
];

/// `out` with `look`'s spacing as the document's paragraph default
/// (`w:docDefaults/w:pPrDefault/w:pPr/w:spacing`) in place of the spacing
/// it had, each element made where the part lacks it: `w:docDefaults`
/// first in `w:styles`, `w:pPrDefault` after `w:rPrDefault`, the spacing
/// where CT_PPrBase puts it. A part with no `w:styles` takes nothing.
fn with_default_spacing(out: &mut String, look: &Given) {
    let mut spacing = String::from("<w:spacing");
    if look.before > 0 {
        let _ = write!(spacing, " w:before=\"{}\"", look.before);
    }
    let _ = write!(
        spacing,
        " w:after=\"{}\" w:line=\"{}\" w:lineRule=\"{}\"/>",
        look.after, look.line_twips, look.line_rule
    );
    let ppr = format!("<w:pPr>{spacing}</w:pPr>");
    let default = format!("<w:pPrDefault>{ppr}</w:pPrDefault>");
    let Some(defaults) = open_tag(out, "docDefaults", 0..out.len()) else {
        if let Some(styles) = open_tag(out, "styles", 0..out.len()).filter(|t| !t.empty) {
            out.insert_str(
                styles.end,
                &format!("<w:docDefaults>{default}</w:docDefaults>"),
            );
        }
        return;
    };
    if defaults.empty {
        out.replace_range(
            defaults.start..defaults.end,
            &format!("<w:docDefaults>{default}</w:docDefaults>"),
        );
        return;
    }
    let Some(close) = out[defaults.end..]
        .find("</w:docDefaults>")
        .map(|at| defaults.end + at)
    else {
        return;
    };
    let Some(ppr_default) = open_tag(out, "pPrDefault", defaults.end..close) else {
        out.insert_str(close, &default);
        return;
    };
    if ppr_default.empty {
        out.replace_range(ppr_default.start..ppr_default.end, &default);
        return;
    }
    let Some(default_close) = out[ppr_default.end..close]
        .find("</w:pPrDefault>")
        .map(|at| ppr_default.end + at)
    else {
        return;
    };
    let Some(own) = open_tag(out, "pPr", ppr_default.end..default_close) else {
        out.insert_str(ppr_default.end, &ppr);
        return;
    };
    if own.empty {
        out.replace_range(own.start..own.end, &ppr);
        return;
    }
    let Some(mut own_close) = out[own.end..default_close]
        .rfind("</w:pPr>")
        .map(|at| own.end + at)
    else {
        return;
    };
    if let Some(old) = open_tag(out, "spacing", own.end..own_close) {
        let end = if old.empty {
            old.end
        } else {
            out[old.end..own_close]
                .find("</w:spacing>")
                .map_or(old.end, |at| old.end + at + "</w:spacing>".len())
        };
        out.replace_range(old.start..end, "");
        own_close -= end - old.start;
    }
    let at = AFTER_SPACING
        .iter()
        .filter_map(|name| open_tag(out, name, own.end..own_close).map(|t| t.start))
        .min()
        .unwrap_or(own_close);
    out.insert_str(at, &spacing);
}

/// `styles` without the definition of style `id`.
fn without_style(styles: &str, id: &str) -> String {
    let key = format!("w:styleId=\"{}\"", escape(id));
    let mut out = String::with_capacity(styles.len());
    let mut rest = styles;
    while let Some(at) = rest.find("<w:style ") {
        let Some(tag_end) = rest[at..].find('>').map(|i| at + i) else {
            break;
        };
        let Some(end) = rest[tag_end..].find("</w:style>").map(|i| tag_end + i + 10) else {
            break;
        };
        out.push_str(&rest[..at]);
        if !rest[at..tag_end].contains(&key) {
            out.push_str(&rest[at..end]);
        }
        rest = &rest[end..];
    }
    out.push_str(rest);
    out
}

/// What a style already inherits, so a property equal to it is not written.
struct Given {
    font: Option<String>,
    size: Option<u32>,
    bold: bool,
    italic: bool,
    before: u32,
    after: u32,
    line_twips: u32,
    line_rule: String,
    align: String,
    keep_next: bool,
    keep_lines: bool,
    contextual: bool,
    left: Option<i64>,
    right: Option<i64>,
    first_line: Option<i64>,
    hanging: Option<i64>,
}

impl Given {
    /// Word's own values when `docDefaults` names nothing.
    fn implicit() -> Self {
        Self {
            font: None,
            size: None,
            bold: false,
            italic: false,
            before: 0,
            after: 0,
            line_twips: 240,
            line_rule: "auto".to_string(),
            align: "left".to_string(),
            keep_next: false,
            keep_lines: false,
            contextual: false,
            left: None,
            right: None,
            first_line: None,
            hanging: None,
        }
    }
}

/// The legend's value for the default style: an omitted spacing is zero or
/// single, an omitted alignment is left, and an omitted indent is none.
fn effective(spec: &StyleSpec) -> Given {
    let (line_twips, line_rule) = spec.line.unwrap_or((240, "auto"));
    Given {
        font: Some(spec.font.clone()),
        size: Some(spec.size),
        bold: spec.bold,
        italic: spec.italic,
        before: spec.before.unwrap_or(0),
        after: spec.after.unwrap_or(0),
        line_twips,
        line_rule: line_rule.to_string(),
        align: spec.align.unwrap_or("left").to_string(),
        keep_next: spec.keep_next,
        keep_lines: spec.keep_lines,
        contextual: spec.contextual_spacing,
        left: spec.left,
        right: spec.right,
        first_line: spec.first_line,
        hanging: spec.hanging,
    }
}

fn whole(element: &Element, attr: &str) -> Option<u32> {
    let n: f64 = element.attr(attr)?.parse().ok()?;
    let n = n.round();
    // `as` cannot overflow: the bound is checked first.
    (n.is_finite() && (0.0..=u32::MAX as f64).contains(&n)).then_some(n as u32)
}

fn signed(element: &Element, attr: &str) -> Option<i64> {
    let n: f64 = element.attr(attr)?.parse().ok()?;
    let n = n.round();
    // `as` cannot overflow: the bound is checked first.
    (n.is_finite() && n.abs() <= 1.0e15).then_some(n as i64)
}

/// `docDefaults` over Word's implicit values. A part that does not parse
/// keeps the implicit values, so the legend's own properties are still written.
fn document_defaults(styles: &str) -> Given {
    let mut given = Given::implicit();
    let Ok(root) = super::from_docx::parse_xml(styles.as_bytes()) else {
        return given;
    };
    let Some(defaults) = root.child("docDefaults") else {
        return given;
    };
    if let Some(rpr) = defaults.path(&["rPrDefault", "rPr"]) {
        // A theme font wins over the named one, so the named one is not
        // what the style inherits.
        if let Some(fonts) = rpr.child("rFonts") {
            given.font = fonts
                .attr("asciiTheme")
                .is_none()
                .then(|| fonts.attr("ascii").or_else(|| fonts.attr("hAnsi")))
                .flatten()
                .map(str::to_string);
        }
        if let Some(size) = rpr.child("sz").and_then(|sz| whole(sz, "val")) {
            given.size = Some(size);
        }
        if let Some(bold) = rpr.toggle("b") {
            given.bold = bold;
        }
        if let Some(italic) = rpr.toggle("i") {
            given.italic = italic;
        }
    }
    if let Some(ppr) = defaults.path(&["pPrDefault", "pPr"]) {
        if let Some(spacing) = ppr.child("spacing") {
            if let Some(before) = whole(spacing, "before") {
                given.before = before;
            }
            if let Some(after) = whole(spacing, "after") {
                given.after = after;
            }
            if let Some(line) = whole(spacing, "line") {
                given.line_twips = line;
                given.line_rule = spacing.attr("lineRule").unwrap_or("auto").to_string();
            }
        }
        if let Some(ind) = ppr.child("ind") {
            if let Some(left) = signed(ind, "left").or_else(|| signed(ind, "start")) {
                given.left = Some(left);
            }
            if let Some(right) = signed(ind, "right").or_else(|| signed(ind, "end")) {
                given.right = Some(right);
            }
            if let Some(first) = signed(ind, "firstLine") {
                given.first_line = Some(first);
            }
            if let Some(hanging) = signed(ind, "hanging") {
                given.hanging = Some(hanging);
            }
        }
        if let Some(on) = ppr.toggle("keepNext") {
            given.keep_next = on;
        }
        if let Some(on) = ppr.toggle("keepLines") {
            given.keep_lines = on;
        }
        if let Some(on) = ppr.toggle("contextualSpacing") {
            given.contextual = on;
        }
        if let Some(align) = ppr.child("jc").and_then(|jc| jc.attr("val")) {
            given.align = align.to_string();
        }
    }
    given
}

/// An indent the legend sets and the style does not already inherit.
fn indent_attr(spec: Option<i64>, inherited: Option<i64>) -> Option<i64> {
    spec.filter(|value| Some(*value) != inherited)
}

/// The gallery flags (`uiPriority`, `semiHidden`, `unhideWhenUsed`,
/// `qFormat`) Word gives built-in style `id` named `name`, in schema order;
/// none for a style Word does not know.
fn gallery_flags(id: &str, name: &str) -> String {
    let Some(builtin) = super::xml::style_definition(id) else {
        return String::new();
    };
    if !builtin.contains(&format!("<w:name w:val=\"{name}\"/>")) {
        return String::new();
    }
    let mut out = String::new();
    for flag in [
        "<w:uiPriority ",
        "<w:semiHidden/>",
        "<w:unhideWhenUsed/>",
        "<w:qFormat/>",
    ] {
        if let Some(at) = builtin.find(flag) {
            let end = builtin[at..]
                .find("/>")
                .map_or(builtin.len(), |e| at + e + 2);
            out.push_str(&builtin[at..end]);
        }
    }
    out
}

/// The `w:style` element of `spec`, based on style `base` unless it is the
/// default. `inherited` is what the style already has, and a property equal
/// to it is left out.
fn definition(spec: &StyleSpec, base: Option<&str>, inherited: &Given) -> String {
    let id = escape(&spec.id);
    let name = match (&spec.name, spec.heading, spec.id.strip_prefix("Heading")) {
        (Some(name), ..) => escape(name).to_string(),
        (None, Some(_), Some(n)) if n.parse::<u32>().is_ok() => format!("heading {n}"),
        _ => id.to_string(),
    };
    // `w:name` holds no comma (pattern `[^,]*`); a style id may.
    let name = name.replace(',', " ");
    let mut out = if spec.default {
        format!(
            "<w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"{id}\"><w:name w:val=\"{name}\"/><w:qFormat/>"
        )
    } else {
        let mut out = format!(
            "<w:style w:type=\"{}\" w:styleId=\"{id}\"><w:name w:val=\"{name}\"/>",
            if spec.character {
                "character"
            } else {
                "paragraph"
            }
        );
        if let Some(base) = base.filter(|b| *b != spec.id) {
            out.push_str(&format!("<w:basedOn w:val=\"{}\"/>", escape(base)));
            if spec.heading.is_some() {
                out.push_str(&format!("<w:next w:val=\"{}\"/>", escape(base)));
            }
        }
        if spec.heading.is_some() {
            out.push_str("<w:uiPriority w:val=\"9\"/><w:qFormat/>");
        } else {
            out.push_str(&gallery_flags(&spec.id, &name));
        }
        out
    };
    // pPr children in schema order: keepNext, keepLines, spacing, ind,
    // contextualSpacing, jc, outlineLvl. The default style's omitted
    // spacing is zero or single and its omitted alignment is left; any
    // other style's omission inherits, so it is not written.
    let mut ppr = String::new();
    if spec.keep_next && !inherited.keep_next {
        ppr.push_str("<w:keepNext/>");
    }
    if spec.keep_lines && !inherited.keep_lines {
        ppr.push_str("<w:keepLines/>");
    }
    let before = if spec.default {
        spec.before.or(Some(0))
    } else {
        spec.before
    };
    let after = if spec.default {
        spec.after.or(Some(0))
    } else {
        spec.after
    };
    let line = if spec.default {
        spec.line.or(Some((240, "auto")))
    } else {
        spec.line
    };
    let write_before = before.is_some_and(|value| value != inherited.before);
    let write_after = after.is_some_and(|value| value != inherited.after);
    let write_line = line
        .is_some_and(|(twips, rule)| twips != inherited.line_twips || rule != inherited.line_rule);
    if write_before || write_after || write_line {
        ppr.push_str("<w:spacing");
        if write_before {
            ppr.push_str(&format!(" w:before=\"{}\"", before.unwrap_or(0)));
        }
        if write_after {
            ppr.push_str(&format!(" w:after=\"{}\"", after.unwrap_or(0)));
        }
        if write_line {
            let (twips, rule) = line.unwrap_or((240, "auto"));
            ppr.push_str(&format!(" w:line=\"{twips}\" w:lineRule=\"{rule}\""));
        }
        ppr.push_str("/>");
    }
    // The default style's omitted indent is zero, as its spacing is: the
    // legend names it only when it is not, so a default indent from
    // `docDefaults` is cleared (#1498 review).
    let indent = |value: Option<i64>, given: Option<i64>| {
        if spec.default {
            indent_attr(value.or(Some(0)), Some(given.unwrap_or(0)))
        } else {
            indent_attr(value, given)
        }
    };
    let left = indent(spec.left, inherited.left);
    let right = indent(spec.right, inherited.right);
    let first = indent(spec.first_line, inherited.first_line);
    let hanging = indent(spec.hanging, inherited.hanging);
    if left.is_some() || right.is_some() || first.is_some() || hanging.is_some() {
        ppr.push_str("<w:ind");
        if let Some(value) = left {
            ppr.push_str(&format!(" w:left=\"{value}\""));
        }
        if let Some(value) = right {
            ppr.push_str(&format!(" w:right=\"{value}\""));
        }
        if let Some(value) = first {
            ppr.push_str(&format!(" w:firstLine=\"{value}\""));
        }
        if let Some(value) = hanging {
            ppr.push_str(&format!(" w:hanging=\"{value}\""));
        }
        ppr.push_str("/>");
    }
    if spec.contextual_spacing && !inherited.contextual {
        ppr.push_str("<w:contextualSpacing/>");
    }
    let align = if spec.default {
        spec.align.or(Some("left"))
    } else {
        spec.align
    };
    if let Some(align) = align.filter(|value| *value != inherited.align) {
        ppr.push_str(&format!("<w:jc w:val=\"{align}\"/>"));
    }
    if let Some(level) = spec.heading {
        ppr.push_str(&format!("<w:outlineLvl w:val=\"{}\"/>", level - 1));
    }
    if !ppr.is_empty() {
        out.push_str(&format!("<w:pPr>{ppr}</w:pPr>"));
    }
    // rPr children in schema order: rFonts, b, bCs, i, iCs, sz, szCs.
    let mut rpr = String::new();
    if inherited.font.as_deref() != Some(spec.font.as_str()) {
        let font = escape(&spec.font);
        rpr.push_str(&format!(
            "<w:rFonts w:ascii=\"{font}\" w:hAnsi=\"{font}\" w:eastAsia=\"{font}\" w:cs=\"{font}\"/>"
        ));
    }
    let toggle = |on: bool, name: &str| {
        if on {
            format!("<w:{name}/><w:{name}Cs/>")
        } else {
            format!("<w:{name} w:val=\"0\"/><w:{name}Cs w:val=\"0\"/>")
        }
    };
    if spec.bold != inherited.bold {
        rpr.push_str(&toggle(spec.bold, "b"));
    }
    if spec.italic != inherited.italic {
        rpr.push_str(&toggle(spec.italic, "i"));
    }
    if inherited.size != Some(spec.size) {
        rpr.push_str(&format!(
            "<w:sz w:val=\"{size}\"/><w:szCs w:val=\"{size}\"/>",
            size = spec.size
        ));
    }
    if !rpr.is_empty() {
        out.push_str(&format!("<w:rPr>{rpr}</w:rPr>"));
    }
    out.push_str("</w:style>");
    out
}

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

    fn defaults_change(styles: &str) -> String {
        let mark = FormatMark {
            id: Some(7),
            author: "Ana".to_string(),
            date: String::new(),
        };
        with_style_changes(
            styles,
            &[(
                "docDefaults".to_string(),
                vec![(StyleChangeKind::Run, mark)],
            )],
        )
    }

    #[test]
    fn a_defaults_change_leaves_the_defaults_unchanged() {
        for styles in [
            "<w:styles xmlns:w=\"W\"><w:style w:styleId=\"A\"><w:rPr><w:b/></w:rPr></w:style></w:styles>",
            "<w:styles><w:docDefaults><w:pPrDefault><w:pPr/></w:pPrDefault></w:docDefaults></w:styles>",
            "<w:styles><w:docDefaults/></w:styles>",
            "<w:styles><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val=\"22\"/></w:rPr></w:rPrDefault>\
             </w:docDefaults><w:style w:styleId=\"A\"><w:rPr><w:b/></w:rPr></w:style></w:styles>",
        ] {
            assert_eq!(defaults_change(styles), styles);
        }
    }

    #[test]
    fn style_change_carrier_first_mark_of_each_kind_is_written() {
        let styles = "<w:styles><w:style w:styleId=\"Normal\"><w:name w:val=\"Normal\"/></w:style></w:styles>";
        let mark = |id: u32, author: &str| FormatMark {
            id: Some(id),
            author: author.to_string(),
            date: String::new(),
        };
        let out = with_style_changes(
            styles,
            &[(
                "Normal".to_string(),
                vec![
                    (StyleChangeKind::Paragraph, mark(7, "Ana")),
                    (StyleChangeKind::Paragraph, mark(8, "Ana")),
                    (StyleChangeKind::Paragraph, mark(9, "Bob")),
                    (StyleChangeKind::Run, mark(3, "Ana")),
                    (StyleChangeKind::Other, mark(4, "Ana")),
                ],
            )],
        );
        assert_eq!(out.matches("<w:pPrChange").count(), 1, "{out}");
        assert_eq!(out.matches("<w:rPrChange").count(), 1, "{out}");
        assert!(out.contains("w:id=\"7\""), "{out}");
        assert!(out.contains("w:id=\"3\""), "{out}");
        assert!(!out.contains("w:id=\"8\""), "{out}");
        assert!(!out.contains("w:id=\"4\""), "{out}");
        let ppr = out.find("<w:pPr>").expect("pPr");
        let rpr = out.find("<w:rPr>").expect("rPr");
        assert!(ppr < rpr, "{out}");
    }

    #[test]
    fn style_change_carrier_replaces_a_nested_run_change() {
        let styles = "<w:styles><w:style w:styleId=\"Normal\"><w:rPr><w:b/>\
            <w:rPrChange w:id=\"1\" w:author=\"Old\"><w:rPr><w:i/></w:rPr></w:rPrChange>\
            </w:rPr></w:style></w:styles>";
        let out = with_style_changes(
            styles,
            &[(
                "Normal".to_string(),
                vec![(
                    StyleChangeKind::Run,
                    FormatMark {
                        id: Some(9),
                        author: "Ana".to_string(),
                        date: String::new(),
                    },
                )],
            )],
        );
        assert_eq!(out.matches("<w:rPrChange").count(), 1, "{out}");
        assert!(out.contains("w:id=\"9\""), "{out}");
        assert!(out.contains("<w:b/>"), "{out}");
        assert!(!out.contains("w:author=\"Old\""), "{out}");
        assert!(!out.contains("<w:i/>"), "{out}");
    }

    #[test]
    fn style_change_carrier_expands_an_empty_run_holder() {
        let styles = "<w:styles><w:style w:styleId=\"Normal\"><w:rPr/></w:style></w:styles>";
        let mark = FormatMark {
            id: Some(4),
            author: "Ana".to_string(),
            date: String::new(),
        };
        let out = with_style_changes(
            styles,
            &[(
                "Normal".to_string(),
                vec![
                    (StyleChangeKind::Run, mark.clone()),
                    (StyleChangeKind::Paragraph, mark),
                ],
            )],
        );
        let ppr = out.find("<w:pPr>").expect("pPr");
        let rpr = out.find("<w:rPr>").expect("rPr");
        assert!(ppr < rpr, "{out}");
        assert!(out.contains("<w:pPr><w:pPrChange"), "{out}");
        assert!(out.contains("<w:rPr><w:rPrChange"), "{out}");
    }

    /// A style's `w:pPr` may hold the paragraph mark's own run properties
    /// (`CT_ParaRPr`), which CT_Style puts before the style's `w:rPr`: the
    /// changes belong to the style's own elements, never to the mark's (#1595
    /// review).
    #[test]
    fn a_style_change_lands_in_the_styles_own_ppr_and_rpr() {
        let mark = FormatMark {
            id: Some(9),
            author: "Ana".to_string(),
            date: String::new(),
        };
        let styles = "<w:styles><w:style w:styleId=\"Heading1\"><w:name w:val=\"heading 1\"/>\
                      <w:pPr><w:keepNext/><w:rPr><w:i/></w:rPr></w:pPr>\
                      <w:rPr><w:sz w:val=\"32\"/></w:rPr></w:style></w:styles>";
        assert_eq!(
            with_style_changes(
                styles,
                &[(
                    "Heading1".to_string(),
                    vec![
                        (StyleChangeKind::Paragraph, mark.clone()),
                        (StyleChangeKind::Run, mark),
                    ],
                )],
            ),
            "<w:styles><w:style w:styleId=\"Heading1\"><w:name w:val=\"heading 1\"/>\
             <w:pPr><w:keepNext/><w:rPr><w:i/></w:rPr>\
             <w:pPrChange w:id=\"9\" w:author=\"Ana\"><w:pPr/></w:pPrChange></w:pPr>\
             <w:rPr><w:sz w:val=\"32\"/><w:rPrChange w:id=\"9\" w:author=\"Ana\"><w:rPr/></w:rPrChange>\
             </w:rPr></w:style></w:styles>"
        );
    }

    const YAML: &str = "view: tracked\nstyles:\n  Normal: Times New Roman 11pt, after 6pt, line 12pt atLeast, left  # default; unannotated paragraphs use it\n  \"#\": Heading1, Times New Roman bold 24pt, before 24pt, keep-next\n  \"##\": Heading2, Arial bold italic 13.5pt, line 1.08, center\n  table: TableGrid, all borders 0.5pt\nbody: p0-p2\n";

    #[test]
    fn every_other_style_and_its_name_read_and_are_defined() {
        let specs = legend(
            "styles:\n  Normal: Arial 12pt, left  # default\n  \
             \"#\": Heading1, Arial bold 16pt, named Heading 1\n  \
             TextHeading2: Times New Roman 12pt, after 6pt, named Text Heading 2\n  \
             TOC2: Arial 11pt\n",
        );
        let ids: Vec<(&str, Option<&str>, bool)> = specs
            .iter()
            .map(|s| (s.id.as_str(), s.name.as_deref(), s.default))
            .collect();
        assert_eq!(
            ids,
            [
                ("Normal", None, true),
                ("Heading1", Some("Heading 1"), false),
                ("TextHeading2", Some("Text Heading 2"), false),
                ("TOC2", None, false),
            ]
        );
        let styles = apply("<w:styles></w:styles>", &specs);
        assert!(
            styles.contains(
                r#"<w:style w:type="paragraph" w:styleId="TextHeading2"><w:name w:val="Text Heading 2"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:rFonts w:ascii="Times New Roman""#
            ),
            "{styles}"
        );
        assert!(
            styles.contains(r#"<w:name w:val="Heading 1"/>"#),
            "{styles}"
        );
        assert!(
            styles.contains(r#"w:styleId="TOC2"><w:name w:val="TOC2"/>"#),
            "{styles}"
        );
        assert_eq!(styles.matches("w:default=\"1\"").count(), 1, "{styles}");
    }

    #[test]
    fn a_character_style_comes_back_as_one() {
        let specs = legend(
            "styles:\n  Normal: Calibri 11pt, left\n  \
             LineNumber: character, Calibri 11pt, named line number\n",
        );
        assert_eq!(specs.len(), 2, "the character style must be read");
        let styles = apply("<w:styles></w:styles>", &specs);
        assert!(
            styles.contains(r#"<w:style w:type="character" w:styleId="LineNumber"><w:name w:val="line number"/>"#),
            "{styles}"
        );
        assert_eq!(legend("styles:\n  Normal: character, Calibri 11pt\n"), []);
    }

    #[test]
    fn a_character_style_keeps_its_font_without_a_paragraph_base() {
        // A basedOn of another kind is ignored by Word. Even when the
        // fonts match Normal, they must be written against docDefaults.
        let specs = legend(
            "styles:\n  Normal: Calibri bold italic 11pt, after 8pt, left\n  \
             LineNumber: character, Calibri bold italic 11pt, named line number\n",
        );
        let styles = apply("<w:styles></w:styles>", &specs);
        let character = styles
            .split(r#"<w:style w:type="character""#)
            .nth(1)
            .expect("a character style is written")
            .split("</w:style>")
            .next()
            .unwrap();
        assert!(!character.contains("<w:basedOn"), "{character}");
        assert!(!character.contains("<w:pPr"), "{character}");
        assert!(character.contains(r#"w:ascii="Calibri""#), "{character}");
        assert!(character.contains(r#"<w:sz w:val="22"/>"#), "{character}");
        assert!(
            character.contains("<w:b/>") && character.contains("<w:i/>"),
            "{character}"
        );
    }

    #[test]
    fn the_legend_reads() {
        let specs = legend(YAML);
        assert_eq!(specs.len(), 3, "{specs:?}");
        assert_eq!(
            (
                specs[0].font.as_str(),
                specs[0].size,
                specs[0].after,
                specs[0].line,
                specs[0].align
            ),
            (
                "Times New Roman",
                22,
                Some(120),
                Some((240, "atLeast")),
                Some("left")
            )
        );
        assert_eq!(
            (specs[1].heading, specs[1].bold, specs[1].before),
            (Some(1), true, Some(480))
        );
        assert!(specs[1].keep_next);
        assert!(!specs[0].keep_lines);
        assert!(!specs[0].contextual_spacing);
        assert_eq!(specs[0].left, None);
        assert_eq!(
            (specs[2].italic, specs[2].size, specs[2].line),
            (true, 27, Some((259, "auto")))
        );
        assert_eq!(specs[2].align, Some("center"));
    }

    #[test]
    fn a_comment_ends_at_a_hash_outside_quotes() {
        assert_eq!(without_comment("  a: b  # c"), "  a: b  ");
        assert_eq!(without_comment("title: Issue #5"), "title: Issue #5");
        assert_eq!(
            without_comment("  a: \"x  #1 \\\" #\"  # c"),
            "  a: \"x  #1 \\\" #\"  "
        );
        assert_eq!(without_comment("  \"#\": H1, A 1pt"), "  \"#\": H1, A 1pt");
    }

    #[test]
    fn what_does_not_read_is_left_out() {
        assert_eq!(
            legend("styles:\n  Normal: 11pt\n  \"#\": Heading1, Arial bold 99999pt\n"),
            []
        );
        assert_eq!(legend("styles:\n  \"#######\": Heading7, Arial 11pt\n"), []);
        assert_eq!(legend("styles:\n  table: TableGrid\n"), []);
        assert_eq!(
            legend("styles:\n  Normal: Calibri 11pt, indent 99in, left\n"),
            []
        );
        assert_eq!(
            legend("styles:\n  Normal: Calibri 11pt, indent 0.5, left\n"),
            []
        );
        assert_eq!(
            legend("styles:\n  Normal: Calibri 11pt, contextual wide, left\n"),
            []
        );
    }

    #[test]
    fn a_default_style_with_another_id_takes_the_default() {
        let specs = legend(
            "styles:\n  \"1\": Arial 12pt, left            # default\n  \"#\": 2, Calibri bold 16pt, before 12pt\n",
        );
        assert_eq!(
            specs.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
            ["1", "2"]
        );
        let styles = "<w:styles><w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\"><w:name w:val=\"Normal\"/></w:style></w:styles>";
        let out = apply(styles, &specs);
        assert_eq!(out.matches("w:default=\"1\"").count(), 1, "{out}");
        assert!(out.contains("w:default=\"1\" w:styleId=\"1\""), "{out}");
        assert!(
            out.contains("<w:name w:val=\"2\"/><w:basedOn w:val=\"1\"/>"),
            "{out}"
        );
    }

    #[test]
    fn a_definition_replaces_the_styles_own() {
        let styles = "<w:styles><w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\"><w:name w:val=\"Normal\"/></w:style><w:style w:type=\"paragraph\" w:styleId=\"Quote\"><w:name w:val=\"Quote\"/></w:style></w:styles>";
        let out = apply(styles, &legend(YAML));
        assert_eq!(out.matches("w:styleId=\"Normal\"").count(), 1, "{out}");
        assert!(out.contains("w:styleId=\"Quote\""), "{out}");
        let normal = style_element(&out, "Normal");
        // The default style's spacing is the document's default.
        assert!(
            out.starts_with(
                "<w:styles><w:docDefaults><w:pPrDefault><w:pPr>\
                 <w:spacing w:after=\"120\" w:line=\"240\" w:lineRule=\"atLeast\"/>\
                 </w:pPr></w:pPrDefault></w:docDefaults>"
            ),
            "{out}"
        );
        assert!(!normal.contains("<w:spacing"), "{normal}");
        assert!(!normal.contains("<w:jc"), "{normal}");
        assert!(!normal.contains("<w:b"), "{normal}");
        assert!(
            normal.contains(
                "<w:rFonts w:ascii=\"Times New Roman\" w:hAnsi=\"Times New Roman\" \
                 w:eastAsia=\"Times New Roman\" w:cs=\"Times New Roman\"/>"
            ),
            "{normal}"
        );
        assert!(
            normal.contains("<w:sz w:val=\"22\"/><w:szCs w:val=\"22\"/>"),
            "{normal}"
        );
        assert!(
            out.contains("<w:name w:val=\"heading 1\"/><w:basedOn w:val=\"Normal\"/>"),
            "{out}"
        );
    }

    fn style_element(styles: &str, id: &str) -> String {
        let key = format!("w:styleId=\"{id}\"");
        let at = styles
            .find(&key)
            .unwrap_or_else(|| panic!("no {id} in {styles}"));
        let start = styles[..at].rfind("<w:style ").unwrap_or(at);
        let end = styles[at..]
            .find("</w:style>")
            .map(|i| at + i + "</w:style>".len())
            .unwrap_or(styles.len());
        styles[start..end].to_string()
    }

    #[test]
    fn an_indent_contextual_spacing_and_keep_lines_are_written() {
        let specs = legend(
            "styles:\n  \
             Normal: Times New Roman 11pt, indent -0.0035in, hanging 0.007in, justify\n  \
             \"#\": Heading1, Times New Roman bold 16pt, keep-next, keep-lines\n  \
             ListParagraph: Times New Roman 11pt, indent 0.5in, first-line 0.25in, \
             contextual spacing, named List Paragraph\n",
        );
        assert_eq!(specs[0].left, Some(-5));
        assert_eq!(specs[0].hanging, Some(10));
        assert!(specs[1].keep_lines);
        assert_eq!(specs[2].left, Some(720));
        assert_eq!(specs[2].first_line, Some(360));
        assert!(specs[2].contextual_spacing);
        let out = apply("<w:styles></w:styles>", &specs);
        let list = style_element(&out, "ListParagraph");
        assert!(
            list.contains("<w:ind w:left=\"720\" w:firstLine=\"360\"/>"),
            "{list}"
        );
        assert!(list.contains("<w:contextualSpacing/>"), "{list}");
        assert!(!list.contains("<w:rPr"), "{list}");
        let heading = style_element(&out, "Heading1");
        assert!(heading.contains("<w:keepNext/><w:keepLines/>"), "{heading}");
        let normal = style_element(&out, "Normal");
        assert!(
            normal.contains("<w:ind w:left=\"-5\" w:hanging=\"10\"/>"),
            "{normal}"
        );
    }

    #[test]
    fn a_right_indent_is_written_and_a_bare_right_still_aligns() {
        // `right 0.5in` is the style's right indent (#1489); `right` alone
        // is still its alignment, as on id lines.
        let specs = legend(
            "styles:\n  \
             Normal: Times New Roman 11pt, left\n  \
             Quote: Times New Roman 11pt, indent 0.5in, right 0.5in, named Quote Text\n  \
             Flush: Times New Roman 11pt, right\n  \
             Back: Times New Roman 11pt, right 0in\n",
        );
        assert_eq!(specs[1].right, Some(720));
        assert_eq!(specs[2].right, None);
        assert_eq!(specs[2].align, Some("right"));
        assert_eq!(specs[3].right, Some(0));
        let out = apply("<w:styles></w:styles>", &specs);
        let quote = style_element(&out, "Quote");
        assert!(
            quote.contains("<w:ind w:left=\"720\" w:right=\"720\"/>"),
            "{quote}"
        );
        let flush = style_element(&out, "Flush");
        assert!(flush.contains("<w:jc w:val=\"right\"/>"), "{flush}");
        assert!(!flush.contains("<w:ind"), "{flush}");
        // An explicit zero is kept, as `indent 0in` is: the source said it.
        let back = style_element(&out, "Back");
        assert!(back.contains("<w:ind w:right=\"0\"/>"), "{back}");
    }

    #[test]
    fn a_theme_font_in_the_defaults_is_not_the_named_font() {
        // Word draws the theme's font where `asciiTheme` is set, whatever
        // `ascii` says, so a legend naming the `ascii` font still writes it.
        let styles = "<w:styles><w:docDefaults><w:rPrDefault><w:rPr>\
            <w:rFonts w:ascii=\"Aptos\" w:hAnsi=\"Aptos\" w:asciiTheme=\"minorHAnsi\" w:hAnsiTheme=\"minorHAnsi\"/>\
            <w:sz w:val=\"22\"/></w:rPr></w:rPrDefault></w:docDefaults></w:styles>";
        let out = apply(styles, &legend("styles:\n  Normal: Aptos 11pt, left\n"));
        let normal = style_element(&out, "Normal");
        assert!(normal.contains("<w:rFonts w:ascii=\"Aptos\""), "{normal}");
    }

    #[test]
    fn a_style_omits_properties_the_defaults_already_give() {
        let styles = "<w:styles><w:docDefaults><w:rPrDefault><w:rPr>\
            <w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\" w:eastAsia=\"Calibri\" w:cs=\"Calibri\"/>\
            <w:sz w:val=\"22\"/><w:szCs w:val=\"22\"/></w:rPr></w:rPrDefault>\
            <w:pPrDefault><w:pPr><w:spacing w:after=\"160\" w:line=\"259\" w:lineRule=\"auto\"/>\
            </w:pPr></w:pPrDefault></w:docDefaults></w:styles>";
        let specs = legend(
            "styles:\n  \
             Normal: Calibri 11pt, after 8pt, line 1.08, left\n  \
             \"#\": Heading1, Calibri bold 16pt, before 12pt, after 4pt, keep-next, keep-lines\n  \
             ListParagraph: Calibri 11pt, indent 0.5in, contextual spacing, named List Paragraph\n  \
             Quote: Calibri 11pt, left\n",
        );
        let out = apply(styles, &specs);
        assert!(
            out.contains(
                "<w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\">\
                 <w:name w:val=\"Normal\"/><w:qFormat/></w:style>"
            ),
            "{out}"
        );
        let list = style_element(&out, "ListParagraph");
        assert!(list.contains("<w:ind w:left=\"720\"/>"), "{list}");
        assert!(list.contains("<w:contextualSpacing/>"), "{list}");
        assert!(!list.contains("<w:rPr"), "{list}");
        assert!(
            list.contains("<w:name w:val=\"List Paragraph\"/>"),
            "{list}"
        );
        // A built-in style keeps Word's gallery flags: List Paragraph is
        // priority 34 and quick-format, as Word itself writes it.
        assert!(
            list.contains(
                "<w:basedOn w:val=\"Normal\"/><w:uiPriority w:val=\"34\"/><w:qFormat/><w:pPr>"
            ),
            "{list}"
        );
        assert!(
            style_element(&out, "Quote").contains("<w:uiPriority w:val=\"29\"/><w:qFormat/>"),
            "{out}"
        );
        let heading = style_element(&out, "Heading1");
        assert!(
            heading.contains(
                "<w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before=\"240\" w:after=\"80\"/>\
                 <w:outlineLvl w:val=\"0\"/></w:pPr>"
            ),
            "{heading}"
        );
        assert!(
            heading.contains(
                "<w:rPr><w:b/><w:bCs/><w:sz w:val=\"32\"/><w:szCs w:val=\"32\"/></w:rPr>"
            ),
            "{heading}"
        );
        // Quote is not bold, and Normal's legend is not bold either, so no toggle.
        let quote = style_element(&out, "Quote");
        assert!(!quote.contains("<w:rPr"), "{quote}");
        assert!(!quote.contains("<w:pPr"), "{quote}");
    }

    #[test]
    fn the_default_style_s_omitted_indent_is_none() {
        // The default style's line names an indent only when it is not
        // zero, so an omitted one is zero: a template's own default
        // indent may not survive under it (#1498 review).
        let styles = "<w:styles><w:docDefaults><w:pPrDefault><w:pPr>\
            <w:ind w:left=\"360\" w:right=\"720\" w:hanging=\"360\"/>\
            </w:pPr></w:pPrDefault></w:docDefaults></w:styles>";
        let out = apply(
            styles,
            &legend("styles:\n  Normal: Calibri 11pt, left\n  Quote: Calibri 11pt, left\n"),
        );
        let normal = style_element(&out, "Normal");
        assert!(
            normal.contains("<w:ind w:left=\"0\" w:right=\"0\" w:hanging=\"0\"/>"),
            "{normal}"
        );
        // A style based on the default inherits its zeros.
        assert!(!style_element(&out, "Quote").contains("<w:ind"), "{out}");
        // With no default indent there is nothing to clear.
        let out = apply(
            "<w:styles></w:styles>",
            &legend("styles:\n  Normal: Calibri 11pt, left\n"),
        );
        assert!(!style_element(&out, "Normal").contains("<w:ind"), "{out}");
    }

    #[test]
    fn a_run_property_is_written_when_it_differs_from_the_base() {
        let specs =
            legend("styles:\n  Normal: Calibri bold 11pt, left\n  Quote: Calibri 11pt, left\n");
        let out = apply("<w:styles></w:styles>", &specs);
        let quote = style_element(&out, "Quote");
        assert!(
            quote.contains("<w:b w:val=\"0\"/><w:bCs w:val=\"0\"/>"),
            "{quote}"
        );
        assert!(!quote.contains("w:rFonts"), "{quote}");
        assert!(!quote.contains("<w:sz"), "{quote}");
        assert!(!quote.contains("<w:jc"), "{quote}");
    }

    /// The `w:pPrDefault` of a styles part, or nothing.
    fn paragraph_defaults(styles: &str) -> &str {
        let Some(start) = styles.find("<w:pPrDefault") else {
            return "";
        };
        let end = styles[start..]
            .find("</w:pPrDefault>")
            .map_or(styles.len(), |i| start + i + "</w:pPrDefault>".len());
        &styles[start..end]
    }

    #[test]
    fn the_default_style_s_spacing_is_the_documents_default() {
        // Word keeps the body's spacing in `docDefaults`. A table style's
        // own spacing then wins in its cells; over `Normal`'s it would not
        // (ISO/IEC 29500 style precedence), so the cells would grow.
        let styles = "<w:styles><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val=\"22\"/></w:rPr></w:rPrDefault>\
            <w:pPrDefault><w:pPr><w:spacing w:after=\"160\" w:line=\"259\" w:lineRule=\"auto\"/></w:pPr></w:pPrDefault>\
            </w:docDefaults></w:styles>";
        let out = apply(
            styles,
            &legend(
                "styles:\n  Normal: Calibri 11pt, after 10pt, line 1.15, left\n  \
                 Quote: Calibri 11pt, before 6pt, left\n",
            ),
        );
        assert_eq!(
            paragraph_defaults(&out),
            "<w:pPrDefault><w:pPr><w:spacing w:after=\"200\" w:line=\"276\" w:lineRule=\"auto\"/>\
             </w:pPr></w:pPrDefault>",
            "{out}"
        );
        let normal = style_element(&out, "Normal");
        assert!(!normal.contains("<w:spacing"), "{normal}");
        // A style based on the default still writes what it sets apart.
        let quote = style_element(&out, "Quote");
        assert!(quote.contains("<w:spacing w:before=\"120\"/>"), "{quote}");
        // An omitted spacing is none and single, as the legend says, so a
        // template's own default does not survive under it.
        let out = apply(styles, &legend("styles:\n  Normal: Calibri 11pt, left\n"));
        assert_eq!(
            paragraph_defaults(&out),
            "<w:pPrDefault><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/>\
             </w:pPr></w:pPrDefault>",
            "{out}"
        );
        assert!(
            !style_element(&out, "Normal").contains("<w:spacing"),
            "{out}"
        );
    }

    #[test]
    fn the_default_spacing_lands_where_the_schema_puts_it() {
        let specs = legend(
            "styles:\n  Normal: Calibri 11pt, before 3pt, after 6pt, line 12pt exact, left\n",
        );
        let spacing =
            "<w:spacing w:before=\"60\" w:after=\"120\" w:line=\"240\" w:lineRule=\"exact\"/>";
        // No docDefaults: one is made, first in the part.
        let out = apply("<w:styles><w:latentStyles/></w:styles>", &specs);
        assert!(
            out.starts_with(&format!(
                "<w:styles><w:docDefaults><w:pPrDefault><w:pPr>{spacing}</w:pPr></w:pPrDefault>\
                 </w:docDefaults><w:latentStyles/>"
            )),
            "{out}"
        );
        // Run defaults only: the paragraph defaults follow them.
        let out = apply(
            "<w:styles><w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults></w:styles>",
            &specs,
        );
        assert!(
            out.contains(&format!(
                "<w:rPrDefault><w:rPr/></w:rPrDefault><w:pPrDefault><w:pPr>{spacing}</w:pPr>\
                 </w:pPrDefault></w:docDefaults>"
            )),
            "{out}"
        );
        // Other paragraph defaults stay, the spacing between them in
        // CT_PPrBase order (after widowControl, before ind).
        let out = apply(
            "<w:styles><w:docDefaults><w:pPrDefault><w:pPr><w:widowControl/>\
             <w:spacing w:after=\"160\" w:line=\"259\" w:lineRule=\"auto\"/><w:ind w:left=\"0\"/></w:pPr>\
             </w:pPrDefault></w:docDefaults></w:styles>",
            &specs,
        );
        assert_eq!(
            paragraph_defaults(&out),
            format!(
                "<w:pPrDefault><w:pPr><w:widowControl/>{spacing}<w:ind w:left=\"0\"/></w:pPr></w:pPrDefault>"
            ),
            "{out}"
        );
        let out = apply(
            "<w:styles><w:docDefaults><w:pPrDefault><w:pPr><w:jc w:val=\"left\"/></w:pPr>\
             </w:pPrDefault></w:docDefaults></w:styles>",
            &specs,
        );
        assert_eq!(
            paragraph_defaults(&out),
            format!("<w:pPrDefault><w:pPr>{spacing}<w:jc w:val=\"left\"/></w:pPr></w:pPrDefault>"),
            "{out}"
        );
        // An empty pPrDefault, or one without its pPr.
        for empty in [
            "<w:pPrDefault/>",
            "<w:pPrDefault></w:pPrDefault>",
            "<w:pPrDefault><w:pPr/></w:pPrDefault>",
        ] {
            let out = apply(
                &format!("<w:styles><w:docDefaults>{empty}</w:docDefaults></w:styles>"),
                &specs,
            );
            assert_eq!(
                paragraph_defaults(&out),
                format!("<w:pPrDefault><w:pPr>{spacing}</w:pPr></w:pPrDefault>"),
                "{out}"
            );
        }
    }
}

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

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

    fn mark(id: Option<u32>) -> FormatMark {
        FormatMark {
            id,
            author: "Ana".to_string(),
            date: "2026-01-01T00:00:00Z".to_string(),
        }
    }

    #[test]
    fn style_changes_land_in_the_styles_own_properties() {
        let styles = format!(
            "<w:styles {W}><w:style w:styleId=\"A\"><w:pPr/><w:rPr><w:b/><w:rPrChange w:id=\"1\" w:author=\"Old\"><w:rPr/></w:rPrChange></w:rPr></w:style><w:style w:styleId=\"B\"><w:rPr><w:i/></w:rPr></w:style><w:style w:styleId=\"C\"><w:name w:val=\"C\"/></w:style><w:style w:styleId=\"Open\">"
        );
        let changes = vec![
            (
                "A".to_string(),
                vec![
                    (StyleChangeKind::Paragraph, mark(Some(2))),
                    (StyleChangeKind::Run, mark(None)),
                ],
            ),
            (
                "B".to_string(),
                vec![(StyleChangeKind::Paragraph, mark(Some(3)))],
            ),
            ("C".to_string(), vec![(StyleChangeKind::Run, mark(Some(4)))]),
            ("D".to_string(), vec![(StyleChangeKind::Run, mark(Some(5)))]),
            (
                "B".to_string(),
                vec![(StyleChangeKind::Other, mark(Some(6)))],
            ),
            (
                "Open".to_string(),
                vec![(StyleChangeKind::Run, mark(Some(7)))],
            ),
            (
                "docDefaults".to_string(),
                vec![(StyleChangeKind::Run, mark(Some(8)))],
            ),
        ];
        let out = with_style_changes(&styles, &changes);
        // A's empty pPr takes the change; its rPr's old change is replaced.
        assert!(
            out.contains(
                "<w:style w:styleId=\"A\"><w:pPr><w:pPrChange w:id=\"2\" w:author=\"Ana\""
            ),
            "{out}"
        );
        assert!(!out.contains("Old"), "{out}");
        // B gets a pPr before its rPr; C an rPr of its own.
        assert!(
            out.contains("<w:style w:styleId=\"B\"><w:pPr><w:pPrChange w:id=\"3\""),
            "{out}"
        );
        assert!(
            out.contains("<w:name w:val=\"C\"/><w:rPr><w:rPrChange w:id=\"4\""),
            "{out}"
        );
        assert!(
            !out.contains("w:id=\"5\"")
                && !out.contains("w:id=\"6\"")
                && !out.contains("w:id=\"7\"")
        );
        assert!(!out.contains("w:id=\"8\""));
    }

    #[test]
    fn style_change_warnings_count_what_is_not_written() {
        let changes = vec![
            (
                "docDefaults".to_string(),
                vec![(StyleChangeKind::Run, mark(Some(1)))],
            ),
            (
                "docDefaults".to_string(),
                vec![
                    (StyleChangeKind::Run, mark(Some(1))),
                    (StyleChangeKind::Paragraph, mark(Some(2))),
                ],
            ),
            ("docDefaults".to_string(), vec![]),
            (
                "A".to_string(),
                vec![
                    (StyleChangeKind::Paragraph, mark(Some(1))),
                    (StyleChangeKind::Paragraph, mark(Some(2))),
                    (StyleChangeKind::Run, mark(Some(3))),
                    (StyleChangeKind::Run, mark(Some(4))),
                    (StyleChangeKind::Other, mark(Some(5))),
                ],
            ),
            (
                "B".to_string(),
                vec![
                    (StyleChangeKind::Other, mark(Some(6))),
                    (StyleChangeKind::Other, mark(Some(7))),
                ],
            ),
        ];
        let legacy = vec![
            ("A".to_string(), vec!["r1 @A".to_string()]),
            (
                "B".to_string(),
                vec!["r2 @A".to_string(), "r3 @A".to_string()],
            ),
            ("C".to_string(), vec![]),
            ("docDefaults".to_string(), vec!["r4 @A".to_string()]),
        ];
        assert_eq!(
            style_change_warnings(&changes, &legacy),
            [
                "style_changes: A: r1 @A has no kind; written as rPr",
                "style_changes: B: r2 @A; r3 @A have no kind; written as rPr",
                "style_changes: docDefaults: the document defaults have no change slot; 1 change is not written",
                "style_changes: docDefaults: the document defaults have no change slot; 2 changes are not written",
                "style_changes: A: 2 pPr changes for one slot; the rest are not written",
                "style_changes: A: 2 rPr changes for one slot; the rest are not written",
                "style_changes: A: 1 other change is not written",
                "style_changes: B: 2 other changes are not written",
            ]
        );
    }

    #[test]
    fn nested_property_elements_close_at_their_own_close() {
        // The pPrChange's own pPr nests: the style's pPr closes after it.
        let block = "<w:style><w:pPr><w:jc/><w:pPrChange><w:pPr><w:ind/></w:pPr></w:pPrChange></w:pPr><w:rPr><w:b/></w:rPr>";
        let ppr = own_ppr(block).expect("pPr");
        assert_eq!(
            &block[ppr.start..ppr.end],
            "<w:pPr><w:jc/><w:pPrChange><w:pPr><w:ind/></w:pPr></w:pPrChange></w:pPr>"
        );
        let span = direct_child_span(block, &ppr, "pPrChange").expect("change");
        assert!(block[span].starts_with("<w:pPrChange>"));
        assert!(direct_child_span(block, &ppr, "missing").is_none());
        assert!(open_tag("<w:pPrX/><w:pPr\t/>", "pPr", 0..18).is_some_and(|t| t.empty));
        assert!(open_tag("<w:pPr", "pPr", 0..6).is_none());
        assert!(close_at("<w:pPr>", "pPr", 7).is_none());
        assert!(own("<w:pPr><w:b/>", "pPr", 0).is_none());
        let open = own("<w:rPr><w:b/></w:rPr>", "rPr", 0).expect("rPr");
        assert!(direct_child_span("<w:rPr><w:b/></w:rPr>", &open, "x").is_none());
        let text = "<w:rPr>text</w:rPr>";
        let open = own(text, "rPr", 0).expect("rPr");
        assert!(direct_child_span(text, &open, "x").is_none());
    }

    #[test]
    fn legend_values_refuse_what_word_cannot_hold() {
        assert_eq!(points("2000pt", 20.0), None);
        assert_eq!(points("-1pt", 20.0), None);
        assert_eq!(points("NaNpt", 20.0), None);
        assert_eq!(twips_in("infin"), None);
        assert_eq!(twips_in("30in"), None);
        assert_eq!(twips_in("-0.5in"), Some(-720));
        assert_eq!(font_clause(" bold 11pt"), None);
        assert_eq!(
            font_clause("Arial bold italic 11pt"),
            Some(("Arial".to_string(), true, true, 22))
        );
        for bad in [
            "Arial 11pt, line 200",
            "Arial 11pt, line NaN",
            "Arial 11pt, line 12pt sometimes",
            "Arial 11pt, sideways",
            "Arial 11pt, tilt 3",
            "Arial 11pt, before 9999pt",
        ] {
            assert!(spec("S", None, false, bad).is_none(), "{bad}");
        }
        let good = spec("S", None, false, "character, Arial 11pt, line 12pt atLeast, right 0.5in, first-line 0.25in, hanging 0.1in, indent 1in, contextual spacing, keep-next, keep-lines, justify, named My S").expect("spec");
        assert!(good.character && good.keep_next && good.keep_lines && good.contextual_spacing);
        assert_eq!(good.align, Some("both"));
        assert_eq!(good.name.as_deref(), Some("My S"));
        assert_eq!(
            without_comment("text: \"a  # b\\\" c\"  # note"),
            "text: \"a  # b\\\" c\"  "
        );
        assert_eq!(unquote("\"bad"), None);
    }

    #[test]
    fn table_legends_read_borders_names_and_stop_at_unknown_clauses() {
        assert_eq!(
            border_sides("borders top double 0.75pt #FF0000 space 4pt left single"),
            Some(vec![
                BorderSide {
                    side: "top".into(),
                    val: "double".into(),
                    size: Some(6),
                    color: Some("FF0000".into()),
                    space: Some(4)
                },
                BorderSide {
                    side: "left".into(),
                    val: "single".into(),
                    size: None,
                    color: None,
                    space: None
                },
            ])
        );
        for bad in [
            "borders middle single",
            "borders top single top double",
            "borders top s!ngle",
            "borders top",
            "borders top single 300pt",
            "borders top single #FF00",
            "borders top single #GGGGGG",
            "borders top single space x",
            "borders top single space",
            "borders top single 1pt 2pt",
            "borders top single wavy",
            "frames top single",
        ] {
            assert_eq!(border_sides(bad), None, "{bad}");
        }
        let yaml = "styles:\n  table: Grid, all borders 1.5pt, named \"My, Grid\", borders vary  # c\n  tables: A, all borders 9pt, B, borders top single, named Bee, C, D, extra\nother:\n  table: Ignored\n";
        assert_eq!(
            table_style(yaml),
            Some((
                "Grid".to_string(),
                Some(TableBorders::All(12)),
                Some("My, Grid".to_string())
            ))
        );
        assert_eq!(
            table_style("styles:\n  table: \"Q, named Z\"\n"),
            Some(("Q".to_string(), None, Some("Z".to_string())))
        );
        let legend = table_legend(yaml);
        let keys: Vec<&str> = legend.keys().map(String::as_str).collect();
        assert_eq!(keys, ["A", "B", "C", "D", "all borders 9pt", "extra"]);
        assert!(table_legend("styles:\n  Normal: Arial 11pt\n").is_empty());
        assert_eq!(table_style("styles:\n  table: \"\"\n"), None);
        assert_eq!(
            take_clause("\"a, \\\"b\", c"),
            ("\"a, \\\"b\"".to_string(), "c")
        );
    }

    #[test]
    fn the_legend_skips_unreadable_keys_and_headings_out_of_range() {
        let specs = legend(
            "styles:\n  no separator\n  \"open: Arial 11pt\n  \"#######\": Heading7, Arial 11pt\n  \"#\": NoComma\n  \"##\": Heading2, Arial bold 13pt\n  changes: x\n  Normal: Arial 11pt\n  Body: Arial 10pt\nother:\n  Skip: Arial 9pt\n",
        );
        let ids: Vec<(&str, bool, Option<u32>)> = specs
            .iter()
            .map(|s| (s.id.as_str(), s.default, s.heading))
            .collect();
        assert_eq!(
            ids,
            [
                ("Heading2", false, Some(2)),
                ("Normal", true, None),
                ("Body", false, None)
            ]
        );
    }
}