f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! The paragraphs and runs of a story: run content, symbols, tracked changes, inline drawings
//! and breaks.

use std::rc::Rc;

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

use super::links::{Hyperlink, LinkMark};
use super::{BufferOnly, Content, InlineDrawing, NoteId, Paragraph, Run, shown_branch};
use crate::ns::{MC, R, W, W14, W16SE, WP};
use crate::numbers;
use crate::on_off;
use crate::params::{
    HYPERLINK_FIELD_EXTRA_LENGTH, HYPERLINK_HISTORY_OFF_LENGTH, TEXT_BUFFER_MARK_LENGTH,
};
use crate::picture::Picture;
use crate::props::{
    Color, FontRef, ListRef, MathScript, ParaProps, RunProps, Strike, TabKind, Underline,
};
use crate::reader::PartReader;
use crate::source_span::SourceSpan;
use crate::warnings::{Drawing, Feature, Reason};

/// Reads a `w:p` element.
pub(super) fn read_paragraph(reader: &mut PartReader, node: NodeId) -> Paragraph {
    let doc = reader.doc;
    let mut paragraph = Paragraph {
        id: reader.paragraph_id(),
        props: ParaProps::default(),
        runs: Vec::new(),
        source: SourceSpan::of(doc, node),
    };
    for ppr in doc
        .child_elements(node)
        .filter(|child| doc.is(*child, W, "pPr"))
    {
        paragraph.props.read_into(reader, ppr);
        // A paragraph's properties belong to its mark, so a tracked change of them marks the
        // paragraph's last line, as a formatting change of the mark does.
        if doc.child(ppr, W, "pPrChange").is_some() {
            paragraph.props.mark.changed = Some(true);
        }
    }
    // A paragraph that holds only equations, or a display of them (`m:oMathPara`), is a
    // display, unless a list label, its own or its style's, stands before them: then its
    // equations are inline after the label, also those of an `m:oMathPara`.
    let alone = crate::math::holds_only_equations(doc, node);
    let display = alone || crate::math::is_display(doc, node);
    let labeled = display
        && reader
            .list_of(&paragraph.props)
            .and_then(ListRef::id)
            .is_some();
    let equations = if labeled {
        Equations::Inline
    } else if alone {
        Equations::Display
    } else {
        Equations::AsWritten
    };
    collect_runs(reader, node, equations, &mut paragraph.runs);
    // Word centers a display of equations, whatever the paragraph's alignment, unless the
    // display's justification puts it at the left or the right indent. A display stands
    // between the left and right indents, without the first-line or hanging indent.
    if display && !labeled {
        paragraph.props.alignment = Some(crate::math::display_alignment(reader, node));
        paragraph.props.indent_first = Some(Length::ZERO);
    }
    paragraph
}

/// A run that holds the start of a named bookmark (`w:bookmarkStart`).
pub(super) fn bookmark_run(doc: &Document, node: NodeId) -> Option<Run> {
    let name = doc.attribute(node, Some(W), "name")?;
    Some(Run {
        content: vec![Content::Bookmark(name.to_owned())],
        ..Run::default()
    })
}

/// How a paragraph sets the equations directly in it.
#[derive(Clone, Copy)]
enum Equations {
    /// An equation (`m:oMath`) inline and a display of equations (`m:oMathPara`) as one, as
    /// beside text and inside a hyperlink, a content control or another container.
    AsWritten,
    /// Every equation as a display: the paragraph holds only equations.
    Display,
    /// Every equation inline, also those of a display: a list label stands before them.
    Inline,
}

impl Equations {
    /// The script level at which an equation starts, or the equations of a display when
    /// `display`.
    fn script(self, display: bool) -> MathScript {
        match self {
            Self::AsWritten if display => MathScript::display(),
            Self::Display => MathScript::display(),
            Self::AsWritten | Self::Inline => MathScript::default(),
        }
    }
}

