f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
//! Paragraph properties (`w:pPr`): alignment, spacing, indents, tab stops and lists.

use std::num::NonZeroU32;

use f_office_units::Length;
use f_office_units::scale::{LINE, PERCENT};
use f_office_xml::NodeId;
use f_office_xml::enumeration::{Values, another, own};

use super::border::read_borders;
use super::{
    Borders, Color, FrameMark, FramePr, NamedSides, RunProps, SetIn, overlay, read_shading,
    value_of,
};
use crate::ns::W;
use crate::numbers;
use crate::on_off::{self, off_also_for_none};
use crate::params;
use crate::reader::{PartReader, val};

/// Paragraph alignment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Alignment {
    /// Left aligned.
    Start,
    /// Centered.
    Center,
    /// Right aligned.
    End,
    /// Justified on every line except the last.
    Both,
    /// Justified as [`Self::Both`] is, except that a line with Thai text keeps its spaces from
    /// shrinking (`thaiDistribute`).
    ThaiDistribute,
}

impl Alignment {
    /// Whether a line of this alignment starts at its paragraph's indent, as a left-aligned
    /// and a justified line do.
    #[must_use]
    pub const fn starts_at_indent(self) -> bool {
        matches!(self, Self::Start | Self::Both | Self::ThaiDistribute)
    }

    /// Whether lines of this alignment other than a paragraph's last span their width.
    #[must_use]
    pub const fn justified(self) -> bool {
        matches!(self, Self::Both | Self::ThaiDistribute)
    }
}

/// Which of the alignments with kashidas a paragraph has (`w:jc`), or none. A justified line
/// of such a paragraph can lengthen joints between Arabic letters with kashidas, tatweel
/// glyphs (U+0640), as well as widen its spaces.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kashidas {
    /// An alignment without kashidas.
    None,
    /// `lowKashida`.
    Low,
    /// `mediumKashida`.
    Medium,
    /// `highKashida`.
    High,
}

/// `ST_Jc` in a paragraph's alignment, with its kashidas. `distribute` and the alignments with
/// kashidas are drawn as justified, and `numTab` counts as not set here, so that the paragraph
/// takes its style's alignment.
pub(super) const JC: &Values<Option<(Alignment, Kashidas)>> = &Values::new(&[
    own("left", Some((Alignment::Start, Kashidas::None))),
    own("start", Some((Alignment::Start, Kashidas::None))),
    own("center", Some((Alignment::Center, Kashidas::None))),
    own("right", Some((Alignment::End, Kashidas::None))),
    own("end", Some((Alignment::End, Kashidas::None))),
    own("both", Some((Alignment::Both, Kashidas::None))),
    another("distribute", Some((Alignment::Both, Kashidas::None))),
    another("mediumKashida", Some((Alignment::Both, Kashidas::Medium))),
    another("highKashida", Some((Alignment::Both, Kashidas::High))),
    another("lowKashida", Some((Alignment::Both, Kashidas::Low))),
    own(
        "thaiDistribute",
        Some((Alignment::ThaiDistribute, Kashidas::None)),
    ),
    another("numTab", None),
]);

/// The text alignment of a paragraph: the vertical alignment of the characters of its lines
/// (`w:textAlignment`, ECMA-376 Part 1, 17.3.1.39). F-Office sets every piece of a line on one
/// baseline, whatever the value; the layout warns of the values that can move a piece off it
/// ([`TextAlignment::off_baseline`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextAlignment {
    /// Word chooses (`auto`).
    Auto,
    /// On the baseline (`baseline`).
    Baseline,
    /// At the top of the line (`top`).
    Top,
    /// In the middle of the line (`center`).
    Center,
    /// At the bottom of the line (`bottom`).
    Bottom,
}

impl TextAlignment {
    /// Whether the value aligns the characters of a line at its top, its middle or its
    /// bottom, which on Word's pages can set a smaller run of a line off the baseline of the
    /// larger one ([`crate::Feature::TextAlignment`]).
    #[must_use]
    pub const fn off_baseline(self) -> bool {
        matches!(self, Self::Top | Self::Center | Self::Bottom)
    }
}

/// `ST_TextAlignment` in a paragraph's text alignment. Each name reads as its own case; the
/// layout, not the reader, warns of the cases that it draws on the baseline, on the lines where
/// they can move a piece.
pub(super) const TEXT_ALIGNMENT: &Values<TextAlignment> = &Values::new(&[
    own("auto", TextAlignment::Auto),
    own("baseline", TextAlignment::Baseline),
    own("top", TextAlignment::Top),
    own("center", TextAlignment::Center),
    own("bottom", TextAlignment::Bottom),
]);

/// `ST_TextboxTightWrap`: whether the lines of a paragraph take part in the tight wrap of its
/// text box (ECMA-376 Part 1, 17.3.1.40), which every value but `none` asks for some of them.
pub(super) const TIGHT_WRAP: &Values<bool> = &Values::new(&[
    own("none", false),
    own("allLines", true),
    own("firstAndLastLine", true),
    own("firstLineOnly", true),
    own("lastLineOnly", true),
]);

/// How the height of a line is computed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineSpacing {
    /// A multiple of single spacing, in 240ths.
    Auto(i64),
    /// Exactly this height.
    Exact(Length),
    /// At least this height.
    AtLeast(Length),
}

impl LineSpacing {
    /// Single lines: one whole line of automatic spacing, which counts in 240ths of a line
    /// (ECMA-376 Part 1, 17.3.1.33).
    pub const SINGLE: Self = Self::Auto(LINE);
}

/// How text lines up at a tab stop.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TabKind {
    /// Text starts at the stop.
    Left,
    /// Text is centered on the stop.
    Center,
    /// Text ends at the stop.
    Right,
    /// The decimal separator sits at the stop.
    Decimal,
}

/// What a tab of `w:tabs` sets, by its kind (`ST_TabJc`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum TabSetting {
    /// A stop of this kind.
    Stop(TabKind),
    /// A clear of the stop at its place (`clear`).
    Clear,
    /// A bar (`bar`), which makes no stop: it draws a vertical line at its place, and a tab
    /// goes on to the next stop (ECMA-376 Part 1, 17.18.84). F-Office does not draw the line.
    Bar,
}

