f-office-docx 0.1.0

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
//! The section properties of the body: page size, margins, columns, page numbers, line
//! numbers, page borders and the references of the headers and footers.

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

use crate::note_setup::{ByNoteKind, NoteProps};
use crate::ns::W;
use crate::numbering::{Format, format_number, read_format};
use crate::numbers;
use crate::on_off;
use crate::props::{
    ArtStyle, BORDER_NAMES, Color, Gap, LineStyle, Relief, parse_color, read_border_as,
    read_line_style,
};
use crate::reader::PartReader;
use crate::table::turns_text;
use crate::warnings::Feature;

/// The relationship IDs of the headers or of the footers of a section.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct References {
    /// The header or footer of most pages.
    pub default: Option<String>,
    /// The header or footer of the first page, when the section has `w:titlePg`.
    pub first: Option<String>,
    /// The header or footer of even pages, when the settings have `w:evenAndOddHeaders`.
    pub even: Option<String>,
}

/// Page size and margins.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Section {
    /// Page width.
    pub width: Length,
    /// Page height.
    pub height: Length,
    /// The orientation that the section sets for the paper (`w:pgSz w:orient`), whatever the
    /// page's sides; portrait when it is missing.
    pub orientation: Orientation,
    /// Top margin.
    pub top: Length,
    /// Right margin.
    pub right: Length,
    /// Bottom margin.
    pub bottom: Length,
    /// Left margin, including the gutter.
    pub left: Length,
    /// The gutter (`w:pgMar w:gutter`), which the left margin includes.
    pub gutter: Length,
    /// The distance from the top edge of the page to the header.
    pub header: Length,
    /// The distance from the bottom edge of the page to the footer.
    pub footer: Length,
    /// Whether the top and the bottom margin are fixed (`w:pgMar` gives them as negative
    /// numbers), so that a header or footer that reaches past them does not move the body.
    pub fixed: (bool, bool),
    /// Whether the first page has its own header and footer (`w:titlePg`).
    pub title_page: bool,
    /// Whether the section runs from right to left (`w:bidi`).
    pub right_to_left: bool,
    /// The number of the first page (`w:pgNumType w:start`).
    pub first_page_number: i64,
    /// How page numbers are written (`w:pgNumType w:fmt`), such as `upperRoman` or
    /// `numberInDash`, in the forms of list labels.
    pub page_number_format: Format,
    /// Page numbers that start with a chapter number (`w:pgNumType w:chapStyle`).
    pub chapter: Option<Chapter>,
    /// The text columns (`w:cols`).
    pub columns: Columns,
    /// Where the body lies on a page between the top and the bottom margin (`w:vAlign`).
    pub vertical: PageAlign,
    /// The pitch of the document grid's lines (`w:docGrid` of the type `lines` or
    /// `linesAndChars`), which lines of automatic spacing fill in whole steps.
    pub line_pitch: Option<Length>,
    /// The pitch that a character grid (`w:docGrid` of the type `linesAndChars`) adds to each
    /// character: `w:charSpace` in 4096ths of a point (ECMA-376 Part 1, 17.6.5), 0 when it is
    /// 0 or missing. It is `Some` for each section with a character grid, whose right indents
    /// Word moves to the grid (`w:adjustRightInd`), and `None` for one without.
    pub char_pitch: Option<Length>,
    /// The numbers of the body lines in the left margin (`w:lnNumType`).
    pub line_numbers: Option<LineNumbers>,
}

/// The numbers that a section draws beside its body lines (`w:lnNumType`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineNumbers {
    /// Only numbers that this divides show (`w:countBy`), at least 1.
    pub count_by: i64,
    /// The number before the first line (`w:start`).
    pub start: i64,
    /// The space between a number and the text column (`w:distance`).
    pub distance: Length,
    /// When the count starts again (`w:restart`).
    pub restart: LineNumberRestart,
}

/// When line numbers start again.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineNumberRestart {
    /// On each page.
    #[default]
    NewPage,
    /// In each section.
    NewSection,
    /// Never.
    Continuous,
}

