f-office-docx 0.2.3

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

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

use f_office_drawingml::theme::ShapeTheme;
use f_office_fonts::FamilyName;
use f_office_units::Length;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};

use crate::mode::{CompatibilityMode, ModeRules};
use crate::note_setup::{ByNoteKind, NoteSetup};
use crate::ns::{A, M, W};
use crate::numbers;
use crate::on_off;
use crate::params;
use crate::props::{
    Alignment, Color, EastAsianScript, FontRef, HtmlAutoSpacing, LineSpacing, ListRef, ParaProps,
    RunProps, UNDERLINE, Underline, read_shading,
};
use crate::reader::PartReader;
use crate::table::{CELL_V_ALIGN, REGION, Region, TableBorders, TableProps, VerticalAlign};

const MAX_CHAIN: usize = params::MAX_STYLE_CHAIN;

/// The kind of a style (`w:type` of `w:style`), of which a paragraph and a table style can be
/// the default one. A style without a kind is a paragraph style.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum StyleKind {
    #[default]
    Paragraph,
    Character,
    Table,
    Numbering,
}

impl StyleKind {
    /// The kind's name in `ST_StyleType`, for a message.
    pub(crate) const fn word(self) -> &'static str {
        match self {
            Self::Paragraph => "paragraph",
            Self::Character => "character",
            Self::Table => "table",
            Self::Numbering => "numbering",
        }
    }
}

/// `ST_StyleType`. A style without a kind is a paragraph style, and text outside the type
/// counts as missing, so a default style with it is the default paragraph style, where
/// F-Office made it the default of no kind before.
const STYLE_KIND: &Values<StyleKind> = &Values::new(&[
    own("paragraph", StyleKind::Paragraph),
    own("character", StyleKind::Character),
    own("table", StyleKind::Table),
    own("numbering", StyleKind::Numbering),
]);

/// The kind of the style `node`: a style without a kind, or with text outside `ST_StyleType`,
/// is a paragraph style.
pub(crate) fn style_kind(reader: &mut PartReader, node: NodeId) -> StyleKind {
    reader
        .enumeration(node, "type", STYLE_KIND)
        .unwrap_or(StyleKind::Paragraph)
}

/// Whether the style `node` is the default style of its kind (`w:default`), by the set of
/// values of [`on_off::on_only_for_1_or_true`].
pub(crate) fn is_default(doc: &Document, node: NodeId) -> bool {
    doc.attribute(node, Some(W), "default")
        .is_some_and(on_off::on_only_for_1_or_true)
}

#[derive(Clone, Debug, Default)]
struct Style {
    kind: StyleKind,
    based_on: Option<String>,
    para: ParaProps,
    run: RunProps,
    /// The kind of the style's underline, which tells apart the kinds that the run's underline
    /// flag shares.
    underline_kind: Option<Underline>,
    table: TableProps,
    /// The fill of a table style's cells.
    shading: Option<Color>,
    /// The vertical alignment of a table style's cells.
    align: Option<VerticalAlign>,
    regions: Vec<(Region, RegionStyle)>,
}

/// What a table style sets for one region of a table.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RegionStyle {
    /// The paragraph properties.
    pub para: ParaProps,
    /// The run properties.
    pub run: RunProps,
    /// The cell borders.
    pub borders: TableBorders,
    /// The fill of the region's cells.
    pub shading: Option<Color>,
    /// The vertical alignment of the region's cells.
    pub align: Option<VerticalAlign>,
}

/// The fill of the cells of a `w:tcPr` element.
fn cell_shading(reader: &mut PartReader, node: NodeId) -> Option<Color> {
    let doc = reader.doc;
    doc.child(node, W, "tcPr")
        .and_then(|t| doc.child(t, W, "shd"))
        .and_then(|s| read_shading(reader, s))
}

/// The vertical alignment of the cells of a `w:tcPr` element, which a cell without its own
/// `w:vAlign` takes (ECMA-376 Part 1, 17.7.6).
fn cell_align(reader: &mut PartReader, node: NodeId) -> Option<VerticalAlign> {
    let doc = reader.doc;
    let align = doc
        .child(node, W, "tcPr")
        .and_then(|t| doc.child(t, W, "vAlign"))?;
    reader.enumeration(align, "val", CELL_V_ALIGN)
}

impl RegionStyle {
    fn apply(&mut self, other: &Self) {
        self.para.apply(&other.para);
        self.run.apply(&other.run);
        self.borders.apply(&other.borders);
        if other.shading.is_some() {
            self.shading = other.shading;
        }
        if other.align.is_some() {
            self.align = other.align;
        }
    }

    fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        Self {
            para: doc
                .child(node, W, "pPr")
                .map_or_default(|p| ParaProps::read(reader, p)),
            run: doc
                .child(node, W, "rPr")
                .map_or_default(|r| RunProps::read(reader, r)),
            borders: doc
                .child(node, W, "tcPr")
                .and_then(|t| doc.child(t, W, "tcBorders"))
                .map_or_default(|b| TableBorders::read(reader, b)),
            shading: cell_shading(reader, node),
            align: cell_align(reader, node),
        }
    }
}

/// A table style after the cascade: its table properties, the paragraph and run properties
/// that it gives the paragraphs in the table, and its formatting for regions of the table.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TableStyle {
    /// The table properties.
    pub table: TableProps,
    /// The paragraph properties.
    pub para: ParaProps,
    /// The run properties.
    pub run: RunProps,
    /// The fill of the table's cells.
    pub shading: Option<Color>,
    /// The vertical alignment of the table's cells.
    pub align: Option<VerticalAlign>,
    /// The formatting of regions, one entry for each region that the style sets.
    pub regions: Vec<(Region, RegionStyle)>,
    /// The alignment set by a conditional region (`w:tblStylePr`) for a cell.
    pub(crate) region_alignment: Option<Alignment>,
    /// Whether this style resolved to a defined table style in `styles.xml`.
    pub(crate) resolved: bool,
}

impl TableStyle {
    /// What the style sets for a region.
    #[must_use]
    pub fn region(&self, region: Region) -> Option<&RegionStyle> {
        self.regions
            .iter()
            .find(|(r, _)| *r == region)
            .map(|(_, style)| style)
    }

    fn add_regions(&mut self, regions: &[(Region, RegionStyle)]) {
        for (region, style) in regions {
            if let Some((_, own)) = self.regions.iter_mut().find(|(r, _)| r == region) {
                own.apply(style);
            } else {
                self.regions.push((*region, style.clone()));
            }
        }
    }
}

/// The paragraph defaults of Word's own template, which Word takes without default paragraph
/// properties: 8 pt after and lines of 278/240. With `own`, the document defaults, the
/// template leaves out each value that `own` gives the same ([`Styles::take_template`]).
fn template_paragraph(own: Option<&ParaProps>) -> ParaProps {
    ParaProps {
        after: unless_own(
            Length::from_twips(params::DEFAULT_SPACE_AFTER),
            own.map(|p| &p.after),
        ),
        line: unless_own(
            Some(LineSpacing::Auto(params::DEFAULT_LINE_SPACING)),
            own.map(|p| &p.line),
        ),
        ..ParaProps::default()
    }
}

/// The run defaults of Word's own template, which Word takes without default run properties:
/// it kerns text from 1 pt and turns on standard ligatures, and draws Latin text in the
/// theme's minor font at 12 pt. With `own`, the document defaults, the template leaves out
/// each value that `own` gives the same ([`Styles::take_template`]).
fn template_run(own: Option<&RunProps>) -> RunProps {
    let minor = Some(FontRef::MinorLatin);
    let size = Some(params::TEMPLATE_FONT_SIZE);
    RunProps {
        kern: unless_own(Some(2), own.map(|r| &r.kern)),
        ligatures: unless_own(Some(true), own.map(|r| &r.ligatures)),
        font_ascii: unless_own(minor.clone(), own.map(|r| &r.font_ascii)),
        font_hansi: unless_own(minor, own.map(|r| &r.font_hansi)),
        size: unless_own(size, own.map(|r| &r.size)),
        size_cs: unless_own(size, own.map(|r| &r.size_cs)),
        ..RunProps::default()
    }
}

/// The template's value `template`, or none where the document's own value `own` is the
/// same.
fn unless_own<T: PartialEq>(template: Option<T>, own: Option<&Option<T>>) -> Option<T> {
    if own == Some(&template) {
        None
    } else {
        template
    }
}

/// The styles part with its document defaults.
#[derive(Clone, Debug)]
pub struct Styles {
    default_para: ParaProps,
    default_run: RunProps,
    by_id: HashMap<String, Style>,
    /// The style IDs by lowercase style name.
    names: HashMap<String, String>,
    default_paragraph_style: Option<String>,
    default_table_style: Option<String>,
    /// Whether a paragraph whose `w:pStyle` names no paragraph style takes the default
    /// paragraph style, rather than the chain of the style that it names.
    paragraph_kind_only: bool,
    /// Whether the run defaults are Word's own template's, as the part has no `w:rPrDefault`.
    template_run_defaults: bool,
}

impl Default for Styles {
    /// No styles and empty defaults, where a paragraph's style ID takes the chain of whatever
    /// style it names, until [`Styles::refer_only_paragraph_styles`] says otherwise.
    fn default() -> Self {
        Self {
            default_para: ParaProps::default(),
            default_run: RunProps::default(),
            by_id: HashMap::new(),
            names: HashMap::new(),
            default_paragraph_style: None,
            default_table_style: None,
            paragraph_kind_only: false,
            template_run_defaults: false,
        }
    }
}

impl Styles {
    /// Reads `word/styles.xml`.
    pub(crate) fn read(reader: &mut PartReader, root: NodeId) -> Self {
        let doc = reader.doc;
        let mut styles = Self::default();
        let defaults = doc.child(root, W, "docDefaults");
        if let Some(defaults) = defaults {
            styles.read_defaults(reader, defaults);
        }
        let lacks = |name| defaults.and_then(|d| doc.child(d, W, name)).is_none();
        if lacks("pPrDefault") {
            styles.default_para = template_paragraph(None);
        }
        if lacks("rPrDefault") {
            styles.default_run = template_run(None);
            styles.template_run_defaults = true;
        }
        for node in doc.child_elements(root).filter(|n| doc.is(*n, W, "style")) {
            styles.read_style(reader, node);
        }
        styles
    }

    /// The styles of a package without a styles part: the paragraph and run defaults of
    /// Word's own template, and no styles.
    #[must_use]
    pub fn without_part() -> Self {
        Self {
            default_para: template_paragraph(None),
            default_run: template_run(None),
            template_run_defaults: true,
            ..Self::default()
        }
    }

    /// Takes the default paragraph style from Word's own template, as a target does that
    /// updates the styles of a document whose settings ask for it: the style loses the
    /// document's properties and has the paragraph and run defaults of the template, each
    /// only where it differs from the document defaults. The document defaults and every
    /// other style stay, so a style that is not based on the default paragraph style keeps the
    /// document defaults, and a table style wins over a value that the document defaults
    /// already give.
    pub fn take_template(&mut self) {
        let para = template_paragraph(Some(&self.default_para));
        let run = template_run(Some(&self.default_run));
        let normal = self.default_paragraph_style.clone();
        if let Some(style) = normal.and_then(|id| self.by_id.get_mut(&id)) {
            style.para = para;
            style.run = run;
        }
    }

    fn read_defaults(&mut self, reader: &mut PartReader, defaults: NodeId) {
        let doc = reader.doc;
        let inner = |outer, inner| {
            doc.child(defaults, W, outer)
                .and_then(|node| doc.child(node, W, inner))
        };
        if let Some(rpr) = inner("rPrDefault", "rPr") {
            self.default_run = RunProps::read(reader, rpr);
        }
        if let Some(ppr) = inner("pPrDefault", "pPr") {
            self.default_para = ParaProps::read(reader, ppr);
        }
    }