/// `ST_TabJc`, what a tab of `w:tabs` sets: `start` is a left stop and `end` a right one, and
/// the list tab `num` is a left stop, as Word draws it. A bar is drawn without its line. A tab
/// without a kind, or whose kind is text outside the type, is a left stop, as Word draws it.
pub(super) const TAB_KIND: &Values<TabSetting> = &Values::new(&[
    own("left", TabSetting::Stop(TabKind::Left)),
    own("start", TabSetting::Stop(TabKind::Left)),
    own("center", TabSetting::Stop(TabKind::Center)),
    own("right", TabSetting::Stop(TabKind::Right)),
    own("end", TabSetting::Stop(TabKind::Right)),
    own("decimal", TabSetting::Stop(TabKind::Decimal)),
    own("clear", TabSetting::Clear),
    own("num", TabSetting::Stop(TabKind::Left)),
    another("bar", TabSetting::Bar),
]);

/// The leader of a tab stop (`ST_TabTlc`): the character that it repeats, if any. A heavy
/// leader is drawn as an underscore.
pub(super) const TAB_LEADER: &Values<Option<char>> = &Values::new(&[
    own("none", None),
    own("dot", Some('.')),
    own("hyphen", Some('-')),
    own("underscore", Some('_')),
    another("heavy", Some('_')),
    own("middleDot", Some('\u{b7}')),
]);

/// One custom tab stop.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TabStop {
    /// The distance from the left edge of the text column.
    pub position: Length,
    /// How text lines up at the stop.
    pub kind: TabKind,
    /// The character that fills the space before the stop, if any.
    pub leader: Option<char>,
}

/// One tab setting of a style or of direct formatting (`w:tab`): a stop, or a tab clear, which
/// removes the stop that an earlier level of the style cascade set at its position.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TabMark {
    /// A stop.
    Stop(TabStop),
    /// A tab clear (`w:val="clear"`) at this distance from the left edge of the text column.
    Clear(Length),
}

impl TabMark {
    /// The distance of the stop or the clear from the left edge of the text column.
    #[must_use]
    pub const fn position(&self) -> Length {
        match self {
            Self::Stop(stop) => stop.position,
            Self::Clear(position) => *position,
        }
    }

    /// The stop, or `None` for a tab clear.
    #[must_use]
    pub const fn stop(&self) -> Option<TabStop> {
        match self {
            Self::Stop(stop) => Some(*stop),
            Self::Clear(_) => None,
        }
    }
}

/// The on and off settings of a paragraph after the cascade, each with its default where no
/// layer of the cascade sets it ([`ParaProps::flags`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "each field is one on and off element of the markup"
)]
pub(crate) struct ParaFlags {
    /// `w:contextualSpacing`, off by default.
    pub(crate) contextual_spacing: bool,
    /// `w:bidi`, off by default.
    pub(crate) bidi: bool,
    /// `w:snapToGrid`, on by default.
    pub(crate) snap_to_grid: bool,
    /// `w:kinsoku`, on by default.
    pub(crate) kinsoku: bool,
    /// `w:wordWrap`, on by default.
    pub(crate) word_wrap: bool,
    /// `w:overflowPunct`, on by default.
    pub(crate) overflow_punct: bool,
    /// `w:widowControl`, on by default.
    pub(crate) widow_control: bool,
    /// `w:keepNext`, off by default.
    pub(crate) keep_next: bool,
    /// `w:autoSpaceDE`, on by default.
    pub(crate) auto_space_latin: bool,
    /// `w:autoSpaceDN`, on by default.
    pub(crate) auto_space_digits: bool,
    /// `w:keepLines`, off by default.
    pub(crate) keep_lines: bool,
    /// `w:suppressLineNumbers`, off by default.
    pub(crate) suppress_line_numbers: bool,
    /// `w:suppressAutoHyphens`, off by default.
    pub(crate) suppress_auto_hyphens: bool,
    /// `w:pageBreakBefore`, off by default.
    pub(crate) page_break_before: bool,
    /// Whether the paragraph is the empty last paragraph of a section before a new page, off
    /// by default.
    pub(crate) section_end: bool,
    /// Whether the paragraph is a continuous section end, off by default.
    pub(crate) continuous_end: bool,
    /// Whether the paragraph ends a single-column section before a continuous section in a mode
    /// that drops a trailing empty line after a line break and its space after, off by default.
    pub(crate) continuous_break_end: bool,
    /// `w:beforeAutospacing`, off by default.
    pub(crate) before_auto: bool,
    /// `w:afterAutospacing`, off by default.
    pub(crate) after_auto: bool,
    /// `w:mirrorIndents`, off by default.
    pub(crate) mirror_indents: bool,
    /// `w:adjustRightInd`, on by default.
    pub(crate) adjust_right_indent: bool,
    /// `w:suppressOverlap`, off by default.
    pub(crate) suppress_overlap: bool,
    /// `w:textboxTightWrap` other than `none`, which it is by default.
    pub(crate) tight_wrap: bool,
}

