f-office-docx 0.2.4

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
//! The document body: paragraphs, runs and the section properties.

mod contents;
mod drawings;
pub(crate) mod field_code;
mod fields;
pub(crate) mod links;
mod runs;
mod section;
pub(crate) mod toc;

pub(crate) use drawings::{DrawingMut, visit_drawings};
pub(crate) use runs::{FIELD_CHAR, FieldChar, RunWrapper, author_color, read_wrapped};
pub(crate) use section::first_column_width;

use std::borrow::Cow;
use std::collections::HashSet;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

use f_office_units::Length;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};

pub(crate) use fields::Updates;
use fields::resolve_fields;
pub use fields::{refers_to_pages, refers_to_pages_and_numbers, refers_to_styles};
use runs::{bookmark_run, read_paragraph};
pub use section::{
    ArtSide, BorderPages, Columns, LineNumberRestart, PageAlign, PageBorders, PageSide, References,
    Section, SectionPart, SectionStart, Sections,
};
use section::{inherit_references, read_section_part};

use crate::mode::ModeRules;
use crate::ns::{
    A, C, DGM, DSP, M, MC, O, PIC, R, V, W, W10, W14, W15, W16SE, WP, WP14, WPC, WPG, WPS,
};
use crate::picture::Picture;
use crate::props::{CodeFormat, ParaProps, RunProps};
use crate::reader::PartReader;
use crate::reader::settings::ReaderSettings;
use crate::source_span::SourceSpan;
use crate::table::Table;
use crate::warnings::{Feature, Reason};

/// One piece of run content.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Content {
    /// Text.
    Text(String),
    /// A tab character.
    Tab,
    /// A positional tab (`w:ptab`): the text after it lines up at the left edge, the middle
    /// or the right edge of the margins.
    PositionTab {
        /// How the text after it lines up there: left, center or right.
        kind: crate::props::TabKind,
        /// The character that fills the space before the position, if any.
        leader: Option<char>,
    },
    /// A line break inside the paragraph.
    LineBreak,
    /// A line break after which the text goes on below the floating objects
    /// (`w:br w:clear="all"`).
    ClearingBreak,
    /// A page break.
    PageBreak,
    /// A column break, which continues in the next column, or on the next page after the last
    /// column.
    ColumnBreak,
    /// The start of a field (`w:fldChar` begin).
    FieldBegin,
    /// A field's lock flag (`w:fldLock`). It shows nothing.
    FieldLock,
    /// A check box form field (`w:ffData` with `w:checkBox` in the field's start), which
    /// shows a square in the face of the run that starts the field.
    CheckBox(CheckBox),
    /// The entry that a drop-down form field shows (`w:ffData` with `w:ddList` in the field's
    /// start). The field reader takes it as the field's value; it shows nothing itself.
    DropDown(String),
    /// Part of a field's code (`w:instrText`).
    FieldCode(String),
    /// The end of a field's code and the start of its last result (`w:fldChar` separate).
    FieldSeparate,
    /// The end of a field (`w:fldChar` end).
    FieldEnd,
    /// The number of the page that the text is on, from a `PAGE` field.
    PageNumber,
    /// The number of pages in the document, from a `NUMPAGES` field.
    PageCount,
    /// A `DATE` or `TIME` field, which shows the time of layout when the caller gives one.
    Date(Box<DateField>),
    /// A `DOCPROPERTY` field, which shows a custom property of the document.
    DocProperty(Box<DocProperty>),
    /// A `STYLEREF` field.
    StyleRef(Box<StyleRef>),
    /// A `PAGEREF` field, which shows the page number of a bookmark.
    PageRef(Box<PageRef>),
    /// A REF field with a paragraph-number switch, or a REF field of text whose bookmark the
    /// document does not have.
    NumberRef(Box<NumberRef>),
    /// The start of a bookmark (`w:bookmarkStart`) with its name. It shows nothing.
    Bookmark(String),
    /// Where a field result that the story shows starts, or where a field ends, which the
    /// reader of fields leaves in place of the field's marks. It shows nothing, and the text
    /// after it starts a glyph run.
    FieldMark,
    /// Where the content of a hyperlink (`w:hyperlink`) starts or ends. It shows nothing. On a
    /// target whose writer takes a hyperlink as a field (`HyperlinkObjects::StartsObject`), the
    /// text after it starts a glyph run, as after a field mark.
    HyperlinkEdge,
    /// Where the content of a content control in a paragraph (`w:sdt`) starts or ends. It shows
    /// nothing. On a target whose writer starts a text object there
    /// (`ControlObjects::StartsObject`), the text after it starts a glyph run, as after a field
    /// mark.
    ControlEdge,
    /// Where tracked deleted or moved-away text stood that the target accepts, at the start of
    /// the first run after it. It shows nothing. On a target whose writer starts a text object
    /// there (`RemovedTextObjects::StartsObject`), the text after it starts a glyph run, as after
    /// a field mark.
    RemovedEdge,
    /// The reference of a comment (`w:commentReference`), at the end of the text that the
    /// comment is about, with the comment's ID. It shows nothing, and Word puts the comment's
    /// balloon beside its line.
    CommentAnchor(String),
    /// An `IF` field, which layout evaluates with the values of the fields in its code.
    If(Box<IfField>),
    /// The move of an `ADVANCE` field: the text after it starts this far right of where it
    /// would start, left when negative. It draws nothing, and its length is a character of
    /// the word around it, at which the line does not break.
    Advance(Length),
    /// A reference to the footnote with this ID (`w:footnoteReference`), shown as its number
    /// unless a custom mark follows it.
    FootnoteReference(NoteId, NoteMark),
    /// The number of the footnote that holds it (`w:footnoteRef`).
    FootnoteMark,
    /// A reference to the endnote with this ID (`w:endnoteReference`), shown as its number
    /// unless a custom mark follows it.
    EndnoteReference(NoteId, NoteMark),
    /// The number of the endnote that holds it (`w:endnoteRef`).
    EndnoteMark,
    /// The reference mark in the text of the comment that holds it (`w:annotationRef`). It
    /// draws nothing, and its run's face sizes its line.
    CommentMark,
    /// The rule above the notes of a page (`w:separator`).
    Separator,
    /// The rule above the rest of a note that started on the page before
    /// (`w:continuationSeparator`).
    ContinuationSeparator,
    /// A place in a stack of two parts of an equation, such as a stacked fraction (`m:f`),
    /// whose run has the fraction's size, or the two scripts of a sub-superscript
    /// (`m:sSubSup`): its start, the end of its first part, or its end.
    Stack(StackMark),
    /// A place in a delimiter of an equation (`m:d`) that grows around content that is not
    /// line high: its start, a character of it, or its end.
    Grown(GrownMark),
    /// A place in a radical of an equation (`m:rad`): its start, the start of its root sign,
    /// the start of its element, or its end.
    Radical(RadicalMark),
    /// A place in an accent of an equation (`m:acc`): its start, the start of its accent
    /// character, or its end.
    Accent(AccentMark),
    /// A place in a matrix of an equation (`m:m`): its start, the start of a cell or of a row,
    /// or its end.
    Matrix(MatrixMark),
    /// The start or the end of a bar structure of an equation (`m:bar`).
    MathBar(BarMark),
    /// A place in a linear or skewed fraction of an equation (`m:f` whose `m:type` is `lin` or
    /// `skw`): its start with its kind, its slash, its denominator, or its end.
    MathSlash(SlashMark),
    /// A place in a lower- or upper-limit structure of an equation (`m:limLow` or `m:limUpp`):
    /// its start with its side, the start of its limit, or its end.
    MathLimit(LimitMark),
    /// A place in a grouping character structure of an equation (`m:groupChr`): its start with
    /// its placement, the start of its grouping character, or its end.
    GroupChr(GroupChrMark),
    /// A place in a math box (`m:box`) or border box (`m:borderBox`) of an equation: the start
    /// or end of a border box, or the end of an operator-emulating box (`m:opEmu`).
    MathBox(MathBoxMark),
    /// A place in the scripts after a base of an equation (`m:sSub`, `m:sSup` and
    /// `m:sSubSup`): the end of the base, the start or the end of a script, or the end of the
    /// scripts.
    Scripts(ScriptMark),
    /// A floating drawing with a text box or a picture, which stands outside the text flow.
    Floating(Box<crate::floating::Floating>),
    /// An inline object, such as a picture, with the size that it takes on the line.
    Object {
        /// The width.
        width: Length,
        /// The height above the baseline.
        height: Length,
        /// The picture that the object shows, if it is one that can be drawn.
        picture: Option<Box<Picture>>,
        /// The height of the DrawingML extent (`wp:extent cy`) when the size comes from one, a
        /// part of `height` that a target may take in whole twips; a VML object has none.
        extent: Option<Length>,
    },
    /// An inline drawing of a shape, with or without a text box, which takes room on the line
    /// like an inline picture. It is shared, so that each measure of its paragraph gives the
    /// layout a pointer and copies no text box.
    Drawing(Rc<InlineDrawing>),
}