/// `ST_LineNumberRestart`; a missing value restarts on each page.
pub(super) const LINE_NUMBER_RESTART: &Values<LineNumberRestart> = &Values::new(&[
    own("newPage", LineNumberRestart::NewPage),
    own("newSection", LineNumberRestart::NewSection),
    own("continuous", LineNumberRestart::Continuous),
]);

/// `ST_PageOrientation` (ECMA-376 Part 1, 17.18.65); a missing value is portrait.
pub(super) const PAGE_ORIENTATION: &Values<Orientation> = &Values::new(&[
    own("portrait", Orientation::Portrait),
    own("landscape", Orientation::Landscape),
]);

/// Where the body lies on a page between the top and the bottom margin.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PageAlign {
    /// At the top margin.
    #[default]
    Top,
    /// In the middle.
    Center,
    /// At the bottom margin.
    Bottom,
}

use crate::params::{
    CHAR_SPACE_STEPS, COLUMN_SPACE, DEFAULT_HEADER_DISTANCE, DEFAULT_MARGIN, DEFAULT_PAGE_SIZE,
    HEADING_LEVELS, LINE_NUMBER_DISTANCE, MAX_COLUMN_COUNT, MAX_COLUMNS,
};

/// The text columns of a section (`w:cols`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Columns {
    /// The number of columns, at least 1.
    pub count: usize,
    /// The space between columns of equal width.
    pub space: Length,
    /// The width of each column and the space after it, when the columns have their own
    /// widths (`w:equalWidth="0"` and `w:col`).
    pub widths: Option<[(Length, Length); MAX_COLUMNS]>,
    /// Whether a line separates the columns (`w:sep`).
    pub separator: bool,
}

impl Default for Columns {
    /// One column, and half an inch between columns (ECMA-376 Part 1, 17.6.4).
    fn default() -> Self {
        Self {
            count: 1,
            space: COLUMN_SPACE,
            widths: None,
            separator: false,
        }
    }
}

impl Columns {
    /// The left edge and the width of each column, in a text area from `left` that is `width`
    /// wide. Equal columns take the width that `equal` gives from their exact width; columns of
    /// their own widths take those.
    #[must_use]
    pub fn areas(
        &self,
        left: Length,
        width: Length,
        equal: impl FnOnce(Length) -> Length,
    ) -> Vec<(Length, Length)> {
        let count = self.count.max(1);
        if count == 1 {
            return vec![(left, width)];
        }
        if let Some(widths) = self.widths {
            let mut x = left;
            return widths
                .iter()
                .take(count)
                .map(|&(column, space)| {
                    let area = (x, column);
                    x += column + space;
                    area
                })
                .collect();
        }
        let n = i64::try_from(count).unwrap_or(1);
        let exact = (width - self.space * (n - 1)).div_toward_zero(n);
        let column = equal(exact);
        (0..n)
            .map(|i| (left + (column + self.space) * i, column))
            .collect()
    }
}

/// Page numbers that start with the number of the last chapter heading, such as "5-3".
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Chapter {
    /// The level of the heading style whose number is the chapter number (`w:chapStyle`),
    /// 1 for "heading 1".
    pub level: u8,
    /// What comes between the chapter number and the page number (`w:chapSep`).
    pub separator: ChapterSeparator,
}

/// What comes between a chapter number and a page number (`w:chapSep`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChapterSeparator {
    Hyphen,
    Period,
    Colon,
    EmDash,
    EnDash,
}

impl ChapterSeparator {
    /// The character of the separator.
    #[must_use]
    pub fn char(self) -> char {
        match self {
            Self::Hyphen => '-',
            Self::Period => '.',
            Self::Colon => ':',
            Self::EmDash => '\u{2014}',
            Self::EnDash => '\u{2013}',
        }
    }
}

/// `ST_ChapterSep`; a missing separator is a hyphen.
pub(super) const CHAPTER_SEPARATOR: &Values<ChapterSeparator> = &Values::new(&[
    own("hyphen", ChapterSeparator::Hyphen),
    own("period", ChapterSeparator::Period),
    own("colon", ChapterSeparator::Colon),
    own("emDash", ChapterSeparator::EmDash),
    own("enDash", ChapterSeparator::EnDash),
]);