/// Paragraph properties. `None` means "not set here".
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ParaProps {
    /// The paragraph style ID.
    pub style: Option<String>,
    /// Alignment.
    pub alignment: Option<Alignment>,
    /// The kashidas of the alignment, which `w:jc` sets with it.
    pub kashidas: Option<Kashidas>,
    /// The text alignment, the vertical alignment of the characters of the lines
    /// (`w:textAlignment`), with the part that sets it.
    pub text_alignment: Option<SetIn<TextAlignment>>,
    /// Whether the text direction (`w:textDirection`, ECMA-376 Part 1, 17.3.1.41) turns the
    /// text ([`crate::table::turns_text`]), with the part that sets it. [MS-OI29500] 2.1.63
    /// says that Word uses it only for a paragraph in a frame, and Word for Windows's pages
    /// show paragraphs elsewhere upright; F-Office lays out every paragraph upright, and the
    /// layout warns of a turned one in a frame.
    pub text_direction: Option<SetIn<bool>>,
    /// Space above the paragraph.
    pub before: Option<Length>,
    /// Space below the paragraph.
    pub after: Option<Length>,
    /// Space above the paragraph in hundredths of a line (`w:beforeLines`).
    pub(crate) before_lines: SpacingLines,
    /// Space below the paragraph in hundredths of a line (`w:afterLines`).
    pub(crate) after_lines: SpacingLines,
    /// Line spacing.
    pub line: Option<LineSpacing>,
    /// Left indent.
    pub indent_left: Option<Length>,
    /// Right indent.
    pub indent_right: Option<Length>,
    /// First line indent; negative for a hanging indent.
    pub indent_first: Option<Length>,
    /// Ignore spacing between paragraphs of the same style.
    pub contextual_spacing: Option<bool>,
    /// Whether the paragraph runs from right to left (`w:bidi`).
    pub bidi: Option<bool>,
    /// Whether the lines follow the document grid of the section (`w:snapToGrid`), which
    /// they do by default.
    pub snap_to_grid: Option<bool>,
    /// Whether East Asian line breaking keeps some characters off the start and the end of a
    /// line (`w:kinsoku`), which it does by default.
    pub kinsoku: Option<bool>,
    /// Whether Latin and Korean text wraps at word boundaries (`w:wordWrap`), which it does by
    /// default.
    pub word_wrap: Option<bool>,
    /// Whether a punctuation mark of East Asian text that does not fit at the end of a line
    /// may stand past it (`w:overflowPunct`, hanging punctuation), which it may by default.
    /// F-Office hangs no mark and warns where Word would hang one.
    pub overflow_punct: Option<SetIn<bool>>,
    /// Keep a first or a last line from standing alone on a page (`w:widowControl`).
    pub widow_control: Option<bool>,
    /// Keep the paragraph on the page of the next paragraph's start (`w:keepNext`).
    pub keep_next: Option<bool>,
    /// Add space between East Asian characters and Latin letters (`w:autoSpaceDE`).
    pub auto_space_latin: Option<bool>,
    /// Add space between East Asian characters and digits (`w:autoSpaceDN`).
    pub auto_space_digits: Option<bool>,
    /// Keep all lines of the paragraph on one page (`w:keepLines`).
    pub keep_lines: Option<bool>,
    /// Leave the paragraph's lines out of the section's line numbers
    /// (`w:suppressLineNumbers`).
    pub suppress_line_numbers: Option<bool>,
    /// Keep the words of the paragraph whole under the document's automatic hyphenation
    /// (`w:suppressAutoHyphens`).
    pub suppress_auto_hyphens: Option<bool>,
    /// Start the paragraph on a new page (`w:pageBreakBefore`).
    pub page_break_before: Option<bool>,
    /// Whether the paragraph is the empty last paragraph of a section that the next section
    /// follows on a new page, which stays on its page even where it does not fit.
    pub section_end: Option<bool>,
    /// Whether the paragraph is a continuous section end: the empty last paragraph of a
    /// section of one column before a continuous section, after a paragraph of its section,
    /// which holds nothing or only bookmarks, as the quirk `ContinuousSectionEnd` reads it.
    pub continuous_end: Option<bool>,
    /// Whether the paragraph ends a single-column section before a continuous section in a
    /// compatibility mode that drops a trailing empty line after a line break (`w:br`, `w:cr`,
    /// or clearing break) together with its space after.
    pub(crate) continuous_break_end: Option<bool>,
    /// Let Word choose the space above, as for HTML.
    pub before_auto: Option<bool>,
    /// Let Word choose the space below, as for HTML.
    pub after_auto: Option<bool>,
    /// How the paragraph's automatic spacing reads: as HTML user agents space paragraphs
    /// where it is not set. Not a property of the file: the layout sets it from the document's
    /// settings and the target.
    pub html_auto_spacing: Option<HtmlAutoSpacing>,
    /// Whether the left and right indents are the inside and outside indents of mirrored
    /// pages (`w:mirrorIndents`, ECMA-376 Part 1, 17.3.1.18), which they are not by default.
    /// F-Office keeps them on the left and the right, and the layout warns of a paragraph whose
    /// two indents differ.
    pub mirror_indents: Option<SetIn<bool>>,
    /// Whether the right indent moves to the section's grid of characters
    /// (`w:adjustRightInd`, 17.3.1.1), which it does by default. F-Office keeps the right
    /// indent as set, and the layout warns of a paragraph in a section with a grid of
    /// characters.
    pub adjust_right_indent: Option<SetIn<bool>>,
    /// Whether the paragraph's frame must not overlap other frames (`w:suppressOverlap`,
    /// 17.3.1.36), which it may by default. F-Office does not move such a frame, and the layout
    /// warns of one that overlaps another frame of its page.
    pub suppress_overlap: Option<SetIn<bool>>,
    /// Whether the paragraph's lines take part in the tight wrap of its text box
    /// (`w:textboxTightWrap` other than `none`, 17.3.1.40), which they do not by default.
    /// F-Office wraps text around the box's rectangle, and the layout warns of such a
    /// paragraph in a text box.
    pub tight_wrap: Option<SetIn<bool>>,
    /// The HTML div that holds the paragraph (`w:divId`, 17.3.1.10), by its ID in the web
    /// settings part. Word adds the margins and borders of the div and of its outer divs to
    /// the paragraph; F-Office leaves them out, and the layout warns of a paragraph of a div
    /// that has any ([`crate::web_settings::HtmlDivs`]).
    pub div: Option<SetIn<i64>>,
    /// The outline level (`w:outlineLvl`, ECMA-376 Part 1, 17.3.1.20): 0 for a heading of the
    /// top level to 8, and 9 for body text, which has no level. Only the outline of a viewer
    /// reads it.
    pub outline_level: Option<u8>,
    /// Custom tab settings, sorted by position. A tab clear removes an inherited stop; after
    /// the cascade only the clears of the document's defaults stay, with no stop to remove
    /// ([`ParaProps::tab_stops`]).
    pub tabs: Vec<TabMark>,
    /// Paragraph borders. `None` means "not set here". They are boxed, since most paragraphs
    /// have none.
    pub borders: Option<Box<Borders>>,
    /// The sides of the paragraph's borders by name, which the cascade overlays side by side
    /// ([`NamedSides`]); `None` where no level names a side. Boxed, as `borders` is.
    pub named_sides: Option<Box<NamedSides>>,
    /// The fill behind the paragraph (`w:shd`).
    pub shading: Option<Color>,
    /// The list reference (`w:numId`): the list of the paragraph, or the removal of its
    /// styles' list.
    pub numbering: Option<ListRef>,
    /// The list level (`w:ilvl`), which a style can set apart from the list, as one style
    /// names the list and a style based on it names the level.
    pub numbering_level: Option<ListLevel>,
    /// The frame that takes the paragraph out of the text flow (`w:framePr`). It is boxed,
    /// since most paragraphs have none.
    pub frame: Option<Box<FramePr>>,
    /// Properties of the paragraph mark, which size an empty paragraph.
    pub mark: RunProps,
    /// The character style of the paragraph mark (`w:rStyle` in `w:pPr/w:rPr`). Few
    /// paragraphs have one, so it is a boxed text, which keeps paragraphs small.
    pub mark_style: Option<Box<str>>,
    /// The tracked change of the paragraph mark (`w:ins` or `w:del` in `w:pPr/w:rPr`).
    pub mark_change: Option<MarkChange>,
    /// The direct properties before a tracked change of them (`w:pPrChange/w:pPr`), which
    /// number the paragraph in the original text.
    pub original: Option<Box<ParaProps>>,
}