/// A place in a stack of two parts of an equation, one above the other.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StackMark {
    /// The start of the stack, which draws a bar between its parts when `bar` is set.
    Start {
        /// The bar between the parts, as between a numerator and a denominator, with the gap
        /// minimum that the parts keep from it; none for a stack without a bar.
        bar: Option<GapMinimum>,
        /// Whether the narrower part is centered on the wider one, as in a fraction, or
        /// starts where the wider one starts, as a script does.
        centered: bool,
    },
    /// The start of the stack of the limits beside an n-ary operator that a display draws with
    /// the larger variant of its glyph, with the operator's character: the first part, the
    /// lower limit, starts the italic correction of that glyph left of the second, and the
    /// stack ends where the part that ends later ends.
    StartBeside(char),
    /// The end of the first part, such as a numerator, and the start of the second.
    Middle,
    /// The end of the stack.
    End,
}

/// A place in a delimiter of an equation (`m:d`) that grows around content that is not line
/// high, as [`crate::math`] reads it: the target decides which glyph each of its characters
/// draws once its content is measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GrownMark {
    /// The start of the delimiter, before its opening character.
    Start,
    /// A character of the delimiter, its opening or closing character or a separator, whose
    /// glyph comes next.
    Character(char),
    /// The end of the delimiter, after its closing character.
    End,
    /// After a thin space before the delimiter's start: the space keeps its width only when
    /// the delimiter's content counts as a subformula.
    SpaceBefore,
    /// After a thin space after the delimiter's end: the space keeps its width only when the
    /// delimiter's content counts as a subformula.
    SpaceAfter,
    /// Before the first piece of a delimiter that is the first element of a grown delimiter's
    /// content and opens with its opening character, or the last one and closes with its closing
    /// character.
    NestedStart,
    /// After the last piece of a nested delimiter, which the delimiter around it measures.
    NestedEnd,
}

/// The root sign of a radical (`m:rad`), whose glyph the layout chooses among the vertical
/// variants of the math font's glyph for it.
pub const ROOT_SIGN: char = '\u{221A}';

/// A place in a radical of an equation (`m:rad`), as [`crate::math`] reads it: the layout
/// chooses and places the root sign, its bar and the degree once the element is measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RadicalMark {
    /// The start of the radical, before its degree when `degree` says that it shows one.
    Start {
        /// Whether the degree shows.
        degree: bool,
    },
    /// The end of the degree and the start of the root sign ([`ROOT_SIGN`]), whose glyph comes
    /// next.
    Sign,
    /// The end of the root sign and the start of the element.
    Element,
    /// The end of the radical, after its element.
    End,
}

/// The character of an accent of an equation (`m:acc`) whose properties name none: the
/// combining circumflex accent (ECMA-376 Part 1, 22.1.2.20).
pub const DEFAULT_ACCENT: char = '\u{0302}';

/// A place in an accent of an equation (`m:acc`), as [`crate::math`] reads it: the layout
/// chooses the accent's glyph and places it over the base once the base is measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccentMark {
    /// The start of the accent, before its base.
    Start,
    /// The end of the base and the start of the accent's character, whose glyph comes next.
    Character,
    /// The end of the accent, after its character.
    End,
}

/// A place in a bar structure of an equation (`m:bar`), as [`crate::math`] reads it: the layout
/// draws the bar over or under the base once the base is measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BarMark {
    /// The start of the bar structure, before its base, with the side of its bar.
    Start(BarSide),
    /// The end of the bar structure, after its base.
    End,
}

/// The side of its base on which a bar structure of an equation draws its bar (`m:pos`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BarSide {
    /// Over the base (`top`).
    Top,
    /// Under the base (`bot`, the default).
    #[default]
    Bottom,
}

/// The kind of a fraction of an equation drawn with a slash (`m:f` whose `m:type` is `lin` or
/// `skw`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SlashKind {
    /// Numerator, slash and denominator on one baseline (`lin`).
    Linear,
    /// Numerator raised and denominator lowered across a slash (`skw`).
    Skewed,
}

/// A place in a linear or skewed fraction of an equation (`m:f`), as [`crate::math`] reads it:
/// the layout sizes and places the slash, and for a skewed fraction lifts the numerator and
/// drops the denominator, once the parts are measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SlashMark {
    /// The start of the fraction, before its numerator, with its kind.
    Start(SlashKind),
    /// The end of the numerator, right before the fraction slash glyph.
    Slash,
    /// The end of the fraction slash glyph, right before the denominator.
    Denominator,
    /// The end of the fraction, after its denominator.
    End,
}

/// The side of its base on which a limit structure of an equation (`m:limLow` or `m:limUpp`)
/// places its limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LimitSide {
    /// Under the base (`m:limLow`).
    Lower,
    /// Over the base (`m:limUpp`).
    Upper,
}

/// A place in a lower- or upper-limit structure of an equation (`m:limLow` or `m:limUpp`), as
/// [`crate::math`] reads it: the layout centers the base and the limit horizontally and shifts
/// the limit below or above the base's ink once both are measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LimitMark {
    /// The start of the limit structure, before its base, with the side of its limit.
    Start(LimitSide),
    /// The end of the base, right before the limit.
    Limit,
    /// The end of the limit structure, after its limit; `operand` is false when the base is a
    /// binary or relation operator, so a following sign stays unary.
    End {
        /// Whether the structure counts as an operand for a following operator.
        operand: bool,
    },
}

/// The default grouping character of `m:groupChr`: the bottom curly bracket (U+23DF).
pub const DEFAULT_GROUP_CHR: char = '\u{23DF}';

/// Where a grouping character (`m:groupChr`) stands relative to its base (`m:pos`) and which of
/// the two aligns on the equation's baseline (`m:vertJc`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GroupChrPlacement {
    /// Side of the base where the grouping character stands (`m:pos`, default bottom).
    pub position: BarSide,
    /// Vertical justification (`m:vertJc`, default top). When equal to `position`, the grouping
    /// character stands on the baseline and the base shifts above or below it at script size;
    /// when opposite, the base stays on the baseline and the character shifts above or below it.
    pub vertical_align: BarSide,
}

/// A place in a grouping character structure of an equation (`m:groupChr`), as [`crate::math`]
/// reads it: the layout stretches the character across the base's width and shifts the character
/// or the base once both are measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GroupChrMark {
    /// The start of the grouping character structure, before its base, with its placement.
    Start(GroupChrPlacement),
    /// The end of the base, right before the grouping character's run.
    Character,
    /// The end of the grouping character structure, after its grouping character's run.
    End {
        /// Whether the structure counts as an operand for a following operator.
        operand: bool,
    },
}

/// Which sides and strikes a border box (`m:borderBox`) draws, stored as a bit mask.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BorderBoxFlags(u8);

impl BorderBoxFlags {
    /// Top border rule.
    pub const TOP: u8 = 1;
    /// Bottom border rule.
    pub const BOTTOM: u8 = Self::TOP << 1;
    /// Left border rule.
    pub const LEFT: u8 = Self::BOTTOM << 1;
    /// Right border rule.
    pub const RIGHT: u8 = Self::LEFT << 1;
    /// Horizontal strike through the box's vertical center.
    pub const STRIKE_H: u8 = Self::RIGHT << 1;
    /// Vertical strike through the box's horizontal center.
    pub const STRIKE_V: u8 = Self::STRIKE_H << 1;
    /// Diagonal strike from bottom-left to top-right.
    pub const STRIKE_BLTR: u8 = Self::STRIKE_V << 1;
    /// Diagonal strike from top-left to bottom-right.
    pub const STRIKE_TLBR: u8 = Self::STRIKE_BLTR << 1;

    /// No sides and no strikes.
    pub const EMPTY: Self = Self(0);

    /// Returns a copy with `flag` set.
    #[must_use]
    pub const fn with(self, flag: u8) -> Self {
        Self(self.0 | flag)
    }

    /// Whether no border side and no strike is drawn.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Whether the bit `flag` is set.
    #[must_use]
    pub const fn has(self, flag: u8) -> bool {
        self.0 & flag != 0
    }
}

/// A place in a border box (`m:borderBox`) of an equation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MathBoxMark {
    /// The start of a border box, before its content, with the sides and strikes it draws.
    BorderStart(BorderBoxFlags),
    /// The end of a border box, after its content.
    BorderEnd,
}

/// A place in a matrix of an equation (`m:m`), as [`crate::math`] reads it: the layout puts
/// its cells in columns and rows once they are measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatrixMark {
    /// The start of the matrix, with its settings.
    Start(MatrixSettings),
    /// The start of a cell, with its column's justification.
    Cell(CellJustification),
    /// The start of a row after the first.
    Row,
    /// The end of the matrix.
    End,
}

/// The settings of a matrix of an equation (`m:mPr`) that place its cells.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MatrixSettings {
    /// Which row stands on the baseline of the line (`m:baseJc`).
    pub base: MatrixBase,
    /// The distance between the baselines of two rows (`m:rSpRule` and `m:rSp`).
    pub rows: RowSpacing,
    /// The least width of a column (`m:cSp`).
    pub column_width: Length,
}

/// Where a matrix of an equation stands on its line (`m:baseJc`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MatrixBase {
    /// Its first row on the line's baseline (`top`).
    Top,
    /// The middle of its ink on the math axis (`center`, the default).
    #[default]
    Center,
    /// Its last row on the line's baseline (`bot`).
    Bottom,
}

/// The distance between the baselines of two rows of a matrix of an equation, by `m:rSpRule`
/// with the value of `m:rSp`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RowSpacing {
    /// One line of the matrix's font (0, the default).
    #[default]
    Single,
    /// One and a half lines (1).
    OneAndAHalf,
    /// Two lines (2).
    Double,
    /// A distance given in twips (3).
    Exactly(Length),
    /// A number of half lines (4).
    HalfLines(i64),
}

