f-office-docx 0.2.3

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

#![deny(clippy::float_arithmetic)]

mod art_pictures;
mod body;
mod buffers;
mod character_class;
mod chart;
mod comments;
pub mod configuration;
mod dates;
mod enumerations;
mod floating;
mod font_choice;
mod grid;
mod image_loader;
mod incremental;
mod kinsoku;
mod layout;
mod lengths;
mod lines;
mod math;
mod mode;
pub mod named_edits;
mod note_setup;
mod ns;
mod numbering;
mod numbers;
pub mod on_off;
mod params;
mod parts;
mod picture;
#[cfg(feature = "development")]
pub mod profile;
#[cfg(not(feature = "development"))]
mod profile;
mod properties;
mod props;
#[cfg(feature = "development")]
pub mod quirks;
#[cfg(not(feature = "development"))]
mod quirks;
mod reader;
mod revisions;
mod smartart;
mod source_span;
mod styles;
mod table;
mod tabs;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
mod text;
mod text_addresses;
mod text_blocks;
mod text_links;
mod text_map;
pub mod timing;
mod toc_links;
mod vml;
pub mod warnings;
mod web_settings;

#[cfg(test)]
mod tests;

use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
use std::sync::Arc;

use f_office_fonts::{
    FamilyName, FontId, Ligature, OutlineError, ShapeFailure, ShapeRequest, ShapedGlyph,
};
use f_office_opc::{Package, Relationship};
use f_office_paint::{DisplayList, Image, ImageFormat, InkConversion};
use f_office_xml::Document;

use crate::image_loader::PackageImageLoader;
pub use crate::incremental::{IncrementalLayout, LayoutStep, PreparedDocx};

use crate::body::{Block, Body, ParagraphIds, References, Sections, read_header_story};
use crate::layout::{
    Context, EarlierPass, HeaderStyles, Layout, PartStory, Pass, SectionLayout, Stories,
};
use crate::note_setup::NotePosition;
use crate::numbering::Numbering;
use crate::parts::{Reading, Role};
use crate::reader::settings::ReaderSettings;
use crate::styles::{FontTable, Settings, Styles, Theme};
use crate::text::Shaper;

/// The font metrics that layout needs, in font units.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FaceMetrics {
    /// Units per em.
    pub units_per_em: u16,
    /// `hhea` ascender.
    pub hhea_ascender: i16,
    /// `hhea` descender, negative below the baseline.
    pub hhea_descender: i16,
    /// `hhea` line gap.
    pub hhea_line_gap: i16,
    /// The depth of a line below the baseline, positive: `OS/2` `usWinDescent`, or the typo
    /// descender when the font sets `USE_TYPO_METRICS` and that descender is smaller.
    pub descent: u16,
    /// `post` underline position, negative below the baseline.
    pub underline_position: i16,
    /// `post` underline thickness.
    pub underline_thickness: i16,
    /// `OS/2` `yStrikeoutPosition`, the top of the strikeout stroke above the baseline.
    pub strikeout_position: i16,
    /// `OS/2` `yStrikeoutSize`.
    pub strikeout_thickness: i16,
    /// `OS/2` `ySuperscriptYOffset`, how far the font raises a superscript, or 0 when the font
    /// does not say.
    pub superscript_offset: i16,
    /// `OS/2` `ySubscriptYOffset`, how far the font lowers a subscript, or 0 when the font
    /// does not say.
    pub subscript_offset: i16,
    /// `OS/2` `ySuperscriptYSize`, the size of a superscript, or 0 when the font does not say.
    pub superscript_size: i16,
    /// `OS/2` `ySubscriptYSize`, the size of a subscript, or 0 when the font does not say.
    pub subscript_size: i16,
    /// The height of the font's line above the baseline, with which a superscript can align
    /// its top: the larger of the `hhea` line (ascender minus descender plus line gap) and the
    /// win line (`usWinAscent` plus `usWinDescent`), less `usWinDescent`; or the typo ascender
    /// plus the typo line gap when the font sets `USE_TYPO_METRICS`; or, for a font without an
    /// `OS/2` table, the `hhea` ascender plus the line gap. With [`Self::descent`], it makes
    /// the line of `quirks::LineHeight::TakesTallerLine`.
    pub line_top: u16,
    /// The top of the font above the baseline without a line gap: `usWinAscent`, or the typo
    /// ascender plus the typo line gap when the font sets `USE_TYPO_METRICS`.
    pub script_top: u16,
    /// Whether the font is made for East Asian text, as its `OS/2` code pages say. Word gives
    /// such a font's lines 0.3 of its height more, half above the text and half below.
    pub east_asian: bool,
    /// `OS/2` `xAvgCharWidth`, the average width of the font's characters, or 0 for a font
    /// without an `OS/2` table. It sets the factor with which some targets draw the glyphs of
    /// a run with a character scale.
    pub average_width: i16,
}

/// A face that the caller chose for a family, with the metrics that layout uses for it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChosenFace {
    /// The font that draws the glyphs.
    pub font: FontId,
    /// The metrics for line heights and decorations. They are usually the font's own, but a
    /// caller that draws a missing font with another one can give the missing font's metrics.
    pub metrics: FaceMetrics,
    /// Whether bold was asked for and the family has no bold face, so that the regular face
    /// stands in and Word makes the bold itself.
    pub synthetic_bold: bool,
    /// Whether italic was asked for and the family has no italic face, so that the upright
    /// face stands in and the target slants it.
    pub synthetic_italic: bool,
    /// Whether the caller draws the family with a face of another family, as a stand-in for a
    /// font that it lacks. Layout reads it only for the warning of a substituted font.
    pub stands_in: bool,
}

/// Which table of a face gives a pair of a kerned run its value; the target's
/// `KerningTableRead` chooses it by the document's mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KerningTable {
    /// The face's kerning source: the `kern` feature of `GPOS` where the face has one, and its
    /// `kern` table otherwise.
    FaceSource,
    /// The face's `kern` table alone: no pair of a face without one.
    KernTable,
}

/// One command of a glyph's outline in whole font units, with y growing upwards from the
/// baseline, as [`Fonts::outline`] gives it. A curve or line starts at the end point of the
/// command before it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutlineCommand {
    /// Starts a contour at the point.
    MoveTo([i32; 2]),
    /// Draws a line to the point.
    LineTo([i32; 2]),
    /// Draws a quadratic curve through the control point to the end point.
    QuadTo([i32; 2], [i32; 2]),
    /// Draws a cubic curve through two control points to the end point.
    CubicTo([i32; 2], [i32; 2], [i32; 2]),
    /// Closes the contour.
    Close,
}