/// A tracked change of a paragraph mark.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MarkChange {
    /// The mark is new (`w:ins` or `w:moveTo`), so the paragraph is not in the original text.
    Inserted,
    /// The mark is gone (`w:del` or `w:moveFrom`), so the paragraph is not in the new text.
    Deleted,
}

impl ParaProps {
    /// The paragraph's borders, when it has any.
    #[must_use]
    pub fn borders(&self) -> Option<Borders> {
        self.borders.as_deref().copied()
    }

    /// Takes the paragraph's borders side by side, each side from the nearest level of the
    /// cascade that names it ([`NamedSides::borders`]), in place of the whole `w:pBdr` of the
    /// nearest level that has one, for a target whose paragraphs take them so
    /// (`BorderSides::EachSide`).
    pub fn take_border_sides(&mut self) {
        self.borders = self
            .named_sides
            .as_deref()
            .map(|sides| Box::new(sides.borders()));
    }

    /// Makes the paragraph's frame, unless it is a drop cap, one that makes no frame
    /// ([`FrameMark::Plain`]), so that the paragraph stays in the flow, for a paragraph in a
    /// table cell on a target whose cells hold no frames (`CellFrames::InFlow`).
    pub(crate) fn plain_cell_frame(&mut self) {
        if let Some(frame) = self.frame.as_deref_mut().filter(|frame| !frame.drop_cap) {
            frame.mark = FrameMark::Plain;
        }
    }

    /// Drops the top and bottom [none borders](super::Border::none) of the paragraph's borders,
    /// for a target whose paragraphs drop them (`NoneBorders::Dropped`).
    pub fn drop_none_borders(&mut self) {
        if let Some(borders) = self.borders.as_deref_mut() {
            *borders = borders.without_none();
        }
    }

    /// Cuts the line of each side of the paragraph's borders to whole twips, for a target that
    /// holds the width of a paragraph's border in whole twips (`BorderWidthUnit::WholeTwips`).
    pub fn cut_border_widths(&mut self) {
        if let Some(borders) = self.borders.as_deref_mut() {
            *borders = borders.in_whole_twips();
        }
    }

    /// Draws each side of a 3-D style of the paragraph's borders as one line, for a target that
    /// draws them so (`ThreeDBorders::OneLine`).
    pub fn draw_three_d_borders_as_lines(&mut self) {
        if let Some(borders) = self.borders.as_deref_mut() {
            *borders = borders.as_one_line();
        }
    }

    /// Drops the side of the paragraph's borders between the paragraphs of a group, for a target
    /// that does not draw it (`BetweenBorders::Dropped`), and returns whether the side had a line.
    pub fn drop_between_border(&mut self) -> bool {
        self.borders
            .as_deref_mut()
            .and_then(|borders| borders.between.take())
            .is_some()
    }

    /// Drops the paragraph's borders, for the empty paragraph that ends a section before a new
    /// page on a target that draws no border for it (`SectionEndBorders::Dropped`).
    pub fn drop_borders(&mut self) {
        self.borders = None;
    }

    /// The indents of the left and the right side of the page, and whether the first line's
    /// indent lies at the right. `w:left` (`w:start`) indents the side where the paragraph's
    /// lines start and `w:right` (`w:end`) the other side, so the two swap sides in a
    /// right-to-left paragraph (`w:bidi`), and its first line's indent lies at the right.
    #[must_use]
    pub fn side_indents(&self) -> (Length, Length, bool) {
        let start = self.indent_left.unwrap_or(Length::ZERO);
        let end = self.indent_right.unwrap_or(Length::ZERO);
        if self.flags().bidi {
            (end, start, true)
        } else {
            (start, end, false)
        }
    }