impl Section {
    /// Writes a page number in the section's page number format.
    #[must_use]
    pub fn page_number(&self, number: i64) -> String {
        format_number(number, self.page_number_format)
    }

    /// The section with its gutter in the top margin instead of the left one, as the setting
    /// `w:gutterAtTop` asks.
    #[must_use]
    pub fn with_gutter_at_top(mut self) -> Self {
        self.left = self.left.checked_sub(self.gutter).unwrap_or(self.left);
        self.top = self.top.checked_add(self.gutter).unwrap_or(self.top);
        self
    }

    /// The left and right margins of a page of the section: swapped on a page with an even
    /// number when the setting `w:mirrorMargins` mirrors them, so that the gutter, a part of
    /// the left margin, stays at the inside edge of facing pages.
    #[must_use]
    pub const fn side_margins(&self, mirrored: bool) -> (Length, Length) {
        if mirrored {
            (self.right, self.left)
        } else {
            (self.left, self.right)
        }
    }
}

impl Default for Section {
    /// US Letter with one-inch margins and half-inch header and footer distances, which Word
    /// uses when the section says nothing.
    fn default() -> Self {
        let (width, height) = DEFAULT_PAGE_SIZE;
        Self {
            width,
            height,
            orientation: Orientation::Portrait,
            top: DEFAULT_MARGIN,
            right: DEFAULT_MARGIN,
            bottom: DEFAULT_MARGIN,
            left: DEFAULT_MARGIN,
            gutter: Length::ZERO,
            header: DEFAULT_HEADER_DISTANCE,
            footer: DEFAULT_HEADER_DISTANCE,
            fixed: (false, false),
            title_page: false,
            right_to_left: false,
            first_page_number: 1,
            page_number_format: Format::Decimal,
            chapter: None,
            columns: Columns::default(),
            vertical: PageAlign::Top,
            line_pitch: None,
            char_pitch: None,
            line_numbers: None,
        }
    }
}

/// How a section starts after the one before it (`w:type` of its `w:sectPr`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SectionStart {
    /// On a new page.
    #[default]
    NextPage,
    /// On the same page.
    Continuous,
    /// On the next even page.
    EvenPage,
    /// On the next odd page.
    OddPage,
}

/// `ST_SectionMark`: a section that starts in the next column is drawn on a new page, and a
/// missing kind starts a new page. Word refuses a document with text outside the type.
pub(super) const SECTION_MARK: &Values<SectionStart> = &Values::new(&[
    own("nextPage", SectionStart::NextPage),
    another("nextColumn", SectionStart::NextPage),
    own("continuous", SectionStart::Continuous),
    own("evenPage", SectionStart::EvenPage),
    own("oddPage", SectionStart::OddPage),
]);

/// The sections of a body in order: one or more. The reader gives every body its last section,
/// the body's own `w:sectPr` or a section of defaults, so that a body never has none. `T` is a
/// section as read ([`SectionPart`]) or as the layout uses it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Sections<T> {
    /// The first section.
    first: T,
    /// The sections after the first, in order.
    rest: Vec<T>,
}

impl<T> Sections<T> {
    /// One section.
    #[must_use]
    pub const fn one(section: T) -> Self {
        Self {
            first: section,
            rest: Vec::new(),
        }
    }

    /// The sections `before` in order, and `last` after them.
    #[must_use]
    pub fn ending_with(before: Vec<T>, last: T) -> Self {
        let mut before = before.into_iter();
        match before.next() {
            Some(first) => Self {
                first,
                rest: before.chain(std::iter::once(last)).collect(),
            },
            None => Self::one(last),
        }
    }

    /// The first section.
    #[must_use]
    pub const fn first(&self) -> &T {
        &self.first
    }

    /// The last section.
    #[must_use]
    pub fn last(&self) -> &T {
        self.rest.last().unwrap_or(&self.first)
    }