/// The font services that layout needs. Choosing the font for a name is the caller's job; a
/// family is a [`FamilyName`], which compares names as Word does.
pub trait Fonts {
    /// Returns the face for a family and style, if the caller has one.
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace>;
    /// Returns the face for a family that stands for another font name, such as the first
    /// font of a name that lists fonts. Word lays out such a face with the font's own line
    /// metrics, so a caller that gives other line metrics for a family in `face` leaves them
    /// out here when it has the font's own file.
    fn substitute(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        self.face(family, bold, italic)
    }
    /// Returns the target's observed family substitute for a missing requested name.
    /// The document's alternate is tried first.
    fn family_substitute(
        &self,
        family: &FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<ChosenFace> {
        let _ = (family, bold, italic);
        None
    }
    /// Returns the family that the target's font mapper gives a metafile font of the family
    /// `family` when the target lacks that family, by the font's character set (`lfCharSet`)
    /// and pitch and family (`lfPitchAndFamily`). A caller that does not know keeps this
    /// default, and the family's name then takes the faces that a run's text would take.
    fn metafile_face(
        &self,
        family: &FamilyName,
        charset: u8,
        pitch_and_family: u8,
    ) -> Option<FamilyName> {
        let _ = (family, charset, pitch_and_family);
        None
    }
    /// Returns the glyph for a character.
    fn glyph(&self, font: FontId, ch: char) -> Option<u32>;
    /// Returns the advance width of a glyph in font units.
    fn advance(&self, font: FontId, glyph: u32) -> Option<u16>;
    /// Returns the pair kerning between two glyphs in font units from the table `table`,
    /// negative to move closer. The default means no pair kerning known: 0 for every pair.
    fn kerning(&self, font: FontId, left: u32, right: u32, table: KerningTable) -> i32 {
        let _ = (font, left, right, table);
        0
    }
    /// Returns where the pair kerning of a font comes from. A caller that does not know keeps
    /// this default, so that the font counts as a legacy-kern face.
    fn kerning_source(&self, font: FontId) -> f_office_fonts::KerningSource {
        let _ = font;
        f_office_fonts::KerningSource::KernTable
    }
    /// Returns the standard ligatures of a sequence of glyphs in one font, in order and
    /// without overlaps. The default means no standard ligatures known: none.
    fn ligatures(&self, font: FontId, glyphs: &[u32]) -> Vec<Ligature> {
        let _ = (font, glyphs);
        Vec::new()
    }
    /// Returns the glyphs of a text of a shaped script by the layout tables of a font, in
    /// the order of the text.
    ///
    /// # Errors
    ///
    /// Returns the cause when the caller cannot shape the text; layout then draws each
    /// character with the glyph of the font's character map. A caller without a shaper
    /// keeps this default.
    fn shape(
        &self,
        font: FontId,
        request: &ShapeRequest<'_>,
    ) -> Result<Vec<ShapedGlyph>, ShapeFailure> {
        let _ = (font, request);
        Err(ShapeFailure::NoShaper)
    }
    /// Returns the font files that did not load when the caller chose one of their faces, so
    /// that those faces counted as missing, for the layout's warnings. A caller whose faces
    /// always load keeps this default.
    fn files_not_read(&self) -> Vec<f_office_fonts::FileNotRead> {
        Vec::new()
    }
    /// Returns the family name of a font, for the warning of a substituted font. A caller that
    /// does not know keeps this default.
    fn family_name(&self, font: FontId) -> Option<String> {
        let _ = font;
        None
    }
    /// Returns the family whose layout a font has, for the rules that choose a face for a
    /// character by the family of its run's face: the target's family that an exact open font
    /// extends, such as Times New Roman for an open font made for it, and else the font's own
    /// family name. A caller that does not know keeps this default, the family name.
    fn layout_family(&self, font: FontId) -> Option<String> {
        self.family_name(font)
    }
    /// Returns the version of a font, such as "7.06.1", for the warning of a substituted font. A
    /// caller that does not know keeps this default.
    fn face_version(&self, font: FontId) -> Option<String> {
        let _ = font;
        None
    }
    /// Returns how the layout of a font that draws another family stands to that family's, for
    /// the warning of a substituted font. A caller that does not know keeps this default.
    fn substitute_layout(&self, font: FontId) -> SubstituteLayout {
        let _ = font;
        SubstituteLayout::Widths
    }
    /// Returns the classification of a font in its `OS/2` table, by which the target chooses
    /// a face for a character that the font lacks. A caller that does not know keeps this
    /// default, and such a font counts as a roman face without an East Asian code page.
    fn classification(&self, font: FontId) -> Option<f_office_fonts::FaceClassification> {
        let _ = font;
        None
    }
    /// Returns the PostScript name and the version string of a font when it is the target's
    /// own face, as the target's font environment says; else nothing. The measured device
    /// widths of a target hold for that face only.
    fn target_face(&self, font: FontId) -> Option<(String, String)> {
        let _ = font;
        None
    }
    /// Returns the advance of a glyph in whole pixels at `ppem` pixels per em, as bi-level
    /// rendering with the font's TrueType instructions gives it, when the caller can hint the
    /// font; else nothing.
    fn bi_level_advance(&self, font: FontId, glyph: u32, ppem: u16) -> Option<i32> {
        let _ = (font, glyph, ppem);
        None
    }
    /// Returns the device width of a glyph in whole dots at `ppem` device dots per em, as
    /// the font's TrueType instructions give it in the interpreter's device-width mode, when
    /// the caller can run them; else nothing.
    fn device_width(&self, font: FontId, glyph: u32, ppem: u16) -> Option<i32> {
        let _ = (font, glyph, ppem);
        None
    }
    /// Returns the largest height above the baseline and the largest depth below it, in
    /// pixels and with the signs that the font stores (`yMax` and `yMin`), that a font's
    /// `VDMX` table gives at `pels` pixels per em, when it has a group that Windows reads for
    /// square pixels and that lists `pels`; else nothing.
    fn device_heights(&self, font: FontId, pels: u16) -> Option<(i16, i16)> {
        let _ = (font, pels);
        None
    }
    /// Returns the lowest and the highest point of a glyph's outline, its ink, in font units
    /// with y growing upwards from the baseline, when the outline has contours; nothing for an
    /// outline without contours, such as a space's. A caller that gives no ink keeps the
    /// default, nothing, as for the other measures of this trait, and the layout falls back.
    ///
    /// # Errors
    ///
    /// Returns why the caller has no outline of the glyph, such as a font of bitmaps only;
    /// the layout then falls back for that glyph and warns once for each font and cause
    /// ([`Warning::InkNotMeasured`]).
    fn ink(&self, font: FontId, glyph: u32) -> Result<Option<(i32, i32)>, OutlineError> {
        let _ = (font, glyph);
        Ok(None)
    }
    /// Returns the outline of a glyph in whole font units, with y growing upwards from the
    /// baseline; a glyph without contours, such as a space, has an empty outline.
    ///
    /// # Errors
    ///
    /// Returns why the caller has no outline of the glyph. A caller that gives no outlines
    /// keeps the default, [`OutlineError::NoOutlines`], and the layout leaves out what it would
    /// draw with them.
    fn outline(&self, font: FontId, glyph: u32) -> Result<Vec<OutlineCommand>, OutlineError> {
        let _ = (font, glyph);
        Err(OutlineError::NoOutlines)
    }
    /// Returns the constants of the font's `MATH` table that place the limits of an n-ary
    /// operator in a display, when the font has them; else nothing.
    fn math_limits(&self, font: FontId) -> Option<f_office_fonts::MathLimits> {
        let _ = font;
        None
    }
    /// Returns the constants of the font's `MATH` table that place the root sign, the bar and
    /// the degree of a radical, when the font has them; else nothing.
    fn math_radical(&self, font: FontId) -> Option<f_office_fonts::MathRadical> {
        let _ = font;
        None
    }
    /// Returns the constants of the font's `MATH` table that place an overbar and an underbar,
    /// when the font has them; else nothing.
    fn math_bars(&self, font: FontId) -> Option<f_office_fonts::MathBars> {
        let _ = font;
        None
    }
    /// Returns the constants of the font's `MATH` table that place a skewed fraction's
    /// numerator and denominator, when the font has them; else nothing.
    fn math_skewed_fraction(&self, font: FontId) -> Option<f_office_fonts::MathSkewedFraction> {
        let _ = font;
        None
    }
    /// Returns the ink gap minimums of the font's `MATH` table for lower and upper limits, when
    /// the font has them; else nothing.
    fn math_limit_gaps(&self, font: FontId) -> Option<f_office_fonts::MathLimitGaps> {
        let _ = font;
        None
    }
    /// Returns the glyph that a display draws for an n-ary operator's glyph, its first
    /// vertical variant at least as tall as the font's `MATH` table asks, when the font has
    /// one; else nothing.
    fn display_variant(&self, font: FontId, glyph: u32) -> Option<u32> {
        let _ = (font, glyph);
        None
    }
    /// Returns the first vertical variant of a glyph in the font's `MATH` table whose height
    /// is at least `least` font units, with `true`, or else its tallest variant, with `false`,
    /// when the font has vertical variants of the glyph; else nothing.
    fn vertical_variant(&self, font: FontId, glyph: u32, least: i32) -> Option<(u32, bool)> {
        let _ = (font, glyph, least);
        None
    }
    /// Returns the constants of the font's `MATH` table that choose and place an accent, when
    /// the font has them; else nothing.
    fn math_accent(&self, font: FontId) -> Option<f_office_fonts::MathAccent> {
        let _ = font;
        None
    }
    /// Returns the constants of the font's `MATH` table that place a grouping character and its
    /// base, when the font has them; else nothing.
    fn math_stretch_stack(&self, font: FontId) -> Option<f_office_fonts::MathStretchStack> {
        let _ = font;
        None
    }
    /// Returns the top accent attachment of a glyph in font units, from the font's `MATH`
    /// table, when the table lists the glyph; else nothing.
    fn top_accent_attachment(&self, font: FontId, glyph: u32) -> Option<i32> {
        let _ = (font, glyph);
        None
    }
    /// Returns the horizontal variants and the glyph assembly of a glyph in the font's `MATH`
    /// table, when the table makes the glyph wider; else nothing.
    fn horizontal_construction(
        &self,
        font: FontId,
        glyph: u32,
    ) -> Option<f_office_fonts::HorizontalConstruction> {
        let _ = (font, glyph);
        None
    }
    /// Returns the flattened form of an accent's glyph, which the font's `flac` feature puts in
    /// its place, when the feature changes it; else nothing.
    fn flattened_accent(&self, font: FontId, glyph: u32) -> Option<u32> {
        let _ = (font, glyph);
        None
    }
    /// Returns the dotless form of a letter's glyph, which the font's `dtls` feature puts in its
    /// place under an accent, when the feature changes it; else nothing.
    fn dotless_form(&self, font: FontId, glyph: u32) -> Option<u32> {
        let _ = (font, glyph);
        None
    }
    /// Returns the italic correction of a glyph in font units, from the font's `MATH` table,
    /// when the table lists the glyph; else nothing.
    fn italic_correction(&self, font: FontId, glyph: u32) -> Option<i32> {
        let _ = (font, glyph);
        None
    }
    /// Returns the space that the font's `MATH` table leaves after a script
    /// (`SpaceAfterScript`) in font units, when the font has the table; else nothing.
    fn space_after_script(&self, font: FontId) -> Option<i32> {
        let _ = font;
        None
    }
    /// Returns the kern of a corner of a glyph at a height in font units from the glyph's
    /// baseline, from the font's `MATH` table (`MathKernInfo`), in font units, when the table
    /// lists the corner; else nothing.
    fn math_kern(
        &self,
        font: FontId,
        glyph: u32,
        corner: f_office_fonts::MathCorner,
        height: i32,
    ) -> Option<i32> {
        let _ = (font, glyph, corner, height);
        None
    }
    /// Returns the script glyph of a glyph, which the font's `ssty` feature puts in its place
    /// in a script or a script of a script, when the feature changes it; else nothing.
    fn script_glyph(
        &self,
        font: FontId,
        glyph: u32,
        level: f_office_fonts::ScriptLevel,
    ) -> Option<u32> {
        let _ = (font, glyph, level);
        None
    }
}

/// Why a document could not be laid out.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    /// The package could not be read.
    Package(f_office_opc::Error),
    /// A part is not valid XML.
    Xml(f_office_xml::Error),
    /// A required part is missing.
    MissingPart(String),
    /// The main document has no body.
    NoBody,
    /// The configuration or the target's profile does not read.
    Configuration(configuration::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Package(_) => f.write_str("the package could not be read"),
            Self::Xml(_) => f.write_str("a part is not valid XML"),
            Self::MissingPart(name) => write!(f, "missing part {name}"),
            Self::NoBody => f.write_str("the document has no body"),
            Self::Configuration(_) => {
                f.write_str("the configuration or the target's profile does not read")
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Package(error) => Some(error),
            Self::Xml(error) => Some(error),
            Self::Configuration(error) => Some(error),
            Self::MissingPart(_) | Self::NoBody => None,
        }
    }
}