/// How a column of a matrix of an equation places a cell narrower than the column
/// (`m:mcJc`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CellJustification {
    /// At the column's left edge.
    Left,
    /// In the column's middle (the default).
    #[default]
    Center,
    /// At the column's right edge.
    Right,
}

/// A place in the scripts after a base of an equation, as [`crate::math`] reads them: the
/// layout starts each script by the corners of the base's last glyph and of the script's first
/// glyph once the script is measured, and leaves a space after the scripts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScriptMark {
    /// The end of the base, before its scripts, which are the two parts of a stack when
    /// `stacked` is set.
    Base {
        /// Whether the scripts are the stacked parts of a sub-superscript.
        stacked: bool,
        /// Whether more of the scripts' argument comes after their structure, so that a glyph
        /// of the same equation follows the scripts.
        followed: bool,
        /// Whether the base is a box, which [`ScriptMark::BoxStart`] started: the scripts keep
        /// the math font's drops from it.
        boxed: bool,
    },
    /// The start of a base that is a box, whose scripts keep the math font's drops from its top
    /// and its bottom: a base that holds a radical, a fraction or a bar structure, or one that
    /// ends in delimiters (`delimited`), which is a box only when they grow.
    BoxStart {
        /// Whether the base is a box only when its closing delimiter draws a grown glyph.
        delimited: bool,
    },
    /// The end of an n-ary operator inside a line, before its limits, which stand beside it as
    /// scripts and are the two parts of a stack when `stacked` is set. The limits of an
    /// integral move away from the operator's ink by the math font's drops (`drops`); those of
    /// other operators move apart as the two scripts of a base do. Neither starts by the
    /// corners of the glyphs or leaves a space after the limits.
    Operator {
        /// Whether the limits are the stacked parts of the structure.
        stacked: bool,
        /// Whether the limits take the drops from the operator's ink.
        drops: bool,
    },
    /// The start of a script.
    Start(ScriptSide),
    /// The end of a script.
    End,
    /// The end of the scripts.
    After,
}

/// Which of the scripts after a base a script is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScriptSide {
    /// A subscript, beside the bottom of the base.
    Sub,
    /// A superscript, beside the top of the base.
    Sup,
}

/// The gap minimum that the parts of a fraction keep between their ink and its bar: that of a
/// fraction in display style, or that of a fraction in any other style.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GapMinimum {
    /// The gap minimum of a fraction in display style.
    Display,
    /// The gap minimum of a fraction in text, script or script-script style, such as a
    /// fraction in a line of text.
    Line,
}

/// The settings of a check box form field (`w:checkBox`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CheckBox {
    /// The size of the box as a font size in half-points (`w:size`), or `None` for the size of
    /// the run's font (`w:sizeAuto`).
    pub size: Option<i64>,
    /// Whether the box is checked: `w:checked`, or else `w:default`.
    pub checked: bool,
}

/// An inline drawing (`wp:inline`) of a shape, with or without a text box.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InlineDrawing {
    /// The width that it takes on the line.
    pub width: Length,
    /// The height that it takes above the baseline.
    pub height: Length,
    /// Where the shape's box starts in that room: the left and the top effect extent.
    pub left: Length,
    /// See `left`.
    pub top: Length,
    /// The shape with the size of its box, its look and its text box.
    pub shape: crate::floating::Floating,
    /// Whether the drawing is a VML shape other than a horizontal rule, which stands lower on
    /// a line of multiple spacing that holds no text.
    pub drops: bool,
    /// Whether the inline VML shape has `w10:anchorlock`.
    pub anchor_locked: bool,
    /// The height of the DrawingML extent (`wp:extent cy`) when the size comes from one, a part
    /// of `height` that a target may take in whole twips; a VML shape has none.
    pub extent: Option<Length>,
}

#[cfg(test)]
impl InlineDrawing {
    /// An inline drawing of `shape` that takes no room on its line.
    pub(crate) fn of_shape(shape: crate::floating::Floating) -> Self {
        Self {
            width: Length::ZERO,
            height: Length::ZERO,
            left: Length::ZERO,
            top: Length::ZERO,
            shape,
            drops: false,
            anchor_locked: false,
            extent: None,
        }
    }
}

/// A `DATE` or `TIME` field.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DateField {
    /// The date and time picture: the field's `\@` switch, or the default of its kind.
    pub picture: String,
    /// The result stored in the file.
    pub stored: String,
}

/// A `DOCPROPERTY` field: the name of the property that it shows, and its stored result for a
/// property that the document does not hold.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocProperty {
    /// The property's name.
    pub name: String,
    /// The date and time picture (`\@`), for a property that holds a date.
    pub picture: Option<String>,
    /// The result stored in the file.
    pub stored: String,
}

/// A `STYLEREF` field, which shows the text of a paragraph or run with a style near its page.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StyleRef {
    /// The name or the ID of the style.
    pub style: String,
    /// Whether the field takes the last text on the page (`\l`) instead of the first.
    pub last: bool,
    /// Whether the field shows the paragraph number of the paragraph that it finds (`\n`)
    /// instead of its text.
    pub number: bool,
    /// The result stored in the file.
    pub stored: String,
}

/// A `PAGEREF` field: the bookmark whose page number it shows, and its stored result.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PageRef {
    /// The name of the bookmark.
    pub bookmark: String,
    /// The result stored in the file.
    pub stored: String,
    /// The first run of the field's code, whose format an error text takes.
    pub code: Option<CodeRun>,
}

/// The first run of a field's code: its character style and its direct properties.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CodeRun {
    /// The ID of the run's character style.
    pub style: Option<String>,
    /// The run's direct properties.
    pub props: RunProps,
}

/// A REF field that layout computes and its stored result.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NumberRef {
    /// The bookmark whose paragraph supplies the number.
    pub bookmark: String,
    /// The requested number context; none for a field that shows the bookmark's text.
    pub kind: Option<crate::numbering::ReferenceKind>,
    /// The result stored in the file.
    pub stored: String,
    /// The first run of the field's code, whose format an error text takes.
    pub code: Option<CodeRun>,
}

/// An `IF` field: its code, with the fields nested in it, and its stored result.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IfField {
    /// The code in order: its text and the fields nested in it.
    pub parts: Vec<CodePart>,
    /// The result stored in the file.
    pub stored: String,
}

/// A part of a field code.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CodePart {
    /// Text of the code.
    Text(String),
    /// A nested field that layout computes.
    Field(Content),
}

/// Characters of Word's text that a run holds before its content and that no page shows, such
/// as the marks and the code of the field that Word makes of a hyperlink (**Buffer-only
/// characters**). They count only in the text buffers (`crate::buffers::mark`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BufferOnly {
    /// The characters that the run's own markup gives.
    pub characters: usize,
    /// A relationship of the part whose target's characters stand there too, such as the
    /// external address of a hyperlink (`r:id`).
    pub relationship: Option<String>,
    /// The marks of the fields that are open after the run: the start of each, and the
    /// separator of each that is in its result. They do not count toward a buffer's length
    /// while their fields are open.
    pub open: usize,
    /// The marks of the fields that are open all through the run, which a buffer that the run
    /// starts holds again.
    pub held: usize,
}

/// A run with its direct properties.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Run {
    /// The character style ID.
    pub style: Option<String>,
    /// Direct run properties.
    pub props: RunProps,
    /// The content in order.
    pub content: Vec<Content>,
    /// The revision IDs of the `w:r` element: the session that added it (`w:rsidR`), the one
    /// that last formatted it (`w:rsidRPr`), and the accepted insertion that held it, if any.
    pub revisions: [Option<u32>; 3],
    /// Whether the run starts a text buffer (`crate::buffers::mark`).
    pub starts_buffer: bool,
    /// The characters of Word's text that the run holds before its content and that no page
    /// shows, which count only in the text buffers.
    pub buffer_only: BufferOnly,
    /// The run's direct properties as written, which decide with the revision IDs whether the
    /// run continues the text object of the run before it.
    pub record: RunRecord,
    /// For a run that shows a page number or page count that Word computes, in a field whose
    /// code has no `\* MERGEFORMAT`, or the box of a check box form field: the format of the
    /// field's code run, which the value or the box takes where the target says so. No markup
    /// sets it; the reader of fields does.
    pub code_format: Option<Box<CodeFormat>>,
    /// The hyperlinks whose text starts or ends at the run, in order (**Link mark**). Only the
    /// text map reads them; layout does not.
    pub links: Vec<links::LinkMark>,
}

impl Run {
    /// The run's character style ID for layout: a computed field value that replaces the showing
    /// run's style takes the code run's style where `code_format`.
    #[must_use]
    pub(crate) fn character_style(&self, code_format: bool) -> Option<&str> {
        match &self.code_format {
            Some(code) if code_format => code.style_over(self.style.as_deref()),
            _ => self.style.as_deref(),
        }
    }

    /// The run's direct properties for layout: a page number or page count that Word computes,
    /// and the box of a check box form field, take the format of the field's code run where
    /// `code_format`, and a page number or page count drops its underline, strikethrough and
    /// highlight unless `page_decorations`.
    #[must_use]
    pub fn direct_props(&self, code_format: bool, page_decorations: bool) -> Cow<'_, RunProps> {
        let props = match &self.code_format {
            Some(code) if code_format => Cow::Owned(code.over(&self.props)),
            _ => Cow::Borrowed(&self.props),
        };
        let page_value = self
            .content
            .iter()
            .any(|content| matches!(content, Content::PageNumber | Content::PageCount));
        if !page_decorations && page_value {
            Cow::Owned(RunProps {
                underline: None,
                strike: None,
                highlight: None,
                ..props.into_owned()
            })
        } else {
            props
        }
    }
}