    /// Overlays `other` on `self`: every property set in `other` wins. It names each field of
    /// `other`, so that a new field does not compile until it is overlaid here.
    pub fn apply(&mut self, other: &Self) {
        let Self {
            style,
            alignment,
            kashidas,
            text_alignment,
            text_direction,
            before,
            after,
            before_lines,
            after_lines,
            line,
            indent_left,
            indent_right,
            indent_first,
            contextual_spacing,
            bidi,
            snap_to_grid,
            kinsoku,
            word_wrap,
            overflow_punct,
            widow_control,
            keep_next,
            auto_space_latin,
            auto_space_digits,
            keep_lines,
            suppress_line_numbers,
            suppress_auto_hyphens,
            page_break_before,
            section_end,
            continuous_end,
            continuous_break_end,
            before_auto,
            after_auto,
            html_auto_spacing,
            mirror_indents,
            adjust_right_indent,
            suppress_overlap,
            tight_wrap,
            div,
            outline_level,
            tabs,
            borders,
            named_sides,
            shading,
            numbering,
            numbering_level,
            frame,
            mark,
            mark_style,
            mark_change,
            // The properties before a tracked change of them belong to the direct properties
            // that hold them, and the cascade does not overlay them.
            original: _,
        } = other;
        overlay(&mut self.style, style.as_ref());
        overlay(&mut self.alignment, alignment.as_ref());
        overlay(&mut self.kashidas, kashidas.as_ref());
        overlay(&mut self.text_alignment, text_alignment.as_ref());
        overlay(&mut self.text_direction, text_direction.as_ref());
        self.apply_spacing(other);
        let _ = (before, after, before_lines, after_lines, line);
        self.apply_indents(other);
        let _ = (indent_left, indent_right, indent_first);
        self.apply_flag_fields(other);
        let _ = (
            contextual_spacing,
            snap_to_grid,
            kinsoku,
            word_wrap,
            overflow_punct,
            bidi,
            widow_control,
            keep_next,
            auto_space_latin,
            auto_space_digits,
            keep_lines,
            suppress_line_numbers,
            suppress_auto_hyphens,
            page_break_before,
            section_end,
            continuous_end,
            continuous_break_end,
            before_auto,
            after_auto,
            html_auto_spacing,
            mirror_indents,
            adjust_right_indent,
            suppress_overlap,
            tight_wrap,
        );
        overlay(&mut self.div, div.as_ref());
        overlay(&mut self.outline_level, outline_level.as_ref());
        overlay(&mut self.borders, borders.as_ref());
        NamedSides::overlay(&mut self.named_sides, named_sides.as_deref());
        overlay(&mut self.shading, shading.as_ref());
        overlay(&mut self.numbering, numbering.as_ref());
        overlay(&mut self.numbering_level, numbering_level.as_ref());
        FramePr::overlay(&mut self.frame, frame.as_deref());
        self.apply_tabs(tabs);
        self.mark.apply(mark);
        overlay(&mut self.mark_style, mark_style.as_ref());
        overlay(&mut self.mark_change, mark_change.as_ref());
    }

    /// Overlays paragraph and line spacing fields from `other`.
    fn apply_spacing(&mut self, other: &Self) {
        overlay(&mut self.before, other.before.as_ref());
        overlay(&mut self.after, other.after.as_ref());
        self.before_lines.overlay(other.before_lines);
        self.after_lines.overlay(other.after_lines);
        overlay(&mut self.line, other.line.as_ref());
    }

    /// Overlays the indents of `other` onto `self`. `w:numId="0"` resets inherited left and
    /// first-line indents at any layer of the cascade, even when no ancestor names a list, while
    /// preserving right indent and `other`'s own `w:ind` values.
    fn apply_indents(&mut self, other: &Self) {
        if other.numbering == Some(ListRef::Removed) {
            self.indent_left = None;
            self.indent_first = None;
        }
        overlay(&mut self.indent_left, other.indent_left.as_ref());
        overlay(&mut self.indent_right, other.indent_right.as_ref());
        overlay(&mut self.indent_first, other.indent_first.as_ref());
    }

    /// Overlays the on/off flag fields of `other` onto `self`.
    fn apply_flag_fields(&mut self, other: &Self) {
        overlay(
            &mut self.contextual_spacing,
            other.contextual_spacing.as_ref(),
        );
        overlay(&mut self.snap_to_grid, other.snap_to_grid.as_ref());
        overlay(&mut self.kinsoku, other.kinsoku.as_ref());
        overlay(&mut self.word_wrap, other.word_wrap.as_ref());
        overlay(&mut self.overflow_punct, other.overflow_punct.as_ref());
        overlay(&mut self.bidi, other.bidi.as_ref());
        overlay(&mut self.widow_control, other.widow_control.as_ref());
        overlay(&mut self.keep_next, other.keep_next.as_ref());
        overlay(&mut self.auto_space_latin, other.auto_space_latin.as_ref());
        overlay(
            &mut self.auto_space_digits,
            other.auto_space_digits.as_ref(),
        );
        overlay(&mut self.keep_lines, other.keep_lines.as_ref());
        overlay(
            &mut self.suppress_line_numbers,
            other.suppress_line_numbers.as_ref(),
        );
        overlay(
            &mut self.suppress_auto_hyphens,
            other.suppress_auto_hyphens.as_ref(),
        );
        overlay(
            &mut self.page_break_before,
            other.page_break_before.as_ref(),
        );
        overlay(&mut self.section_end, other.section_end.as_ref());
        overlay(&mut self.continuous_end, other.continuous_end.as_ref());
        overlay(
            &mut self.continuous_break_end,
            other.continuous_break_end.as_ref(),
        );
        overlay(&mut self.before_auto, other.before_auto.as_ref());
        overlay(&mut self.after_auto, other.after_auto.as_ref());
        overlay(
            &mut self.html_auto_spacing,
            other.html_auto_spacing.as_ref(),
        );
        overlay(&mut self.mirror_indents, other.mirror_indents.as_ref());
        overlay(
            &mut self.adjust_right_indent,
            other.adjust_right_indent.as_ref(),
        );
        overlay(&mut self.suppress_overlap, other.suppress_overlap.as_ref());
        overlay(&mut self.tight_wrap, other.tight_wrap.as_ref());
    }

    /// Overlays the tab settings `tabs` on the tab settings: each setting replaces the one at
    /// its position, and a clear only removes it.
    fn apply_tabs(&mut self, tabs: &[TabMark]) {
        for mark in tabs {
            self.tabs.retain(|t| t.position() != mark.position());
            if let TabMark::Stop(_) = mark {
                self.tabs.push(*mark);
            }
        }
        self.tabs.sort_by_key(TabMark::position);
    }