pub use art_pictures::{
    ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
    ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT, ArtPictures,
    ArtPicturesError, ArtPicturesFault,
};
pub use body::ParagraphId;
pub use body::links::LinkTarget;
pub use configuration::{
    Configuration, NumberSeparators, NumberSeparatorsError, PageOffset, PageOffsetError, Printer,
    Target,
};
pub use dates::DateTime;
pub(crate) use font_choice::FontChoice;
pub use grid::{EdgeCheck, FixedPlace, ObjectStart};
pub use layout::{
    AlignedParts, BaselineForm, CellEdgeParts, CellPlace, DrawnGlyph, FirstItem, LineArea,
    LineStory, LineText, LineTextEnd, LineTurn, PlacedLine, StepsStart, StoryPart, TableColumns,
    TextCluster,
};
pub use lines::{EndHyphen, Fit, Step};
pub use props::{Alignment, LineSpacing};
pub use text_blocks::{Address, AddressError, AddressStep, TextBlock, TextBlockKind};
pub use text_map::{StoryBookmark, StoryLink, StoryParagraph, TextLine, TextMap, TextStory};
pub use warnings::{
    ChartReason, Drawing, DrawingMlFeature, DrawingMlWarning, Feature, GroupTransform, Limit,
    MetafileRecordType, MetafileWarning, NoteKind, ReadAs, Reason, SubstituteLayout, ValuePlace,
    Warned, Warning, Warnings,
};

/// The layout's own choices: the choices of `f_office::Options` that the layout reads, which
/// `f_office::Document::open` copies in, and the switch for the device's places, which only the
/// suite sets (`f_office::suite::open_with_device_places`). The default lays out for the base
/// target with its defaults.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Options {
    /// The time that `DATE` and `TIME` fields show, or none for the results that the file
    /// stores (`f_office::Options::now`).
    pub now: Option<DateTime>,
    /// The configuration, whose target's profile the layout and the output stage read
    /// (`f_office::Options::configuration`).
    pub configuration: Configuration,
    /// The development override, after the configuration (`f_office::Options::overrides`).
    #[cfg(feature = "development")]
    pub overrides: profile::Overrides,
    /// The development override of a test, after the configuration.
    #[cfg(all(test, not(feature = "development")))]
    pub(crate) overrides: profile::Overrides,
    /// Whether every glyph goes to its place on the layout device, without the PDF writer's
    /// adjustments, for a tool that measures those places. `false`, the default, draws the
    /// writer's places, as every page that the suite compares does.
    pub device_places: bool,
}

/// Lays out a DOCX package into pages with the fonts `fonts` and the pictures of the art page
/// borders `art`, with the warnings of what the layout left out or drew in another way than the
/// file asks.
///
/// # Errors
///
/// Returns an error when the package or one of its parts cannot be read.
pub fn layout(
    package: &Package,
    (fonts, art): (&dyn Fonts, &ArtPictures),
    options: &Options,
) -> Result<Warned<DisplayList>, Error> {
    layout_with_fonts(package, (fonts, art), options)
        .map(|warned| warned.map(|laid_out| laid_out.list))
}

/// What [`layout_lines`] gives: the pages, the lines that the last pass placed, the text blocks
/// of the body with the pages of those lines, and the target's PDF writer.
#[derive(Clone, Debug)]
pub struct LaidOut {
    /// The pages.
    pub list: DisplayList,
    /// The upright lines of the body, the headers and the footers, in table cells too, that the
    /// last pass placed. The turned lines, such as those of a cell with a turned text direction,
    /// are the text map's own.
    pub lines: Vec<PlacedLine>,
    /// The paragraphs and tables of the body in order, with the pages of their lines.
    pub text_blocks: Vec<TextBlock>,
    /// What the text map of the lines needs besides them, the turned lines too.
    pub text_map: TextMap,
    /// The widths of the grid columns that the last pass gave each table of the body.
    pub tables: Vec<TableColumns>,
    /// The PDF writer of the configuration's target, which writes the pages.
    pub writer: f_office_paint::Writer,
}

/// The first warnings of a package's layout: one for each entry that the package skips as
/// equivalent to another.
fn equivalent_entries(package: &Package) -> Warnings {
    let mut warnings = Warnings::new();
    for entry in package.equivalent_entries() {
        warnings.push(Warning::PartSkipped {
            part: f_office_warnings::Name::new(entry),
            reason: Reason::Equivalent,
        });
    }
    warnings
}