    fn read_style(&mut self, reader: &mut PartReader, node: NodeId) {
        let doc = reader.doc;
        let Some(id) = doc.attribute(node, Some(W), "styleId") else {
            return;
        };
        let kind = style_kind(reader, node);
        if is_default(doc, node) {
            match kind {
                StyleKind::Paragraph => self.default_paragraph_style = Some(id.to_owned()),
                StyleKind::Table => self.default_table_style = Some(id.to_owned()),
                StyleKind::Character | StyleKind::Numbering => {}
            }
        }
        let has_table_props = kind == StyleKind::Table
            && (["tblPr", "trPr", "tcPr"].into_iter().any(|tag| {
                doc.child(node, W, tag)
                    .is_some_and(|child| doc.child_elements(child).next().is_some())
            }) || doc.child(node, W, "tblStylePr").is_some());
        let based_on = doc
            .child(node, W, "basedOn")
            .and_then(|b| doc.attribute(b, Some(W), "val"))
            // A table style that carries its own table, row, cell, or region properties drops a
            // forward `w:basedOn` link whose target has not yet appeared in `styles.xml`.
            .filter(|base| !has_table_props || self.by_id.contains_key(*base))
            .map(str::to_owned);
        let style = Style {
            kind,
            // `RunProps::read` reads this `w:u` again through the part's reader and keeps the
            // warnings of its value.
            underline_kind: doc
                .child(node, W, "rPr")
                .and_then(|r| doc.child(r, W, "u"))
                .map(|u| {
                    reader
                        .again()
                        .enumeration(u, "val", UNDERLINE)
                        .unwrap_or(Underline::Single)
                }),
            based_on,
            para: doc
                .child(node, W, "pPr")
                .map_or_default(|p| ParaProps::read(reader, p)),
            run: doc
                .child(node, W, "rPr")
                .map_or_default(|r| RunProps::read(reader, r)),
            table: doc
                .child(node, W, "tblPr")
                .map_or_default(|t| TableProps::read(reader, t)),
            shading: cell_shading(reader, node),
            align: cell_align(reader, node),
            regions: doc
                .child_elements(node)
                .filter(|n| doc.is(*n, W, "tblStylePr"))
                .filter_map(|n| {
                    let region = reader.enumeration(n, "type", REGION)?;
                    Some((region, RegionStyle::read(reader, n)))
                })
                .collect(),
        };
        self.by_id.insert(id.to_owned(), style);
        let name = doc
            .child(node, W, "name")
            .and_then(|n| doc.attribute(n, Some(W), "val"));
        if let Some(name) = name {
            self.names.insert(name.to_lowercase(), id.to_owned());
            let aliases = doc
                .child(node, W, "aliases")
                .and_then(|n| doc.attribute(n, Some(W), "val"))
                .filter(|aliases| !aliases.is_empty());
            if let Some(aliases) = aliases {
                self.names
                    .entry(format!("{name},{aliases}").to_lowercase())
                    .or_insert_with(|| id.to_owned());
            }
        }
    }

    /// The ID of the style with this name, as a `STYLEREF` field names it, or of the style with
    /// this ID. Names match without regard to case, and a name followed by a comma and the
    /// style's aliases names the style too.
    #[must_use]
    pub fn id_of<'s>(&'s self, name: &'s str) -> &'s str {
        self.names
            .get(&name.to_lowercase())
            .map_or(name, String::as_str)
    }

    /// Returns a table style after the cascade. A missing or unknown style ID selects the
    /// default table style.
    #[must_use]
    pub fn table(&self, style: Option<&str>) -> TableStyle {
        let id = style
            .filter(|id| self.by_id.contains_key(*id))
            .or(self.default_table_style.as_deref());
        let mut out = TableStyle {
            resolved: id.is_some(),
            ..TableStyle::default()
        };
        for style in self.chain(id) {
            out.table.apply(&style.table);
            out.para.apply(&style.para);
            out.run.apply(&style.run);
            if style.shading.is_some() {
                out.shading = style.shading;
            }
            if style.align.is_some() {
                out.align = style.align;
            }
            out.add_regions(&style.regions);
        }
        out
    }

    /// The run properties of the document defaults (`w:rPrDefault`), or Word's own template's
    /// when the styles part has none.
    pub(crate) const fn default_run(&self) -> &RunProps {
        &self.default_run
    }

    /// Whether the run defaults are Word's own template's, as the styles part has no
    /// `w:rPrDefault`.
    pub(crate) const fn template_run_defaults(&self) -> bool {
        self.template_run_defaults
    }

    /// The ID of the default paragraph style, when the styles part names one.
    #[must_use]
    pub fn default_paragraph_style(&self) -> Option<&str> {
        self.default_paragraph_style.as_deref()
    }

    /// Makes a paragraph whose `w:pStyle` names no paragraph style of the part take the
    /// default paragraph style, as a target does that refers paragraphs to paragraph styles
    /// only.
    pub fn refer_only_paragraph_styles(&mut self) {
        self.paragraph_kind_only = true;
    }

    /// The style ID whose chain a paragraph of the style ID `style` takes: that ID, or the
    /// default paragraph style when the paragraph names none, or names an ID that is no
    /// paragraph style of the part where the styles refer to paragraph styles only.
    pub(crate) fn paragraph_style_id<'s>(&'s self, style: Option<&'s str>) -> Option<&'s str> {
        let style = style.filter(|id| {
            !self.paragraph_kind_only
                || self
                    .by_id
                    .get(*id)
                    .is_some_and(|s| s.kind == StyleKind::Paragraph)
        });
        style.or(self.default_paragraph_style.as_deref())
    }

    /// Whether the document defaults or any style in the paragraph's own style chain sets
    /// `w:jc`.
    pub(crate) fn paragraph_style_sets_alignment(&self, style: Option<&str>) -> bool {
        self.default_para.alignment.is_some()
            || self
                .chain(self.paragraph_style_id(style))
                .iter()
                .any(|s| s.para.alignment.is_some())
    }

    /// The list that a paragraph style gives a paragraph (`w:numPr` of the style or of a style
    /// that it is based on, or of the document defaults), as [`Self::paragraph`] reads it;
    /// `None` selects the default paragraph style.
    pub(crate) fn list_of(&self, style: Option<&str>) -> Option<ListRef> {
        self.paragraph(style, None).0.numbering
    }

    /// Returns the paragraph and run properties of a paragraph style after the cascade from the
    /// document defaults. `None` selects the default paragraph style, and so does an ID that
    /// is no paragraph style of the part where [`Self::refer_only_paragraph_styles`] set that. In
    /// a table, the table style comes after the document defaults and before the paragraph
    /// style.
    #[must_use]
    pub fn paragraph(
        &self,
        style: Option<&str>,
        table: Option<&TableStyle>,
    ) -> (ParaProps, RunProps) {
        let mut para = self.default_para.clone();
        let mut run = self.default_run.clone();
        if let Some(table) = table {
            para.apply(&table.para);
            run.apply_style_layer(&table.run, &self.default_run);
        }
        let id = self.paragraph_style_id(style);
        let mut para_run = RunProps::default();
        for style in self.chain(id) {
            para.apply(&style.para);
            para_run.apply(&style.run);
        }
        run.apply_style_layer(&para_run, &self.default_run);
        para.style = id.map(str::to_owned);
        (para, run)
    }

    /// Returns the paragraph properties of a paragraph whose own properties are `own`: the
    /// cascade of its style, after the table style `table` ([`Self::paragraph`]), and then
    /// `own`. It leaves out the paragraph properties of a list level, which the layout's
    /// cascade of a paragraph that it lays out puts between the style and `own`. The layout
    /// asks it where it needs a few properties of a paragraph: of the first paragraph of the
    /// next footnote, of a table or of a table row, of a footnote's paragraph for its widow
    /// control, and of a paragraph's properties before a tracked change, for their list.
    #[must_use]
    pub fn paragraph_properties_without_list_level(
        &self,
        own: &ParaProps,
        table: Option<&TableStyle>,
    ) -> ParaProps {
        let (mut para, _) = self.paragraph(own.style.as_deref(), table);
        para.apply(own);
        para
    }

    /// Returns the paragraph properties of a style with a list level's paragraph properties in
    /// the cascade: right below the youngest style of the chain that names a list, so that the
    /// styles it is based on lose to the level and it and the styles based on it win. The list
    /// of such a paragraph comes from its style.
    #[must_use]
    pub fn paragraph_with_level(
        &self,
        style: Option<&str>,
        table: Option<&TableStyle>,
        level: &ParaProps,
    ) -> ParaProps {
        let mut para = self.default_para.clone();
        if let Some(table) = table {
            para.apply(&table.para);
        }
        let id = self.paragraph_style_id(style);
        let chain = self.chain(id);
        let names_list = |style: &&Style| style.para.numbering.and_then(ListRef::id).is_some();
        let at = chain.iter().rposition(names_list).unwrap_or(chain.len());
        for (index, style) in chain.iter().enumerate() {
            if index == at {
                para.apply(level);
            }
            para.apply(&style.para);
        }
        if at == chain.len() {
            para.apply(level);
        }
        para.style = id.map(str::to_owned);
        para
    }

    /// Returns the run properties of a character style chain, without the defaults.
    #[must_use]
    pub fn character(&self, style: &str) -> RunProps {
        let mut run = RunProps::default();
        for style in self.chain(Some(style)) {
            run.apply(&style.run);
        }
        run
    }

    /// Applies a character style chain onto `target` using ECMA-376 Part 1, 17.7.3 toggle
    /// combination relative to the document defaults.
    pub(crate) fn apply_character(&self, target: &mut RunProps, style: &str) {
        target.apply_style_layer(&self.character(style), &self.default_run);
    }

    /// Whether the directly selected style has one of the built-in link names.
    /// Derived custom styles do not take this identity.
    pub(crate) fn is_link_style(&self, id: &str) -> bool {
        ["hyperlink", "followedhyperlink"]
            .iter()
            .any(|name| self.names.get(*name).is_some_and(|own| own == id))
    }

    /// The selected character style's full underline value after its style chain.
    pub(crate) fn character_underline(&self, id: &str) -> Option<Underline> {
        self.chain(Some(id))
            .iter()
            .rev()
            .find_map(|style| style.underline_kind)
    }

    /// Returns a style and its ancestors, the oldest ancestor first.
    /// Whether the styles part defines a style with this ID.
    #[must_use]
    pub fn has(&self, id: &str) -> bool {
        self.by_id.contains_key(id)
    }

    fn chain(&self, id: Option<&str>) -> Vec<&Style> {
        let mut chain = Vec::new();
        let mut next = id;
        // A style ID that the part does not define stands for no style.
        let find = |id: &str| {
            self.by_id.get(id).or_else(|| {
                params::MISSING_STYLE_FALLBACK.and_then(|fallback| self.by_id.get(fallback))
            })
        };
        while let Some(style) = next.and_then(find) {
            if chain.len() == MAX_CHAIN {
                break;
            }
            chain.push(style);
            next = style.based_on.as_deref();
        }
        chain.reverse();
        chain
    }
}

/// One value for the minor (body) fonts of a theme (`a:minorFont`) and one for its major
/// (heading) fonts (`a:majorFont`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MinorMajor<T> {
    /// The value of the minor fonts.
    pub minor: T,
    /// The value of the major fonts.
    pub major: T,
}

impl<T> MinorMajor<T> {
    /// The value of each of the two font kinds through `f`, which takes the kind's element name.
    fn read(mut f: impl FnMut(&str) -> T) -> Self {
        Self {
            minor: f("minorFont"),
            major: f("majorFont"),
        }
    }
}

/// The theme fonts.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Theme {
    /// The minor (body) and major (heading) Latin fonts (`a:latin`).
    pub latin: MinorMajor<Option<String>>,
    /// The minor (body) and major (heading) complex script fonts.
    pub bidi: MinorMajor<Option<String>>,
    /// The minor (body) and major (heading) East Asian fonts (`a:ea`), when they are set.
    pub east_asian: MinorMajor<Option<String>>,
    /// The minor and major fonts by script (`a:font`), such as `Jpan` and `Hans`.
    pub scripts: MinorMajor<Vec<(String, String)>>,
    /// The colors and line widths that shapes refer to.
    pub shapes: ShapeTheme,
    /// The Latin fonts of the theme of the target's default template, which the theme font
    /// references of a document without a theme part take.
    pub template: MinorMajor<Option<&'static str>>,
}

impl Theme {
    /// The theme of a document without a theme part, on a target whose default template has
    /// the minor (body) Latin font `minor` and the major (heading) Latin font `major`.
    #[must_use]
    pub fn of_template(minor: &'static str, major: &'static str) -> Self {
        Self {
            template: MinorMajor {
                minor: Some(minor),
                major: Some(major),
            },
            ..Self::default()
        }
    }