    /// The section `index`, from 0, or none past the last.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&T> {
        match index.checked_sub(1) {
            Some(after_first) => self.rest.get(after_first),
            None => Some(&self.first),
        }
    }

    /// The number of sections, 1 or more.
    #[must_use]
    pub const fn count(&self) -> usize {
        self.rest.len() + 1
    }

    /// The sections in order.
    pub fn iter(&self) -> std::iter::Chain<std::iter::Once<&T>, std::slice::Iter<'_, T>> {
        std::iter::once(&self.first).chain(&self.rest)
    }

    /// The sections in order, to change.
    pub fn iter_mut(
        &mut self,
    ) -> std::iter::Chain<std::iter::Once<&mut T>, std::slice::IterMut<'_, T>> {
        std::iter::once(&mut self.first).chain(&mut self.rest)
    }

    /// The sections that `make` makes of these, in order, or the first error that it gives.
    ///
    /// # Errors
    ///
    /// Returns the first error of `make`.
    pub fn try_map<U, E>(
        &self,
        mut make: impl FnMut(&T) -> Result<U, E>,
    ) -> Result<Sections<U>, E> {
        Ok(Sections {
            first: make(&self.first)?,
            rest: self.rest.iter().map(make).collect::<Result<_, _>>()?,
        })
    }
}

impl<'a, T> IntoIterator for &'a Sections<T> {
    type Item = &'a T;
    type IntoIter = std::iter::Chain<std::iter::Once<&'a T>, std::slice::Iter<'a, T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut Sections<T> {
    type Item = &'a mut T;
    type IntoIter = std::iter::Chain<std::iter::Once<&'a mut T>, std::slice::IterMut<'a, T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

/// One section of the body.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SectionPart {
    /// The page size and margins.
    pub section: Section,
    /// The headers, with those that the section does not name taken from the section before.
    pub headers: References,
    /// The footers, taken in the same way.
    pub footers: References,
    /// How the section starts.
    pub start: SectionStart,
    /// The index after the section's last block in [`Body::blocks`](super::Body::blocks).
    pub end: usize,
    /// Whether the section sets its own first page number.
    pub restarts_numbers: bool,
    /// The borders around its pages (`w:pgBorders`).
    pub borders: Option<PageBorders>,
    /// What it sets for its footnotes and endnotes (`w:footnotePr`, `w:endnotePr`), which
    /// stands over the settings.
    pub notes: ByNoteKind<NoteProps>,
}

/// The borders around the pages of a section (`w:pgBorders`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PageBorders {
    /// The line or the art of each side.
    pub sides: Edges<Option<PageSide>>,
    /// Whether the space of each line counts from the page edge (`w:offsetFrom="page"`)
    /// instead of from the text margins.
    pub from_page: bool,
    /// Which pages of the section show them.
    pub pages: BorderPages,
}

/// One side of a page border: a line, or pictures of an art style.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PageSide {
    /// A line of a line style, such as `single`.
    Line(crate::props::Border),
    /// Pictures of an art style, such as `apples`, on a target that draws them
    /// (`BorderStyles::draws_art`).
    Art(ArtSide),
}

impl PageSide {
    /// The side's line, or `None` for an art side.
    #[must_use]
    pub const fn line(self) -> Option<crate::props::Border> {
        match self {
            Self::Line(border) => Some(border),
            Self::Art(_) => None,
        }
    }

    /// The side's art, or `None` for a line.
    #[must_use]
    pub const fn art(self) -> Option<ArtSide> {
        match self {
            Self::Line(_) => None,
            Self::Art(art) => Some(art),
        }
    }
}

/// A page border's side of an art style.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ArtSide {
    /// The art style.
    pub style: ArtStyle,
    /// The size, in whole points (`w:sz`, which counts in points for an art style): the side
    /// of the corner square, and the height of each picture across the side.
    pub size: u32,
    /// The space between the side and the page edge or the text, as `w:offsetFrom` says.
    pub space: Length,
    /// The color that takes the place of black in the pictures.
    pub color: Color,
}

/// Which pages of a section show its page borders (`w:display`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BorderPages {
    /// Every page.
    #[default]
    All,
    /// The first page only.
    First,
    /// Every page but the first.
    NotFirst,
}