/// Lays out a DOCX package into pages as [`layout()`] does, with the faces of `fonts` that the
/// configuration's target permits, and also gives the lines that the last pass placed, the text
/// blocks of the body and the target's PDF writer.
///
/// # Errors
///
/// Returns an error when the configuration does not resolve, or the package or one of its parts
/// cannot be read.
pub fn layout_lines(
    package: &Package,
    (fonts, art): (&f_office_fonts::FontDb, &ArtPictures),
    options: &Options,
) -> Result<Warned<LaidOut>, Error> {
    let profile = options.profile().map_err(Error::Configuration)?;
    // The fonts that the target lacks are missing for it, also where the caller has them.
    let font_choice = FontChoice::of(fonts, &profile);
    let laid_out = lay_out(package, (&font_choice, art), options, &profile)?;
    // A symbol stand-in face's runs take the face that draws it, which the caller's fonts hold.
    Ok(laid_out.map(|laid_out| LaidOut {
        list: font_choice.draw_symbol_stand_ins(laid_out.list),
        ..laid_out
    }))
}

/// Lays out a DOCX package as [`layout_lines`] does, with the fonts `fonts` as they are.
///
/// # Errors
///
/// As [`layout_lines`].
pub(crate) fn layout_with_fonts(
    package: &Package,
    (fonts, art): (&dyn Fonts, &ArtPictures),
    options: &Options,
) -> Result<Warned<LaidOut>, Error> {
    let profile = options.profile().map_err(Error::Configuration)?;
    lay_out(package, (fonts, art), options, &profile)
}

/// Lays out a DOCX package with the fonts `fonts` for the profile `profile` of `options`.
fn lay_out(
    package: &Package,
    (fonts, art): (&dyn Fonts, &ArtPictures),
    options: &Options,
    profile: &profile::Profile,
) -> Result<Warned<LaidOut>, Error> {
    let mut warnings = equivalent_entries(package);
    // The one source of paragraph IDs of the document, which every part reader takes.
    let paragraph_ids = ParagraphIds::default();
    let (quirks, device, reader, zone_minutes) = quirks_and_device(profile)?;
    let device = device.with_device_places(options.device_places);
    let main = package.main_document().map_err(Error::Package)?;
    let relationships = parts::relationships(package, &main, &mut warnings)?;
    let related =
        |suffix: &str| Relationship::by_type(relationships, suffix).map(|rel| rel.target.clone());
    // Each part reader takes the reading until the last part is read; the passes warn after it.
    let mut reading = Reading {
        warnings: &mut warnings,
        ids: &paragraph_ids,
        settings: reader,
        notes: None,
        colors: f_office_drawingml::color::SchemeColors::default(),
        styles: None,
        small_frac: crate::props::SmallFractions::Off,
    };
    let image_loader = PackageImageLoader::new(package);
    let LoadedMain {
        settings,
        styles,
        theme,
        table,
        numbering,
        notes,
        endnotes,
        comments,
        mut body,
    } = read_main_document(
        package,
        &image_loader,
        &main,
        &related,
        reader,
        &mut reading,
    )?;
    reading.styles = Some(&styles);
    reading.small_frac = settings.small_frac;
    body.place_pages(&reader.template_section(), settings.gutter_at_top);
    attach_parts(
        package,
        &image_loader,
        (&main, relationships),
        &theme,
        &mut [&mut body.blocks],
        &mut reading,
    );
    mark_buffers(&mut body.blocks, reader, relationships);
    let shaper_settings = text::ShaperSettings::of(&settings, &quirks, device.dot_size());
    let shaper = Shaper::new(fonts, &theme, &table, &shaper_settings);
    let mut stories = StoryParts::new(
        package,
        &image_loader,
        relationships,
        (reader, &styles, &theme, settings.small_frac),
        &paragraph_ids,
    );
    let sections = build_sections(&body.sections, &mut stories, &settings, reading.warnings)?;
    warn_of_note_positions(&sections, (&notes, &endnotes), &main, reading.warnings);
    let web_part = related(ns::REL_WEB_SETTINGS);
    let html_divs = web_settings::HtmlDivs::of_part(package, web_part, (&paragraph_ids, reader));
    let context = Context {
        main: &main,
        styles: &styles,
        settings: &settings,
        html_divs: &html_divs,
        numbering,
        notes,
        endnotes,
        comments,
        device,
        quirks,
        now: options.now,
        properties: std::sync::Arc::new(read_custom_properties(package, &mut reading)?),
        zone_minutes,
        earlier: EarlierPass::default(),
        deleted_cell_label: paragraph_ids.next(),
        art,
    };
    let paragraphs = text_addresses::story_paragraphs(
        &body.blocks,
        &sections,
        (&context.notes, &context.endnotes),
    );
    let pass = run_passes(context, (&sections, shaper), &body);
    LaidOut::of(
        pass,
        (&body, &styles, paragraphs),
        (html_divs, fonts, profile.writer()),
        warnings,
    )
}

impl LaidOut {
    /// The pages and the placed lines of the last pass, with the text blocks of the blocks of
    /// `body` under `styles`, the text map with the addresses, hyperlinks and bookmarks of the
    /// `paragraphs` of every story, the PDF writer `writer`, and the warnings of the reading before it with those of
    /// the pass, of the web settings part (`html_divs`) and of the fonts.
    ///
    /// # Errors
    ///
    /// When the web settings part did not read, as [`web_settings::HtmlDivs::finish`] says.
    fn of(
        pass: Pass,
        (body, styles, paragraphs): (&body::Body, &Styles, text_addresses::StoryParagraphs),
        (html_divs, fonts, writer): (
            web_settings::HtmlDivs<'_>,
            &dyn Fonts,
            f_office_paint::Writer,
        ),
        mut warnings: Warnings,
    ) -> Result<Warned<Self>, Error> {
        // Each pass has its own warnings, and only those of the pass that gives the pages count.
        warnings.extend(pass.warnings, std::convert::identity);
        // The web settings part, read when a paragraph named a div.
        warnings.extend(html_divs.finish()?, std::convert::identity);
        warnings::of_fonts(&pass.font_notes, fonts, &mut warnings);
        let (lines, turned) = text_map::turned_apart(pass.lines);
        let toc = body.table_of_contents.as_ref();
        let text_blocks = text_blocks::text_blocks(&body.blocks, &lines, (styles, toc));
        let laid_out = Self {
            text_blocks,
            text_map: TextMap::new(paragraphs, &lines, turned),
            list: pass.list,
            lines,
            tables: pass.tables,
            writer,
        };
        Ok(Warned::new(laid_out, warnings))
    }
}

impl Default for Options {
    fn default() -> Self {
        Self {
            now: None,
            configuration: Configuration::of(Target::default()),
            #[cfg(any(test, feature = "development"))]
            overrides: profile::Overrides::default(),
            device_places: false,
        }
    }
}

impl Options {
    /// Options for the base target, used by internal unit tests written against the base profile.
    #[cfg(test)]
    pub(crate) fn base() -> Self {
        Self {
            configuration: Configuration::of(Target::base()),
            ..Self::default()
        }
    }

    /// The profile of the configuration's target with the configuration and the development
    /// override, which the layout, the font choice and the output stage read.
    ///
    /// # Errors
    ///
    /// Returns an error when the configuration names no target, sets a value that F-Office does
    /// not read yet or a wrong value, or the profile does not read.
    pub(crate) fn profile(&self) -> Result<profile::Profile, profile::Error> {
        // Only a development build or a test sets the development override.
        #[cfg(any(test, feature = "development"))]
        let overrides = &self.overrides;
        #[cfg(not(any(test, feature = "development")))]
        let overrides = &profile::Overrides::default();
        profile::Profile::resolve(&self.configuration, overrides)
    }
}

/// The quirks, the layout device, the reader's settings and the time zone of the machine that
/// `options` give, which the layout and the reader read.
fn quirks_and_device(
    profile: &profile::Profile,
) -> Result<(quirks::Quirks, grid::Device, ReaderSettings, i32), Error> {
    Ok((
        profile.quirks(),
        profile.device(),
        profile.reader_settings(),
        profile.zone_minutes().map_err(Error::Configuration)?,
    ))
}