/// Collects runs, also from inside hyperlinks, smart tags and content controls. The equations
/// directly in `node` start as `equations` says, and those further in as written. An equation
/// right after another one, with nothing drawn between them, goes on from it.
fn collect_runs(reader: &mut PartReader, node: NodeId, equations: Equations, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    let nested = |reader: &mut PartReader, child, runs: &mut Vec<Run>| {
        collect_runs(reader, child, Equations::AsWritten, runs);
    };
    let mut after_equation = false;
    for child in doc.child_elements(node) {
        let local = doc.element(child).map_or("", |e| e.name.local);
        if let Some(wrapper) = RunWrapper::of(local) {
            collect_wrapped(reader, (child, local), wrapper, runs);
            after_equation = false;
            continue;
        }
        let drawn = runs.len();
        match local {
            "r" => runs.extend(read_run(reader, child)),
            // A break outside a run still breaks the line.
            "br" => runs.push(Run {
                content: vec![read_break(reader, child)],
                ..Run::default()
            }),
            "AlternateContent" if doc.is(child, MC, "AlternateContent") => {
                if let Some(branch) = shown_branch(reader, child) {
                    nested(reader, branch, runs);
                }
            }
            "bookmarkStart" => runs.extend(bookmark_run(doc, child)),
            "oMath" | "oMathPara" if doc.is(child, crate::ns::M, local) => {
                let script = equations.script(local == "oMathPara");
                crate::math::read(reader, child, (script, after_equation), runs);
                after_equation = local == "oMath";
                continue;
            }
            "fldSimple" => {
                let code = doc.attribute(child, Some(W), "instr").unwrap_or("");
                let marker = |content: Vec<Content>| Run {
                    content,
                    ..Run::default()
                };
                let mut begin = vec![Content::FieldBegin];
                begin.extend(field_locked(doc, child).then_some(Content::FieldLock));
                begin.extend([Content::FieldCode(code.to_owned()), Content::FieldSeparate]);
                runs.push(marker(begin));
                nested(reader, child, runs);
                runs.push(marker(vec![Content::FieldEnd]));
            }
            // Text in a bidirectional embedding or override is left out with a warning.
            "dir" | "bdo" if doc.is(child, W, local) => {
                reader.feature_not_supported(Feature::BidirectionalEmbedding);
            }
            // The elements that draw nothing are left out: the properties of a paragraph and of
            // the containers above (`w:pPr`, `w:sdtPr`, `w:sdtEndPr`, `w:customXmlPr`,
            // `w:smartTagPr`, `w:fldData`), the marks of proofing (`w:proofErr`) and of
            // permissions (`w:permStart`, `w:permEnd`), and the starts and ends of ranges
            // (`w:bookmarkEnd`, `w:commentRangeStart`, `w:commentRangeEnd` and the ranges of
            // moves and of custom XML). Any other element, such as one of another namespace, is
            // left out without a warning too.
            _ => {}
        }
        after_equation &= runs.len() == drawn;
    }
}

/// Collects the runs of the run wrapper `node`, of the local name `local`, which is a `wrapper`:
/// a hyperlink's edges stand around them, and a content control's start and end marks, which
/// stay open through its runs.
fn collect_wrapped(
    reader: &mut PartReader,
    (node, local): (NodeId, &str),
    wrapper: RunWrapper,
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let control = local == "sdt";
    if control {
        runs.push(Run {
            content: vec![Content::ControlEdge],
            ..mark_run(TEXT_BUFFER_MARK_LENGTH, 1)
        });
    }
    let start = runs.len();
    read_wrapped(doc, node, wrapper, runs, |runs| {
        collect_runs(reader, node, Equations::AsWritten, runs);
    });
    mark_hyperlink_edges(doc, (node, local), start, runs);
    if control {
        for run in runs.get_mut(start..).unwrap_or_default() {
            run.buffer_only.open += 1;
            run.buffer_only.held += 1;
        }
        runs.push(Run {
            content: vec![Content::ControlEdge],
            ..mark_run(TEXT_BUFFER_MARK_LENGTH, 0)
        });
    }
}

/// The characters that a target's acceptance of tracked changes left on the run `node` for
/// Word's text buffers (`revisions::accept`).
fn buffered(doc: &Document, node: NodeId) -> Option<usize> {
    doc.attribute(node, Some(crate::ns::NOTE), "buffered")
        .and_then(|value| value.parse().ok())
}

/// A run with no content that holds `characters` of Word's text buffers, after which `open`
/// marks of a container stay open.
fn mark_run(characters: usize, open: usize) -> Run {
    Run {
        buffer_only: BufferOnly {
            characters,
            open,
            ..BufferOnly::default()
        },
        ..Run::default()
    }
}