/// The on/off children of a run's `w:rPr` (`CT_OnOff` in `CT_RPr`, ECMA-376 Part 1, 17.3.2),
/// whose value a run record holds as on or off, whatever its spelling.
const ON_OFF_RUN_PROPERTIES: [&str; 20] = [
    "b",
    "bCs",
    "i",
    "iCs",
    "caps",
    "smallCaps",
    "strike",
    "dstrike",
    "outline",
    "shadow",
    "emboss",
    "imprint",
    "noProof",
    "snapToGrid",
    "vanish",
    "webHidden",
    "rtl",
    "cs",
    "specVanish",
    "oMath",
];

/// A run's direct properties as written (**Run record**): each child of its `w:rPr` but the
/// tracked change `w:rPrChange`, with its attributes, in no order. An on/off child, such as
/// `w:noProof`, is on or off, however its value is spelled; another child keeps its attributes'
/// values as written. Two neighbouring runs that draw with the same properties and have the same
/// revision IDs are one text object when their records are equal, and the second starts a text
/// object when they differ: in a child that one holds and the other does not, also a child with
/// the value that the run would have without it, or in a child's value.
///
/// The record holds a child's attributes, not the child's own children: two runs that differ
/// only inside such a child, as in the text effects `w14:textFill` or `w14:textOutline`, have
/// equal records.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RunRecord(Vec<RecordChild>);

/// One child of a run record: its namespace and local name, and its value.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct RecordChild {
    namespace: String,
    local: String,
    value: RecordValue,
}

/// The value of a child of a run record.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum RecordValue {
    /// An on/off child of WordprocessingML, on or off ([`crate::on_off::element`]).
    OnOff(bool),
    /// Another child: its attributes by namespace and local name, in that order, with their
    /// values as written, without namespace declarations, and without the child's own children.
    Attributes(Vec<(String, String, String)>),
}

impl RunRecord {
    /// Reads the children of the `w:rPr` element `rpr` into `self`, replacing any recorded
    /// child with the same namespace and local name.
    pub(crate) fn read_into(&mut self, doc: &Document, rpr: NodeId) {
        let added = doc
            .child_elements(rpr)
            .filter(|&child| !doc.is(child, W, "rPrChange"))
            .filter_map(|child| {
                let element = doc.element(child)?;
                let namespace = element
                    .name
                    .namespace
                    .map_or_default(|id| doc.namespace_uri(id).to_owned());
                let local = element.name.local.to_owned();
                let value = if namespace == W && ON_OFF_RUN_PROPERTIES.contains(&local.as_str()) {
                    RecordValue::OnOff(crate::on_off::element(doc, child, W))
                } else {
                    let mut attributes: Vec<(String, String, String)> = element
                        .attributes
                        .iter()
                        .filter(|attribute| {
                            attribute.name.prefix != Some("xmlns")
                                && !(attribute.name.prefix.is_none()
                                    && attribute.name.local == "xmlns")
                        })
                        .map(|attribute| {
                            (
                                attribute
                                    .name
                                    .namespace
                                    .map_or_default(|id| doc.namespace_uri(id).to_owned()),
                                attribute.name.local.to_owned(),
                                attribute.value.to_owned(),
                            )
                        })
                        .collect();
                    attributes.sort();
                    RecordValue::Attributes(attributes)
                };
                Some(RecordChild {
                    namespace,
                    local,
                    value,
                })
            });
        for child in added {
            if let Some(existing) = self
                .0
                .iter_mut()
                .find(|c| c.namespace == child.namespace && c.local == child.local)
            {
                existing.value = child.value;
            } else {
                self.0.push(child);
            }
        }
        self.0.sort();
    }
}

impl Run {
    /// A run of `content` with the direct properties `props`, no character style and no
    /// revision IDs.
    #[must_use]
    pub(crate) fn new(props: RunProps, content: Vec<Content>) -> Self {
        Self {
            props,
            content,
            ..Self::default()
        }
    }

    /// A run of `content` with the direct properties `props` and the character style and the
    /// revision IDs of this run, such as a run that a part of this run's content starts.
    #[must_use]
    pub(crate) fn part(&self, props: RunProps, content: Vec<Content>) -> Self {
        Self {
            style: self.style.clone(),
            props,
            content,
            revisions: self.revisions,
            starts_buffer: false,
            buffer_only: BufferOnly::default(),
            record: self.record.clone(),
            code_format: None,
            links: Vec::new(),
        }
    }
}

/// The identity of a paragraph of the document, which the paragraph gets when it is read and
/// keeps in every copy (**Paragraph ID**). The record of styled text knows the paragraph whose
/// lines it places by it, also where the layout lays out a copy.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ParagraphId(u64);

/// The source of the paragraph IDs of one document, each of which it gives once. The reading of
/// the document owns one and passes it to every part reader, so that two paragraphs of
/// different parts never share an ID. It is an atomic count, so that a type that holds it stays
/// `Sync`, as the lazy reader of the web settings part does.
#[derive(Debug, Default)]
pub struct ParagraphIds(AtomicU64);

/// The one source of paragraph IDs of all tests of the crate. Each paragraph that a test builds or
/// reads takes an ID of its own from it, so that no test hides a fault of the record of styled
/// text behind two paragraphs with equal IDs. The tests run in parallel, so a test compares IDs
/// with each other and never with a value.
#[cfg(test)]
pub(crate) static TEST_PARAGRAPH_IDS: ParagraphIds = ParagraphIds(AtomicU64::new(0));

impl ParagraphIds {
    /// The next ID. The count does not overflow: no document holds 2^64 paragraphs.
    pub fn next(&self) -> ParagraphId {
        ParagraphId(self.0.fetch_add(1, Ordering::Relaxed))
    }
}

/// A paragraph with its direct properties.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Paragraph {
    /// The paragraph's identity, which every copy keeps.
    pub id: ParagraphId,
    /// Direct paragraph properties.
    pub props: ParaProps,
    /// The runs in order.
    pub runs: Vec<Run>,
    /// Where the reader found its element, which layout never reads.
    pub source: SourceSpan,
}

#[cfg(test)]
impl Paragraph {
    /// An empty paragraph of a test, without properties or runs, with an ID of its own from
    /// [`TEST_PARAGRAPH_IDS`].
    pub(crate) fn empty() -> Self {
        Self {
            id: TEST_PARAGRAPH_IDS.next(),
            props: ParaProps::default(),
            runs: Vec::new(),
            source: SourceSpan::NONE,
        }
    }
}

/// A paragraph or a table.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Block {
    /// A paragraph.
    Paragraph(Paragraph),
    /// A table.
    Table(Table),
}

/// The body of a document.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Body {
    /// The paragraphs and tables in order.
    pub blocks: Vec<Block>,
    /// Every section in order: those that paragraphs end, then the last one, the body's own.
    pub sections: Sections<SectionPart>,
    /// Whether the body has no section properties at all: no `w:sectPr` of its own or in a
    /// paragraph.
    pub without_section: bool,
    /// The part that holds the body, which the warnings of its layout name.
    pub part: std::rc::Rc<f_office_warnings::Name>,
    /// The body's table of contents, which the reader takes before it replaces the fields by
    /// their results.
    pub(crate) table_of_contents: Option<toc::TableOfContents>,
}

impl Body {
    /// Gives a body without section properties the section `template`, the one that the
    /// target gives such a document, then moves the gutter of every section to the top margin
    /// when `gutter_at_top`, as the setting `w:gutterAtTop` asks.
    pub fn place_pages(&mut self, template: &Section, gutter_at_top: bool) {
        self.place_template_page(template);
        self.place_gutters(gutter_at_top);
    }

    /// Gives a body without section properties the section `section`.
    fn place_template_page(&mut self, section: &Section) {
        if !self.without_section {
            return;
        }
        for part in &mut self.sections {
            part.section = *section;
        }
    }

    /// Moves the gutter of every section from the left margin to the top margin when
    /// `at_top`, as the setting `w:gutterAtTop` asks.
    fn place_gutters(&mut self, at_top: bool) {
        if !at_top {
            return;
        }
        for part in &mut self.sections {
            part.section = part.section.with_gutter_at_top();
        }
    }