/// Lays out the body, in two passes when it needs what a first pass finds. A `NUMPAGES` field
/// in the body shows the count of the whole document, drawings placed from a page or its
/// margins keep the text before their anchors out of their wraps, and `PAGEREF` fields show
/// the pages of bookmarks, so a first pass counts the pages and finds those drawings and
/// bookmarks.
fn run_passes(
    context: Context<'_>,
    sections_and_shaper: (&Sections<SectionLayout>, Shaper<'_>),
    body: &Body,
) -> Pass {
    // The layout's own time, for profiling (`timing`).
    timing::span("layout", || {
        layout_passes(context, sections_and_shaper, body)
    })
}

/// The passes of [`run_passes`]. Each later pass takes what the pass before found into the
/// context, in place of the earlier pass, and borrows the same document's parts.
fn layout_passes(
    mut context: Context<'_>,
    (sections, shaper): (&Sections<SectionLayout>, Shaper<'_>),
    body: &Body,
) -> Pass {
    let stories = context.for_stories();
    let first_pass =
        Layout::new((&context, &stories), sections, shaper.fork()).run_with_wraps(body);
    let counts = body::refers_to_pages(&body.blocks);
    // Headers and footers with `STYLEREF` fields take the height of their page's text.
    let header_fields = stories_refer_to_styles(sections);
    // Footnotes that start their numbers again on each page take their places on their pages
    // from the pass before, drawings placed down from their paragraph whose anchor stands on a
    // later page take their place from the pass that found them there, and drawings of the body
    // that count from the body's area take the footnotes of their page from the pass before.
    if !counts
        && first_pass.wraps.is_empty()
        && !header_fields
        && first_pass.note_places.is_empty()
        && first_pass.later_anchors.is_empty()
        && !first_pass.notes_missed
    {
        return first_pass;
    }
    // Move the small cross-pass state directly into `context.earlier` and drop `first_pass`
    // (its display list and placed lines) before allocating the second pass.
    let page_count = f_office_units::count_factor(first_pass.list.pages().len());
    let stored_refs = body::refers_to_pages_and_numbers(&body.blocks);
    let mut font_notes = first_pass.font_notes;
    context.earlier = EarlierPass {
        page_count: counts.then_some(page_count),
        wraps: first_pass.wraps,
        bookmarks: Some(first_pass.bookmarks),
        bookmark_numbers: first_pass.bookmark_numbers,
        stored_number_refs: stored_refs,
        header_styles: if header_fields {
            first_pass.styles
        } else {
            HeaderStyles::default()
        },
        note_places: first_pass.note_places,
        later_anchors: first_pass.later_anchors,
        note_heights: first_pass.note_heights,
    };
    let mut pass = Layout::new((&context, &stories), sections, shaper.fork()).run_with_wraps(body);
    for _ in 0..params::FURTHER_PASSES {
        let moved = context.earlier.wraps.after(&pass.wraps);
        let grew = context.earlier.later_anchors.join(&pass.later_anchors);
        if moved.is_none()
            && context.earlier.bookmarks.as_ref() == Some(&pass.bookmarks)
            && pass.bookmark_numbers == context.earlier.bookmark_numbers
            && pass.note_places == context.earlier.note_places
            && !grew
            && !pass.notes_missed
        {
            break;
        }
        if let Some(wraps) = moved {
            context.earlier.wraps = wraps;
        }
        context.earlier.bookmarks = Some(pass.bookmarks);
        context.earlier.bookmark_numbers = pass.bookmark_numbers;
        context.earlier.note_places = pass.note_places;
        context.earlier.note_heights = pass.note_heights;
        font_notes.add(pass.font_notes);
        drop(pass.list);
        drop(pass.lines);
        drop(pass.tables);
        pass = Layout::new((&context, &stories), sections, shaper.fork()).run_with_wraps(body);
    }
    if stored_refs {
        context.earlier.bookmarks = Some(pass.bookmarks);
        context.earlier.stored_number_refs = false;
        font_notes.add(pass.font_notes);
        drop(pass.list);
        drop(pass.lines);
        drop(pass.tables);
        pass = Layout::new((&context, &stories), sections, shaper.fork()).run_with_wraps(body);
    }
    font_notes.add(pass.font_notes);
    pass.font_notes = font_notes;
    pass
}

/// Reads the comments, with the parts of their drawings from the comments part's own
/// relationships, links their replies, and hides those whose ranges end outside a paragraph of
/// the body. A target that prints without markup reads no comments.
/// Parsed document parts returned by [`read_main_document`] after the main XML has been read
/// and dropped.
struct LoadedMain {
    settings: Settings,
    styles: Styles,
    theme: Theme,
    table: FontTable,
    numbering: Numbering,
    notes: body::Notes,
    endnotes: body::Notes,
    comments: comments::Comments,
    body: Body,
}

/// Reads the main document part and its companion parts. When the main XML is UTF-8 and contains
/// no tracked changes or cross-block features (`commentRange*`, `fldSimple`, `instrText`,
/// top-level `sdt`/`AlternateContent`), streams `<w:body>` children one block at a time without
/// constructing a whole-document XML tree; otherwise parses into the compact flat-arena tree.
fn read_main_document(
    package: &Package,
    image_loader: &Arc<PackageImageLoader>,
    main: &str,
    related: &dyn Fn(&str) -> Option<String>,
    reader: ReaderSettings,
    reading: &mut Reading<'_>,
) -> Result<LoadedMain, Error> {
    let main_bytes = package
        .read_part(main)
        .map_err(Error::Package)?
        .ok_or_else(|| Error::MissingPart(main.to_owned()))?;
    let streamed = f_office_xml::scan_body_children(
        &main_bytes,
        &[ns::W, ns::W_STRICT],
        &package.limits().xml,
    )
    .map_err(Error::Xml)?;
    if let Some(streamed) = streamed
        && !streamed.has_revisions
        && !streamed.has_cross_block_features
    {
        return read_main_streamed(
            package,
            image_loader,
            (main, &main_bytes, &streamed),
            related,
            reader,
            reading,
        );
    }
    read_main_dom(
        package,
        image_loader,
        (main, &main_bytes),
        related,
        reader,
        reading,
    )
}

/// Streams `<w:body>` children one block at a time without constructing a whole-document XML tree.
fn read_main_streamed(
    package: &Package,
    image_loader: &Arc<PackageImageLoader>,
    (main, main_bytes, streamed): (&str, &[u8], &f_office_xml::StreamedBody),
    related: &dyn Fn(&str) -> Option<String>,
    reader: ReaderSettings,
    reading: &mut Reading<'_>,
) -> Result<LoadedMain, Error> {
    let page_color = read_streamed_page_color(main_bytes, streamed, &package.limits().xml);
    let (settings, styles, theme, table, numbering) =
        read_main_parts(package, image_loader, related, page_color, reading)?;
    let (notes, endnotes, comments, body) = {
        let mut sub = Reading {
            warnings: reading.warnings,
            ids: reading.ids,
            settings: reading.settings,
            notes: None,
            colors: reading.colors,
            styles: Some(&styles),
            small_frac: settings.small_frac,
        };
        let (notes, endnotes) = read_footnotes_and_endnotes(
            package,
            image_loader,
            related,
            (&styles, &theme, &settings),
            &mut sub,
        )?;
        let comments = read_comments(package, image_loader, related, None, &theme, &mut sub)?;
        let body = Body::read_streamed(
            main_bytes,
            streamed,
            (main, &package.limits().xml),
            &mut sub,
            (reader, settings.mode_rules),
        )?;
        (notes, endnotes, comments, body)
    };
    Ok(LoadedMain {
        settings,
        styles,
        theme,
        table,
        numbering,
        notes,
        endnotes,
        comments,
        body,
    })
}

/// Fallback full-DOM reader for main documents with tracked changes, cross-block features, or
/// non-UTF-8 encoding.
fn read_main_dom(
    package: &Package,
    image_loader: &Arc<PackageImageLoader>,
    (main, main_bytes): (&str, &[u8]),
    related: &dyn Fn(&str) -> Option<String>,
    reader: ReaderSettings,
    reading: &mut Reading<'_>,
) -> Result<LoadedMain, Error> {
    let (mut doc, root) = parts::parse_text_bytes(
        package,
        (Role::Main, main),
        main_bytes,
        reader,
        reading.warnings,
    )?
    .ok_or_else(|| Error::MissingPart(main.to_owned()))?;
    let page_color = props::read_page_color(&doc, root);
    let (settings, styles, theme, table, numbering) =
        read_main_parts(package, image_loader, related, page_color, reading)?;
    let (notes, endnotes, comments, body) = {
        let mut sub = Reading {
            warnings: reading.warnings,
            ids: reading.ids,
            settings: reading.settings,
            notes: None,
            colors: reading.colors,
            styles: Some(&styles),
            small_frac: settings.small_frac,
        };
        reader.prepare_toc_links(&mut doc, (main, sub.ids), &styles);
        let (notes, endnotes) = read_footnotes_and_endnotes(
            package,
            image_loader,
            related,
            (&styles, &theme, &settings),
            &mut sub,
        )?;
        let body_node = doc.child(root, ns::W, "body").ok_or(Error::NoBody)?;
        let comments = read_comments(
            package,
            image_loader,
            related,
            Some((&doc, body_node)),
            &theme,
            &mut sub,
        )?;
        let body = parts::read_with(&doc, (main, body_node), &mut sub, |part, node| {
            Body::read(part, node, (reader, settings.mode_rules))
        });
        (notes, endnotes, comments, body)
    };
    drop(doc);
    Ok(LoadedMain {
        settings,
        styles,
        theme,
        table,
        numbering,
        notes,
        endnotes,
        comments,
        body,
    })
}

/// Parses only the `<w:background>` element slice from a streamed main document to read its page
/// color without constructing a full-document XML tree.
fn read_streamed_page_color(
    main_bytes: &[u8],
    streamed: &f_office_xml::StreamedBody,
    xml_limits: &f_office_xml::Limits,
) -> Option<[u8; 3]> {
    let range = streamed.background.as_ref()?;
    let slice = main_bytes.get(range.clone())?;
    let frag = Document::parse_fragment_with_aliases_at(
        slice,
        &streamed.doc_in_scope,
        ns::STRICT_ALIASES,
        u64::try_from(range.start).unwrap_or(0),
        xml_limits,
    )
    .ok()?;
    let root = frag.document().root().ok()?;
    props::read_page_color(frag.document(), root)
}

fn read_comments(
    package: &Package,
    image_loader: &Arc<PackageImageLoader>,
    related: &dyn Fn(&str) -> Option<String>,
    body_dom: Option<(&Document, f_office_xml::NodeId)>,
    theme: &Theme,
    reading: &mut Reading<'_>,
) -> Result<comments::Comments, Error> {
    if !reading.settings.prints_comments() {
        return Ok(comments::Comments::default());
    }
    let target = related(ns::REL_COMMENTS);
    let mut comments = parts::read(
        package,
        (Role::Comments, target.clone()),
        reading,
        comments::Comments::read,
    )?;
    if let Some(target) = target {
        // A part whose relationships do not read shows no pictures, charts or SmartArt.
        let own = parts::relationships(package, &target, reading.warnings)?;
        // In the order of the IDs, so that the warnings keep one order.
        let mut by_id: Vec<_> = comments.by_id.iter_mut().collect();
        by_id.sort_unstable_by(|a, b| a.0.cmp(b.0));
        let mut stories: Vec<&mut [Block]> = by_id
            .into_iter()
            .map(|(_, comment)| comment.blocks.as_mut_slice())
            .collect();
        attach_parts(
            package,
            image_loader,
            (&target, own),
            theme,
            &mut stories,
            reading,
        );
    }
    let parents = parts::read(
        package,
        (Role::Comments, related(ns::REL_COMMENTS_EXTENDED)),
        reading,
        |reader, root| comments::read_parents(reader.doc, root),
    )?;
    comments.link_replies(&parents);
    if let Some((doc, body)) = body_dom {
        comments.hide(&comments::marked_outside_paragraphs(doc, body));
        comments.deleted_cells = comments::holds_deleted_cells(doc, body);
    }
    Ok(comments)
}

/// Reads the header and footer stories of each section and attaches section-level note settings.
fn build_sections(
    sections: &Sections<crate::body::SectionPart>,
    stories: &mut StoryParts<'_>,
    settings: &Settings,
    warnings: &mut Warnings,
) -> Result<Sections<SectionLayout>, Error> {
    sections.try_map(|part| {
        Ok(SectionLayout {
            section: part.section,
            start: part.start,
            end: part.end,
            restarts_numbers: part.restarts_numbers,
            headers: stories.stories(&part.headers, warnings)?,
            footers: stories.stories(&part.footers, warnings)?,
            borders: part.borders,
            notes: part.notes.over(settings.notes),
        })
    })
}

/// Whether a header or footer of any section holds a `STYLEREF` field.
fn stories_refer_to_styles(sections: &Sections<SectionLayout>) -> bool {
    let stories = |s: &Stories| {
        [&s.default, &s.first, &s.even]
            .into_iter()
            .flatten()
            .any(|story| body::refers_to_styles(&story.blocks))
    };
    sections
        .iter()
        .any(|s| stories(&s.headers) || stories(&s.footers))
}

/// Warns once for each section whose footnotes stand elsewhere than at the bottom of the page,
/// when the document holds footnotes, and once for each section whose endnotes stand at the
/// end of the section, when it holds endnotes: F-Office places footnotes at the bottom of the
/// page and endnotes after the text at the end of the document.
fn warn_of_note_positions(
    sections: &Sections<SectionLayout>,
    (notes, endnotes): (&body::Notes, &body::Notes),
    main: &str,
    warnings: &mut Warnings,
) {
    let mut warn = |feature| {
        warnings.push(Warning::FeatureNotSupported {
            part: f_office_warnings::Name::new(main),
            feature,
        });
    };
    for section in sections {
        if !notes.by_id.is_empty() && section.notes.footnotes.position != NotePosition::PageBottom {
            warn(Feature::FootnotePosition);
        }
        if !endnotes.by_id.is_empty() && section.notes.endnotes.position == NotePosition::SectionEnd
        {
            warn(Feature::EndnotePosition);
        }
    }
}

/// Marks the runs of the body's `blocks` that start a text buffer, counting the fields and
/// hyperlinks, and the comments' references, as the reader's `settings` say, with the addresses
/// of the body part's `relationships`: a hyperlink's address is the URI of an external target,
/// as `buffers::address_characters` counts it.
fn mark_buffers(blocks: &mut [Block], settings: ReaderSettings, relationships: &[Relationship]) {
    let target = |id: &str| {
        relationships
            .iter()
            .find(|rel| rel.id == id && rel.external)
            .map_or(0, |rel| buffers::address_characters(&rel.target))
    };
    buffers::mark(
        blocks,
        &buffers::Counting {
            settings,
            target: &target,
        },
    );
}

/// Gives the drawings of `stories`, the stories of one part, their parts from the part's
/// relationships: the SmartArt graphics their saved drawings, the charts their parts and the
/// pictures their images; and the hyperlinks their external addresses. The body, the notes,
/// the comments, the headers and the footers each take them here. Each part that they name is
/// read once for all the stories of the part.
fn attach_parts(
    package: &Package,
    image_loader: &Arc<PackageImageLoader>,
    part: (&str, &[Relationship]),
    theme: &Theme,
    stories: &mut [&mut [Block]],
    reading: &mut Reading<'_>,
) {
    // Each finder holds the reading until the end of its block.
    {
        let mut find = diagrams(package, part, &theme.shapes, reading);
        for blocks in stories.iter_mut() {
            smartart::attach_drawings(blocks, &mut find);
        }
    }
    {
        let mut find = charts(package, part, reading);
        for blocks in stories.iter_mut() {
            chart::attach_charts(blocks, &mut find);
        }
    }
    let inks = reading.settings.ink_conversion();
    let mut find = images(package, image_loader, part, inks, reading.warnings);
    for blocks in stories.iter_mut() {
        picture::attach_images(blocks, &mut find);
        body::links::give_addresses(blocks, part.1);
    }
}

/// Finds the image part that a relationship ID of a part names. Raster formats become lightweight
/// lazy [`f_office_paint::ImageRef`] handles backed by `image_loader` (reading only a 64-byte
/// format-sniffing prefix here, with full decompression deferred to header inspection or rendering).
/// EMF and WMF metafiles are read eagerly because layout plays them directly into vector groups.
fn images<'a>(
    package: &'a Package,
    image_loader: &'a Arc<PackageImageLoader>,
    (source, relationships): (&'a str, &'a [Relationship]),
    inks: InkConversion,
    warnings: &'a mut Warnings,
) -> impl FnMut(&str) -> Option<Image> + 'a {
    let mut loaded: HashMap<&str, Option<Image>> = HashMap::new();
    move |id| {
        let Some(rel) = Relationship::by_id(relationships, id) else {
            warnings.push(warnings::skipped(
                Drawing::Picture,
                source,
                Reason::Unlinked,
            ));
            return None;
        };
        let image = loaded
            .entry(rel.target.as_str())
            .or_insert_with(|| {
                let prefix = package
                    .read_part_prefix(&rel.target, params::IMAGE_FORMAT_PREFIX_BYTES)
                    .ok()
                    .flatten()?;
                let format = ImageFormat::detect(&prefix);
                if matches!(format, ImageFormat::Emf | ImageFormat::Wmf) {
                    let data = package.read_part(&rel.target).ok().flatten()?;
                    let image = Image {
                        inks,
                        ..Image::new(data)
                    };
                    warnings::of_metafile(&image, &rel.target, warnings);
                    return Some(image);
                }
                let byte_len = package
                    .part_size(&rel.target)
                    .unwrap_or_else(|| u64::try_from(prefix.len()).unwrap_or(0));
                let handle = image_loader.intern(&rel.target, format, byte_len);
                Some(Image {
                    inks,
                    ..Image::from_ref(format, handle)
                })
            })
            .clone();
        if image.is_none() {
            warnings.push(warnings::skipped(
                Drawing::Picture,
                &rel.target,
                Reason::Missing,
            ));
        }
        image
    }
}