/// Leaves a hyperlink edge before the runs from `start` on and one after them, when the element
/// `node` that held them, of the local name `local`, is a hyperlink: its content's start and
/// end stay as marks, at which a target's writer can start text objects. The edges hold the
/// characters of the field that Word makes of the hyperlink, before and after its result, for
/// the text buffers ([`hyperlink_field_start`]). The run of the field's start marks where the
/// hyperlink's text starts, and the edge after the runs where it ends ([`LinkMark`]).
fn mark_hyperlink_edges(
    doc: &Document,
    (node, local): (NodeId, &str),
    start: usize,
    runs: &mut Vec<Run>,
) {
    if local != "hyperlink" {
        return;
    }
    let edge = |buffer_only| Run {
        content: vec![Content::HyperlinkEdge],
        buffer_only,
        ..Run::default()
    };
    // The field's start and its one character more stand apart from its code: a buffer can
    // start between them.
    let start = start.min(runs.len());
    runs.insert(
        start,
        Run {
            buffer_only: hyperlink_field_start(doc, node),
            links: vec![LinkMark::Start(Box::new(Hyperlink::of_element(doc, node)))],
            ..Run::default()
        },
    );
    runs.insert(
        start,
        edge(BufferOnly {
            characters: TEXT_BUFFER_MARK_LENGTH + HYPERLINK_FIELD_EXTRA_LENGTH,
            ..BufferOnly::default()
        }),
    );
    runs.push(Run {
        links: vec![LinkMark::End],
        ..edge(BufferOnly {
            characters: TEXT_BUFFER_MARK_LENGTH,
            ..BufferOnly::default()
        })
    });
}

/// The characters of Word's text before the content of the hyperlink `node`, which Word holds as
/// a `HYPERLINK` field, after the field's start and its one character more: its code and the
/// mark before its result. The code is `HYPERLINK`, then ` "address"` for an external
/// address (`r:id`), whose characters the relationship adds, and ` \l "anchor"` for an anchor
/// (`w:anchor`), then ` \o "tooltip"` and ` \t "frame"` when the hyperlink has them, as many
/// characters as a switch with its value for a location in the target (`w:docLocation`), and a
/// switch when it does not record history (`w:history` not on).
fn hyperlink_field_start(doc: &Document, node: NodeId) -> BufferOnly {
    let utf16 = crate::buffers::characters;
    let value = |name: &str| doc.attribute(node, Some(W), name);
    let relationship = doc.attribute(node, Some(R), "id").map(str::to_owned);
    let mut code = utf16("HYPERLINK");
    if relationship.is_some() {
        code += utf16(" \"\"");
    }
    for (switch, name) in [
        ("l", "anchor"),
        ("o", "tooltip"),
        ("t", "tgtFrame"),
        ("l", "docLocation"),
    ] {
        if let Some(text) = value(name) {
            code += utf16(&format!(" \\{switch} \"{text}\""));
        }
    }
    if value("history").is_none_or(|history| on_off::read(history) != Some(true)) {
        code += HYPERLINK_HISTORY_OFF_LENGTH;
    }
    BufferOnly {
        characters: code + TEXT_BUFFER_MARK_LENGTH,
        relationship,
        ..BufferOnly::default()
    }
}

/// An element around runs that a reader enters (a run wrapper).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RunWrapper {
    /// A tracked change: an insertion or content moved here (`w:ins`, `w:moveTo`), or a
    /// deletion or content moved away (`w:del`, `w:moveFrom`) when `removed`. Word prints
    /// tracked changes inline and marks them, so deleted and moved text is laid out too.
    Change { removed: bool },
    /// A hyperlink, a smart tag, custom XML, a content control or the content of one, which
    /// only holds its runs.
    Container,
}

impl RunWrapper {
    /// The run wrapper that an element of the local name `local` is, if it is one.
    pub(crate) fn of(local: &str) -> Option<Self> {
        match local {
            "ins" | "del" | "moveFrom" | "moveTo" => Some(Self::Change {
                removed: crate::revisions::REMOVED.contains(&local),
            }),
            "hyperlink" | "smartTag" | "customXml" | "sdt" | "sdtContent" => Some(Self::Container),
            _ => None,
        }
    }
}