/// `ST_PageBorderDisplay`; a missing value shows the borders on every page.
pub(super) const BORDER_DISPLAY: &Values<BorderPages> = &Values::new(&[
    own("allPages", BorderPages::All),
    own("firstPage", BorderPages::First),
    own("notFirstPage", BorderPages::NotFirst),
]);

/// `ST_PageBorderOffset`, as whether the space of a page border counts from the page edge; a
/// missing value counts from the text.
pub(super) const BORDER_OFFSET: &Values<bool> =
    &Values::new(&[own("page", true), own("text", false)]);

/// What a document grid sets (`ST_DocGrid`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum DocGrid {
    /// Nothing.
    None,
    /// The pitch of lines.
    Lines,
    /// The pitch of lines and of characters.
    LinesAndChars,
}

/// `ST_DocGrid`: a grid that snaps characters is drawn as no grid, and a missing type sets
/// nothing.
pub(super) const DOC_GRID: &Values<DocGrid> = &Values::new(&[
    own("default", DocGrid::None),
    own("lines", DocGrid::Lines),
    own("linesAndChars", DocGrid::LinesAndChars),
    another("snapToChars", DocGrid::None),
]);

/// The kind of a header or a footer (`ST_HdrFtr`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HeaderKind {
    Default,
    First,
    Even,
}

/// `ST_HdrFtr`; a reference without a kind is the default one.
pub(super) const HEADER_KIND: &Values<HeaderKind> = &Values::new(&[
    own("default", HeaderKind::Default),
    own("first", HeaderKind::First),
    own("even", HeaderKind::Even),
]);

/// `ST_VerticalJc` of a section: vertical justification is drawn at the top, and a missing
/// value is the top.
pub(super) const SECTION_V_ALIGN: &Values<PageAlign> = &Values::new(&[
    own("top", PageAlign::Top),
    own("center", PageAlign::Center),
    another("both", PageAlign::Top),
    own("bottom", PageAlign::Bottom),
]);

/// The width of the first text column of the section `node` (`w:sectPr`), as the body reader
/// reads its page, its margins and its columns, for the named edit that inserts an image: none
/// when the margins leave no width.
pub(crate) fn first_column_width(reader: &mut PartReader, node: NodeId) -> Option<Length> {
    let section = read_section(reader, node);
    let width = section.width - section.left - section.right;
    let (_, column) = *section
        .columns
        .areas(Length::ZERO, width, |exact| exact)
        .first()?;
    (column > Length::ZERO).then_some(column)
}

/// Reads a `w:sectPr` element as the section that ends before the block with the index `end`.
pub(super) fn read_section_part(reader: &mut PartReader, node: NodeId, end: usize) -> SectionPart {
    let doc = reader.doc;
    let start = doc
        .child(node, W, "type")
        .and_then(|n| reader.enumeration(n, "val", SECTION_MARK))
        .unwrap_or_default();
    let restarts_numbers = doc
        .child(node, W, "pgNumType")
        .and_then(|n| doc.attribute(n, Some(W), "start"))
        .is_some();
    warn_of_text_direction(reader, node);
    SectionPart {
        section: read_section(reader, node),
        headers: read_references(reader, node, "headerReference"),
        footers: read_references(reader, node, "footerReference"),
        start,
        end,
        restarts_numbers,
        borders: doc
            .child(node, W, "pgBorders")
            .and_then(|b| read_page_borders(reader, b)),
        notes: ByNoteKind::read(reader, node),
    }
}

/// Warns when a section's text direction (`w:textDirection`) is a name of `ST_TextDirection`
/// other than upright from left to right (`lrTb`, `tb` in the Strict schema): the section's
/// text is laid out upright (ECMA-376 Part 1, `w:textDirection` of the section properties). A
/// value outside the type counts as missing, with a warning, and changes nothing else.
fn warn_of_text_direction(reader: &mut PartReader, node: NodeId) {
    let turned = reader
        .doc
        .child(node, W, "textDirection")
        .and_then(|direction| reader.or_missing(direction, "val", turns_text))
        .unwrap_or(false);
    if turned {
        reader.feature_not_supported(Feature::SectionTextDirection);
    }
}