/// Reads the parts of a SmartArt graphic from the saved drawing that its data part names. A
/// graphic without a saved drawing, or with a part that does not read, has no parts.
fn diagrams<'a>(
    package: &'a Package,
    part: (&'a str, &'a [Relationship]),
    theme: &'a f_office_drawingml::theme::ShapeTheme,
    reading: &'a mut Reading<'_>,
) -> impl FnMut(&smartart::Diagram) -> smartart::Parts + 'a {
    move |diagram| {
        let found = related_xml(package, part, &diagram.data, reading.warnings);
        let (data_name, data, data_root) = match found {
            Ok(found) => found,
            Err((name, reason)) => {
                reading
                    .warnings
                    .push(warnings::skipped(Drawing::SmartArt, &name, reason));
                return Vec::new();
            }
        };
        let colors = diagram
            .colors
            .as_deref()
            .map(|id| related_xml(package, part, id, reading.warnings));
        let text_colors = match colors {
            Some(Ok((colors_name, doc, root))) => {
                parts::read_with(&doc, (&colors_name, root), reading, |reader, root| {
                    smartart::text_colors((&data, data_root), (reader, root), theme)
                })
            }
            Some(Err((name, reason))) => {
                reading.warnings.push(Warning::PartSkipped {
                    part: f_office_warnings::Name::new(&name),
                    reason,
                });
                HashMap::default()
            }
            None => HashMap::default(),
        };
        // F-Office draws a graphic from the drawing that Word saved with it.
        let Some(drawing) = smartart::drawing_id(&data, data_root) else {
            reading.warnings.push(warnings::skipped(
                Drawing::SmartArt,
                &data_name,
                Reason::Unsupported,
            ));
            return Vec::new();
        };
        match related_xml(package, part, &drawing, reading.warnings) {
            Ok((name, doc, root)) => {
                parts::read_with(&doc, (&name, root), reading, |reader, root| {
                    smartart::read_drawing(reader, root, theme, &text_colors)
                })
            }
            Err((name, reason)) => {
                reading
                    .warnings
                    .push(warnings::skipped(Drawing::SmartArt, &name, reason));
                Vec::new()
            }
        }
    }
}