/// Reads the runs of the run wrapper `node`, which is a `wrapper`, with `read`, and marks those
/// of a tracked change as its author's change.
pub(crate) fn read_wrapped(
    doc: &Document,
    node: NodeId,
    wrapper: RunWrapper,
    runs: &mut Vec<Run>,
    read: impl FnOnce(&mut Vec<Run>),
) {
    let start = runs.len();
    read(runs);
    if let RunWrapper::Change { removed } = wrapper {
        let author = doc.attribute(node, Some(W), "author").unwrap_or("");
        for run in runs.get_mut(start..).unwrap_or_default() {
            mark_change(&mut run.props, author, removed);
        }
    }
}

use crate::params::{AUTHOR_COLORS, FNV_32};

/// Marks a run of a tracked change in its author's color: removed text with a line through
/// it, added text with a line under it. Word picks each author's color for its own session,
/// so F-Office picks one from the author's name.
fn mark_change(props: &mut RunProps, author: &str, removed: bool) {
    props.color = Some(Color::Rgb(author_color(author)));
    props.changed = Some(true);
    if removed {
        props.strike = Some(Strike::Single);
    } else {
        props.underline = Some(Underline::Single);
    }
}

/// The color of an author's tracked changes, one of Word's colors picked by the author's name.
pub(crate) fn author_color(author: &str) -> [u8; 3] {
    // FNV-1a, so that the same name always gets the same color.
    let (basis, prime) = FNV_32;
    let hash = author.bytes().fold(basis, |hash, byte| {
        (hash ^ u32::from(byte)).wrapping_mul(prime)
    });
    let index = usize::try_from(hash).unwrap_or(0) % AUTHOR_COLORS.len();
    AUTHOR_COLORS.get(index).copied().unwrap_or_default()
}

/// Reads a run. A symbol (`w:sym`) becomes a run of its own with the symbol's font, between
/// the parts of the run before and after it.
fn read_run(reader: &mut PartReader, node: NodeId) -> Vec<Run> {
    let doc = reader.doc;
    let mut runs = Vec::new();
    let mut revision = |name: &str| reader.hex(node, name, numbers::LONG_HEX);
    // The insertion that held the run, which a target that prints without markup accepts and
    // notes on the run (`revisions::accept`).
    let change = doc
        .attribute(node, Some(crate::ns::NOTE), "change")
        .and_then(|value| value.parse().ok());
    let mut run = Run {
        revisions: [revision("rsidR"), revision("rsidRPr"), change],
        starts_buffer: false,
        ..Run::default()
    };
    // Deleted or moved-away runs that the target accepted stood before the run.
    if doc
        .attribute(node, Some(crate::ns::NOTE), "removed")
        .is_some()
    {
        run.content.push(Content::RemovedEdge);
    }
    run.buffer_only.characters = buffered(doc, node).unwrap_or(0);
    for child in doc.child_elements(node) {
        if doc.is(child, W, "sym") {
            let Some(symbol) = read_symbol(reader, child, &run) else {
                continue;
            };
            let rest = run.part(run.props.clone(), Vec::new());
            let before = std::mem::replace(&mut run, rest);
            if !before.content.is_empty() {
                runs.push(before);
            }
            runs.push(symbol);
        } else {
            read_run_child(reader, child, &mut runs, &mut run);
        }
    }
    if !run.content.is_empty() || runs.is_empty() {
        runs.push(run);
    }
    runs
}

/// A run of one symbol character (`w:sym`): the character `w:char`, in hexadecimal, in the
/// font `w:font`, with the other properties of the run that holds it.
fn read_symbol(reader: &mut PartReader, node: NodeId, run: &Run) -> Option<Run> {
    let doc = reader.doc;
    let ch = reader
        .hex(node, "char", numbers::SHORT_HEX)
        .and_then(char::from_u32)?;
    let mut props = run.props.clone();
    if let Some(font) = doc.attribute(node, Some(W), "font") {
        let font = Some(FontRef::Name(font.to_owned()));
        props.font_ascii.clone_from(&font);
        props.font_hansi = font;
    }
    Some(run.part(props, vec![Content::Text(ch.to_string())]))
}

/// Merges a `w:rPr` element onto `run` in document order, flushing any earlier content of the
/// run first so a later `w:rPr` applies only to content that follows it.
fn read_run_props(reader: &mut PartReader, child: NodeId, runs: &mut Vec<Run>, run: &mut Run) {
    let doc = reader.doc;
    if run
        .content
        .iter()
        .any(|content| !matches!(content, Content::RemovedEdge))
    {
        let rest = run.part(run.props.clone(), Vec::new());
        runs.push(std::mem::replace(run, rest));
    }
    run.props.read_into(reader, child);
    run.record.read_into(doc, child);
    if let Some(style) = doc
        .child(child, W, "rStyle")
        .and_then(|s| doc.attribute(s, Some(W), "val"))
    {
        run.style = Some(style.to_owned());
    }
}