    /// Reads the `w:body` element of `word/document.xml`, whose fields show what the reader's
    /// settings `settings` say, and whose empty paragraphs that end a section before a
    /// continuous section follow `settings` and the document's mode rules `mode`.
    pub(crate) fn read(
        reader: &mut PartReader,
        body: NodeId,
        (settings, mode): (ReaderSettings, ModeRules),
    ) -> Self {
        let doc = reader.doc;
        let mut out = Self {
            part: std::rc::Rc::new(f_office_warnings::Name::new(reader.part())),
            ..Self::default()
        };
        let mut parts = Vec::new();
        let mut bookmarks = Vec::new();
        let mut text_columns = Vec::new();
        let mut marks = 0;
        for child in block_children(reader, body) {
            let block = read_block(reader, child);
            // The shapes of a child that gives no block are not drawn, so they never go with the
            // next block.
            let shapes = reader.take_text_columns().into_iter();
            if let Some(mut block) = block {
                give_bookmarks(&mut bookmarks, &mut block);
                give_marks(&mut marks, &mut block);
                text_columns.extend(shapes.map(|shape| (out.blocks.len(), child, shape)));
                out.push_block(reader, child, block, &mut parts);
            } else if doc.is(child, W, "sectPr") {
                parts.push(MetSection::Body(child));
            } else if doc.is(child, W, "bookmarkStart") {
                bookmarks.extend(bookmark_run(doc, child));
            } else if doc.is(child, W, "sdt") || doc.is(child, W, "sdtContent") {
                marks += crate::params::TEXT_BUFFER_MARK_LENGTH;
            }
        }
        let count = out.blocks.len();
        out.without_section = parts.is_empty();
        // The body's own `w:sectPr` gives the last section; without one, the last section has
        // the defaults.
        let own = match parts.pop() {
            Some(MetSection::Body(node)) => Some(node),
            other => {
                parts.extend(other);
                None
            }
        };
        let before = parts
            .into_iter()
            .map(|part| match part {
                MetSection::Ended(part) => *part,
                // One before a paragraph's `w:sectPr` also ends where the blocks end.
                MetSection::Body(node) => read_section_part(reader, node, count),
            })
            .collect();
        let last = match own {
            Some(node) => read_section_part(reader, node, count),
            None => SectionPart {
                end: count,
                ..SectionPart::default()
            },
        };
        out.sections = Sections::ending_with(before, last);
        warn_text_columns(reader, &out.sections, &text_columns);
        inherit_references(&mut out.sections);
        keep_section_ends(&mut out.blocks, &out.sections, (settings, mode));
        out.table_of_contents = toc::read(&out.blocks);
        resolve_fields(reader, &mut out.blocks, settings.body_updates());
        fields::keep_stored_properties(&mut out.blocks);
        out
    }

    /// Streams `<w:body>` direct child elements one block at a time from raw `main_bytes` using
    /// the byte ranges in `streamed`, parsing each block into a transient single-block XML
    /// fragment with exact part byte spans and dropping it before reading the next block.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Xml`] if any streamed block fails XML fragment parsing.
    pub(crate) fn read_streamed(
        main_bytes: &[u8],
        streamed: &f_office_xml::StreamedBody,
        (main_part, xml_limits): (&str, &f_office_xml::Limits),
        reading: &mut crate::parts::Reading<'_>,
        (settings, mode): (ReaderSettings, ModeRules),
    ) -> Result<Self, crate::Error> {
        let mut out = Self {
            part: std::rc::Rc::new(f_office_warnings::Name::new(main_part)),
            ..Self::default()
        };
        let mut parts: Vec<StreamedSection> = Vec::new();
        let mut bookmarks = Vec::new();
        let mut text_columns: Vec<(usize, f_office_warnings::Name)> = Vec::new();
        let mut marks = 0;
        let mut seen_undeclared: HashSet<String> = HashSet::new();

        for range in &streamed.children {
            let Some(slice) = main_bytes.get(range.clone()) else {
                continue;
            };
            let frag = Document::parse_fragment_with_aliases_at(
                slice,
                &streamed.in_scope,
                crate::ns::STRICT_ALIASES,
                u64::try_from(range.start).unwrap_or(u64::MAX),
                xml_limits,
            )
            .map_err(crate::Error::Xml)?;
            for prefix in frag.document().undeclared_prefixes() {
                if seen_undeclared.insert(prefix.clone()) {
                    crate::parts::undeclared_prefixes(
                        main_part,
                        std::slice::from_ref(prefix),
                        reading.warnings,
                    );
                }
            }
            let Some(&child) = frag.nodes().first() else {
                continue;
            };
            crate::parts::read_with(
                frag.document(),
                (main_part, child),
                reading,
                |part_reader, root_node| {
                    for node in unwrap_streamed_child(part_reader, root_node) {
                        out.ingest_streamed_node(
                            part_reader,
                            node,
                            &mut parts,
                            &mut bookmarks,
                            &mut marks,
                            &mut text_columns,
                        );
                    }
                },
            );
        }

        out.finish_streamed_sections(parts);

        // Emit VML text-column warnings and resolve body-level fields using a minimal empty XML
        // document (neither step inspects XML nodes).
        let empty = Document::parse(b"<r/>", xml_limits).map_err(crate::Error::Xml)?;
        let empty_root = empty.root().map_err(crate::Error::Xml)?;
        crate::parts::read_with(
            &empty,
            (main_part, empty_root),
            reading,
            |part_reader, _| {
                warn_streamed_text_columns(part_reader, &out.sections, &text_columns);
                inherit_references(&mut out.sections);
                keep_section_ends(&mut out.blocks, &out.sections, (settings, mode));
                out.table_of_contents = toc::read(&out.blocks);
                resolve_fields(part_reader, &mut out.blocks, settings.body_updates());
                fields::keep_stored_properties(&mut out.blocks);
            },
        );
        Ok(out)
    }

    /// Ingests one unwrapped body child element into the streamed [`Body`].
    fn ingest_streamed_node(
        &mut self,
        part_reader: &mut PartReader,
        node: NodeId,
        parts: &mut Vec<StreamedSection>,
        bookmarks: &mut Vec<Run>,
        marks: &mut usize,
        text_columns: &mut Vec<(usize, f_office_warnings::Name)>,
    ) {
        let doc = part_reader.doc;
        let block = read_block(part_reader, node);
        let shapes = part_reader.take_text_columns();
        if let Some(mut block) = block {
            give_bookmarks(bookmarks, &mut block);
            give_marks(marks, &mut block);
            if !shapes.is_empty() && doc.is(node, W, "p") {
                let outside = outside_text_boxes(doc, node);
                let block_idx = self.blocks.len();
                for shape in shapes {
                    if outside.contains(&shape) {
                        let name = doc
                            .element(shape)
                            .map_or_default(|e| f_office_warnings::Name::new(e.name.local));
                        text_columns.push((block_idx, name));
                    }
                }
            }
            self.push_streamed_block(part_reader, node, block, parts);
        } else if doc.is(node, W, "sectPr") {
            let sect = read_section_part(part_reader, node, 0);
            parts.push(StreamedSection::Body(Box::new(sect)));
        } else if doc.is(node, W, "bookmarkStart") {
            bookmarks.extend(bookmark_run(doc, node));
        } else if doc.is(node, W, "sdt") || doc.is(node, W, "sdtContent") {
            *marks += crate::params::TEXT_BUFFER_MARK_LENGTH;
        }
    }

    /// Finalizes the body's [`Sections`] list from streamed section markers.
    fn finish_streamed_sections(&mut self, mut parts: Vec<StreamedSection>) {
        let count = self.blocks.len();
        self.without_section = parts.is_empty();
        let own = match parts.pop() {
            Some(StreamedSection::Body(mut sect)) => {
                sect.end = count;
                Some(*sect)
            }
            other => {
                parts.extend(other);
                None
            }
        };
        let before = parts
            .into_iter()
            .map(|part| match part {
                StreamedSection::Ended(sect) => *sect,
                StreamedSection::Body(mut sect) => {
                    sect.end = count;
                    *sect
                }
            })
            .collect();
        let last = own.unwrap_or_else(|| SectionPart {
            end: count,
            ..SectionPart::default()
        });
        self.sections = Sections::ending_with(before, last);
    }

    /// Adds a streamed block and records any paragraph-level `w:sectPr` ending at this block.
    fn push_streamed_block(
        &mut self,
        reader: &mut PartReader,
        node: NodeId,
        block: Block,
        parts: &mut Vec<StreamedSection>,
    ) {
        let doc = reader.doc;
        self.blocks.push(block);
        let inner = doc
            .child(node, W, "pPr")
            .and_then(|ppr| doc.child(ppr, W, "sectPr"));
        if let Some(sect) = inner.filter(|_| doc.is(node, W, "p")) {
            let part = read_section_part(reader, sect, self.blocks.len());
            parts.push(StreamedSection::Ended(Box::new(part)));
        }
    }

    /// Adds a block of the body, and to `parts` the section that a paragraph's `w:sectPr` ends
    /// there.
    fn push_block(
        &mut self,
        reader: &mut PartReader,
        node: NodeId,
        block: Block,
        parts: &mut Vec<MetSection>,
    ) {
        let doc = reader.doc;
        self.blocks.push(block);
        let inner = doc
            .child(node, W, "pPr")
            .and_then(|ppr| doc.child(ppr, W, "sectPr"));
        if let Some(sect) = inner.filter(|_| doc.is(node, W, "p")) {
            let part = read_section_part(reader, sect, self.blocks.len());
            parts.push(MetSection::Ended(Box::new(part)));
        }
    }
}