/// Reads the chart part that a relationship ID names, when F-Office draws its chart for a
/// target, as the reading's settings say.
fn charts<'a>(
    package: &'a Package,
    part: (&'a str, &'a [Relationship]),
    reading: &'a mut Reading<'_>,
) -> impl FnMut(&str) -> Option<chart::Part> + 'a {
    let rules = reading.settings.plot_rules();
    move |id| match related_xml(package, part, id, reading.warnings) {
        Ok((name, doc, root)) => {
            let chart = parts::read_with(&doc, (&name, root), reading, |reader, space| {
                chart::read(reader, space, rules)
            });
            chart
                .inspect_err(|&reason| {
                    reading.warnings.push(warnings::skipped(
                        Drawing::Chart,
                        &name,
                        Reason::Chart(reason),
                    ));
                })
                .ok()
        }
        Err((name, reason)) => {
            reading
                .warnings
                .push(warnings::skipped(Drawing::Chart, &name, reason));
            None
        }
    }
}

/// The XML part that a relationship ID of a part names, with its name and its root element;
/// or, when it does not read, the name to warn of and why: the part that names it when the
/// ID names no part of the package, else the part itself. It warns of each namespace prefix
/// that the part uses without a declaration.
fn related_xml(
    package: &Package,
    (source, relationships): (&str, &[Relationship]),
    id: &str,
    warnings: &mut Warnings,
) -> Result<(String, Document, f_office_xml::NodeId), (String, Reason)> {
    let rel = Relationship::by_id(relationships, id)
        .ok_or_else(|| (source.to_owned(), Reason::Unlinked))?;
    let fault = |reason| (rel.target.clone(), reason);
    let bytes = package
        .read_part(&rel.target)
        .ok()
        .flatten()
        .ok_or_else(|| fault(Reason::Missing))?;
    let (doc, root) =
        parts::xml(package, (&rel.target, &bytes), warnings).map_err(|_| fault(Reason::NotXml))?;
    Ok((rel.target.clone(), doc, root))
}

/// The footnotes and the endnotes, from the parts that `related` names by relationship type. The
/// footnotes take the separator that Word draws itself when the settings list no special
/// footnotes.
fn read_footnotes_and_endnotes(
    package: &Package,
    image_loader: &Arc<PackageImageLoader>,
    related: &dyn Fn(&str) -> Option<String>,
    (styles, theme, settings): (&Styles, &Theme, &Settings),
    reading: &mut Reading<'_>,
) -> Result<(body::Notes, body::Notes), Error> {
    let parts = (styles, theme);
    let endnotes = read_notes(
        package,
        image_loader,
        related(ns::REL_ENDNOTES),
        parts,
        reading,
    )?;
    let notes = read_notes(
        package,
        image_loader,
        related(ns::REL_FOOTNOTES),
        parts,
        reading,
    )?;
    // The written separator counts only when the settings list it.
    let notes = match settings.footnote_separators {
        styles::NoteSeparators::Listed => notes,
        styles::NoteSeparators::Own => {
            notes.with_own_separator(reading.ids, &reading.settings.own_separator_props())
        }
    };
    // The parts read after the notes check each note reference against them.
    reading.notes = Some(note_setup::ByNoteKind {
        footnotes: notes.ids(),
        endnotes: endnotes.ids(),
    });
    Ok((notes, endnotes))
}

/// The custom properties of the document, from the part that the package's own relationships
/// name.
fn read_custom_properties(
    package: &Package,
    reading: &mut Reading<'_>,
) -> Result<properties::Properties, Error> {
    let own = parts::relationships(package, parts::PACKAGE, reading.warnings)?;
    let custom =
        Relationship::by_type(own, ns::REL_CUSTOM_PROPERTIES).map(|rel| rel.target.clone());
    parts::read(
        package,
        (Role::CustomProperties, custom),
        reading,
        |reader, root| properties::read(reader.doc, root),
    )
}