fn read_run_child(reader: &mut PartReader, child: NodeId, runs: &mut Vec<Run>, run: &mut Run) {
    let doc = reader.doc;
    {
        let Some(element) = doc.element(child) else {
            return;
        };
        let local = element.name.local;
        match local {
            // Alternate content offers choices, such as DrawingML shapes, and a fallback for
            // older readers (ECMA-376 Part 3).
            "AlternateContent" if doc.is(child, MC, "AlternateContent") => {
                let branch = shown_branch(reader, child);
                for inner in branch.into_iter().flat_map(|b| doc.child_elements(b)) {
                    read_run_child(reader, inner, runs, run);
                }
            }
            "rPr" => read_run_props(reader, child, runs, run),
            // A line end inside the text of a run is a space.
            "t" | "delText" => push_text(
                run,
                &compose_marks(&doc.text_content(child).replace(['\n', '\r'], " ")),
            ),
            "noBreakHyphen" => push_text(run, &crate::text::NON_BREAKING_HYPHEN.to_string()),
            "softHyphen" => push_text(run, &crate::text::SOFT_HYPHEN.to_string()),
            "tab" => run.content.push(Content::Tab),
            "ptab" => run.content.push(Content::PositionTab {
                kind: reader
                    .enumeration(child, "alignment", PTAB_ALIGNMENT)
                    .unwrap_or(TabKind::Left),
                leader: reader.enumeration(child, "leader", PTAB_LEADER).flatten(),
            }),
            "cr" => run.content.push(Content::LineBreak),
            "br" => run.content.push(read_break(reader, child)),
            "instrText" | "delInstrText" => run
                .content
                .push(Content::FieldCode(doc.text_content(child))),
            "pict" | "object" => run.content.extend(crate::vml::read(reader, child)),
            // Ink is left out with a warning.
            "contentPart" if doc.is(child, W14, "contentPart") => {
                reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
            }
            // A character of the symbol extension, in a choice of alternate content that
            // F-Office takes, is left out with a warning.
            "symEx" if doc.is(child, W16SE, "symEx") => {
                reader.feature_not_supported(Feature::SymbolExtension);
            }
            "drawing" => {
                run.content.extend(read_inline(reader, child));
                run.content.extend(
                    crate::floating::read_anchor(reader, child)
                        .map(|floating| Content::Floating(Box::new(floating))),
                );
            }
            "footnoteReference" => run.content.extend(NoteId::read(reader, child).map(|id| {
                reader.note_reference(crate::NoteKind::Footnote, id);
                Content::FootnoteReference(id, super::NoteMark::read(doc, child))
            })),
            "footnoteRef" => run.content.push(Content::FootnoteMark),
            "commentReference" => run.content.extend(
                doc.attribute(child, Some(W), "id")
                    .map(|id| Content::CommentAnchor(id.to_owned())),
            ),
            "endnoteReference" => run.content.extend(NoteId::read(reader, child).map(|id| {
                reader.note_reference(crate::NoteKind::Endnote, id);
                Content::EndnoteReference(id, super::NoteMark::read(doc, child))
            })),
            "endnoteRef" => run.content.push(Content::EndnoteMark),
            "annotationRef" => run.content.push(Content::CommentMark),
            "separator" => run.content.push(Content::Separator),
            "continuationSeparator" => run.content.push(Content::ContinuationSeparator),
            "fldChar" => match reader.enumeration(child, "fldCharType", FIELD_CHAR) {
                Some(FieldChar::Begin) => {
                    run.content.push(Content::FieldBegin);
                    if field_locked(doc, child) {
                        run.content.push(Content::FieldLock);
                    }
                    run.content
                        .extend(read_check_box(reader, child).map(Content::CheckBox));
                    run.content
                        .extend(read_drop_down(reader, child).map(Content::DropDown));
                }
                Some(FieldChar::Separate) => run.content.push(Content::FieldSeparate),
                Some(FieldChar::End) => run.content.push(Content::FieldEnd),
                None => {}
            },
            // The children of [`WARNED_RUN_CHILDREN`] are left out with a warning. Word's mark
            // of a page break of its last layout (`w:lastRenderedPageBreak`) draws nothing, as
            // F-Office lays the pages out again. Any other element, such as one of another
            // namespace, is left out without a warning too.
            _ => warn_of_left_out_run_child(reader, child, local),
        }
    }
}