    /// The custom tab stops, by position: the settings without their tab clears.
    pub fn tab_stops(&self) -> impl Iterator<Item = TabStop> + '_ {
        self.tabs.iter().filter_map(TabMark::stop)
    }

    /// The space above the paragraph after automatic spacing.
    #[must_use]
    pub fn space_before(&self) -> Length {
        let automatic = self.html_auto_spacing.unwrap_or_default().automatic();
        auto_or(self.flags().before_auto, self.before, automatic)
    }

    /// The space below the paragraph after automatic spacing.
    #[must_use]
    pub fn space_after(&self) -> Length {
        let automatic = self.html_auto_spacing.unwrap_or_default().automatic();
        auto_or(self.flags().after_auto, self.after, automatic)
    }

    /// Resolves non-zero `w:beforeLines` and `w:afterLines` against `unit` (the section's
    /// document-grid line pitch on a typed grid, or 12 pt otherwise), overriding `before` and
    /// `after` on each side where the line count is positive.
    pub(crate) fn resolve_line_spacing(&mut self, unit: Length) {
        if let Some(lines) = self.before_lines.positive() {
            self.before = Some(lines_to_length(unit, lines));
        }
        if let Some(lines) = self.after_lines.positive() {
            self.after = Some(lines_to_length(unit, lines));
        }
    }

    /// The on and off settings of the paragraph, each with its default where it is not set.
    /// After the cascade, these are the paragraph's settings; no other place applies their
    /// defaults.
    #[must_use]
    pub(crate) fn flags(&self) -> ParaFlags {
        let on = |value: Option<bool>| value.unwrap_or(true);
        let off = |value: Option<bool>| value.unwrap_or(false);
        ParaFlags {
            contextual_spacing: off(self.contextual_spacing),
            bidi: off(self.bidi),
            snap_to_grid: on(self.snap_to_grid),
            kinsoku: on(self.kinsoku),
            word_wrap: on(self.word_wrap),
            overflow_punct: on(value_of(self.overflow_punct.as_ref())),
            widow_control: on(self.widow_control),
            keep_next: off(self.keep_next),
            auto_space_latin: on(self.auto_space_latin),
            auto_space_digits: on(self.auto_space_digits),
            keep_lines: off(self.keep_lines),
            suppress_line_numbers: off(self.suppress_line_numbers),
            suppress_auto_hyphens: off(self.suppress_auto_hyphens),
            page_break_before: off(self.page_break_before),
            section_end: off(self.section_end),
            continuous_end: off(self.continuous_end),
            continuous_break_end: off(self.continuous_break_end),
            before_auto: off(self.before_auto),
            after_auto: off(self.after_auto),
            mirror_indents: off(value_of(self.mirror_indents.as_ref())),
            adjust_right_indent: on(value_of(self.adjust_right_indent.as_ref())),
            suppress_overlap: off(value_of(self.suppress_overlap.as_ref())),
            tight_wrap: off(value_of(self.tight_wrap.as_ref())),
        }
    }

    /// Reads a `w:pPr` element.
    pub(crate) fn read(reader: &mut PartReader, ppr: NodeId) -> Self {
        let mut props = Self::default();
        props.read_into(reader, ppr);
        props
    }

    /// Reads the children of a `w:pPr` element into `self`, letting later siblings override
    /// earlier ones.
    pub(crate) fn read_into(&mut self, reader: &mut PartReader, ppr: NodeId) {
        for child in reader.doc.child_elements(ppr) {
            self.read_child(reader, child);
        }
    }

    /// The alignment of `w:jc` and the kashidas that come with it.
    fn read_alignment(&mut self, reader: &mut PartReader, child: NodeId) {
        let jc = reader.enumeration(child, "val", JC).flatten();
        self.alignment = jc.map(|(alignment, _)| alignment);
        self.kashidas = jc.map(|(_, kashidas)| kashidas);
    }

    fn read_child(&mut self, reader: &mut PartReader, child: NodeId) {
        let doc = reader.doc;
        let Some(element) = doc.element(child) else {
            return;
        };
        match element.name.local {
            "pStyle" => self.style = val(doc, child).map(str::to_owned),
            "jc" => self.read_alignment(reader, child),
            "textAlignment" => {
                self.text_alignment = reader
                    .enumeration(child, "val", TEXT_ALIGNMENT)
                    .map(|alignment| SetIn::read(alignment, reader));
            }
            "textDirection" => {
                self.text_direction = reader
                    .or_missing(child, "val", crate::table::turns_text)
                    .map(|turned| SetIn::read(turned, reader));
            }
            "spacing" => self.read_spacing(reader, child),
            "ind" => self.read_indent(reader, child),
            "tabs" => self.tabs = read_tabs(reader, child),
            "pBdr" => {
                let (borders, sides) = read_borders(reader, child);
                self.borders = Some(Box::new(borders));
                self.named_sides = Some(Box::new(sides));
            }
            "shd" => self.shading = read_shading(reader, child),
            "numPr" => {
                let (list, level) = read_numbering(reader, child);
                self.numbering = list.or(self.numbering.take());
                self.numbering_level = level.or(self.numbering_level);
            }
            "framePr" => self.frame = Some(Box::new(FramePr::read(reader, child))),
            "pPrChange" => {
                self.original = doc
                    .child(child, W, "pPr")
                    .map(|ppr| Box::new(Self::read(reader, ppr)));
            }
            "contextualSpacing" => self.contextual_spacing = Some(off_also_for_none(doc, child)),
            "snapToGrid" => self.snap_to_grid = Some(off_also_for_none(doc, child)),
            "kinsoku" => self.kinsoku = Some(off_also_for_none(doc, child)),
            "wordWrap" => self.word_wrap = Some(off_also_for_none(doc, child)),
            "overflowPunct" => {
                self.overflow_punct = Some(SetIn::read(off_also_for_none(doc, child), reader));
            }
            "bidi" => self.bidi = Some(off_also_for_none(doc, child)),
            "widowControl" => self.widow_control = Some(off_also_for_none(doc, child)),
            "keepNext" => self.keep_next = Some(off_also_for_none(doc, child)),
            "autoSpaceDE" => self.auto_space_latin = Some(off_also_for_none(doc, child)),
            "autoSpaceDN" => self.auto_space_digits = Some(off_also_for_none(doc, child)),
            "keepLines" => self.keep_lines = Some(off_also_for_none(doc, child)),
            "suppressLineNumbers" => {
                self.suppress_line_numbers = Some(off_also_for_none(doc, child));
            }
            "suppressAutoHyphens" => {
                self.suppress_auto_hyphens = Some(off_also_for_none(doc, child));
            }
            "pageBreakBefore" => self.page_break_before = Some(off_also_for_none(doc, child)),
            "mirrorIndents" => {
                self.mirror_indents = Some(SetIn::read(off_also_for_none(doc, child), reader));
            }
            "adjustRightInd" => {
                self.adjust_right_indent = Some(SetIn::read(off_also_for_none(doc, child), reader));
            }
            "suppressOverlap" => {
                self.suppress_overlap = Some(SetIn::read(off_also_for_none(doc, child), reader));
            }
            "textboxTightWrap" => {
                self.tight_wrap = reader
                    .enumeration(child, "val", TIGHT_WRAP)
                    .map(|wraps| SetIn::read(wraps, reader));
            }
            "divId" => {
                self.div = reader
                    .number(child, "val", numbers::ANY)
                    .map(|div| SetIn::read(div, reader));
            }
            "outlineLvl" => {
                self.outline_level =
                    reader.number(child, "val", 0..=i64::from(params::BODY_TEXT_OUTLINE_LEVEL));
            }
            "rPr" => {
                self.mark = RunProps::read(reader, child);
                self.mark_style = doc
                    .child(child, W, "rStyle")
                    .and_then(|s| doc.attribute(s, Some(W), "val"))
                    .map(Box::from);
                let changed =
                    |names: [&str; 2]| names.iter().any(|n| doc.child(child, W, n).is_some());
                self.mark_change = if changed(["del", "moveFrom"]) {
                    Some(MarkChange::Deleted)
                } else if changed(["ins", "moveTo"]) {
                    Some(MarkChange::Inserted)
                } else {
                    None
                };
            }
            _ => {}
        }
    }

    fn read_spacing(&mut self, reader: &mut PartReader, node: NodeId) {
        let doc = reader.doc;
        if let Some(before) = reader.twips(node, "before") {
            self.before = Some(before);
        }
        if let Some(after) = reader.twips(node, "after") {
            self.after = Some(after);
        }
        self.read_spacing_lines(reader, node);
        let flag = |name| {
            doc.attribute(node, Some(W), name)
                .map(|v| on_off::read(v) != Some(false))
        };
        if let Some(auto) = flag("beforeAutospacing") {
            self.before_auto = Some(auto);
        }
        if let Some(auto) = flag("afterAutospacing") {
            self.after_auto = Some(auto);
        }
        let rule = reader
            .enumeration(node, "lineRule", LINE_RULE)
            .unwrap_or(LineRule::Auto);
        // The value is in twips or a universal measure such as `12.95pt`, which a Strict
        // document has (ECMA-376 Part 1, 17.3.1.33 and 22.9.2.15); for the rule `auto`, its
        // twips are 240ths of a line.
        if let Some(line) = reader.line(node, "line") {
            self.line = match rule {
                LineRule::Exact => Length::from_twips(line.abs()).map(LineSpacing::Exact),
                LineRule::AtLeast => Length::from_twips(line).map(LineSpacing::AtLeast),
                LineRule::Auto => Some(LineSpacing::Auto(reader.bounded_line_multiple(line))),
            };
        }
    }

    fn read_spacing_lines(&mut self, reader: &mut PartReader, node: NodeId) {
        if let Some(before) = reader.number::<i32>(node, "beforeLines", numbers::NOT_NEGATIVE) {
            self.before_lines = SpacingLines::of(before);
        }
        if let Some(after) = reader.number::<i32>(node, "afterLines", numbers::NOT_NEGATIVE) {
            self.after_lines = SpacingLines::of(after);
        }
    }

    fn read_indent(&mut self, reader: &mut PartReader, node: NodeId) {
        let left = reader
            .twips(node, "left")
            .or_else(|| reader.twips(node, "start"));
        let right = reader
            .twips(node, "right")
            .or_else(|| reader.twips(node, "end"));
        if left.is_some() {
            self.indent_left = left;
        }
        if right.is_some() {
            self.indent_right = right;
        }
        if let Some(first) = reader.twips(node, "firstLine") {
            self.indent_first = Some(first);
        }
        if let Some(hanging) = reader.twips(node, "hanging") {
            self.indent_first = Length::ZERO.checked_sub(hanging);
        }
    }
}