    /// Reads `word/theme/theme1.xml`.
    pub(crate) fn read(reader: &mut PartReader, root: NodeId) -> Self {
        let doc = reader.doc;
        let scheme = doc
            .child(root, A, "themeElements")
            .and_then(|node| doc.child(node, A, "fontScheme"));
        let latin = |kind: &str| {
            scheme
                .and_then(|node| doc.child(node, A, kind))
                .and_then(|node| doc.child(node, A, "latin"))
                .and_then(|node| doc.attribute(node, None, "typeface"))
                .map(str::to_owned)
        };
        // The complex script font, or else the font of the Arabic script.
        let bidi = |kind: &str| {
            let font = scheme.and_then(|node| doc.child(node, A, kind))?;
            let typeface = |node: NodeId| {
                doc.attribute(node, None, "typeface")
                    .filter(|name| !name.is_empty())
                    .map(str::to_owned)
            };
            doc.child(font, A, "cs").and_then(typeface).or_else(|| {
                doc.child_elements(font)
                    .filter(|node| doc.is(*node, A, "font"))
                    .find(|node| doc.attribute(*node, None, "script") == Some("Arab"))
                    .and_then(typeface)
            })
        };
        let east_asian = |kind: &str| {
            let font = scheme.and_then(|node| doc.child(node, A, kind))?;
            doc.child(font, A, "ea")
                .and_then(|node| doc.attribute(node, None, "typeface"))
                .filter(|name| !name.is_empty())
                .map(str::to_owned)
        };
        let scripts = |kind: &str| -> Vec<(String, String)> {
            let Some(font) = scheme.and_then(|node| doc.child(node, A, kind)) else {
                return Vec::new();
            };
            doc.child_elements(font)
                .filter(|node| doc.is(*node, A, "font"))
                .filter_map(|node| {
                    let script = doc.attribute(node, None, "script")?;
                    let typeface = doc.attribute(node, None, "typeface")?;
                    Some((script.to_owned(), typeface.to_owned()))
                })
                .collect()
        };
        Self {
            latin: MinorMajor::read(latin),
            bidi: MinorMajor::read(bidi),
            east_asian: MinorMajor::read(east_asian),
            scripts: MinorMajor::read(scripts),
            shapes: ShapeTheme::read(doc, root, reader.drawing_warnings()),
            template: MinorMajor::default(),
        }
    }

    /// The family name that a font reference stands for, for text whose East Asian language
    /// is `lang`. The theme's East Asian font is its `a:ea` typeface, or else its font for the
    /// script of that language.
    #[must_use]
    pub fn family_for<'a>(
        &'a self,
        font: &'a FontRef,
        script: Option<EastAsianScript>,
    ) -> Option<&'a str> {
        let (own, scripts) = match font {
            FontRef::MinorEastAsia => (&self.east_asian.minor, &self.scripts.minor),
            FontRef::MajorEastAsia => (&self.east_asian.major, &self.scripts.major),
            _ => return self.family(font),
        };
        own.as_deref().or_else(|| {
            let name = script?.theme_name();
            scripts
                .iter()
                .find(|(script, _)| script == name)
                .map(|(_, typeface)| typeface.as_str())
        })
    }

    /// Returns the family name that a font reference stands for.
    #[must_use]
    pub fn family<'a>(&'a self, font: &'a FontRef) -> Option<&'a str> {
        match font {
            FontRef::Name(name) => Some(name),
            FontRef::MinorLatin => self.latin.minor.as_deref().or(self.template.minor),
            FontRef::MajorLatin => self.latin.major.as_deref().or(self.template.major),
            FontRef::MinorBidi => self.bidi.minor.as_deref(),
            FontRef::MajorBidi => self.bidi.major.as_deref(),
            FontRef::MinorEastAsia => self.east_asian.minor.as_deref(),
            FontRef::MajorEastAsia => self.east_asian.major.as_deref(),
        }
    }
}

/// Alternate font names from the font table, and the East Asian character sets and the
/// character sets of suffixed font names that the fonts' entries name.
///
///
/// Word finds an entry whose name differs from the run's font name in the case of ASCII
/// letters, as [`FamilyName`] compares names.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FontTable {
    alternates: HashMap<FamilyName, FamilyName>,
    charsets: HashMap<FamilyName, EntryCharset>,
    /// The font class of each entry, `None` for an entry that names none.
    classes: HashMap<FamilyName, Option<FontClass>>,
    /// The complex script that each entry names, for the entries that name one.
    scripts: HashMap<FamilyName, EntryScript>,
}

/// The **font class** of a font table entry, its `w:family` (in the WordprocessingML schema of
/// ECMA-376, `wml.xsd`: a child of `CT_Font` whose `w:val` has the type `ST_FontFamily`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FontClass {
    /// `decorative`: novelty fonts.
    Decorative,
    /// `modern`: fonts of one width for each character.
    Modern,
    /// `roman`: proportional fonts with serifs.
    Roman,
    /// `script`: fonts that look like handwriting.
    Script,
    /// `swiss`: proportional fonts without serifs.
    Swiss,
    /// `auto`: no class.
    Auto,
}

/// What a font table holds for a font name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FontEntry {
    /// The table has no entry of the name.
    Absent,
    /// The entry names no font class, or one that `ST_FontFamily` lacks.
    NoClass,
    /// The entry's font class.
    Class(FontClass),
}

impl FontClass {
    /// The class of a `w:family` value, or `None` for a value that `ST_FontFamily` lacks.
    fn of(value: &str) -> Option<Self> {
        match value {
            "decorative" => Some(Self::Decorative),
            "modern" => Some(Self::Modern),
            "roman" => Some(Self::Roman),
            "script" => Some(Self::Script),
            "swiss" => Some(Self::Swiss),
            "auto" => Some(Self::Auto),
            _ => None,
        }
    }
}

/// An East Asian character set that a font table entry names in `w:charset` (ECMA-376
/// Part 1, 17.8.3.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EastAsianCharset {
    /// Shift JIS, for Japanese (`80`).
    ShiftJis,
    /// Hangul, for Korean (`81`).
    Hangul,
    /// GB 2312, for Simplified Chinese (`86`).
    Gb2312,
    /// Big5, for Traditional Chinese (`88`).
    Big5,
}

impl EastAsianCharset {
    /// The character set of a `w:charset` value, a byte in hexadecimal.
    fn of(value: &str) -> Option<Self> {
        match value {
            "80" => Some(Self::ShiftJis),
            "81" => Some(Self::Hangul),
            "86" => Some(Self::Gb2312),
            "88" => Some(Self::Big5),
            _ => None,
        }
    }
}

/// A character set of a **suffixed font name**: a font name whose last word names a Windows
/// character set, such as `CYR` in `Times New Roman CYR`. A font table entry names the set in
/// `w:charset` (ECMA-376 Part 1, 17.8.3.2), as the character set values of a Windows `LOGFONT`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SuffixCharset {
    /// Central European, the suffix `CE` (`EE`).
    CentralEuropean,
    /// Cyrillic, the suffix `CYR` (`CC`).
    Cyrillic,
    /// Greek, the suffix `Greek` (`A1`).
    Greek,
    /// Baltic, the suffix `Baltic` (`BA`).
    Baltic,
    /// Turkish, the suffix `TUR` (`A2`).
    Turkish,
}

impl SuffixCharset {
    /// The suffixes of suffixed font names, each with the `w:charset` value of its character
    /// set and the set.
    const SUFFIXES: [(&'static str, &'static str, Self); 5] = [
        ("CE", "EE", Self::CentralEuropean),
        ("CYR", "CC", Self::Cyrillic),
        ("Greek", "A1", Self::Greek),
        ("Baltic", "BA", Self::Baltic),
        ("TUR", "A2", Self::Turkish),
    ];

    /// The character set of a `w:charset` value, a byte in hexadecimal that compares as
    /// [`numbers::hex`] reads it.
    fn of(value: &str) -> Option<Self> {
        let value = numbers::hex(value)?;
        Self::SUFFIXES
            .into_iter()
            .find(|(_, code, _)| numbers::hex(code) == Some(value))
            .map(|(_, _, set)| set)
    }

    /// The family name before the suffix of a suffixed font name, and the suffix's character
    /// set, or `None` for another name. The suffix compares as [`FamilyName`] compares names,
    /// without regard to the case of ASCII letters.
    #[must_use]
    pub fn split(name: &str) -> Option<(&str, Self)> {
        let (base, suffix) = name.trim().rsplit_once(' ')?;
        let suffix = FamilyName::new(suffix);
        let (_, _, set) = Self::SUFFIXES
            .into_iter()
            .find(|(written, _, _)| suffix.is(written))?;
        let base = base.trim_end();
        (!base.is_empty()).then_some((base, set))
    }
}

/// The complex script that a font table entry names: by its character set (`w:charset`,
/// ECMA-376 Part 1, 17.8.3.2), or else by a code page of its font signature (`w:csb0` of
/// `w:sig`, 17.8.3.16, whose bits are those of `ulCodePageRange1` in the OpenType `OS/2`
/// table).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntryScript {
    /// Arabic: the character set `B2`, or the code page 1256.
    Arabic,
    /// Hebrew: the character set `B1`, or the code page 1255.
    Hebrew,
}

impl EntryScript {
    /// The script of an entry's `w:charset` value and its signature's `w:csb0` value: that of
    /// the character set, or else that of the lowest code page of a complex script that the
    /// signature names, or `None` when neither names one.
    fn of(charset: Option<&str>, code_pages: Option<&str>) -> Option<Self> {
        use crate::params::{
            ARABIC_CHARSET, ARABIC_CODE_PAGE_BIT, HEBREW_CHARSET, HEBREW_CODE_PAGE_BIT,
        };
        match charset.and_then(numbers::hex) {
            Some(ARABIC_CHARSET) => return Some(Self::Arabic),
            Some(HEBREW_CHARSET) => return Some(Self::Hebrew),
            _ => {}
        }
        let pages = code_pages.and_then(numbers::hex)?;
        if pages >> HEBREW_CODE_PAGE_BIT & 1 == 1 {
            Some(Self::Hebrew)
        } else if pages >> ARABIC_CODE_PAGE_BIT & 1 == 1 {
            Some(Self::Arabic)
        } else {
            None
        }
    }
}

/// A character set that a font table entry names and that a rule reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EntryCharset {
    /// An East Asian character set.
    EastAsian(EastAsianCharset),
    /// The character set of a suffixed font name.
    Suffix(SuffixCharset),
}

impl EntryCharset {
    /// The character set of a `w:charset` value, or `None` for a set that no rule reads.
    fn of(value: &str) -> Option<Self> {
        EastAsianCharset::of(value)
            .map(Self::EastAsian)
            .or_else(|| SuffixCharset::of(value).map(Self::Suffix))
    }
}

impl FontTable {
    /// Reads `word/fontTable.xml`.
    ///
    /// Of entries whose names name one family, the first one counts and the others are left
    /// out, as the package reader keeps the first of equivalent entries.
    pub fn read(doc: &Document, root: NodeId) -> Self {
        let mut table = Self::default();
        let mut seen = HashSet::new();
        let fonts = doc
            .child_elements(root)
            .filter(|node| doc.is(*node, W, "font"));
        for node in fonts {
            let Some(name) = doc.attribute(node, Some(W), "name") else {
                continue;
            };
            let name = FamilyName::new(name);
            if !seen.insert(name.clone()) {
                continue;
            }
            let charset = doc
                .child(node, W, "charset")
                .and_then(|set| doc.attribute(set, Some(W), "val"));
            if let Some(set) = charset.and_then(EntryCharset::of) {
                table.charsets.insert(name.clone(), set);
            }
            let code_pages = doc
                .child(node, W, "sig")
                .and_then(|sig| doc.attribute(sig, Some(W), "csb0"));
            if let Some(script) = EntryScript::of(charset, code_pages) {
                table.scripts.insert(name.clone(), script);
            }
            let class = doc
                .child(node, W, "family")
                .and_then(|family| doc.attribute(family, Some(W), "val"))
                .and_then(FontClass::of);
            table.classes.insert(name.clone(), class);
            let alternate = doc
                .child(node, W, "altName")
                .and_then(|alt| doc.attribute(alt, Some(W), "val"))
                .and_then(|alt| alt.split(',').next())
                .map(str::trim)
                .filter(|alt| !alt.is_empty());
            if let Some(alt) = alternate {
                table.alternates.insert(name, FamilyName::new(alt));
            }
        }
        table
    }