/// `ST_Border` of a side of a page border: the line styles that F-Office draws on a page, as it
/// draws them in a paragraph's border, and no line for the others, the art borders, whose
/// `w:sz` counts in points. A side without a style, or whose style is text outside the type,
/// has no line.
pub(super) const PAGE_BORDER_LINE: &Values<LineStyle> = &Values::with_others(
    &[
        own("nil", LineStyle::None),
        own("none", LineStyle::None),
        own("single", LineStyle::Single),
        own("double", LineStyle::Double),
        own("triple", LineStyle::Triple),
        own("thinThickSmallGap", LineStyle::ThinThick(Gap::Small)),
        own("thickThinSmallGap", LineStyle::ThickThin(Gap::Small)),
        own(
            "thinThickThinSmallGap",
            LineStyle::ThinThickThin(Gap::Small),
        ),
        own("thinThickMediumGap", LineStyle::ThinThick(Gap::Medium)),
        own("thickThinMediumGap", LineStyle::ThickThin(Gap::Medium)),
        own(
            "thinThickThinMediumGap",
            LineStyle::ThinThickThin(Gap::Medium),
        ),
        another("thick", LineStyle::Single),
        another("dotted", LineStyle::Single),
        another("dashed", LineStyle::Single),
        another("dotDash", LineStyle::Single),
        another("dotDotDash", LineStyle::Single),
        another("dashSmallGap", LineStyle::Single),
        another("dashDotStroked", LineStyle::Single),
        own("thinThickLargeGap", LineStyle::ThinThick(Gap::Large)),
        own("thickThinLargeGap", LineStyle::ThickThin(Gap::Large)),
        own(
            "thinThickThinLargeGap",
            LineStyle::ThinThickThin(Gap::Large),
        ),
        another("wave", LineStyle::Single),
        another("doubleWave", LineStyle::Single),
        own("threeDEmboss", LineStyle::ThreeD(Relief::Emboss)),
        own("threeDEngrave", LineStyle::ThreeD(Relief::Engrave)),
        own("inset", LineStyle::Single),
        own("outset", LineStyle::Single),
    ],
    BORDER_NAMES,
    LineStyle::None,
);

/// Reads `w:pgBorders`, or gives `None` when it has no side that F-Office draws. A side of an
/// art style is an art side on a target that draws them (`BorderStyles::draws_art`), and has no
/// line on another, with a warning that its style is not supported.
fn read_page_borders(reader: &mut PartReader, node: NodeId) -> Option<PageBorders> {
    let doc = reader.doc;
    let side = |name: &str| {
        let side = doc.child(node, W, name)?;
        if reader.border_styles().draws_art()
            && let Some(art) = read_art_side(reader, side)
        {
            return Some(PageSide::Art(art));
        }
        let style = read_line_style(reader, side, PAGE_BORDER_LINE)?;
        read_border_as(reader, side, style).map(PageSide::Line)
    };
    let [top, left, bottom, right] = ["top", "left", "bottom", "right"].map(side);
    let sides = Edges {
        left,
        top,
        right,
        bottom,
    };
    let pages = reader
        .enumeration(node, "display", BORDER_DISPLAY)
        .unwrap_or_default();
    let from_page = reader
        .enumeration(node, "offsetFrom", BORDER_OFFSET)
        .unwrap_or(false);
    [left, top, right, bottom]
        .iter()
        .any(Option::is_some)
        .then_some(PageBorders {
            sides,
            from_page,
            pages,
        })
}

/// Reads a page border's side `node` of an art style, or gives `None` for a side of another
/// style. Its size counts in points; a missing size, space or color, or one that does not read,
/// is 0 or automatic, as for a line.
fn read_art_side(reader: &mut PartReader, node: NodeId) -> Option<ArtSide> {
    let doc = reader.doc;
    let style = doc
        .attribute(node, Some(W), "val")
        .and_then(ArtStyle::of_name)?;
    let points = u32::try_from(reader.whole_number(node, "sz").unwrap_or(0)).unwrap_or(0);
    let space = Length::from_points(reader.whole_number(node, "space").unwrap_or(0))?;
    Some(ArtSide {
        style,
        size: points,
        space,
        color: doc
            .attribute(node, Some(W), "color")
            .map_or(Color::Auto, parse_color),
    })
}