/// Warns of each VML shape that F-Office draws from the margins where Part 4's text column
/// that holds its anchor can lie apart from them (`vml::across`): a shape in a paragraph of the
/// body, outside a text box, in a section of more than one column. Each of `shapes` is the
/// index of the body's block that holds the shape, that block's element and the shape. In a
/// table cell the margins already count from the cell's column, and a header or a footer is laid
/// out in one column. A footnote or an endnote is laid out in its section's first column, where
/// the two can lie apart too, but its part is read apart from the body, so its shapes are not
/// warned of.
///
/// The shapes come in the order of the body, and the shapes of one block are next to each
/// other. So one cursor finds the section of each shape, the first one that ends after its
/// block, and each paragraph is walked once for all its shapes ([`outside_text_boxes`]): the
/// work grows with the shapes, the sections and the elements of the paragraphs, and not with
/// their products.
fn warn_text_columns(
    reader: &mut PartReader,
    sections: &Sections<SectionPart>,
    shapes: &[(usize, NodeId, NodeId)],
) {
    let doc = reader.doc;
    let mut parts = sections.iter().peekable();
    // The last paragraph walked, with the elements that it holds outside a text box.
    let mut walked: Option<(NodeId, HashSet<NodeId>)> = None;
    for &(index, block, shape) in shapes {
        while parts
            .next_if(|part| {
                count_text_column_step();
                index >= part.end
            })
            .is_some()
        {}
        let columns = parts.peek().map_or(1, |part| part.section.columns.count);
        if columns <= 1 || !doc.is(block, W, "p") {
            continue;
        }
        if walked.as_ref().is_none_or(|(node, _)| *node != block) {
            walked = Some((block, outside_text_boxes(doc, block)));
        }
        if walked
            .as_ref()
            .is_some_and(|(_, outside)| outside.contains(&shape))
        {
            crate::vml::warn_text_column(reader, shape);
        }
    }
}

/// The element `node` and the elements that it holds outside a text box (`w:txbxContent` or
/// `wne:txbxContent`).
fn outside_text_boxes(doc: &Document, node: NodeId) -> HashSet<NodeId> {
    let mut outside = HashSet::new();
    let mut stack = vec![node];
    while let Some(next) = stack.pop() {
        count_text_column_step();
        outside.insert(next);
        stack.extend(
            doc.child_elements(next)
                .filter(|&child| !crate::ns::is_text_box_content(doc, child)),
        );
    }
    outside
}

#[cfg(test)]
thread_local! {
    /// The steps of the warnings of text columns on this thread: the sections that the cursor
    /// looks at and the elements that the walks of paragraphs visit. A test bounds the work of
    /// many shapes by this count, and not by a time.
    static TEXT_COLUMN_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Counts a step of the warnings of text columns (`TEXT_COLUMN_STEPS`). Only a test build
/// keeps the count.
fn count_text_column_step() {
    #[cfg(test)]
    TEXT_COLUMN_STEPS.with(|steps| steps.set(steps.get() + 1));
}

/// Emits deferred VML text-column warnings for streamed `<w:body>` blocks that fall inside
/// multi-column sections.
fn warn_streamed_text_columns(
    reader: &mut PartReader,
    sections: &Sections<SectionPart>,
    shapes: &[(usize, f_office_warnings::Name)],
) {
    let mut parts = sections.iter().peekable();
    for (index, element_name) in shapes {
        while parts.next_if(|part| *index >= part.end).is_some() {}
        let columns = parts.peek().map_or(1, |part| part.section.columns.count);
        if columns > 1 {
            crate::vml::warn_text_column_named(reader, element_name.clone());
        }
    }
}

/// A `w:sectPr` encountered while streaming `<w:body>` blocks.
#[derive(Debug)]
enum StreamedSection {
    /// Section ended by a paragraph's `w:pPr/w:sectPr`.
    Ended(Box<SectionPart>),
    /// Body-level `w:sectPr` whose `end` is set once all blocks are counted.
    Body(Box<SectionPart>),
}

/// A `w:sectPr` of the body as the reader meets it, in the order of the body.
#[derive(Debug)]
enum MetSection {
    /// The section that a paragraph's `w:sectPr` ends, read where the reader meets it, with
    /// the index after its last block.
    Ended(Box<SectionPart>),
    /// The body's own `w:sectPr`, whose section ends where the blocks end. The reader reads it
    /// when it knows that end, after the last block, which is where the element stands in a
    /// valid body, so that its warnings keep their place.
    Body(NodeId),
}

/// An empty paragraph that ends a section, before a section that starts on a new page, takes no
/// page break before it, so that it gets no page of its own. Before a continuous section, a
/// paragraph that holds nothing takes no room, unless it is the only block of its section; in a
/// section where `settings` keep its spaces (`ReaderSettings::keeps_end_spaces`), one that
/// holds nothing or only bookmarks after a paragraph of its section is a continuous section end
/// instead, which layout lays out, and one after a table keeps its line in the modes that
/// `mode` says.
fn keep_section_ends(
    blocks: &mut [Block],
    sections: &Sections<SectionPart>,
    (settings, mode): (ReaderSettings, ModeRules),
) {
    let mut start = 0;
    for (part, next) in sections.iter().zip(sections.iter().skip(1)) {
        let alone = part.end <= start + 1;
        start = part.end;
        let after_paragraph = part
            .end
            .checked_sub(2)
            .and_then(|i| blocks.get(i))
            .is_some_and(|b| matches!(b, Block::Paragraph(_)));
        let last = part.end.checked_sub(1).and_then(|i| blocks.get_mut(i));
        let Some(Block::Paragraph(paragraph)) = last else {
            continue;
        };
        if next.start != SectionStart::Continuous || !part.section.same_page_size(&next.section) {
            if is_empty_paragraph(paragraph) {
                paragraph.props.page_break_before = Some(false);
                paragraph.props.section_end = Some(true);
            }
            continue;
        }
        let keeps_spaces = settings.keeps_end_spaces(part.section.columns.count);
        let keeps_line = keeps_spaces && mode.keeps_section_end_line_after_table();
        if keeps_spaces && !keeps_line {
            paragraph.props.continuous_break_end = Some(true);
        }
        if alone {
            // quirk: ContinuousSectionEnd::OnlyBlockKeepsLine (src/quirks.rs)
            continue;
        }
        mark_continuous_end(paragraph, (keeps_spaces, after_paragraph), keeps_line);
    }
}

/// Marks the empty paragraph that ends a section before a continuous section and is not the
/// only block of its section: in a section where it `keeps_spaces`, after a paragraph, it is a
/// continuous section end when it holds nothing or only bookmarks, and after a table it keeps
/// its line when `keeps_line` holds; else it shows nothing when it holds nothing.
///
/// quirk: `ContinuousSectionEnd::KeepsSpacesWithoutLine` (src/quirks.rs)
fn mark_continuous_end(
    paragraph: &mut Paragraph,
    (keeps_spaces, after_paragraph): (bool, bool),
    keeps_line: bool,
) {
    if keeps_spaces && after_paragraph {
        if holds_only_bookmarks(paragraph) {
            paragraph.props.continuous_end = Some(true);
        }
        return;
    }
    if !keeps_line && holds_nothing(paragraph) {
        // It shows nothing, as an empty paragraph whose mark is hidden.
        paragraph.props.mark.hidden = Some(true);
    }
}

/// Whether a paragraph is empty at the end of its section: its text is only white space, and
/// its other content is breaks, the marks of fields and bookmarks, and comment anchors. A tab,
/// a drawing, an object, a check box, a note reference, the number of a note, the rule of the
/// notes, a field that shows a value, and the places of an equation are content.
fn is_empty_paragraph(paragraph: &Paragraph) -> bool {
    paragraph
        .runs
        .iter()
        .flat_map(|r| &r.content)
        .all(|c| match c {
            Content::Text(text) => text.trim().is_empty(),
            // Explicit breaks count as empty for section-end emptiness checks.
            Content::LineBreak
            | Content::ClearingBreak
            | Content::PageBreak
            | Content::ColumnBreak
            | Content::FieldBegin
            | Content::FieldLock
            | Content::DropDown(_)
            | Content::FieldCode(_)
            | Content::FieldSeparate
            | Content::FieldEnd
            | Content::FieldMark
            | Content::HyperlinkEdge
            | Content::ControlEdge
            | Content::RemovedEdge
            | Content::Bookmark(_)
            | Content::CommentAnchor(_)
            | Content::CommentMark
            | Content::Advance(_) => true,
            Content::Tab
            | Content::PositionTab { .. }
            | Content::CheckBox(_)
            | Content::PageNumber
            | Content::PageCount
            | Content::Date(_)
            | Content::DocProperty(_)
            | Content::StyleRef(_)
            | Content::PageRef(_)
            | Content::NumberRef(_)
            | Content::If(_)
            | Content::FootnoteReference(..)
            | Content::FootnoteMark
            | Content::EndnoteReference(..)
            | Content::EndnoteMark
            | Content::Separator
            | Content::ContinuationSeparator
            | Content::Stack(_)
            | Content::Grown(_)
            | Content::Radical(_)
            | Content::Accent(_)
            | Content::Matrix(_)
            | Content::MathBar(_)
            | Content::MathSlash(_)
            | Content::MathLimit(_)
            | Content::GroupChr(_)
            | Content::MathBox(_)
            | Content::Scripts(_)
            | Content::Floating(_)
            | Content::Object { .. }
            | Content::Drawing(_) => false,
        })
}

/// Whether a paragraph holds nothing but the starts of bookmarks: its runs have no other
/// content than empty text and bookmarks.
fn holds_only_bookmarks(paragraph: &Paragraph) -> bool {
    paragraph
        .runs
        .iter()
        .flat_map(|r| &r.content)
        .all(|c| match c {
            Content::Text(text) => text.is_empty(),
            Content::Bookmark(_) => true,
            _ => false,
        })
}

/// Whether a paragraph holds nothing at all: its runs have no content but empty text.
pub(crate) fn holds_nothing(paragraph: &Paragraph) -> bool {
    paragraph
        .runs
        .iter()
        .flat_map(|r| &r.content)
        .all(|c| matches!(c, Content::Text(text) if text.is_empty()))
}

/// Reads a `w:p` or `w:tbl` element. Other elements are not blocks.
pub(crate) fn read_block(reader: &mut PartReader, node: NodeId) -> Option<Block> {
    let doc = reader.doc;
    if doc.is(node, W, "p") {
        Some(Block::Paragraph(read_paragraph(reader, node)))
    } else if doc.is(node, W, "tbl") {
        Some(Block::Table(Table::read(reader, node)))
    } else {
        None
    }
}

/// Reads the paragraphs and tables of a story, such as a note or a text box.
pub(crate) fn read_story(reader: &mut PartReader, root: NodeId) -> Vec<Block> {
    let mut blocks = read_blocks(reader, root);
    resolve_fields(reader, &mut blocks, Updates::Computed);
    blocks
}

/// Reads the paragraphs and tables of a header or footer part (`w:hdr` or `w:ftr`), whose
/// fields show what the reader's settings `settings` say.
pub(crate) fn read_header_story(
    reader: &mut PartReader,
    root: NodeId,
    settings: ReaderSettings,
) -> Vec<Block> {
    let mut blocks = read_blocks(reader, root);
    resolve_fields(reader, &mut blocks, settings.header_updates());
    blocks
}

/// Reads the paragraphs and tables in an element, such as a table cell.
pub(crate) fn read_blocks(reader: &mut PartReader, node: NodeId) -> Vec<Block> {
    let doc = reader.doc;
    let mut bookmarks = Vec::new();
    let mut blocks = Vec::new();
    let mut marks = 0;
    for child in block_children(reader, node) {
        if let Some(mut block) = read_block(reader, child) {
            give_bookmarks(&mut bookmarks, &mut block);
            give_marks(&mut marks, &mut block);
            blocks.push(block);
        } else if doc.is(child, W, "bookmarkStart") {
            bookmarks.extend(bookmark_run(doc, child));
        } else if doc.is(child, W, "sdt") || doc.is(child, W, "sdtContent") {
            marks += crate::params::TEXT_BUFFER_MARK_LENGTH;
        }
    }
    blocks
}

/// Gives the marks of block content controls before `block` (`marks` characters of Word's text
/// buffers) to the first run of its first paragraph, when it has one.
fn give_marks(marks: &mut usize, block: &mut Block) {
    if *marks == 0 {
        return;
    }
    if let Some(run) = first_run(block) {
        run.buffer_only.characters += std::mem::take(marks);
    }
}

/// The first run of a block's first paragraph, in a table its first cell's.
fn first_run(block: &mut Block) -> Option<&mut Run> {
    match block {
        Block::Paragraph(paragraph) => paragraph.runs.first_mut(),
        Block::Table(table) => table
            .rows
            .first_mut()?
            .cells
            .first_mut()?
            .blocks
            .first_mut()
            .and_then(first_run),
    }
}

/// Puts the bookmarks that start between blocks (`w:bookmarkStart` outside a paragraph) at the
/// start of the first paragraph of the next block, where Word counts their page.
fn give_bookmarks(bookmarks: &mut Vec<Run>, block: &mut Block) {
    if bookmarks.is_empty() {
        return;
    }
    if let Some(paragraph) = paragraphs_mut(std::slice::from_mut(block))
        .into_iter()
        .next()
    {
        paragraph.runs.splice(0..0, bookmarks.drain(..));
    }
}

/// The paragraphs of `blocks` in document order, also those in the cells of their tables at any
/// depth.
pub(crate) fn all_paragraphs(blocks: &[Block]) -> Vec<&Paragraph> {
    let mut out = Vec::new();
    for block in blocks {
        match block {
            Block::Paragraph(paragraph) => out.push(paragraph),
            Block::Table(table) => {
                for cell in table.rows.iter().flat_map(|row| &row.cells) {
                    out.extend(all_paragraphs(&cell.blocks));
                }
            }
        }
    }
    out
}

/// The paragraphs of blocks in document order, with those in table cells.
fn paragraphs_mut(blocks: &mut [Block]) -> Vec<&mut Paragraph> {
    let mut out = Vec::new();
    for block in blocks {
        match block {
            Block::Paragraph(paragraph) => out.push(paragraph),
            Block::Table(table) => {
                for cell in table.rows.iter_mut().flat_map(|row| row.cells.iter_mut()) {
                    out.extend(paragraphs_mut(&mut cell.blocks));
                }
            }
        }
    }
    out
}

/// The ID of a footnote or an endnote (`w:id`, `ST_DecimalNumber`), read once as its number by
/// the one number reader, for a note and for a reference to it: a reference finds its note by
/// the number, so `01` and `1` name one note, as two list IDs of one number name one list. The
/// footnotes and the endnotes each have their own IDs, which their parts keep apart. A value
/// that does not read is a missing ID, with a warning: a reference without an ID shows no
/// number, and a note without one is not kept. Of two normal notes of one number in a part,
/// the layout keeps the later one, with a warning (`Warning::NoteIdRepeated`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NoteId(i64);

impl NoteId {
    /// The ID in the attribute `w:id` of `node`, a note or a reference to one. Every number
    /// of `ST_DecimalNumber` is an ID: a normal note of a written document can have the ID 0
    /// or a negative one.
    pub(crate) fn read(reader: &mut PartReader, node: NodeId) -> Option<Self> {
        reader.number(node, "id", crate::numbers::ANY).map(Self)
    }

    /// The number of the ID, which a warning names.
    pub(crate) const fn number(self) -> i64 {
        self.0
    }

    /// The ID with the number `number`, for a test that looks up a note.
    #[cfg(test)]
    pub(crate) const fn of(number: i64) -> Self {
        Self(number)
    }
}

/// What a note reference shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NoteMark {
    /// The note's number, which the automatic numbering of its kind of note gives it.
    #[default]
    Number,
    /// Nothing: the text after the reference is its mark (`w:customMarkFollows`), and the note
    /// takes no number in the automatic numbering.
    Custom,
}