    /// Returns the alternate name that the font table gives for a font.
    #[must_use]
    pub fn alternate(&self, name: &FamilyName) -> Option<&FamilyName> {
        self.alternates.get(name)
    }

    /// The East Asian character set that the font table's entry for a font names.
    #[must_use]
    pub fn east_asian_charset(&self, name: &FamilyName) -> Option<EastAsianCharset> {
        match self.charsets.get(name) {
            Some(EntryCharset::EastAsian(set)) => Some(*set),
            Some(EntryCharset::Suffix(_)) | None => None,
        }
    }

    /// The character set of a suffixed font name that the font table's entry for a font names.
    #[must_use]
    pub fn suffix_charset(&self, name: &FamilyName) -> Option<SuffixCharset> {
        match self.charsets.get(name) {
            Some(EntryCharset::Suffix(set)) => Some(*set),
            Some(EntryCharset::EastAsian(_)) | None => None,
        }
    }

    /// The complex script that the font table's entry for a font names.
    #[must_use]
    pub fn complex_script(&self, name: &FamilyName) -> Option<EntryScript> {
        self.scripts.get(name).copied()
    }

    /// What the font table's entry for a font says of its font class.
    #[must_use]
    pub fn entry(&self, name: &FamilyName) -> FontEntry {
        match self.classes.get(name) {
            None => FontEntry::Absent,
            Some(None) => FontEntry::NoClass,
            Some(Some(class)) => FontEntry::Class(*class),
        }
    }
}

/// Document settings that layout needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Settings {
    /// The distance between default tab stops.
    pub default_tab_stop: Length,
    /// What the rules that depend on the compatibility mode do in this document, from the
    /// `compatibilityMode` compatibility setting.
    pub mode_rules: ModeRules,
    /// Whether even pages have their own headers and footers (`w:evenAndOddHeaders`).
    pub even_and_odd_headers: bool,
    /// How footnotes and endnotes are numbered and where they stand (`w:footnotePr`,
    /// `w:endnotePr`), which each section's own elements stand over.
    pub notes: ByNoteKind<NoteSetup>,
    /// Whether the left indent of a hanging indent is a tab stop for the tab after a list
    /// label. `w:doNotUseIndentAsNumberingTabStop` turns it off.
    pub indent_is_numbering_tab_stop: bool,
    /// Whether the gutter lies in the top margin (`w:gutterAtTop`) instead of the left one.
    pub gutter_at_top: bool,
    /// Which side margins the pages take (`w:mirrorMargins`).
    pub side_margins: SideMargins,
    /// Which separator stands above the footnotes of a page.
    pub footnote_separators: NoteSeparators,
    /// The script of the document's East Asian language (`w:themeFontLang w:eastAsia`), for
    /// text whose run properties name none.
    pub east_asian_script: Option<EastAsianScript>,
    /// Whether kerned runs close up pairs of punctuation marks.
    pub punctuation_kerning: PunctuationKerning,
    /// What justified lines do with the blank halves of punctuation marks.
    pub punctuation: Punctuation,
    /// Whether justified lines without spaces spread their room over the gaps between glyphs.
    pub gap_spread: GapSpread,
    /// How much of its run's character spacing a full-width character takes.
    pub full_width_spacing: FullWidthSpacing,
    /// How wide a space next to East Asian text is.
    pub space_balance: SpaceBalance,
    /// Whether the lines of table cells follow the section's line grid.
    pub cell_grid: CellGrid,
    /// Whether a justified paragraph justifies its lines that end in a soft line break.
    pub soft_break_lines: SoftBreakLines,
    /// Whose justification the settings ask for (`w:wpJustification`).
    pub justification: Justification,
    /// How the document reads automatic paragraph spacing.
    pub html_auto_spacing: HtmlAutoSpacing,
    /// Whether the settings ask for the styles of the template.
    pub template_styles: TemplateStyles,
    /// The document's automatic hyphenation (`w:autoHyphenation`), or `None` when it is off.
    pub hyphenation: Option<AutoHyphenation>,
    /// The page color of the main document (`w:background w:color`), or `None` when it has
    /// none. It fills every page under all else, also when the settings do not ask to show it
    /// (`w:displayBackgroundShape`), and it is the shading behind automatic text where no fill
    /// lies.
    pub page_color: Option<[u8; 3]>,
    /// Whether display fractions step down in size like inline fractions (`m:mathPr/m:smallFrac`).
    pub(crate) small_frac: crate::props::SmallFractions,
    /// Whether `w:compat/w:spaceForUL` is set, which shifts the alignment box of exact lines
    /// under `w:textAlignment`.
    pub(crate) space_for_ul: SpaceForUl,
}

/// Whether `w:compat/w:spaceForUL` is set in `word/settings.xml`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SpaceForUl {
    /// Option absent or off.
    #[default]
    Off,
    /// Option set.
    On,
}

impl SpaceForUl {
    const fn of(set: bool) -> Self {
        if set { Self::On } else { Self::Off }
    }
}

/// The settings of a document's automatic hyphenation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AutoHyphenation {
    /// The hyphenation zone (`w:hyphenationZone`): in the compatibility modes where it holds, a
    /// word that does not fit is hyphenated only when the room that the line leaves for it is
    /// wider than the zone.
    pub zone: Length,
    /// The most lines in a row that may end with a hyphen (`w:consecutiveHyphenLimit`), or
    /// `None` for no limit, which 0 and a missing element give.
    pub limit: Option<std::num::NonZeroUsize>,
    /// Whether words in capitals are hyphenated (`w:doNotHyphenateCaps`).
    pub capitals: Capitals,
}

/// Whether automatic hyphenation hyphenates a word whose letters are all capitals.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Capitals {
    /// Words in capitals are hyphenated as other words.
    Hyphenated,
    /// Words in capitals stay whole (`w:doNotHyphenateCaps`).
    Kept,
}

/// Which separator stands above the footnotes of a page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NoteSeparators {
    /// The settings list no special footnotes, so the separator is the application's own
    /// and not the one that the footnotes part has.
    #[default]
    Own,
    /// The settings list special footnotes (`w:footnotePr` with `w:footnote`), which are the
    /// separators of the footnotes part.
    Listed,
}

impl NoteSeparators {
    /// Reads which separator the settings under `root` ask for.
    fn read(doc: &Document, root: NodeId) -> Self {
        let listed = doc
            .child(root, W, "footnotePr")
            .is_some_and(|list| doc.child(list, W, "footnote").is_some());
        if listed { Self::Listed } else { Self::Own }
    }
}

/// Whether a document's settings ask the application to update its styles from the template.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TemplateStyles {
    /// No `w:linkStyles`, or the settings name an attached template.
    #[default]
    Kept,
    /// `w:linkStyles` is on and the settings name no attached template, so the template is
    /// the application's own.
    Linked,
}

/// Whether the lines of table cells follow the section's line grid.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CellGrid {
    /// A cell's lines keep their own heights, as without a grid.
    #[default]
    Own,
    /// A cell's lines follow the grid as the body's do: the compatibility option
    /// `w:adjustLineHeightInTable` is set.
    Follows,
}

/// Which side margins the pages of a document take.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SideMargins {
    /// Every page takes the left and right margins of its section.
    #[default]
    Section,
    /// A mirrored page, one with an even number, swaps the left and right margins of its
    /// section (`w:mirrorMargins`).
    Mirrored,
    /// Book-fold printing (`w:bookFoldPrinting`): on landscape sections, `w:right + w:gutter`
    /// sits on the inside edge (left on odd pages, right on even pages) and `w:left` sits on the
    /// outside edge; on portrait sections, `w:gutter` is omitted from `w:left`.
    BookFold,
    /// Reverse book-fold printing (`w:bookFoldRevPrinting`): on landscape sections,
    /// `w:right + w:gutter` sits on the inside edge (right on odd pages, left on even pages) and
    /// `w:left` sits on the outside edge; on portrait sections, `w:gutter` is omitted from
    /// `w:left`.
    BookFoldReverse,
}

impl SideMargins {
    /// Reads side-margin settings (`w:mirrorMargins`, `w:bookFoldPrinting`, `w:bookFoldRevPrinting`).
    fn read(doc: &Document, root: NodeId) -> Self {
        let on = |name: &str| {
            doc.child(root, W, name)
                .is_some_and(|n| on_off::off_only_for_0_or_false(doc, n))
        };
        if on("mirrorMargins") {
            Self::Mirrored
        } else if on("bookFoldPrinting") {
            Self::BookFold
        } else if on("bookFoldRevPrinting") {
            Self::BookFoldReverse
        } else {
            Self::Section
        }
    }
}

/// How wide a space (U+0020) next to East Asian text is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SpaceBalance {
    /// Every space keeps its font's own width.
    #[default]
    Own,
    /// A space next to an East Asian character, and the spaces that it stands among, advance
    /// half an em of their font: the compatibility options
    /// `w:balanceSingleByteDoubleByteWidth` and `w:useFELayout` are both set.
    HalfEm,
}

/// How much of its run's character spacing a full-width character takes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FullWidthSpacing {
    /// The spacing once, as every other character.
    #[default]
    Once,
    /// The spacing twice, once for each half cell: the compatibility option
    /// `w:balanceSingleByteDoubleByteWidth` is set.
    Twice,
}

/// Whether kerned runs close up pairs of East Asian punctuation marks by half an em.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PunctuationKerning {
    /// Every mark keeps its width.
    #[default]
    Off,
    /// Kerned runs close up the pairs: the compatibility option `w:useFELayout` is set and
    /// `w:noPunctuationKerning` is not.
    On,
}

/// `ST_CharacterSpacing` (`w:characterSpacingControl`), as whether punctuation is compressed:
/// the compression of Japanese kana too is drawn as that of punctuation only.
const CHARACTER_SPACING: &Values<bool> = &Values::new(&[
    own("doNotCompress", false),
    own("compressPunctuation", true),
    another("compressPunctuationAndJapaneseKana", true),
]);

/// What justified lines do with the blank halves of punctuation marks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Punctuation {
    /// They keep their width.
    #[default]
    Kept,
    /// They shrink so that more text fits: `w:characterSpacingControl` is
    /// `compressPunctuation` and the compatibility option `w:useFELayout` is set.
    Compressed,
}

/// What a justified line without spaces does with the room that it has left.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GapSpread {
    /// It keeps the room at its end.
    #[default]
    Kept,
    /// It spreads the room over the gaps between its glyphs in equal shares: the compatibility
    /// option `w:useFELayout` is set, whatever the punctuation does.
    Spread,
}

impl GapSpread {
    /// The gap spread of a document that sets `w:useFELayout` (`east_asian_layout`) or not.
    const fn of(east_asian_layout: bool) -> Self {
        if east_asian_layout {
            Self::Spread
        } else {
            Self::Kept
        }
    }
}

/// Whose justification the settings ask for: Word's own, or that of `WordPerfect`, which the
/// compatibility option `w:wpJustification` asks for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Justification {
    /// Word's own.
    #[default]
    Word,
    /// That of `WordPerfect`: the option is set.
    WordPerfect,
}

impl Justification {
    /// The justification where the option is set (`set`) or not.
    const fn of(set: bool) -> Self {
        if set { Self::WordPerfect } else { Self::Word }
    }
}

/// Whether a justified paragraph justifies its lines that end in a soft line break (a `w:br`
/// without a page or column type, or a `w:cr`), as the compatibility option
/// `w:doNotExpandShiftReturn` says (ECMA-376 Part 1, 17.15.3.5).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SoftBreakLines {
    /// Justified, as every line of the paragraph but its last.
    #[default]
    Justified,
    /// Aligned as the paragraph's last line: the option is set.
    AsLastLine,
}