/// The children of a run that F-Office leaves out with a warning of their feature: a phonetic
/// guide, with its base text, and a page number or a part of the date as an element, not as a
/// field.
const WARNED_RUN_CHILDREN: [(&str, Feature); 8] = [
    ("ruby", Feature::Ruby),
    ("pgNum", Feature::PageNumberElement),
    ("dayShort", Feature::DateBlock),
    ("dayLong", Feature::DateBlock),
    ("monthShort", Feature::DateBlock),
    ("monthLong", Feature::DateBlock),
    ("yearShort", Feature::DateBlock),
    ("yearLong", Feature::DateBlock),
];

/// Keeps the warning of the run child `child` of the local name `local` when it is one of
/// [`WARNED_RUN_CHILDREN`].
fn warn_of_left_out_run_child(reader: &mut PartReader, child: NodeId, local: &str) {
    let feature = WARNED_RUN_CHILDREN
        .iter()
        .find(|(name, _)| *name == local)
        .map(|&(_, feature)| feature);
    if let Some(feature) = feature.filter(|_| reader.doc.is(child, W, local)) {
        reader.feature_not_supported(feature);
    }
}

/// ECMA-376 Part 1, 17.16: the lock is an on/off attribute of the field start.
fn field_locked(doc: &Document, node: NodeId) -> bool {
    doc.attribute(node, Some(W), "fldLock")
        .is_some_and(|value| on_off::read(value) == Some(true))
}

/// Reads the check box of a form field from its start (`w:fldChar` with `w:ffData`). ECMA-376
/// Part 1, 17.16.7 and 17.16.11: `w:checked` gives the state, else `w:default`, and both are
/// on/off values whose `w:val` defaults to on.
fn read_check_box(reader: &mut PartReader, begin: NodeId) -> Option<super::CheckBox> {
    let doc = reader.doc;
    let check_box = doc.child(doc.child(begin, W, "ffData")?, W, "checkBox")?;
    let on = |name: &str| {
        doc.child(check_box, W, name)
            .map(|node| on_off::element(doc, node, W))
    };
    // A size in half points (`ST_HpsMeasure`), read as the run sizes are.
    let size = doc
        .child(check_box, W, "size")
        .and_then(|node| reader.half_points(node, "val"));
    Some(super::CheckBox {
        size,
        checked: on("checked").or_else(|| on("default")).unwrap_or(false),
    })
}

/// Reads the entry that a drop-down form field shows from its start (`w:fldChar` with
/// `w:ffData`). ECMA-376 Part 1, 17.16: `w:ddList` lists the entries (`w:listEntry`), and the
/// index from 0 of `w:result`, else of `w:default`, else 0 selects one. An index past the list
/// counts as missing.
fn read_drop_down(reader: &mut PartReader, begin: NodeId) -> Option<String> {
    let doc = reader.doc;
    let list = doc.child(doc.child(begin, W, "ffData")?, W, "ddList")?;
    let entries: Vec<&str> = doc
        .children(list)
        .iter()
        .filter(|&&node| doc.is(node, W, "listEntry"))
        .filter_map(|&node| crate::reader::val(doc, node))
        .collect();
    let range = numbers::indices(entries.len());
    let mut index = |name: &str| {
        let node = doc.child(list, W, name)?;
        reader.number::<usize>(node, "val", range.clone())
    };
    let selected = index("result").or_else(|| index("default")).unwrap_or(0);
    entries.get(selected).map(|entry| (*entry).to_owned())
}