/// A section without a header or footer of a kind takes the previous section's.
pub(super) fn inherit_references(sections: &mut Sections<SectionPart>) {
    let mut previous: Option<(References, References)> = None;
    for current in sections {
        if let Some((headers, footers)) = &previous {
            fill(&mut current.headers, headers);
            fill(&mut current.footers, footers);
        }
        previous = Some((current.headers.clone(), current.footers.clone()));
    }
}

fn fill(refs: &mut References, from: &References) {
    for (slot, other) in [
        (&mut refs.default, &from.default),
        (&mut refs.first, &from.first),
        (&mut refs.even, &from.even),
    ] {
        if slot.is_none() {
            slot.clone_from(other);
        }
    }
}

/// Reads `w:lnNumType`. A section numbers its lines only with a `w:countBy` of 1 or more.
/// Without `w:distance`, the numbers end a quarter inch left of the text.
fn read_line_numbers(reader: &mut PartReader, node: NodeId) -> Option<LineNumbers> {
    let count_by = reader
        .number(node, "countBy", numbers::ANY)
        .filter(|count| *count >= 1)?;
    Some(LineNumbers {
        count_by,
        start: reader
            .number(node, "start", numbers::ANY)
            .unwrap_or(0)
            .max(0),
        distance: reader
            .twips(node, "distance")
            .unwrap_or(LINE_NUMBER_DISTANCE),
        restart: reader
            .enumeration(node, "restart", LINE_NUMBER_RESTART)
            .unwrap_or_default(),
    })
}

/// Whether a section has the on/off property `name` turned on.
fn flag(doc: &Document, node: NodeId, name: &str) -> bool {
    doc.child(node, W, name)
        .is_some_and(|n| on_off::off_only_for_0_or_false(doc, n))
}

fn read_section(reader: &mut PartReader, node: NodeId) -> Section {
    let doc = reader.doc;
    let mut section = Section::default();
    let mut twips = |child: Option<NodeId>, name: &str| child.and_then(|c| reader.twips(c, name));
    let size = doc.child(node, W, "pgSz");
    let margins = doc.child(node, W, "pgMar");
    let [width, height] = ["w", "h"].map(|name| twips(size, name));
    let [top, bottom, right, left, gutter, header, footer] = [
        "top", "bottom", "right", "left", "gutter", "header", "footer",
    ]
    .map(|name| twips(margins, name));
    let set = |slot: &mut Length, value: Option<Length>| {
        if let Some(value) = value {
            *slot = value;
        }
    };
    set(&mut section.width, width);
    set(&mut section.height, height);
    section.orientation = size
        .and_then(|size| reader.enumeration(size, "orient", PAGE_ORIENTATION))
        .unwrap_or_default();
    set(&mut section.top, top.map(abs));
    set(&mut section.bottom, bottom.map(abs));
    let negative = |margin: Option<Length>| margin.is_some_and(|m| m.units() < 0);
    if margins.is_some() {
        section.fixed = (negative(top), negative(bottom));
    }
    set(&mut section.right, right);
    set(&mut section.left, left);
    if let Some(gutter) = gutter {
        section.left = section.left.checked_add(gutter).unwrap_or(section.left);
        section.gutter = gutter;
    }
    set(&mut section.header, header.map(abs));
    set(&mut section.footer, footer.map(abs));
    section.title_page = flag(doc, node, "titlePg");
    section.right_to_left = flag(doc, node, "bidi");
    section.line_numbers = doc
        .child(node, W, "lnNumType")
        .and_then(|n| read_line_numbers(reader, n));
    let numbering = doc.child(node, W, "pgNumType");
    if let Some(start) = numbering.and_then(|n| reader.number(n, "start", numbers::ANY)) {
        section.first_page_number = start;
    }
    section.chapter = numbering.and_then(|n| {
        let level = reader.number(n, "chapStyle", 1..=i64::from(HEADING_LEVELS))?;
        let separator = reader
            .enumeration(n, "chapSep", CHAPTER_SEPARATOR)
            .unwrap_or(ChapterSeparator::Hyphen);
        Some(Chapter { level, separator })
    });
    section.page_number_format = numbering
        .and_then(|n| read_format(reader, n, "fmt"))
        .unwrap_or(Format::Decimal);
    if let Some(cols) = doc.child(node, W, "cols") {
        section.columns = read_columns(reader, cols);
    }
    let grid = doc.child(node, W, "docGrid");
    let kind = grid
        .and_then(|grid| reader.enumeration(grid, "type", DOC_GRID))
        .unwrap_or(DocGrid::None);
    section.line_pitch = grid
        .filter(|_| kind != DocGrid::None)
        .and_then(|grid| reader.twips(grid, "linePitch"))
        .filter(|pitch| pitch.units() > 0);
    // `charSpace` is an `xsd:integer`, which has no bound; it reads into 32 bits, so that its
    // product in units fits, and a value beyond counts as missing, with a warning. A missing
    // pitch adds 0.
    section.char_pitch = grid.filter(|_| kind == DocGrid::LinesAndChars).map(|grid| {
        let space = reader
            .number::<i32>(grid, "charSpace", numbers::ANY)
            .unwrap_or(0);
        let units = i64::from(space) * Length::UNITS_PER_POINT;
        Length::from_units(f_office_units::div_round(units, CHAR_SPACE_STEPS))
    });
    // Vertical justification (`both`) is not done yet, and keeps the body at the top.
    section.vertical = doc
        .child(node, W, "vAlign")
        .and_then(|n| reader.enumeration(n, "val", SECTION_V_ALIGN))
        .unwrap_or_default();
    section
}