impl SoftBreakLines {
    /// The alignment of the lines where the option is set (`set`) or not.
    fn of(set: bool) -> Self {
        if set {
            Self::AsLastLine
        } else {
            Self::Justified
        }
    }
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            default_tab_stop: Length::from_units(
                params::DEFAULT_TAB_DISTANCE * Length::UNITS_PER_TWIP,
            ),
            mode_rules: ModeRules::default(),
            even_and_odd_headers: false,
            notes: ByNoteKind::DEFAULT,
            indent_is_numbering_tab_stop: true,
            gutter_at_top: false,
            side_margins: SideMargins::Section,
            footnote_separators: NoteSeparators::Own,
            east_asian_script: None,
            punctuation_kerning: PunctuationKerning::Off,
            punctuation: Punctuation::Kept,
            gap_spread: GapSpread::Kept,
            full_width_spacing: FullWidthSpacing::Once,
            space_balance: SpaceBalance::Own,
            cell_grid: CellGrid::Own,
            soft_break_lines: SoftBreakLines::Justified,
            justification: Justification::Word,
            html_auto_spacing: HtmlAutoSpacing::Html,
            template_styles: TemplateStyles::Kept,
            hyphenation: None,
            page_color: None,
            small_frac: crate::props::SmallFractions::Off,
            space_for_ul: SpaceForUl::Off,
        }
    }
}

/// The automatic hyphenation that the settings `root` turn on (`w:autoHyphenation`, read as
/// `ST_OnOff`), with its zone, its limit and its rule for capitals, or `None` when it is off.
fn auto_hyphenation(reader: &mut PartReader, root: NodeId) -> Option<AutoHyphenation> {
    let doc = reader.doc;
    if !doc
        .child(root, W, "autoHyphenation")
        .is_some_and(|node| on_off::element(doc, node, W))
    {
        return None;
    }
    let zone = doc
        .child(root, W, "hyphenationZone")
        .and_then(|node| reader.twips(node, "val"))
        .filter(|zone| zone.units() >= 0)
        .unwrap_or(Length::from_units(
            params::DEFAULT_HYPHENATION_ZONE * Length::UNITS_PER_TWIP,
        ));
    let limit = doc
        .child(root, W, "consecutiveHyphenLimit")
        .and_then(|node| reader.number::<usize>(node, "val", numbers::NOT_NEGATIVE))
        .and_then(std::num::NonZeroUsize::new);
    let capitals = if doc
        .child(root, W, "doNotHyphenateCaps")
        .is_some_and(|node| on_off::element(doc, node, W))
    {
        Capitals::Kept
    } else {
        Capitals::Hyphenated
    };
    Some(AutoHyphenation {
        zone,
        limit,
        capitals,
    })
}

impl Settings {
    /// Reads `word/settings.xml`.
    pub(crate) fn read(reader: &mut PartReader, root: NodeId) -> Self {
        let doc = reader.doc;
        let defaults = Self::default();
        // A distance of 0 leaves no default stops, so that a tab without a custom stop after
        // it takes no room.
        let default_tab_stop = doc
            .child(root, W, "defaultTabStop")
            .and_then(|node| reader.twips(node, "val"))
            .filter(|stop| stop.units() >= 0)
            .unwrap_or(defaults.default_tab_stop);
        let compat = doc.child(root, W, "compat");
        let compat_on = |name: &str| {
            compat
                .and_then(|c| doc.child(c, W, name))
                .is_some_and(|n| on_off::off_only_for_0_or_false(doc, n))
        };
        let use_fe_layout = compat_on("useFELayout");
        let indent_is_numbering_tab_stop = !compat
            .and_then(|c| doc.child(c, W, "doNotUseIndentAsNumberingTabStop"))
            .is_some_and(|n| on_off::off_only_for_0_or_false(doc, n));
        // Word also reads the mode outside `w:compat`.
        let compat_setting = |name: &str| {
            compat
                .into_iter()
                .flat_map(|compat| doc.child_elements(compat))
                .chain(doc.child_elements(root))
                .filter(|node| doc.is(*node, W, "compatSetting"))
                .find(|node| doc.attribute(*node, Some(W), "name") == Some(name))
        };
        let compatibility_mode = CompatibilityMode::read(
            compat_setting("compatibilityMode")
                .and_then(|node| reader.number(node, "val", numbers::ANY)),
        );
        let open_type_features = compat_setting("enableOpenTypeFeatures")
            .and_then(|node| doc.attribute(node, Some(W), "val"))
            .is_some_and(|value| on_off::read(value) == Some(true));
        let on = |name: &str| {
            doc.child(root, W, name)
                .is_some_and(|n| on_off::off_only_for_0_or_false(doc, n))
        };
        let even_and_odd_headers = on("evenAndOddHeaders");
        let hyphenation = auto_hyphenation(reader, root);
        let notes = ByNoteKind::read(reader, root).over(defaults.notes);
        let compressed = doc
            .child(root, W, "characterSpacingControl")
            .and_then(|node| reader.enumeration(node, "val", CHARACTER_SPACING))
            .unwrap_or(false);
        Self {
            default_tab_stop,
            mode_rules: ModeRules::of(compatibility_mode)
                .with_open_type_features(open_type_features),
            even_and_odd_headers,
            notes,
            indent_is_numbering_tab_stop,
            gutter_at_top: on("gutterAtTop"),
            side_margins: SideMargins::read(doc, root),
            footnote_separators: NoteSeparators::read(doc, root),
            template_styles: if on("linkStyles") && doc.child(root, W, "attachedTemplate").is_none()
            {
                TemplateStyles::Linked
            } else {
                TemplateStyles::Kept
            },
            east_asian_script: doc
                .child(root, W, "themeFontLang")
                .and_then(|node| doc.attribute(node, Some(W), "eastAsia"))
                .and_then(EastAsianScript::of),
            punctuation_kerning: if use_fe_layout && !on("noPunctuationKerning") {
                PunctuationKerning::On
            } else {
                PunctuationKerning::Off
            },
            punctuation: if use_fe_layout && compressed {
                Punctuation::Compressed
            } else {
                Punctuation::Kept
            },
            gap_spread: GapSpread::of(use_fe_layout),
            full_width_spacing: if compat_on("balanceSingleByteDoubleByteWidth") {
                FullWidthSpacing::Twice
            } else {
                FullWidthSpacing::Once
            },
            space_balance: if use_fe_layout && compat_on("balanceSingleByteDoubleByteWidth") {
                SpaceBalance::HalfEm
            } else {
                SpaceBalance::Own
            },
            cell_grid: if compat_on("adjustLineHeightInTable") {
                CellGrid::Follows
            } else {
                CellGrid::Own
            },
            soft_break_lines: SoftBreakLines::of(compat_on("doNotExpandShiftReturn")),
            justification: Justification::of(compat_on("wpJustification")),
            html_auto_spacing: HtmlAutoSpacing::of(compat_on("doNotUseHTMLParagraphAutoSpacing")),
            hyphenation,
            page_color: None,
            small_frac: small_fractions(doc, root),
            space_for_ul: SpaceForUl::of(compat_on("spaceForUL")),
        }
    }
}

fn small_fractions(doc: &Document, root: NodeId) -> crate::props::SmallFractions {
    if doc
        .child(root, M, "mathPr")
        .and_then(|pr| doc.child(pr, M, "smallFrac"))
        .is_some_and(|node| on_off::element(doc, node, M))
    {
        crate::props::SmallFractions::On
    } else {
        crate::props::SmallFractions::Off
    }
}

#[cfg(test)]
mod tests {
    use super::{Settings, Styles, TemplateStyles, Theme};
    use crate::mode::{CompatibilityMode, ModeRules};
    use crate::ns::{A, M, W};
    use crate::numbering::Format;
    use crate::params;
    use crate::props::{Alignment, EastAsianScript, FontRef, LineSpacing, ParaProps};
    use crate::quirks::TemplateFonts;
    use crate::reader::PartReader;
    use crate::table::{Region, VerticalAlign};
    use f_office_fonts::FamilyName;
    use f_office_units::Length;
    use f_office_xml::{Document, Limits};

    const STYLES: &str = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
      <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:pPr></w:pPrDefault></w:docDefaults>
      <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:pPr><w:jc w:val="left"/></w:pPr></w:style>
      <w:style w:type="paragraph" w:styleId="Title"><w:basedOn w:val="Normal"/><w:pPr><w:jc w:val="center"/></w:pPr><w:rPr><w:sz w:val="56"/></w:rPr></w:style>
      <w:style w:type="paragraph" w:styleId="Loop"><w:basedOn w:val="Loop"/></w:style>
      <w:style w:type="character" w:styleId="Strong"><w:rPr><w:b/></w:rPr></w:style>
    </w:styles>"#;

    fn parse(xml: &str) -> Document {
        Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
    }

    #[test]
    fn reads_text_outside_the_kind_of_a_style_as_a_paragraph_style() {
        let default_style = |kind: &str| {
            let doc = parse(&format!(
                r#"<w:styles xmlns:w="{W}"><w:style w:type="{kind}" w:default="1" w:styleId="S"/></w:styles>"#
            ));
            let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
            styles.default_paragraph_style().map(str::to_owned)
        };
        let read = ["paragraph", "Paragraph", "", "list", "table"].map(default_style);
        let s = Some("S".to_owned());
        assert_eq!(read, [s.clone(), s.clone(), s.clone(), s, None]);
    }

    #[test]
    fn finds_a_style_by_its_name_by_its_name_and_aliases_and_by_its_id() {
        let doc = parse(&format!(
            r#"<w:styles xmlns:w="{W}"><w:style w:type="paragraph" w:styleId="H2"><w:name w:val="Head Two"/><w:aliases w:val="h2,Second"/></w:style></w:styles>"#
        ));
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let found = ["head two", "HEAD TWO,h2,second", "H2", "h2", "Head Two,h2"]
            .map(|name| styles.id_of(name).to_owned());
        // An alias alone, or only some of the aliases, names no style.
        assert_eq!(found, ["H2", "H2", "H2", "h2", "Head Two,h2"]);
    }

    #[test]
    fn cascades_paragraph_styles() {
        let doc = parse(STYLES);
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let (para, run) = styles.paragraph(Some("Title"), None);
        assert_eq!(para.alignment, Some(Alignment::Center));
        assert_eq!(para.after, Length::from_twips(160));
        assert_eq!(run.size, Some(56));
    }

    #[test]
    fn puts_a_list_level_right_below_the_style_that_names_the_list() {
        // `Base` sets the left indent, `List` names a list and sets the hanging indent, and
        // `Item` is based on `List`.
        let doc = parse(&format!(
            r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:pPrDefault/></w:docDefaults>
            <w:style w:type="paragraph" w:styleId="Base"><w:pPr><w:ind w:left="100"/></w:pPr></w:style>
            <w:style w:type="paragraph" w:styleId="List"><w:basedOn w:val="Base"/><w:pPr><w:numPr><w:numId w:val="3"/></w:numPr><w:ind w:hanging="50"/></w:pPr></w:style>
            <w:style w:type="paragraph" w:styleId="Item"><w:basedOn w:val="List"/><w:pPr><w:spacing w:after="20"/></w:pPr></w:style>
            </w:styles>"#
        ));
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let twips = |t: i64| Length::from_twips(t);
        let level = crate::props::ParaProps {
            indent_left: twips(720),
            indent_first: twips(-360),
            after: twips(40),
            ..crate::props::ParaProps::default()
        };
        let props = styles.paragraph_with_level(Some("Item"), None, &level);
        // The level wins over `Base`, and `List` and `Item` win over the level.
        assert_eq!(
            (props.indent_left, props.indent_first, props.after),
            (twips(720), twips(-50), twips(20))
        );
        // Without a style that names a list, the level comes after all styles.
        let props = styles.paragraph_with_level(Some("Base"), None, &level);
        assert_eq!(
            (props.indent_left, props.indent_first),
            (twips(720), twips(-360))
        );
    }

    #[test]
    fn spaces_paragraphs_like_word_without_default_paragraph_properties() {
        let read = |defaults: &str| {
            let doc = parse(&format!(
                r#"<w:styles xmlns:w="{W}"><w:docDefaults>{defaults}</w:docDefaults></w:styles>"#
            ));
            let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
            let (para, _) = styles.paragraph(None, None);
            (para.after, para.line)
        };
        let word = (Length::from_twips(160), Some(LineSpacing::Auto(278)));
        assert_eq!(read(""), word);
        // A default that is present, even without spacing, keeps the defaults of ECMA-376.
        assert_eq!(read("<w:pPrDefault><w:pPr/></w:pPrDefault>"), (None, None));
    }