/// Reads the footnotes or the endnotes, with the parts of their drawings from their own
/// relationships.
fn read_notes(
    package: &Package,
    image_loader: &Arc<PackageImageLoader>,
    target: Option<String>,
    (styles, theme): (&Styles, &Theme),
    reading: &mut Reading<'_>,
) -> Result<body::Notes, Error> {
    let settings = reading.settings;
    let mut notes = parts::read_text(
        package,
        (Role::Notes, target.clone()),
        styles,
        reading,
        |reader, root| body::Notes::read(reader, root, settings),
    )?;
    if let Some(target) = target {
        // A part whose relationships do not read shows no pictures, charts or SmartArt.
        let own = parts::relationships(package, &target, reading.warnings)?;
        let mut stories: Vec<&mut [Block]> =
            notes.by_id.values_mut().map(Vec::as_mut_slice).collect();
        attach_parts(
            package,
            image_loader,
            (&target, own),
            theme,
            &mut stories,
            reading,
        );
    }
    Ok(notes)
}

/// The headers and footers of the sections, read from the parts that their relationship IDs
/// name. Each part is read once, and the sections that name it share it.
struct StoryParts<'p> {
    package: &'p Package,
    image_loader: &'p Arc<PackageImageLoader>,
    relationships: &'p [Relationship],
    settings: ReaderSettings,
    styles: &'p Styles,
    theme: &'p Theme,
    small_frac: crate::props::SmallFractions,
    /// The document's source of paragraph IDs.
    ids: &'p ParagraphIds,
    /// The stories read so far, by the name of their part.
    read: HashMap<String, Option<PartStory>>,
}

impl<'p> StoryParts<'p> {
    fn new(
        package: &'p Package,
        image_loader: &'p Arc<PackageImageLoader>,
        relationships: &'p [Relationship],
        (settings, styles, theme, small_frac): (
            ReaderSettings,
            &'p Styles,
            &'p Theme,
            crate::props::SmallFractions,
        ),
        ids: &'p ParagraphIds,
    ) -> Self {
        Self {
            package,
            image_loader,
            relationships,
            settings,
            styles,
            theme,
            small_frac,
            ids,
            read: HashMap::new(),
        }
    }

    /// The headers or the footers of a section.
    fn stories(&mut self, refs: &References, warnings: &mut Warnings) -> Result<Stories, Error> {
        Ok(Stories {
            default: self.story(refs.default.as_deref(), warnings)?,
            first: self.story(refs.first.as_deref(), warnings)?,
            even: self.story(refs.even.as_deref(), warnings)?,
        })
    }

    /// The story of the part that a relationship ID names, read on its first use.
    fn story(
        &mut self,
        id: Option<&str>,
        warnings: &mut Warnings,
    ) -> Result<Option<PartStory>, Error> {
        let Some(target) = id.and_then(|id| {
            Relationship::by_id(self.relationships, id).map(|rel| rel.target.clone())
        }) else {
            return Ok(None);
        };
        if let Some(story) = self.read.get(&target) {
            return Ok(story.clone());
        }
        let story = self.read_story(&target, warnings)?.map(|blocks| PartStory {
            part: Rc::from(target.as_str()),
            blocks: Rc::from(blocks),
        });
        self.read.insert(target, story.clone());
        Ok(story)
    }

    /// Reads the story of a part, with the parts of its drawings from its own relationships.
    fn read_story(
        &self,
        target: &str,
        warnings: &mut Warnings,
    ) -> Result<Option<Vec<Block>>, Error> {
        let package = self.package;
        // A header or a footer checks no note reference against the notes.
        let mut reading = Reading {
            warnings,
            ids: self.ids,
            settings: self.settings,
            notes: None,
            colors: self.theme.shapes.colors,
            styles: Some(self.styles),
            small_frac: self.small_frac,
        };
        let mut story = parts::read_text(
            package,
            (Role::Story, Some(target.to_owned())),
            self.styles,
            &mut reading,
            |reader, root| Some(read_header_story(reader, root, self.settings)),
        )?;
        if let Some(paragraphs) = &mut story {
            // A story whose relationships do not read shows no pictures, charts or SmartArt.
            let own = parts::relationships(package, target, reading.warnings)?;
            let stories: &mut [&mut [Block]] = &mut [paragraphs];
            attach_parts(
                package,
                self.image_loader,
                (target, own),
                self.theme,
                stories,
                &mut reading,
            );
        }
        Ok(story)
    }
}

/// The settings, the styles, the theme, the font table and the numbering, from the parts that
/// `related` names by relationship type, each with its default when the package lacks it or
/// when it does not read, and the settings with the page color of the main document `main`.
/// A package without a numbering part numbers its lists as Word does without one.
fn read_main_parts(
    package: &Package,
    image_loader: &Arc<PackageImageLoader>,
    related: &dyn Fn(&str) -> Option<String>,
    page_color: Option<[u8; 3]>,
    reading: &mut Reading<'_>,
) -> Result<(Settings, Styles, Theme, FontTable, Numbering), Error> {
    let settings_of_reader = reading.settings;
    let mut settings = parts::read(
        package,
        (Role::Settings, related(ns::REL_SETTINGS)),
        reading,
        |reader, root| {
            let settings = Settings::read(reader, root);
            settings_of_reader.check_hyphenation(reader, settings.hyphenation.is_some());
            settings
        },
    )?;
    settings.page_color = page_color;
    let (styles, theme) = read_styles_and_theme(package, related, &settings, reading)?;
    let table = parts::read(
        package,
        (Role::FontTable, related(ns::REL_FONT_TABLE)),
        reading,
        |reader, root| FontTable::read(reader.doc, root),
    )?;
    let numbering = match related(ns::REL_NUMBERING) {
        Some(name) => {
            let mut numbering = parts::read(
                package,
                (Role::Numbering, Some(name.clone())),
                reading,
                |reader, root| Numbering::read(reader, root, settings_of_reader),
            )?;
            if numbering.has_picture_embeds() {
                let rels = parts::relationships(package, &name, reading.warnings)?;
                let inks = reading.settings.ink_conversion();
                let mut find = images(package, image_loader, (&name, rels), inks, reading.warnings);
                numbering.attach_images(&mut find);
            }
            numbering
        }
        None => Numbering::without_part(settings_of_reader),
    };
    Ok((settings, styles, theme, table, numbering))
}

/// The styles and the theme of a package, from the parts that `related` names by relationship
/// type. A package without a styles part takes the defaults of Word's own template, and one
/// without a theme part the fonts of the theme of the target's template. When the settings link
/// the styles to the template and the target follows that, the styles take the default
/// paragraph style of Word's own template. A styles or theme part that does not read is
/// skipped with a warning, as `parts` says, and counts as missing.
fn read_styles_and_theme(
    package: &Package,
    related: &dyn Fn(&str) -> Option<String>,
    settings: &Settings,
    reading: &mut Reading<'_>,
) -> Result<(Styles, Theme), Error> {
    // The theme is read first, so that the styles and every later part give a color that
    // names a theme color the theme's color.
    let theme_part = related(ns::REL_THEME);
    let parsed = match &theme_part {
        Some(name) => parts::parse(package, Role::Theme, name, reading.warnings)?,
        None => None,
    };
    let theme = match (parsed, theme_part) {
        (Some((doc, root)), Some(name)) => {
            parts::read_with(&doc, (&name, root), reading, Theme::read)
        }
        _ => reading.settings.template_theme(),
    };
    reading.colors = theme.shapes.colors;
    let styles_part = related(ns::REL_STYLES);
    let parsed = match &styles_part {
        Some(name) => parts::parse(package, Role::Styles, name, reading.warnings)?,
        None => None,
    };
    let mut styles = match (parsed, styles_part) {
        (Some((doc, root)), Some(name)) => {
            parts::read_with(&doc, (&name, root), reading, Styles::read)
        }
        _ => Styles::without_part(),
    };
    reading
        .settings
        .link_template_styles(settings.template_styles, &mut styles);
    reading.settings.refer_paragraphs(&mut styles);
    Ok((styles, theme))
}