/// A list reference (`w:numId` of a paragraph's or a style's `w:numPr`): the list instance whose
/// paragraphs the paragraph joins, or the removal of the list that its styles give it.
/// ECMA-376 17.9.18 has the ID 0 never point to a list instance and only remove the numbering,
/// so an instance that a numbering part defines with the ID 0 numbers no paragraph.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ListRef {
    /// The ID 0: the paragraph is in no list, also when one of its styles names a list.
    Removed,
    /// The ID of a list instance (`w:num w:numId`).
    Id(NonZeroU32),
}

impl ListRef {
    /// The list reference of the list ID `id`.
    #[must_use]
    pub fn of(id: u32) -> Self {
        NonZeroU32::new(id).map_or(Self::Removed, Self::Id)
    }

    /// The ID of the list instance, or `None` when the reference removes the list.
    #[must_use]
    pub const fn id(self) -> Option<NonZeroU32> {
        match self {
            Self::Removed => None,
            Self::Id(id) => Some(id),
        }
    }
}

/// The list reference and the level of `w:numPr`, each of which may be missing. Both read as
/// numbers through the one reader (`ST_DecimalNumber`), and the level as the part's reader
/// reads a list level.
fn read_numbering(reader: &mut PartReader, node: NodeId) -> (Option<ListRef>, Option<ListLevel>) {
    let doc = reader.doc;
    let list = doc
        .child(node, W, "numId")
        .and_then(|n| reader.number(n, "val", numbers::NOT_NEGATIVE))
        .map(ListRef::of);
    let ilvl = doc
        .child(node, W, "ilvl")
        .and_then(|n| read_list_level(reader, n));
    (list, ilvl)
}