/// Reads the size of an inline drawing (`wp:inline`): its box plus the effect extent on each
/// side. The box is the extent, or for a rotated picture the box that the target gives it
/// (`TurnedPictures::turned_box`), with the picture's frame at its centre. A floating drawing
/// (`wp:anchor`) takes no room on the line.
fn read_inline(reader: &mut PartReader, drawing: NodeId) -> Option<Content> {
    let doc = reader.doc;
    let inline = doc.child(drawing, WP, "inline")?;
    let (
        [cx, cy],
        Edges {
            left,
            top,
            right,
            bottom,
        },
    ) = crate::floating::extents(reader, inline);
    let rotation = crate::picture::rotation(doc, inline);
    let (box_width, box_height) = reader.turned_pictures().turned_box((cx, cy), rotation);
    // Each value reads within `f_office_drawingml::COORDINATE_LIMIT`; the sums are taken as
    // lengths, which hold them also beyond that range.
    let width = (box_width + left + right).max(Length::ZERO);
    let height = (box_height + top + bottom).max(Length::ZERO);
    // The picture lies inside the effect extent, its frame centred in the box.
    let frame_left = left + (box_width - cx).div_round(2);
    let frame_top = top + (box_height - cy).div_round(2);
    let picture = Edges::placed(frame_left, frame_top, cx, cy)
        .and_then(|frame| Picture::read(reader, inline, frame));
    // A shape takes the same room, and shows its look and its text box in its box.
    let shape = picture
        .is_none()
        .then(|| crate::floating::read_inline_shape(reader, inline, cx, cy))
        .flatten()
        .map(|shape| InlineDrawing {
            width,
            height,
            left,
            top,
            shape,
            drops: false,
            anchor_locked: false,
            extent: Some(cy),
        });
    Some(match shape {
        Some(drawing) => Content::Drawing(Rc::new(drawing)),
        None => Content::Object {
            width,
            height,
            picture: picture.map(Box::new),
            extent: Some(box_height),
        },
    })
}

/// The text with each character and the combining marks after it (canonical combining class
/// above 0) joined into the precomposed character of Unicode's composition table where it has
/// one. Other characters stay as they are, such as the Greek question mark or the ohm sign,
/// whose canonical forms are other characters.
fn compose_marks(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut last: Option<char> = None;
    for ch in text.chars() {
        if let Some(previous) = last {
            let mark = unicode_normalization::char::canonical_combining_class(ch) > 0;
            if let Some(composed) =
                unicode_normalization::char::compose(previous, ch).filter(|_| mark)
            {
                last = Some(composed);
                continue;
            }
            out.push(previous);
        }
        last = Some(ch);
    }
    out.extend(last);
    out
}

fn push_text(run: &mut Run, text: &str) {
    if let Some(Content::Text(existing)) = run.content.last_mut() {
        existing.push_str(text);
    } else {
        run.content.push(Content::Text(text.to_owned()));
    }
}

/// The kind of a break (`ST_BrType`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum BreakKind {
    Page,
    Column,
    TextWrapping,
}

/// `ST_BrType`; a break without a kind breaks the line.
pub(super) const BREAK_KIND: &Values<BreakKind> = &Values::new(&[
    own("page", BreakKind::Page),
    own("column", BreakKind::Column),
    own("textWrapping", BreakKind::TextWrapping),
]);

/// `ST_BrClear`, as whether a line break clears both sides: a break that clears one side is
/// drawn as a plain line break.
pub(super) const BREAK_CLEAR: &Values<bool> = &Values::new(&[
    own("none", false),
    another("left", false),
    another("right", false),
    own("all", true),
]);

fn read_break(reader: &mut PartReader, node: NodeId) -> Content {
    match reader.enumeration(node, "type", BREAK_KIND) {
        Some(BreakKind::Page) => Content::PageBreak,
        Some(BreakKind::Column) => Content::ColumnBreak,
        _ if reader.enumeration(node, "clear", BREAK_CLEAR) == Some(true) => Content::ClearingBreak,
        _ => Content::LineBreak,
    }
}

/// The kind of a field character (`ST_FldCharType`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FieldChar {
    /// The start of a field.
    Begin,
    /// The end of its instruction and the start of its result.
    Separate,
    /// The end of the field.
    End,
}

/// `ST_FldCharType`; a field character without a kind is left out.
pub(crate) const FIELD_CHAR: &Values<FieldChar> = &Values::new(&[
    own("begin", FieldChar::Begin),
    own("separate", FieldChar::Separate),
    own("end", FieldChar::End),
]);

/// `ST_PTabLeader` of a positional tab: the character that its leader repeats, if any. A
/// heavy leader, which a tab stop takes, is text outside this type and counts as missing, no
/// leader, where F-Office drew it as an underscore before.
pub(super) const PTAB_LEADER: &Values<Option<char>> = &Values::new(&[
    own("none", None),
    own("dot", Some('.')),
    own("hyphen", Some('-')),
    own("underscore", Some('_')),
    own("middleDot", Some('\u{b7}')),
]);