    #[test]
    fn kerns_and_joins_ligatures_like_word_without_default_run_properties() {
        let read = |styles: &str| {
            let doc = parse(&format!(r#"<w:styles xmlns:w="{W}">{styles}</w:styles>"#));
            let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
            let (_, run) = styles.paragraph(None, None);
            (run.kern, run.ligatures)
        };
        assert_eq!(read(""), (Some(2), Some(true)));
        assert_eq!(read("<w:docDefaults/>"), (Some(2), Some(true)));
        // A default that is present, even without these properties, keeps them off, and a
        // style can turn them off.
        let present = "<w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults>";
        assert_eq!(read(present), (None, None));
        let normal = r#"<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:rPr><w:kern w:val="0"/></w:rPr></w:style>"#;
        assert_eq!(read(normal), (Some(0), Some(true)));
    }

    #[test]
    fn takes_the_template_font_and_size_without_default_run_properties() {
        let template = (Some(FontRef::MinorLatin), Some(params::TEMPLATE_FONT_SIZE));
        let read = |styles: &str| {
            let doc = parse(&format!(r#"<w:styles xmlns:w="{W}">{styles}</w:styles>"#));
            let (_, run) =
                Styles::read(&mut PartReader::new(&doc), doc.root().unwrap()).paragraph(None, None);
            (run.font_ascii, run.size)
        };
        assert_eq!(read(""), template);
        assert_eq!(
            read("<w:docDefaults><w:pPrDefault/></w:docDefaults>"),
            template
        );
        // Default run properties that name no font or size keep the defaults of ECMA-376.
        let present = "<w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults>";
        assert_eq!(read(present), (None, None));
        let (para, run) = Styles::without_part().paragraph(None, None);
        assert_eq!((run.font_hansi, run.size), template);
        assert_eq!(para.after, Length::from_twips(params::DEFAULT_SPACE_AFTER));
    }

    #[test]
    fn gives_theme_references_the_template_fonts_without_a_theme_part() {
        let aptos = Theme::of_template(TemplateFonts::Aptos.minor(), TemplateFonts::Aptos.major());
        assert_eq!(aptos.family(&FontRef::MinorLatin), Some("Aptos"));
        assert_eq!(aptos.family(&FontRef::MajorLatin), Some("Aptos Display"));
        assert_eq!(aptos.latin.minor, None);
        let calibri = Theme::of_template(
            TemplateFonts::Calibri.minor(),
            TemplateFonts::Calibri.major(),
        );
        assert_eq!(calibri.family(&FontRef::MinorLatin), Some("Calibri"));
        assert_eq!(calibri.family(&FontRef::MajorLatin), Some("Calibri Light"));
        assert_eq!(Theme::default().family(&FontRef::MinorLatin), None);
    }

    #[test]
    fn a_missing_style_gets_the_defaults() {
        let doc = parse(&format!(
            r#"<w:styles xmlns:w="{W}"><w:docDefaults/><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:pPr><w:spacing w:after="0"/></w:pPr></w:style></w:styles>"#
        ));
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let (para, _) = styles.paragraph(Some("Heading1"), None);
        assert_eq!(
            (para.after, para.line, para.style),
            (
                Length::from_twips(160),
                Some(LineSpacing::Auto(278)),
                Some("Heading1".to_owned())
            )
        );
        assert_eq!(styles.paragraph(None, None).0.after, Length::from_twips(0));
    }

    #[test]
    fn a_table_style_wins_over_a_template_value_that_the_defaults_give() {
        let size_in_table = |default_size: u32| {
            let doc = parse(&format!(
                r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="{default_size}"/></w:rPr></w:rPrDefault><w:pPrDefault/></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:rPr><w:sz w:val="32"/></w:rPr></w:style><w:style w:type="table" w:styleId="Grid"><w:rPr><w:sz w:val="18"/></w:rPr></w:style></w:styles>"#
            ));
            let mut styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
            styles.take_template();
            let table = styles.table(Some("Grid"));
            let (para, run) = styles.paragraph(None, Some(&table));
            (run.size, para.line)
        };
        assert_eq!(size_in_table(24), (Some(18), Some(LineSpacing::Auto(278))));
        assert_eq!(size_in_table(20), (Some(24), Some(LineSpacing::Auto(278))));
    }

    #[test]
    fn gives_a_paragraph_its_own_properties_over_its_style_and_its_table_style() {
        // Each level of the cascade sets one value that the level above it sets again: the
        // table style the defaults' space after, the paragraph style the table style's
        // alignment, and the paragraph its style's left indent. So a level that is missing, or
        // that comes in another order, gives another tuple. The helper takes no list level and
        // the styles hold no numbering, so its signature keeps it from a list level.
        let doc = parse(&format!(
            r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:pPrDefault><w:pPr><w:spacing w:after="160"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"/><w:style w:type="paragraph" w:styleId="Kept"><w:pPr><w:keepNext/><w:jc w:val="both"/><w:ind w:left="720"/></w:pPr></w:style><w:style w:type="table" w:styleId="Grid"><w:pPr><w:spacing w:after="0"/><w:jc w:val="center"/></w:pPr></w:style></w:styles>"#
        ));
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let grid = styles.table(Some("Grid"));
        let own = ParaProps {
            style: Some("Kept".to_owned()),
            indent_left: Length::from_twips(360),
            ..ParaProps::default()
        };
        // (table style, space after): the table style's space after wins over the defaults'.
        let cases = [
            (None, Length::from_twips(160)),
            (Some(&grid), Some(Length::ZERO)),
        ];
        for (table, after) in cases {
            let props = styles.paragraph_properties_without_list_level(&own, table);
            let read = (
                props.flags().keep_next,
                props.style.as_deref(),
                props.alignment,
                props.indent_left,
                props.after,
            );
            let (both, left) = (Some(Alignment::Both), Length::from_twips(360));
            assert_eq!(read, (true, Some("Kept"), both, left, after), "{table:?}");
        }
    }

    #[test]
    fn gives_a_reference_to_no_paragraph_style_the_default_paragraph_style() {
        let doc = parse(&format!(
            r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="20"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:rPr><w:sz w:val="28"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Other"><w:basedOn w:val="Normal"/><w:rPr><w:sz w:val="32"/></w:rPr></w:style><w:style w:type="character" w:styleId="BigChar"><w:rPr><w:sz w:val="40"/></w:rPr></w:style><w:style w:type="table" w:styleId="BigTable"><w:rPr><w:sz w:val="36"/></w:rPr></w:style></w:styles>"#
        ));
        let mut styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let sizes = |styles: &Styles| {
            ["Other", "BigChar", "BigTable", "Absent"]
                .map(|id| styles.paragraph(Some(id), None).1.size)
        };
        // Each ID takes the chain of what it names; an undefined one only the defaults.
        assert_eq!(sizes(&styles), [Some(32), Some(40), Some(36), Some(20)]);
        styles.refer_only_paragraph_styles();
        // A character style, a table style and an undefined ID give the default paragraph
        // style's 14 pt; a paragraph style keeps its own.
        assert_eq!(sizes(&styles), [Some(32), Some(28), Some(28), Some(28)]);
        let level = ParaProps::default();
        let props = styles.paragraph_with_level(Some("BigChar"), None, &level);
        assert_eq!(props.style.as_deref(), Some("Normal"));
    }

    #[test]
    fn takes_the_default_style_of_the_template_and_keeps_the_defaults() {
        let doc = parse(&format!(
            r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="20"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="0" w:line="240"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:pPr><w:spacing w:after="240"/><w:jc w:val="center"/></w:pPr><w:rPr><w:sz w:val="32"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Own"><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="60"/></w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Free"/></w:styles>"#
        ));
        let mut styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        styles.take_template();
        let (free, free_run) = styles.paragraph(Some("Free"), None);
        assert_eq!(
            (free.after, free.line, free_run.size),
            (
                Length::from_twips(0),
                Some(LineSpacing::Auto(240)),
                Some(20)
            )
        );
        let (normal, normal_run) = styles.paragraph(None, None);
        assert_eq!(
            (normal.after, normal.line, normal.alignment),
            (Length::from_twips(160), Some(LineSpacing::Auto(278)), None)
        );
        assert_eq!(normal_run.size, Some(24));
        let (own, own_run) = styles.paragraph(Some("Own"), None);
        assert_eq!(
            (own.after, own.line, own_run.size),
            (
                Length::from_twips(60),
                Some(LineSpacing::Auto(278)),
                Some(40)
            )
        );
    }

    #[test]
    fn reads_whether_the_settings_link_the_styles_to_the_template() {
        let read = |inner: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).template_styles
        };
        assert_eq!(read("<w:linkStyles/>"), TemplateStyles::Linked);
        assert_eq!(read(r#"<w:linkStyles w:val="0"/>"#), TemplateStyles::Kept);
        assert_eq!(read(""), TemplateStyles::Kept);
        assert_eq!(
            read("<w:attachedTemplate/><w:linkStyles/>"),
            TemplateStyles::Kept
        );
    }

    #[test]
    fn uses_the_default_style_and_stops_cycles() {
        let doc = parse(STYLES);
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let (normal, normal_run) = styles.paragraph(None, None);
        assert_eq!(normal.style.as_deref(), Some("Normal"));
        assert_eq!(normal.alignment, Some(Alignment::Start));
        assert_eq!(normal_run.size, Some(22));
        assert_eq!(styles.character("Strong").bold, Some(true));
        assert_eq!(styles.paragraph(Some("Loop"), None).1.size, Some(22));
    }

    const TABLE_STYLES: &str = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
      <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:pPr></w:pPrDefault></w:docDefaults>
      <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:pPr><w:spacing w:line="288"/></w:pPr></w:style>
      <w:style w:type="table" w:default="1" w:styleId="Plain"><w:tblPr><w:tblCellMar><w:left w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr>
        <w:tblStylePr w:type="firstRow"><w:rPr><w:i/></w:rPr></w:tblStylePr></w:style>
      <w:style w:type="table" w:styleId="Grid"><w:basedOn w:val="Plain"/><w:pPr><w:spacing w:after="0" w:line="240"/></w:pPr><w:rPr><w:sz w:val="20"/></w:rPr>
        <w:tblPr><w:tblBorders><w:top w:val="single" w:sz="4"/></w:tblBorders></w:tblPr>
        <w:tblStylePr w:type="firstRow"><w:pPr><w:jc w:val="center"/></w:pPr><w:rPr><w:b/></w:rPr><w:tcPr><w:tcBorders><w:bottom w:val="single" w:sz="12"/></w:tcBorders></w:tcPr></w:tblStylePr>
        <w:tblStylePr w:type="lastRow"><w:rPr><w:b/></w:rPr></w:tblStylePr>
        <w:tblStylePr w:type="unknown"><w:rPr><w:b/></w:rPr></w:tblStylePr><w:tblStylePr/></w:style>
    </w:styles>"#;

    #[test]
    fn cascades_table_styles() {
        let doc = parse(TABLE_STYLES);
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let grid = styles.table(Some("Grid"));
        assert_eq!(grid.table.margins.left, Length::from_twips(108));
        assert!(grid.table.borders.top.is_some());
        assert_eq!(grid.run.size, Some(20));
        let fallback = styles.table(Some("Missing"));
        assert_eq!(fallback, styles.table(None));
        assert_eq!(fallback.table.margins.left, Length::from_twips(108));
        assert_eq!(fallback.table.borders.top, None);
    }

    #[test]
    fn merges_the_regions_of_a_table_style_chain() {
        let doc = parse(TABLE_STYLES);
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let grid = styles.table(Some("Grid"));
        assert_eq!(grid.regions.len(), 2);
        let first = grid.region(Region::FirstRow).unwrap();
        assert_eq!((first.run.italic, first.run.bold), (Some(true), Some(true)));
        assert_eq!(first.para.alignment, Some(Alignment::Center));
        assert!(first.borders.bottom.is_some());
        assert_eq!(grid.region(Region::LastRow).unwrap().run.bold, Some(true));
        assert_eq!(grid.region(Region::FirstCol), None);
    }

    #[test]
    fn reads_the_cell_alignment_of_a_table_style_and_its_regions() {
        let doc = parse(&format!(
            r#"<w:styles xmlns:w="{W}">
              <w:style w:type="table" w:styleId="Base"><w:tcPr><w:vAlign w:val="center"/></w:tcPr>
                <w:tblStylePr w:type="firstRow"><w:tcPr><w:vAlign w:val="bottom"/></w:tcPr></w:tblStylePr></w:style>
              <w:style w:type="table" w:styleId="Own"><w:basedOn w:val="Base"/></w:style>
              <w:style w:type="table" w:styleId="Odd"><w:tcPr><w:vAlign w:val="middle"/></w:tcPr></w:style>
            </w:styles>"#
        ));
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let own = styles.table(Some("Own"));
        assert_eq!(own.align, Some(VerticalAlign::Center));
        assert_eq!(
            own.region(Region::FirstRow).unwrap().align,
            Some(VerticalAlign::Bottom)
        );
        // A value outside `ST_VerticalJc` counts as missing.
        assert_eq!(styles.table(Some("Odd")).align, None);
    }

    #[test]
    fn reads_the_cell_shading_of_a_table_style_and_its_regions() {
        let doc = parse(&TABLE_STYLES.replace(
            r#"<w:tblStylePr w:type="lastRow">"#,
            r#"<w:tcPr><w:shd w:val="clear" w:fill="DDDDDD"/></w:tcPr><w:tblStylePr w:type="lastRow"><w:tcPr><w:shd w:val="clear" w:fill="002060"/></w:tcPr>"#,
        ));
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let grid = styles.table(Some("Grid"));
        assert_eq!(
            grid.shading,
            Some(crate::props::Color::Rgb([221, 221, 221]))
        );
        let last = grid.region(Region::LastRow).unwrap();
        assert_eq!(last.shading, Some(crate::props::Color::Rgb([0, 32, 96])));
        assert_eq!(grid.region(Region::FirstRow).unwrap().shading, None);
        assert_eq!(styles.table(Some("Plain")).shading, None);
    }

    #[test]
    fn puts_the_table_style_between_the_defaults_and_the_paragraph_style() {
        let doc = parse(TABLE_STYLES);
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let grid = styles.table(Some("Grid"));
        let (para, run) = styles.paragraph(None, Some(&grid));
        assert_eq!(para.after, Some(Length::ZERO));
        assert_eq!(para.line, Some(LineSpacing::Auto(288)));
        assert_eq!(run.size, Some(20));
        let (para, run) = styles.paragraph(None, None);
        assert_eq!(para.after, Length::from_twips(160));
        assert_eq!(run.size, Some(22));
    }

    #[test]
    fn reads_theme_fonts() {
        let xml = format!(
            r#"<a:theme xmlns:a="{A}"><a:themeElements><a:fontScheme><a:majorFont><a:latin typeface="Calibri Light"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#
        );
        let doc = parse(&xml);
        let theme = Theme::read(&mut PartReader::new(&doc), doc.root().unwrap());
        assert_eq!(theme.family(&FontRef::MinorLatin), Some("Calibri"));
        assert_eq!(theme.family(&FontRef::MajorLatin), Some("Calibri Light"));
        assert_eq!(theme.family(&FontRef::Name("Arial".into())), Some("Arial"));
        assert_eq!(theme.family(&FontRef::MinorBidi), None);
    }

    #[test]
    fn picks_the_east_asian_font_of_the_theme_by_language() {
        let xml = format!(
            r#"<a:theme xmlns:a="{A}"><a:themeElements><a:fontScheme><a:majorFont><a:latin typeface="Calibri Light"/><a:ea typeface="Yu Gothic"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:font script="Jpan" typeface="Yu Mincho"/><a:font script="Hans" typeface="DengXian"/><a:font script="Hant" typeface="PMingLiU"/><a:font script="Hang" typeface="Malgun Gothic"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#
        );
        let doc = parse(&xml);
        let theme = Theme::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let minor = |lang| theme.family_for(&FontRef::MinorEastAsia, EastAsianScript::of(lang));
        assert_eq!(minor("ja-JP"), Some("Yu Mincho"));
        assert_eq!(minor("zh-CN"), Some("DengXian"));
        assert_eq!(minor("zh-TW"), Some("PMingLiU"));
        assert_eq!(minor("ko-KR"), Some("Malgun Gothic"));
        assert_eq!(minor("en-US"), None);
        // A set `a:ea` typeface wins over the script fonts.
        assert_eq!(
            theme.family_for(&FontRef::MajorEastAsia, EastAsianScript::of("ja-JP")),
            Some("Yu Gothic")
        );
        assert_eq!(
            theme.family_for(&FontRef::MinorLatin, None),
            Some("Calibri")
        );
    }

    #[test]
    fn reads_the_complex_script_fonts_of_the_theme() {
        let xml = format!(
            r#"<a:theme xmlns:a="{A}"><a:themeElements><a:fontScheme><a:majorFont><a:latin typeface="Calibri Light"/><a:cs typeface="Tahoma"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:cs typeface=""/><a:font script="Hebr" typeface="David"/><a:font script="Arab" typeface="Arial"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#
        );
        let doc = parse(&xml);
        let theme = Theme::read(&mut PartReader::new(&doc), doc.root().unwrap());
        assert_eq!(theme.family(&FontRef::MajorBidi), Some("Tahoma"));
        // Without a complex script typeface, the font of the Arabic script stands in.
        assert_eq!(theme.family(&FontRef::MinorBidi), Some("Arial"));
    }

    #[test]
    fn reads_alternate_font_names() {
        let doc = parse(&format!(
            r#"<w:fonts xmlns:w="{W}"><w:font w:name="ArialMT"><w:altName w:val="Arial, Helvetica"/></w:font><w:font w:name="Calibri"/></w:fonts>"#
        ));
        let table = super::FontTable::read(&doc, doc.root().unwrap());
        let alternate = |name: &str| {
            table
                .alternate(&FamilyName::new(name))
                .map(FamilyName::as_str)
        };
        assert_eq!(alternate("ArialMT"), Some("Arial"));
        assert_eq!(alternate("Calibri"), None);
        // Word finds the entry of a name in another case.
        assert_eq!(alternate("arialmt"), Some("Arial"));
        assert_eq!(alternate("ARIALMT"), Some("Arial"));
    }

    #[test]
    fn keeps_the_first_of_entries_that_name_one_family() {
        use super::EastAsianCharset;
        let doc = parse(&format!(
            r#"<w:fonts xmlns:w="{W}"><w:font w:name="Probe"><w:altName w:val="Courier New"/><w:charset w:val="80"/></w:font><w:font w:name="PROBE"><w:altName w:val="Arial"/><w:charset w:val="86"/></w:font><w:font w:name="Other"/><w:font w:name="other"><w:altName w:val="Arial"/><w:charset w:val="81"/></w:font></w:fonts>"#
        ));
        let table = super::FontTable::read(&doc, doc.root().unwrap());
        let probe = FamilyName::new("probe");
        assert_eq!(
            table.alternate(&probe).map(FamilyName::as_str),
            Some("Courier New")
        );
        assert_eq!(
            table.east_asian_charset(&probe),
            Some(EastAsianCharset::ShiftJis)
        );
        // The first entry of a family counts even when it gives neither field.
        let other = FamilyName::new("Other");
        assert_eq!(table.alternate(&other), None);
        assert_eq!(table.east_asian_charset(&other), None);
    }

    #[test]
    fn knows_the_east_asian_character_sets_of_the_entries() {
        use super::EastAsianCharset;
        let doc = parse(&format!(
            r#"<w:fonts xmlns:w="{W}"><w:font w:name="仿宋_GB2312"><w:charset w:val="86"/></w:font><w:font w:name="標楷體"><w:charset w:val="88"/></w:font><w:font w:name="MS Mincho"><w:charset w:val="80"/></w:font><w:font w:name="Batang"><w:charset w:val="81"/></w:font><w:font w:name="Calibri"><w:charset w:val="00"/></w:font><w:font w:name="Arial"/></w:fonts>"#
        ));
        let table = super::FontTable::read(&doc, doc.root().unwrap());
        let cases = [
            ("仿宋_GB2312", Some(EastAsianCharset::Gb2312)),
            ("標楷體", Some(EastAsianCharset::Big5)),
            ("MS Mincho", Some(EastAsianCharset::ShiftJis)),
            ("Batang", Some(EastAsianCharset::Hangul)),
            ("ms mincho", Some(EastAsianCharset::ShiftJis)),
            ("Calibri", None),
            ("Arial", None),
            ("Missing", None),
        ];
        for (name, set) in cases {
            assert_eq!(
                table.east_asian_charset(&FamilyName::new(name)),
                set,
                "{name}"
            );
        }
    }

    #[test]
    fn reads_the_default_tab_stop() {
        let doc = parse(&format!(
            r#"<w:settings xmlns:w="{W}"><w:defaultTabStop w:val="708"/></w:settings>"#
        ));
        let settings = Settings::read(&mut PartReader::new(&doc), doc.root().unwrap());
        assert_eq!(Some(settings.default_tab_stop), Length::from_twips(708));
        let doc = parse(&format!(r#"<w:settings xmlns:w="{W}"/>"#));
        assert_eq!(
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()),
            Settings::default()
        );
    }

    #[test]
    fn kerns_punctuation_with_east_asian_layout_unless_the_setting_turns_it_off() {
        let read = |inner: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).punctuation_kerning
        };
        let layout = "<w:compat><w:useFELayout/></w:compat>";
        assert_eq!(read(layout), super::PunctuationKerning::On);
        assert_eq!(
            read(&format!("<w:noPunctuationKerning/>{layout}")),
            super::PunctuationKerning::Off
        );
        assert_eq!(
            read("<w:compat><w:balanceSingleByteDoubleByteWidth/></w:compat>"),
            super::PunctuationKerning::Off
        );
    }

    #[test]
    fn lets_cells_follow_the_line_grid_only_with_adjust_line_height_in_table() {
        let read = |inner: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).cell_grid
        };
        assert_eq!(read(""), super::CellGrid::Own);
        assert_eq!(
            read("<w:compat><w:adjustLineHeightInTable/></w:compat>"),
            super::CellGrid::Follows
        );
        assert_eq!(
            read(r#"<w:compat><w:adjustLineHeightInTable w:val="0"/></w:compat>"#),
            super::CellGrid::Own
        );
    }

    #[test]
    fn compresses_punctuation_only_with_east_asian_layout() {
        let read = |inner: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).punctuation
        };
        let control = r#"<w:characterSpacingControl w:val="compressPunctuation"/>"#;
        assert_eq!(
            read(&format!("{control}<w:compat><w:useFELayout/></w:compat>")),
            super::Punctuation::Compressed
        );
        assert_eq!(read(control), super::Punctuation::Kept);
        assert_eq!(
            read(
                r#"<w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:useFELayout/></w:compat>"#
            ),
            super::Punctuation::Kept
        );
    }