impl NoteMark {
    /// The mark of the reference `node` (`w:footnoteReference` or `w:endnoteReference`), whose
    /// on/off attribute `w:customMarkFollows` is off when it is missing.
    pub(crate) fn read(doc: &Document, node: NodeId) -> Self {
        let custom = doc
            .attribute(node, Some(W), "customMarkFollows")
            .is_some_and(|value| crate::on_off::read(value) == Some(true));
        if custom { Self::Custom } else { Self::Number }
    }
}

/// The IDs of the normal notes of the footnotes part and of the endnotes part, against which
/// the readers of the parts read after them check each note reference
/// ([`PartReader::note_reference`]).
pub(crate) type NoteIds = crate::note_setup::ByNoteKind<std::collections::HashSet<NoteId>>;

/// The footnotes of a document and their separator.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Notes {
    /// The separator above the footnotes of a page.
    pub separator: Vec<Block>,
    /// The separator above the rest of a footnote that started on the page before.
    pub continuation: Vec<Block>,
    /// The footnotes by ID.
    pub by_id: std::collections::HashMap<NoteId, Vec<Block>>,
    /// The IDs of the normal notes, each once, in the order in which the part first gives it,
    /// which numbers the notes in their addresses.
    pub order: Vec<NoteId>,
    /// The name of the part, which the layout's warnings of the notes' text name: empty for
    /// the notes of a document without the part.
    pub part: std::rc::Rc<f_office_warnings::Name>,
}

/// The type of a footnote or an endnote (`w:type`, `ST_FtnEdn`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NoteType {
    Normal,
    Separator,
    ContinuationSeparator,
    ContinuationNotice,
}

/// `ST_FtnEdn`: the notice of a note continued on the next page is not drawn, and a note
/// without a kind is a normal note.
const NOTE_TYPE: &Values<NoteType> = &Values::new(&[
    own("normal", NoteType::Normal),
    own("separator", NoteType::Separator),
    own("continuationSeparator", NoteType::ContinuationSeparator),
    another("continuationNotice", NoteType::ContinuationNotice),
]);

impl Notes {
    /// The IDs of the normal notes.
    pub(crate) fn ids(&self) -> std::collections::HashSet<NoteId> {
        self.by_id.keys().copied().collect()
    }

    /// Reads the footnotes part (`w:footnotes`) or the endnotes part (`w:endnotes`), of whose
    /// normal notes of one number it keeps the one that the reader's settings `settings` say.
    pub(crate) fn read(reader: &mut PartReader, root: NodeId, settings: ReaderSettings) -> Self {
        let doc = reader.doc;
        let mut out = Self {
            part: std::rc::Rc::new(f_office_warnings::Name::new(reader.part())),
            ..Self::default()
        };
        for note in doc
            .child_elements(root)
            .filter(|n| doc.is(*n, W, "footnote") || doc.is(*n, W, "endnote"))
        {
            let story = read_story(reader, note);
            match reader.enumeration(note, "type", NOTE_TYPE) {
                Some(NoteType::Separator) => out.separator = story,
                Some(NoteType::ContinuationSeparator) => out.continuation = story,
                Some(NoteType::ContinuationNotice) => {}
                Some(NoteType::Normal) | None => {
                    // Of two normal notes of one number, the target keeps one, with a warning
                    // for each repeat.
                    let Some(id) = NoteId::read(reader, note) else {
                        continue;
                    };
                    if !out.by_id.contains_key(&id) {
                        out.order.push(id);
                    }
                    if settings.file_note(&mut out.by_id, id, story) {
                        reader.note_id_repeated(id.number());
                    }
                }
            }
        }
        out
    }