/// `ST_PTabAlignment` of a positional tab; a missing alignment is the left.
pub(super) const PTAB_ALIGNMENT: &Values<TabKind> = &Values::new(&[
    own("left", TabKind::Left),
    own("center", TabKind::Center),
    own("right", TabKind::Right),
]);

#[cfg(test)]
mod tests {
    use f_office_units::Length;
    use f_office_xml::{Document, Limits};

    use super::{read_inline, read_paragraph};
    use crate::body::Content;
    use crate::ns::{W, WP};
    use crate::props::{Alignment, ListLevel, ListRef};
    use crate::reader::PartReader;

    #[test]
    fn merges_multiple_ppr_siblings_with_later_overriding_earlier() {
        let xml = format!(
            concat!(
                r#"<w:p xmlns:w="{w}">"#,
                r#"<w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr><w:ind w:left="720"/></w:pPr>"#,
                r#"<w:pPr><w:numPr><w:ilvl w:val="1"/><w:numId w:val="2"/></w:numPr><w:jc w:val="right"/><w:spacing w:after="240"/></w:pPr>"#,
                r#"<w:r><w:t>text</w:t></w:r></w:p>"#,
            ),
            w = W
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let paragraph = read_paragraph(&mut PartReader::new(&doc), doc.root().unwrap());
        assert_eq!(
            paragraph.props.numbering,
            Some(ListRef::Id(std::num::NonZeroU32::new(2).unwrap()))
        );
        assert_eq!(paragraph.props.numbering_level, Some(ListLevel::At(1)));
        assert_eq!(paragraph.props.indent_left, Length::from_twips(720));
        assert_eq!(paragraph.props.alignment, Some(Alignment::End));
        assert_eq!(
            paragraph.props.space_after(),
            Length::from_twips(240).unwrap()
        );
    }

    #[test]
    fn merges_leading_rpr_siblings_and_splits_run_on_later_rpr() {
        let xml = format!(
            concat!(
                r#"<w:p xmlns:w="{w}">"#,
                r#"<w:r><w:t>P2</w:t><w:rPr><w:sz w:val="48"/></w:rPr></w:r>"#,
                r#"<w:r><w:rPr><w:rStyle w:val="PlainBlue"/><w:sz w:val="36"/></w:rPr>"#,
                r#"<w:rPr><w:sz w:val="48"/></w:rPr><w:t>P5</w:t></w:r>"#,
                r#"<w:r><w:lastRenderedPageBreak/><w:rPr><w:sz w:val="48"/></w:rPr><w:t>P8</w:t></w:r>"#,
                r#"<w:r><w:t>A</w:t><w:rPr><w:sz w:val="48"/></w:rPr><w:t>B</w:t></w:r>"#,
                r#"</w:p>"#,
            ),
            w = W
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let paragraph = read_paragraph(&mut PartReader::new(&doc), doc.root().unwrap());
        let got: Vec<_> = paragraph
            .runs
            .iter()
            .map(|r| (&r.content[..], r.style.as_deref(), r.props.size))
            .collect();
        let text = |s: &str| [Content::Text(s.to_owned())];
        let expected = [
            (text("P2"), None, None),
            (text("P5"), Some("PlainBlue"), Some(48)),
            (text("P8"), None, Some(48)),
            (text("A"), None, None),
            (text("B"), None, Some(48)),
        ];
        let expected: Vec<_> = expected
            .iter()
            .map(|(c, style, size)| (&c[..], *style, *size))
            .collect();
        assert_eq!(got, expected);
    }

    #[test]
    fn sizes_an_inline_drawing_whose_extents_add_up_beyond_the_range_of_a_length() {
        // The extent and the effect extents at each side are each the largest coordinate,
        // which is a length; their sum is three times as much, beyond the range of a length.
        let most = f_office_drawingml::COORDINATE_LIMIT;
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}"><wp:inline><wp:extent cx="{most}" cy="914400"/><wp:effectExtent l="{most}" t="0" r="{most}" b="0"/></wp:inline></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let drawing = read_inline(&mut PartReader::new(&doc), doc.root().unwrap());
        let Some(Content::Object { width, height, .. }) = drawing else {
            panic!("{drawing:?}");
        };
        assert_eq!(width, Length::from_emus(most).unwrap() * 3);
        assert_eq!(height, Length::from_emus(914_400).unwrap());
    }
}