/// A paragraph's level in its list (`w:ilvl` of `w:numPr`), as the document's target reads
/// its value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ListLevel {
    /// The level of this index, which counts from 0.
    At(usize),
    /// No level: the paragraph shows no number and takes no property of its list's levels.
    Unnumbered,
}

impl ListLevel {
    /// The level of a paragraph that names a list and no level.
    pub const FIRST: Self = Self::At(0);

    /// The index of the level, or `None` for a paragraph without a number.
    #[must_use]
    pub const fn index(self) -> Option<usize> {
        match self {
            Self::At(index) => Some(index),
            Self::Unnumbered => None,
        }
    }
}

/// The list level of the value of `node`'s `w:val`, read as the part's reader reads a list
/// level.
fn read_list_level(reader: &mut PartReader, node: NodeId) -> Option<ListLevel> {
    reader.list_levels().read(reader, node)
}

/// Reads `w:tabs`, sorted by position. A bar makes no mark: it neither sets a stop nor clears
/// one.
fn read_tabs(reader: &mut PartReader, node: NodeId) -> Vec<TabMark> {
    let doc = reader.doc;
    let mut tabs: Vec<TabMark> = doc
        .child_elements(node)
        .filter(|tab| doc.is(*tab, W, "tab"))
        .filter_map(|tab| {
            let position = reader.twips(tab, "pos")?;
            let setting = reader
                .enumeration(tab, "val", TAB_KIND)
                .unwrap_or(TabSetting::Stop(TabKind::Left));
            let leader = reader.enumeration(tab, "leader", TAB_LEADER).flatten();
            match setting {
                TabSetting::Stop(kind) => Some(TabMark::Stop(TabStop {
                    position,
                    kind,
                    leader,
                })),
                TabSetting::Clear => Some(TabMark::Clear(position)),
                TabSetting::Bar => None,
            }
        })
        .collect();
    tabs.sort_by_key(TabMark::position);
    tabs
}

/// The `automatic` space where automatic spacing is on, whatever the given value says.
fn auto_or(auto: bool, given: Option<Length>, automatic: Length) -> Length {
    if auto {
        automatic
    } else {
        given.unwrap_or(Length::ZERO)
    }
}

/// How a document reads automatic paragraph spacing (`w:beforeAutospacing`,
/// `w:afterAutospacing`): its HTML auto spacing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HtmlAutoSpacing {
    /// As HTML user agents space paragraphs: 14 pt above and below, the larger of two spaces
    /// that meet, and no automatic space at the top of the document, at the top and end of a
    /// table cell, or between two paragraphs of one list.
    #[default]
    Html,
    /// As fixed values, which the compatibility option `w:doNotUseHTMLParagraphAutoSpacing`
    /// asks for (ECMA-376 Part 4, 14.8.3.15): 5 pt above and below, the sum of two spaces that
    /// meet, and every automatic space kept.
    Fixed,
}

impl HtmlAutoSpacing {
    /// The reading where the option `w:doNotUseHTMLParagraphAutoSpacing` is set (`set`) or not.
    #[must_use]
    pub const fn of(set: bool) -> Self {
        if set { Self::Fixed } else { Self::Html }
    }

    /// The space that automatic spacing gives above or below a paragraph.
    #[must_use]
    pub const fn automatic(self) -> Length {
        Length::from_units(
            match self {
                Self::Html => params::AUTOMATIC_SPACING,
                Self::Fixed => params::FIXED_AUTOMATIC_SPACING,
            } * Length::UNITS_PER_TWIP,
        )
    }

    /// The space between two paragraphs from the space `after` the first and the space
    /// `before` the second: the larger of the two, or their sum in the fixed reading.
    #[must_use]
    pub fn space_between(self, after: Length, before: Length) -> Length {
        match self {
            Self::Html => after.max(before),
            Self::Fixed => after + before,
        }
    }

    /// Whether automatic spacing is left out above the first paragraph of the document, at the
    /// top and end of a table cell and between two paragraphs of one list.
    #[must_use]
    pub const fn drops_automatic_spacing(self) -> bool {
        matches!(self, Self::Html)
    }
}

/// The rule of a paragraph's line spacing (`ST_LineSpacingRule`): a multiple of single
/// spacing, an exact height or a least height.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum LineRule {
    Auto,
    Exact,
    AtLeast,
}

/// `ST_LineSpacingRule`; a missing rule is `auto`.
pub(super) const LINE_RULE: &Values<LineRule> = &Values::new(&[
    own("auto", LineRule::Auto),
    own("exact", LineRule::Exact),
    own("atLeast", LineRule::AtLeast),
]);

/// Optional `w:beforeLines` / `w:afterLines` count in hundredths of a line, stored in two bytes
/// (`0` = absent, `n + 1` = `Some(n)`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct SpacingLines(u16);

impl SpacingLines {
    /// Stores a non-negative line count (clamped to `u16::MAX - 1`).
    fn of(lines: i32) -> Self {
        let clamped = u16::try_from(lines.max(0))
            .unwrap_or(u16::MAX)
            .min(u16::MAX - 1);
        Self(clamped + 1)
    }

    /// Replaces `self` when `other` is set (including explicit `0`, which clears inherited lines).
    const fn overlay(&mut self, other: Self) {
        if other.0 != 0 {
            self.0 = other.0;
        }
    }

    /// Returns the positive hundredths-of-a-line count, or `None` when absent or `0`.
    const fn positive(self) -> Option<i32> {
        if self.0 > 1 {
            Some((self.0 - 1) as i32)
        } else {
            None
        }
    }
}

/// Scales `unit` (the height of one line, in twips) by `lines` hundredths of a line, truncating
/// toward zero to whole twips.
fn lines_to_length(unit: Length, lines: i32) -> Length {
    let twip = i128::from(Length::UNITS_PER_TWIP);
    let unit_twips = i128::from(unit.units().max(0)) / twip;
    let twips = (unit_twips * i128::from(lines.max(0))) / i128::from(PERCENT);
    let units = twips.saturating_mul(twip);
    Length::from_units(i64::try_from(units).unwrap_or(i64::MAX))
}