/// Reads the columns of a section (`w:cols`).
fn read_columns(reader: &mut PartReader, node: NodeId) -> Columns {
    let doc = reader.doc;
    let mut columns = Columns::default();
    let count = reader
        .number(node, "num", numbers::NOT_NEGATIVE)
        .unwrap_or(1);
    let mut twips = |n: NodeId, name: &str| reader.twips(n, name);
    let flag = |name: &str| {
        doc.attribute(node, Some(W), name)
            .is_some_and(|v| on_off::read(v) != Some(false))
    };
    if let Some(space) = twips(node, "space") {
        columns.space = space;
    }
    columns.separator = flag("sep");
    let own: Vec<NodeId> = doc
        .child_elements(node)
        .filter(|c| doc.is(*c, W, "col"))
        .collect();
    let equal = doc
        .attribute(node, Some(W), "equalWidth")
        .is_none_or(|v| on_off::read(v) != Some(false));
    if !equal && !own.is_empty() && own.len() <= MAX_COLUMNS {
        let mut widths = [(Length::ZERO, Length::ZERO); MAX_COLUMNS];
        for (slot, col) in widths.iter_mut().zip(&own) {
            *slot = (
                twips(*col, "w").unwrap_or(Length::ZERO),
                twips(*col, "space").unwrap_or(Length::ZERO),
            );
        }
        columns.widths = Some(widths);
        columns.count = own.len();
    } else {
        columns.count = count.clamp(1, MAX_COLUMN_COUNT);
    }
    columns
}

/// Reads `w:headerReference` or `w:footerReference` children by their type.
fn read_references(reader: &mut PartReader, node: NodeId, name: &str) -> References {
    let doc = reader.doc;
    let mut refs = References::default();
    for child in doc.child_elements(node).filter(|c| doc.is(*c, W, name)) {
        let Some(id) = doc.attribute(child, Some(crate::ns::R), "id") else {
            continue;
        };
        let slot = match reader.enumeration(child, "type", HEADER_KIND) {
            Some(HeaderKind::First) => &mut refs.first,
            Some(HeaderKind::Even) => &mut refs.even,
            Some(HeaderKind::Default) | None => &mut refs.default,
        };
        *slot = Some(id.to_owned());
    }
    refs
}

fn abs(length: Length) -> Length {
    Length::from_units(length.units().saturating_abs())
}