    #[test]
    fn spreads_gaps_with_east_asian_layout_whatever_the_punctuation() {
        let read = |inner: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).gap_spread
        };
        assert_eq!(
            read(
                r#"<w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:useFELayout/></w:compat>"#
            ),
            super::GapSpread::Spread
        );
        assert_eq!(
            read(r#"<w:characterSpacingControl w:val="compressPunctuation"/>"#),
            super::GapSpread::Kept
        );
    }

    #[test]
    fn balances_byte_widths_only_with_its_own_option() {
        let read = |compat: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).full_width_spacing
        };
        let twice = super::FullWidthSpacing::Twice;
        assert_eq!(read("<w:balanceSingleByteDoubleByteWidth/>"), twice);
        assert_ne!(
            read(r#"<w:balanceSingleByteDoubleByteWidth w:val="0"/>"#),
            twice
        );
        assert_ne!(read("<w:useFELayout/><w:doNotExpandShiftReturn/>"), twice);
    }

    #[test]
    fn keeps_soft_break_lines_unjustified_only_with_its_own_option() {
        let read = |compat: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).soft_break_lines
        };
        let kept = super::SoftBreakLines::AsLastLine;
        assert_eq!(read("<w:doNotExpandShiftReturn/>"), kept);
        assert_ne!(read(r#"<w:doNotExpandShiftReturn w:val="0"/>"#), kept);
        assert_ne!(
            read("<w:useFELayout/><w:balanceSingleByteDoubleByteWidth/>"),
            kept
        );
    }

    #[test]
    fn reads_fixed_automatic_spacing_only_with_its_own_option() {
        use crate::props::HtmlAutoSpacing;
        let read = |compat: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).html_auto_spacing
        };
        assert_eq!(
            read("<w:doNotUseHTMLParagraphAutoSpacing/>"),
            HtmlAutoSpacing::Fixed
        );
        assert_eq!(
            read(r#"<w:doNotUseHTMLParagraphAutoSpacing w:val="0"/>"#),
            HtmlAutoSpacing::Html
        );
        assert_eq!(read("<w:doNotExpandShiftReturn/>"), HtmlAutoSpacing::Html);
    }

    #[test]
    fn balances_spaces_only_with_both_options() {
        let read = |compat: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).space_balance
        };
        let half = super::SpaceBalance::HalfEm;
        assert_eq!(
            read("<w:balanceSingleByteDoubleByteWidth/><w:useFELayout/>"),
            half
        );
        assert_ne!(read("<w:balanceSingleByteDoubleByteWidth/>"), half);
        assert_ne!(read("<w:useFELayout/><w:doNotExpandShiftReturn/>"), half);
        assert_ne!(
            read(r#"<w:balanceSingleByteDoubleByteWidth/><w:useFELayout w:val="0"/>"#),
            half
        );
    }

    #[test]
    fn reads_the_open_type_features_setting() {
        // As Word 2010 writes it, and turned off.
        for (value, on) in [("1", true), ("0", false)] {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}"><w:compat><w:compatSetting w:name="compatibilityMode" w:val="14"/><w:compatSetting w:name="enableOpenTypeFeatures" w:val="{value}"/></w:compat></w:settings>"#
            ));
            let rules = Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).mode_rules;
            let expected = ModeRules::of(CompatibilityMode::Mode14).with_open_type_features(on);
            assert_eq!(rules, expected);
        }
    }

    #[test]
    fn reads_the_compatibility_mode() {
        let doc = parse(&format!(
            r#"<w:settings xmlns:w="{W}"><w:compat><w:compatSetting w:name="other" w:val="1"/><w:compatSetting w:name="compatibilityMode" w:val="14"/></w:compat></w:settings>"#
        ));
        let settings = Settings::read(&mut PartReader::new(&doc), doc.root().unwrap());
        assert_eq!(
            settings.mode_rules,
            ModeRules::of(CompatibilityMode::Mode14)
        );
        assert!(!settings.even_and_odd_headers);
        // Word also reads the setting outside `w:compat`.
        let outside = parse(&format!(
            r#"<w:settings xmlns:w="{W}"><w:compatSetting w:name="compatibilityMode" w:val="16"/></w:settings>"#
        ));
        let rules =
            Settings::read(&mut PartReader::new(&outside), outside.root().unwrap()).mode_rules;
        assert_eq!(rules, ModeRules::of(CompatibilityMode::Mode15));
        let doc = parse(&format!(
            r#"<w:settings xmlns:w="{W}"><w:evenAndOddHeaders/></w:settings>"#
        ));
        assert!(
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).even_and_odd_headers
        );
        assert_eq!(settings.notes.endnotes.format, Format::LowerRoman);
        let doc = parse(&format!(
            r#"<w:settings xmlns:w="{W}"><w:endnotePr><w:numFmt w:val="decimal"/></w:endnotePr></w:settings>"#
        ));
        let settings = Settings::read(&mut PartReader::new(&doc), doc.root().unwrap());
        assert_eq!(settings.notes.endnotes.format, Format::Decimal);
    }

    #[test]
    fn reads_whether_the_indent_is_a_tab_stop_for_list_labels() {
        let read = |compat: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap())
                .indent_is_numbering_tab_stop
        };
        assert!(read(""));
        assert!(!read("<w:doNotUseIndentAsNumberingTabStop/>"));
        assert!(read(r#"<w:doNotUseIndentAsNumberingTabStop w:val="0"/>"#));
    }

    #[test]
    fn reads_whether_math_settings_turn_on_small_fractions() {
        use crate::props::SmallFractions;
        let read = |inner: &str| {
            let doc = parse(&format!(
                r#"<w:settings xmlns:w="{W}" xmlns:m="{M}">{inner}</w:settings>"#
            ));
            Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).small_frac
        };
        assert_eq!(read(""), SmallFractions::Off);
        assert_eq!(
            read(r#"<m:mathPr><m:smallFrac m:val="0"/></m:mathPr>"#),
            SmallFractions::Off
        );
        assert_eq!(
            read(r#"<m:mathPr><m:smallFrac m:val="1"/></m:mathPr>"#),
            SmallFractions::On
        );
        assert_eq!(
            read("<m:mathPr><m:smallFrac/></m:mathPr>"),
            SmallFractions::On
        );
    }

    #[test]
    fn each_enumeration_table_holds_each_name_of_its_type() {
        // The names of each simple type in ISO/IEC 29500-4:2016 (Transitional), wml.xsd.
        // ST_StyleType
        crate::enumerations::assert_names(super::STYLE_KIND, "paragraph character table numbering");
        // ST_CharacterSpacing
        crate::enumerations::assert_names(
            super::CHARACTER_SPACING,
            "doNotCompress compressPunctuation compressPunctuationAndJapaneseKana",
        );
    }

    #[test]
    fn toggle_properties_xor_across_style_layers() {
        let doc = parse(&format!(
            concat!(
                r#"<w:styles xmlns:w="{W}">"#,
                r#"<w:style w:type="paragraph" w:styleId="PNoBold"/>"#,
                r#"<w:style w:type="paragraph" w:styleId="PBold"><w:rPr><w:b/></w:rPr></w:style>"#,
                r#"<w:style w:type="character" w:styleId="COn"><w:rPr><w:b/></w:rPr></w:style>"#,
                r#"<w:style w:type="character" w:styleId="COff"><w:rPr><w:b w:val="0"/></w:rPr></w:style>"#,
                r#"<w:style w:type="character" w:styleId="CChildOff"><w:basedOn w:val="COn"/><w:rPr><w:b w:val="0"/></w:rPr></w:style>"#,
                r#"<w:style w:type="character" w:styleId="CGrandOn"><w:basedOn w:val="COn"/><w:rPr><w:b/></w:rPr></w:style>"#,
                r#"<w:style w:type="table" w:styleId="TBold"><w:rPr><w:b/></w:rPr></w:style>"#,
                r#"</w:styles>"#,
            ),
            W = W,
        ));
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let table = styles.table(Some("TBold"));

        let cases = [
            ("PBold", false, None, true),
            ("PBold", false, Some("COn"), false),
            ("PBold", false, Some("COff"), true),
            ("PBold", false, Some("CChildOff"), true),
            ("PBold", false, Some("CGrandOn"), false),
            ("PNoBold", false, Some("COn"), true),
            ("PNoBold", true, None, true),
            ("PBold", true, None, false),
            ("PNoBold", true, Some("COn"), false),
            ("PBold", true, Some("COn"), true),
        ];
        let got: Vec<bool> = cases
            .iter()
            .map(|&(ps, use_tbl, cs, _)| {
                let (_, mut run) = styles.paragraph(Some(ps), use_tbl.then_some(&table));
                if let Some(cs) = cs {
                    styles.apply_character(&mut run, cs);
                }
                run.bold.unwrap_or(false)
            })
            .collect();
        let want: Vec<bool> = cases.iter().map(|c| c.3).collect();
        assert_eq!(got, want);
    }

    #[test]
    fn toggle_properties_overlay_without_xor_when_doc_defaults_enable_them() {
        let dd_doc = parse(&format!(
            concat!(
                r#"<w:styles xmlns:w="{W}">"#,
                r#"<w:docDefaults><w:rPrDefault><w:rPr><w:b/></w:rPr></w:rPrDefault></w:docDefaults>"#,
                r#"<w:style w:type="paragraph" w:styleId="POn"><w:rPr><w:b/></w:rPr></w:style>"#,
                r#"<w:style w:type="paragraph" w:styleId="POff"><w:rPr><w:b w:val="0"/></w:rPr></w:style>"#,
                r#"<w:style w:type="character" w:styleId="COn"><w:rPr><w:b/></w:rPr></w:style>"#,
                r#"<w:style w:type="character" w:styleId="COff"><w:rPr><w:b w:val="0"/></w:rPr></w:style>"#,
                r#"</w:styles>"#,
            ),
            W = W,
        ));
        let dd_styles = Styles::read(&mut PartReader::new(&dd_doc), dd_doc.root().unwrap());
        let (_, mut r1) = dd_styles.paragraph(Some("POn"), None);
        dd_styles.apply_character(&mut r1, "COn");
        let (_, r2) = dd_styles.paragraph(Some("POff"), None);
        let (_, mut r3) = dd_styles.paragraph(None, None);
        dd_styles.apply_character(&mut r3, "COff");
        assert_eq!(
            (r1.bold, r2.bold, r3.bold),
            (Some(true), Some(false), Some(false))
        );
    }

    #[test]
    fn table_style_with_table_properties_drops_forward_based_on() {
        let doc = parse(&format!(
            concat!(
                r#"<w:styles xmlns:w="{W}">"#,
                r#"<w:style w:type="table" w:styleId="FNone"><w:basedOn w:val="Base"/></w:style>"#,
                r#"<w:style w:type="table" w:styleId="FEmptyTblPr"><w:basedOn w:val="Base"/><w:tblPr/></w:style>"#,
                r#"<w:style w:type="table" w:styleId="FPPr"><w:basedOn w:val="Base"/><w:pPr><w:jc w:val="left"/></w:pPr></w:style>"#,
                r#"<w:style w:type="table" w:styleId="FRPr"><w:basedOn w:val="Base"/><w:rPr><w:b/></w:rPr></w:style>"#,
                r#"<w:style w:type="table" w:styleId="FTblPr"><w:basedOn w:val="Base"/><w:tblPr><w:tblInd w:w="0" w:type="dxa"/></w:tblPr></w:style>"#,
                r#"<w:style w:type="table" w:styleId="FTrPr"><w:basedOn w:val="Base"/><w:trPr><w:cantSplit/></w:trPr></w:style>"#,
                r#"<w:style w:type="table" w:styleId="FTcPr"><w:basedOn w:val="Base"/><w:tcPr><w:vAlign w:val="top"/></w:tcPr></w:style>"#,
                r#"<w:style w:type="table" w:styleId="FRegion"><w:basedOn w:val="Base"/><w:tblStylePr w:type="lastRow"><w:rPr><w:i/></w:rPr></w:tblStylePr></w:style>"#,
                r#"<w:style w:type="table" w:styleId="Base"><w:rPr><w:sz w:val="32"/></w:rPr><w:tblPr><w:tblCellMar><w:left w:w="240" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>"#,
                r#"<w:style w:type="table" w:styleId="BTblPr"><w:basedOn w:val="Base"/><w:tblPr><w:tblInd w:w="0" w:type="dxa"/></w:tblPr></w:style>"#,
                r#"<w:style w:type="paragraph" w:styleId="PChild"><w:basedOn w:val="PBase"/><w:pPr><w:spacing w:after="0"/></w:pPr></w:style>"#,
                r#"<w:style w:type="paragraph" w:styleId="PBase"><w:pPr><w:ind w:left="720"/></w:pPr></w:style>"#,
                r#"<w:style w:type="character" w:styleId="CChild"><w:basedOn w:val="CBase"/><w:rPr><w:b/></w:rPr></w:style>"#,
                r#"<w:style w:type="character" w:styleId="CBase"><w:rPr><w:sz w:val="36"/></w:rPr></w:style>"#,
                r#"</w:styles>"#,
            ),
            W = W,
        ));
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let left = Length::from_twips(240);
        let got: Vec<_> = [
            "FNone",
            "FEmptyTblPr",
            "FPPr",
            "FRPr",
            "BTblPr",
            "FTblPr",
            "FTrPr",
            "FTcPr",
            "FRegion",
        ]
        .into_iter()
        .map(|id| {
            let t = styles.table(Some(id));
            (t.resolved, t.table.margins.left, t.run.size)
        })
        .collect();
        let want = [
            (true, left, Some(32)),
            (true, left, Some(32)),
            (true, left, Some(32)),
            (true, left, Some(32)),
            (true, left, Some(32)),
            (true, None, None),
            (true, None, None),
            (true, None, None),
            (true, None, None),
        ];
        assert_eq!(got, want);
        assert_eq!(
            (
                styles.table(None).resolved,
                styles.table(Some("Missing")).resolved,
                styles.paragraph(Some("PChild"), None).0.indent_left,
                styles.character("CChild").size,
            ),
            (false, false, Length::from_twips(720), Some(36))
        );
    }
}