    /// The notes with the separator that Word draws when the settings list no special
    /// footnotes: not the written one, but a paragraph of the properties `props` that holds the
    /// rule. Each of the two paragraphs takes an ID from `ids`.
    #[must_use]
    pub fn with_own_separator(mut self, ids: &ParagraphIds, props: &ParaProps) -> Self {
        let holds = |rule: Content| {
            let rule = Run {
                content: vec![rule],
                ..Run::default()
            };
            vec![Block::Paragraph(Paragraph {
                id: ids.next(),
                props: props.clone(),
                runs: vec![rule],
                source: SourceSpan::NONE,
            })]
        };
        self.separator = holds(Content::Separator);
        self.continuation = holds(Content::ContinuationSeparator);
        self
    }
}

/// Why F-Office takes the choices of alternate content that require a namespace of
/// [`TAKEN_CHOICES`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TakenBecause {
    /// F-Office reads the namespace's markup.
    Read,
    /// Word's symbol extension: F-Office does not draw a character of it (the run reader warns of
    /// each, [`Feature::SymbolExtension`]), and leaves out the fallback rather than drawing
    /// substitute text. The entry goes when F-Office draws the symbol extension.
    FallbackRejected,
}

/// The namespaces whose choice of alternate content F-Office takes, each with its reason: a
/// choice all of whose `Requires` namespaces are here is the branch that F-Office shows
/// ([`alternate_branch`]), as ECMA-376 Part 3 (10.2.1) has a consumer take the first choice
/// whose namespaces it understands. The namespaces that F-Office reads are the content
/// namespaces of [`crate::ns`] but the chart of Office 2016 and later (`cx`) and
/// the symbol extension; the namespaces of markup compatibility, of the custom properties and
/// their values, and F-Office's own note namespace hold no content that a choice requires.
const TAKEN_CHOICES: [(&str, TakenBecause); 19] = [
    (W, TakenBecause::Read),
    (R, TakenBecause::Read),
    (W14, TakenBecause::Read),
    (W15, TakenBecause::Read),
    (WP, TakenBecause::Read),
    (WP14, TakenBecause::Read),
    (WPS, TakenBecause::Read),
    (WPG, TakenBecause::Read),
    (WPC, TakenBecause::Read),
    (A, TakenBecause::Read),
    (PIC, TakenBecause::Read),
    (C, TakenBecause::Read),
    (DGM, TakenBecause::Read),
    (DSP, TakenBecause::Read),
    (V, TakenBecause::Read),
    (W10, TakenBecause::Read),
    (O, TakenBecause::Read),
    (M, TakenBecause::Read),
    (W16SE, TakenBecause::FallbackRejected),
];

/// The branch of alternate content (`mc:AlternateContent`, ECMA-376 Part 3, 10.2) that
/// F-Office shows: the first choice (`mc:Choice`) that it takes, else the fallback
/// (`mc:Fallback`), else none. F-Office takes a choice when each prefix that its `Requires`
/// names is bound, at the choice, to a namespace of [`TAKEN_CHOICES`]; a choice without
/// `Requires` requires nothing. A reader of content shows the branch through [`shown_branch`],
/// which warns of the choices that it passes over ([`passed_choices`]).
pub fn alternate_branch(doc: &Document, node: NodeId) -> Option<NodeId> {
    let mut fallback = None;
    for child in doc.child_elements(node) {
        if doc.is(child, MC, "Choice") {
            if takes_choice(doc, child) {
                return Some(child);
            }
        } else if fallback.is_none() && doc.is(child, MC, "Fallback") {
            fallback = Some(child);
        }
    }
    fallback
}

/// The choices of the alternate content `node` that F-Office passes over: those before the
/// first choice that it takes, in document order, so every choice when it takes none, wherever
/// the fallback stands ([`alternate_branch`]). [`shown_branch`] warns of them, and a group
/// member with no branch takes the kind of the first drawing in them.
pub(crate) fn passed_choices(doc: &Document, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
    doc.child_elements(node)
        .filter(move |child| doc.is(*child, MC, "Choice"))
        .take_while(move |choice| !takes_choice(doc, *choice))
}

/// Whether F-Office takes the choice of alternate content `choice` ([`alternate_branch`]).
fn takes_choice(doc: &Document, choice: NodeId) -> bool {
    doc.attribute(choice, None, "Requires")
        .unwrap_or("")
        .split_whitespace()
        .all(|prefix| {
            doc.prefix_namespace(choice, prefix)
                .is_some_and(|namespace| TAKEN_CHOICES.iter().any(|(taken, _)| *taken == namespace))
        })
}

/// The branch of the alternate content `node` that F-Office shows ([`alternate_branch`]), with
/// a warning of each choice that it passes over, so that the branch in its place is never
/// silent: of the first drawing in the choice, which is left out (such as ink, `shape-skipped`),
/// else of the choice ([`Feature::AlternateChoice`]).
pub(crate) fn shown_branch(reader: &mut PartReader, node: NodeId) -> Option<NodeId> {
    let doc = reader.doc;
    for choice in passed_choices(doc, node) {
        match passed_choice(doc, choice) {
            PassedChoice::Drawing(drawing) => reader.drawing_skipped(drawing, Reason::Unsupported),
            PassedChoice::Other => reader.feature_not_supported(Feature::AlternateChoice),
        }
    }
    alternate_branch(doc, node)
}

/// What a choice of alternate content that F-Office passes over holds, for its warning.
enum PassedChoice {
    /// A drawing (`a:graphicData`, or ink as `w14:contentPart`) of this kind, the first in the
    /// choice.
    Drawing(crate::warnings::Drawing),
    /// No drawing.
    Other,
}

/// What the choice `choice` holds, by the first drawing in it, in document order.
fn passed_choice(doc: &Document, choice: NodeId) -> PassedChoice {
    let mut stack: Vec<NodeId> = doc.child_elements(choice).collect();
    stack.reverse();
    while let Some(node) = stack.pop() {
        if doc.is(node, A, "graphicData") {
            return PassedChoice::Drawing(crate::floating::graphic_data_drawing(doc, node));
        }
        // Ink can stand in the drawing in place of its graphic.
        if doc.is(node, W14, "contentPart") {
            return PassedChoice::Drawing(crate::warnings::Drawing::Shape);
        }
        let start = stack.len();
        stack.extend(doc.child_elements(node));
        if let Some(added) = stack.get_mut(start..) {
            added.reverse();
        }
    }
    PassedChoice::Other
}

/// Wrapper elements at story/body level whose child blocks are unwrapped by [`block_children`]
/// and flagged by [`f_office_xml::scan_body_children`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BodyWrapper {
    /// Custom XML element (`w:customXml`).
    CustomXml,
    /// Block-level structured document tag (`w:sdt`).
    Sdt,
    /// Markup compatibility alternate content (`mc:AlternateContent`).
    AlternateContent,
}

impl BodyWrapper {
    const CUSTOM_XML: &'static str = "customXml";
    const SDT: &'static str = "sdt";
    const ALTERNATE_CONTENT: &'static str = "AlternateContent";

    /// Single source of truth for the local names of body wrapper elements, passed to
    /// [`f_office_xml::scan_body_children`].
    pub(crate) const LOCALS: [&'static str; 3] =
        [Self::CUSTOM_XML, Self::SDT, Self::ALTERNATE_CONTENT];

    /// Matches `node` against the shared wrapper element list.
    fn of(doc: &Document, node: NodeId) -> Option<Self> {
        if doc.is(node, W, Self::CUSTOM_XML) {
            Some(Self::CustomXml)
        } else if doc.is(node, W, Self::SDT) {
            Some(Self::Sdt)
        } else if doc.is(node, MC, Self::ALTERNATE_CONTENT) {
            Some(Self::AlternateContent)
        } else {
            None
        }
    }
}

/// Unwraps one body child element (whether from a tree or a streamed fragment) using the shared
/// [`BodyWrapper`] rules.
fn unwrap_streamed_child(reader: &mut PartReader, child: NodeId) -> Vec<NodeId> {
    let mut out = Vec::new();
    push_unwrapped_child(reader, child, &mut out);
    out
}

fn push_unwrapped_child(reader: &mut PartReader, child: NodeId, out: &mut Vec<NodeId>) {
    let doc = reader.doc;
    match BodyWrapper::of(doc, child) {
        Some(BodyWrapper::Sdt) => {
            if let Some(content) = doc.child(child, W, "sdtContent") {
                // The control's start and end marks stand in Word's text: the control and
                // its content mark them for the reader.
                out.push(child);
                out.extend(block_children(reader, content));
                out.push(content);
            }
        }
        Some(BodyWrapper::CustomXml) => {
            out.extend(block_children(reader, child));
        }
        Some(BodyWrapper::AlternateContent) => {
            if let Some(branch) = shown_branch(reader, child) {
                out.extend(block_children(reader, branch));
            }
        }
        None => out.push(child),
    }
}

/// The block-level children of a story, with the content of block-level content controls
/// (`w:sdt`), custom XML elements and the shown branch of alternate content in their place
/// (ECMA-376 Part 1, 17.5.2.31).
pub(crate) fn block_children(reader: &mut PartReader, node: NodeId) -> Vec<NodeId> {
    let mut out = Vec::new();
    for child in reader.doc.child_elements(node) {
        push_unwrapped_child(reader, child, &mut out);
    }
    out
}

#[cfg(test)]
mod tests;