f-office-docx 0.2.1

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
//! Fields (`w:fldChar`, `w:instrText`, `w:fldSimple`): the stored results that layout shows,
//! and the fields that layout computes itself, such as page numbers and dates.

use std::collections::{BTreeMap, BTreeSet};

use super::contents::{any_content, visit_contents_mut};
use super::field_code::{
    self, ADVANCE_LEFT, ADVANCE_RIGHT, CHAR_FORMAT, FORM_DROP_DOWN, FORM_TEXT, FORMAT,
    MERGE_FORMAT, PAGE_POSITION, PICTURE, REF_FULL, REF_LINK, REF_PATTERN, REF_RELATIVE,
    STYLE_LAST, STYLE_NUMBER,
};
use super::links::{Hyperlink, LinkMark};
use super::{
    Block, CodePart, CodeRun, Content, DateField, DocProperty, IfField, NumberRef, PageRef, Run,
    StyleRef, paragraphs_mut,
};
use crate::params::{MAX_FIELD_DEPTH, TEXT_BUFFER_MARK_LENGTH};
use crate::props::CodeFormat;
use crate::reader::PartReader;
use crate::warnings::Limit;
use f_office_units::Length;

#[cfg(test)]
mod tests;

/// The kind of a field that layout computes itself. `saved` is the date and time picture of a
/// `SAVEDATE` or `PRINTDATE` field without its own, or none where such a field keeps its stored
/// result.
fn computed_field(code: &str, saved: Option<&str>) -> Option<Content> {
    let date = |default: &str| {
        Content::Date(Box::new(DateField {
            picture: picture_switch(code).unwrap_or_else(|| default.to_owned()),
            stored: String::new(),
        }))
    };
    match field_code::kind(code)?.to_ascii_uppercase().as_str() {
        "PAGE" => Some(Content::PageNumber),
        "NUMPAGES" => Some(Content::PageCount),
        "DATE" => Some(date(crate::dates::DATE_PICTURE)),
        "TIME" => Some(date(crate::dates::TIME_PICTURE)),
        // Word saves and prints the document when it makes the PDF, so these show that time
        // too. Without a picture, they take `saved`.
        "SAVEDATE" | "PRINTDATE" => match picture_switch(code) {
            Some(_) => Some(date(crate::dates::DATE_PICTURE)),
            None => saved.map(date),
        },
        "DOCPROPERTY" => property_name(code).map(|name| {
            Content::DocProperty(Box::new(DocProperty {
                name,
                picture: picture_switch(code),
                stored: String::new(),
            }))
        }),
        "STYLEREF" => style_ref(code).map(|s| Content::StyleRef(Box::new(s))),
        "PAGEREF" => page_ref(code).map(|p| Content::PageRef(Box::new(p))),
        "REF" => number_ref(code).map(|field| Content::NumberRef(Box::new(field))),
        "IF" => Some(Content::If(Box::new(IfField {
            parts: Vec::new(),
            stored: String::new(),
        }))),
        "ADVANCE" => advance(code).map(Content::Advance),
        _ => None,
    }
}

/// The move of an `ADVANCE` field whose switches are `\r` and `\l`, in any case, each with a
/// number of points: the sum of the moves to the right less those to the left. A field with
/// another switch, such as `\x`, `\y`, `\d` or `\u`, or with a switch without a number, moves
/// nothing.
fn advance(code: &str) -> Option<Length> {
    let mut words = field_code::words_after_kind(code);
    let mut by = Length::ZERO;
    let mut any = false;
    while let Some(word) = words.next() {
        let sign = if ADVANCE_RIGHT.is(word) {
            1
        } else if ADVANCE_LEFT.is(word) {
            -1
        } else {
            return None;
        };
        let thousandths = f_office_units::measure::decimal_thousandths(words.next()?)?;
        let units = f_office_units::checked_div_round(
            thousandths.checked_mul(sign * Length::UNITS_PER_POINT)?,
            f_office_units::scale::THOUSANDTHS,
        )?;
        by = by.checked_add(Length::from_units(units))?;
        any = true;
    }
    any.then_some(by)
}

/// Number switches of a `REF` field (`\n`, `\r`, `\w`), or none for a field that shows its
/// bookmark's text. Other switches keep the stored result. The bookmark is a word argument, and
/// the switches read only in their own case.
fn number_ref(code: &str) -> Option<NumberRef> {
    use crate::numbering::ReferenceKind;
    let kinds = [
        (REF_PATTERN, ReferenceKind::Pattern),
        (REF_RELATIVE, ReferenceKind::Relative),
        (REF_FULL, ReferenceKind::Full),
    ];
    let mut words = field_code::words_after_kind(code);
    let bookmark = field_code::word_argument(words.next()?);
    if bookmark.is_empty() || bookmark.starts_with('\\') {
        return None;
    }
    let mut kind = None;
    while let Some(word) = words.next() {
        if let Some((_, of)) = kinds.iter().find(|(switch, _)| switch.is(word)) {
            kind = Some(*of);
            continue;
        }
        // The link of `\h` and the format of `\* MERGEFORMAT` leave the number as it is.
        let keeps_number = REF_LINK.is(word)
            || (FORMAT.is(word)
                && words
                    .next()
                    .is_some_and(|format| field_code::is_format(format, &[MERGE_FORMAT])));
        if !keeps_number {
            return None;
        }
    }
    Some(NumberRef {
        bookmark: bookmark.to_owned(),
        kind,
        stored: String::new(),
        code: None,
    })
}

/// The name of the property that a `DOCPROPERTY` field shows: its first argument, a quoted
/// argument, also when the code does not close its quote.
fn property_name(code: &str) -> Option<String> {
    let name = field_code::quoted_argument(field_code::after_kind(code)).text;
    (!name.is_empty() && !name.starts_with('\\')).then(|| name.to_owned())
}

/// A `PAGEREF` field with its bookmark. A field with the `\p` switch, which shows "above" or
/// "below" instead of a number, keeps its stored result.
fn page_ref(code: &str) -> Option<PageRef> {
    let mut words = field_code::words_after_kind(code);
    let bookmark = field_code::word_argument(words.next()?);
    if bookmark.is_empty() || bookmark.starts_with('\\') {
        return None;
    }
    if words.any(|word| PAGE_POSITION.is(word)) {
        return None;
    }
    Some(PageRef {
        bookmark: bookmark.to_owned(),
        stored: String::new(),
        code: None,
    })
}

/// A `STYLEREF` field with its style, a quoted argument that the code closes, and its `\l`
/// and `\n` switches. `\* CHARFORMAT` and `\* MERGEFORMAT` only format the result. A field
/// with any other switch, such as `\r` for the number in its context, keeps its stored result.
/// Whether the paragraph number of `\n` updates is the target's ([`Updates::updates`]).
fn style_ref(code: &str) -> Option<StyleRef> {
    let argument = field_code::quoted_argument(field_code::after_kind(code));
    let (style, switches) = (argument.text, argument.rest);
    if argument.unclosed || style.is_empty() {
        return None;
    }
    let (mut last, mut number) = (false, false);
    let mut switches = switches.split_whitespace();
    while let Some(switch) = switches.next() {
        if STYLE_LAST.is(switch) {
            last = true;
        } else if STYLE_NUMBER.is(switch) {
            number = true;
        } else if FORMAT.is(switch) {
            let format = switches.next().unwrap_or_default();
            if !field_code::is_format(format, &[CHAR_FORMAT, MERGE_FORMAT]) {
                return None;
            }
        } else {
            return None;
        }
    }
    Some(StyleRef {
        style: style.to_owned(),
        last,
        number,
        stored: String::new(),
    })
}

/// The argument of a field code's date and time picture switch (`\@`), an escaped argument after
/// the first `\@` anywhere in the code.
pub(super) fn picture_switch(code: &str) -> Option<String> {
    PICTURE.after_first(code).map(field_code::escaped_argument)
}

/// Whether `blocks` hold a `NUMPAGES`, `PAGEREF` or paragraph-number `REF` field, which need
/// the pages of an earlier pass: in a table cell, in the text box of a floating or inline
/// drawing or of a part of its group, and in the code of an `IF` field too.
#[must_use]
pub fn refers_to_pages(blocks: &[Block]) -> bool {
    any_content(blocks, &mut |content| {
        matches!(
            content,
            Content::PageCount | Content::PageRef(_) | Content::NumberRef(_)
        )
    })
}

/// Whether `blocks` hold both a `PAGEREF` field and a paragraph-number `REF` field, in the same
/// places as [`refers_to_pages`].
#[must_use]
pub fn refers_to_pages_and_numbers(blocks: &[Block]) -> bool {
    let (mut pages, mut numbers) = (false, false);
    any_content(blocks, &mut |content| {
        pages |= matches!(content, Content::PageRef(_));
        numbers |= matches!(content, Content::NumberRef(_));
        pages && numbers
    })
}

/// Whether `blocks` hold a `STYLEREF` field, whose text depends on the page: in the same places
/// as [`refers_to_pages`].
#[must_use]
pub fn refers_to_styles(blocks: &[Block]) -> bool {
    any_content(blocks, &mut |content| {
        matches!(content, Content::StyleRef(_))
    })
}

/// Gives the `DOCPROPERTY` fields of the main document their stored results, also in table
/// cells and in the text boxes of floating and inline drawings and of the parts of their
/// groups. Word updates these fields in headers and footers when it prints, but not in the
/// body.
pub(super) fn keep_stored_properties(blocks: &mut [Block]) {
    // The stored result becomes the run's text, so it leaves the run's buffer-only characters.
    for run in paragraphs_mut(blocks)
        .into_iter()
        .flat_map(|paragraph| paragraph.runs.iter_mut())
    {
        let stored: usize = run
            .content
            .iter()
            .map(|content| match content {
                Content::DocProperty(property) => property.stored.encode_utf16().count(),
                _ => 0,
            })
            .sum();
        run.buffer_only.characters = run.buffer_only.characters.saturating_sub(stored);
    }
    visit_contents_mut(blocks, &mut |content| {
        if let Content::DocProperty(property) = content {
            let stored = std::mem::take(&mut property.stored);
            *content = Content::Text(stored);
        }
    });
}

/// Which fields of a story Word updates when it prints.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Updates {
    /// The fields that layout computes, except an `IF` field with a stored result, which keeps
    /// it, as in the body and in notes.
    #[default]
    Computed,
    /// The computed body fields, including unlocked REF paragraph numbers.
    References,
    /// The fields that layout computes, also an `IF` field with a stored result, as in a header
    /// or footer.
    Live,
    /// As `Live`, and also the paragraph number of a `STYLEREF` field (`\n`).
    LiveNumbers,
    /// Only the fields without a stored result: a field with one shows it.
    WithoutResult,
    /// The fields whose value comes from the pages, `IF` fields, and the other fields without a
    /// stored result: any other field with one shows it.
    PageFields,
}

impl Updates {
    /// The direction of a page number or page count that Word computes, as `w:rtl` of a run
    /// says it; none for another value, which keeps the direction of its own run. In a header
    /// or footer the number keeps the UAX 9 class of its digits, as in a run with `w:rtl`,
    /// whatever the runs of the field say. Elsewhere it has the direction of the run of the
    /// field's code, `code_rtl`. A stored result that Word shows is no value of this function.
    fn result_direction(self, value: &Content, code_rtl: Option<bool>) -> Option<bool> {
        if !matches!(value, Content::PageNumber | Content::PageCount) {
            return None;
        }
        match self {
            Self::Live | Self::LiveNumbers | Self::PageFields => Some(true),
            Self::Computed | Self::References | Self::WithoutResult => code_rtl,
        }
    }

    /// Whether Word updates a field whose value is `value`, and which has a stored result when
    /// `stored` holds.
    fn updates(self, value: &Content, stored: bool) -> bool {
        if matches!(value, Content::NumberRef(_)) {
            return self == Self::References;
        }
        if matches!(value, Content::StyleRef(field) if field.number) {
            return self == Self::LiveNumbers;
        }
        let field_if = matches!(value, Content::If(_));
        match self {
            Self::Live | Self::LiveNumbers => true,
            Self::Computed | Self::References => !field_if,
            Self::WithoutResult => !stored && !field_if,
            Self::PageFields => {
                let on_page = matches!(
                    value,
                    Content::PageNumber
                        | Content::PageCount
                        | Content::PageRef(_)
                        | Content::StyleRef(_)
                );
                on_page || field_if || !stored
            }
        }
    }
}

/// Replaces each `PAGE` and `NUMPAGES` field with the number that layout computes, and drops
/// the field's stored result. Other fields keep their stored result. Fields may nest, and a
/// field may span paragraphs. `updates` says which fields Word updates in the story. A field
/// that begins while [`MAX_FIELD_DEPTH`] fields are open is read as content of the field around
/// it, with a warning of `reader`.
pub(super) fn resolve_fields(reader: &mut PartReader, blocks: &mut [Block], updates: Updates) {
    let mut bookmarks = BTreeSet::new();
    any_content(blocks, &mut |content| {
        if let Content::Bookmark(name) = content {
            bookmarks.insert(name.clone());
        }
        false
    });
    let mut paragraphs = paragraphs_mut(blocks);
    let mut fields = Fields {
        stored: stored_results(paragraphs.iter().flat_map(|p| &p.runs)),
        bookmarks,
        updates,
        saved_date: reader.saved_date_picture(),
        ..Fields::default()
    };
    for (index, run) in paragraphs
        .iter_mut()
        .flat_map(|p| p.runs.iter_mut())
        .enumerate()
    {
        fields.run = index;
        let content = std::mem::take(&mut run.content);
        // A simple field (`w:fldSimple`) has no run of its code: its marker holds the code
        // and the separator together. Outside a header or footer its result keeps the
        // direction of its own run.
        let simple = content
            .iter()
            .any(|item| matches!(item, Content::FieldCode(_)))
            && content
                .iter()
                .any(|item| matches!(item, Content::FieldSeparate));
        fields.run_rtl = (!simple).then(|| run.props.rtl.unwrap_or(false));
        fields.result_rtl = None;
        let codes = content
            .iter()
            .any(|item| matches!(item, Content::FieldCode(_)));
        fields.run_code = (!simple && codes).then(|| CodeRun {
            style: run.style.clone(),
            props: run.props.clone(),
        });
        fields.result_format = None;
        // The marks and the code of the fields leave the run's content but stay in Word's text,
        // and so does the stored result that a computed value replaces.
        run.buffer_only.characters += crate::buffers::field_characters(&content);
        let before = fields.open_marks();
        for item in content {
            fields.push(item, &mut run.content);
        }
        run.links.append(&mut fields.links);
        let after = fields.open_marks();
        run.buffer_only.open += after;
        run.buffer_only.held += before.min(after);
        run.buffer_only.characters += std::mem::take(&mut fields.stored_characters);
        // A run that shows a page number or page count that Word computes has the direction
        // of `Updates::result_direction`.
        if fields.result_rtl.is_some() {
            run.props.field_rtl = fields.result_rtl;
        }
        if std::mem::take(&mut fields.form_text) {
            run.props.form_text = Some(true);
        }
        // A run that shows a page number or page count keeps the format of the field's code run,
        // which layout gives it where the target says so.
        run.code_format = fields
            .result_format
            .take()
            .map(Box::new)
            .or(run.code_format.take());
    }
    // The run that shows a check box keeps the format of the field's code run too, which is
    // known only after that run: layout gives it to the box where the target says so.
    let formats: BTreeMap<usize, &CodeFormat> = fields
        .check_boxes
        .iter()
        .filter_map(|(run, field)| fields.check_box_formats.get(field).map(|f| (*run, f)))
        .collect();
    if !formats.is_empty() {
        for (index, run) in paragraphs
            .iter_mut()
            .flat_map(|p| p.runs.iter_mut())
            .enumerate()
        {
            if let Some(format) = formats.get(&index)
                && run.code_format.is_none()
            {
                run.code_format = Some(Box::new((*format).clone()));
            }
        }
    }
    reader.limit_reached_times(Limit::FieldDepth, fields.too_deep);
}

/// The text of each field's stored result, by the order in which the fields begin. The text of
/// a nested field counts for the innermost field.
fn stored_results<'r>(runs: impl Iterator<Item = &'r Run>) -> Vec<String> {
    let mut stored = Vec::new();
    // The index of each open field, and whether its result has begun.
    let mut open: Vec<(usize, bool)> = Vec::new();
    for item in runs.flat_map(|run| &run.content) {
        match item {
            Content::FieldBegin => {
                open.push((stored.len(), false));
                stored.push(String::new());
            }
            Content::FieldSeparate => {
                if let Some(field) = open.last_mut() {
                    field.1 = true;
                }
            }
            Content::FieldEnd => {
                open.pop();
            }
            Content::Text(text) => {
                let result = open
                    .last()
                    .filter(|field| field.1)
                    .and_then(|field| stored.get_mut(field.0));
                if let Some(result) = result {
                    result.push_str(text);
                }
            }
            _ => {}
        }
    }
    stored
}

/// The fields that are open at a point of a story.
#[derive(Default)]
struct Fields {
    /// The fields that are open, the innermost last: at most [`MAX_FIELD_DEPTH`].
    open: Vec<Field>,
    /// How many fields are open inside the innermost field of `open` when `open` holds
    /// [`MAX_FIELD_DEPTH`] fields. The reader does not read them as fields
    /// ([`Fields::push_too_deep`]).
    too_deep_open: usize,
    /// How many fields of the story began while [`MAX_FIELD_DEPTH`] fields were open, for the
    /// warning.
    too_deep: u32,
    /// The stored result of each field of the story, by the order in which they begin.
    stored: Vec<String>,
    /// The names of the bookmarks of the story.
    bookmarks: BTreeSet<String>,
    /// The characters of the stored results that computed values replaced in the current run.
    stored_characters: usize,
    /// How many fields have begun so far.
    begun: usize,
    /// Which fields Word updates in the story when it prints.
    updates: Updates,
    /// The date and time picture of a `SAVEDATE` or `PRINTDATE` field without its own, or
    /// none where such a field keeps its stored result.
    saved_date: Option<&'static str>,
    /// Whether the run that is being read has `w:rtl`; none for the marker of a simple
    /// field, which is no run of the file.
    run_rtl: Option<bool>,
    /// For the run that is being read, when it shows a page number or page count that Word
    /// computes: the direction of that number, as `w:rtl` of a run says it.
    result_rtl: Option<bool>,
    /// The run that is being read, when it holds a field's code; none for the marker of a
    /// simple field.
    run_code: Option<CodeRun>,
    /// For the run that is being read, when it shows a page number or page count: the format of the
    /// field's code run, from [`Field::value_format`].
    result_format: Option<CodeFormat>,
    /// Whether the run that is being read shows text of the result of a text form field.
    form_text: bool,
    /// The index of the run that is being read, in the order of the story's runs.
    run: usize,
    /// For each check box that shows, the index of the run that holds it and of its field.
    check_boxes: Vec<(usize, usize)>,
    /// The format of the first run of the code of each check box field that has ended, by
    /// the field's index.
    check_box_formats: BTreeMap<usize, CodeFormat>,
    /// The marks of the hyperlinks that start or end in the run that is being read: the result
    /// of a field that links starts at its separator and ends at its end.
    links: Vec<LinkMark>,
}

/// Whether the code `code` holds the format `\* MERGEFORMAT`.
fn merges_format(code: &str) -> bool {
    let mut words = field_code::words_after_kind(code);
    while let Some(word) = words.next() {
        if FORMAT.is(word)
            && words
                .next()
                .is_some_and(|format| field_code::is_format(format, &[MERGE_FORMAT]))
        {
            return true;
        }
    }
    false
}

/// Whether content shows as it is inside the open fields `open`: it lies in no field's code
/// and in no stored result that a computed value replaces.
fn shows(open: &[Field]) -> bool {
    !open.iter().any(|field| {
        matches!(
            field.state,
            FieldState::Code | FieldState::Pending(_) | FieldState::Replaced
        )
    })
}

/// An open field.
struct Field {
    code: String,
    /// The code in order, with the values of the fields nested in it.
    parts: Vec<CodePart>,
    /// The order in which the field begins in its story.
    index: usize,
    state: FieldState,
    /// Whether the field is a check box form field, which shows its box and no result.
    check_box: bool,
    /// The entry that the field shows when it is a drop-down form field.
    drop_down: Option<String>,
    /// The lock flag of this field's start.
    locked: bool,
    /// Whether the first run of the field's code has `w:rtl`; none before the code.
    code_rtl: Option<bool>,
    /// The first run of the field's code; none before the code.
    code_run: Option<CodeRun>,
    /// Whether the field links and its shown result has started, so that its end ends a
    /// hyperlink's text.
    linked: bool,
}

enum FieldState {
    /// Before the separator.
    Code,
    /// In the stored result, which is shown.
    Kept,
    /// In the stored result of a computed field, before its first content, which takes the
    /// computed value with that content's run properties.
    Pending(Box<Content>),
    /// In the stored result of a computed field, after the value.
    Replaced,
}

impl Field {
    /// Whether the field is a text form field.
    fn is_form_text(&self) -> bool {
        field_code::kind(&self.code).is_some_and(|kind| kind.eq_ignore_ascii_case(FORM_TEXT))
    }

    /// The format that the computed `value` of the field takes from its code run: for a page
    /// number or page count, when the code has no `\* MERGEFORMAT`. Word
    /// for Windows lays out and draws the value with the size, face, weight, slant and color of
    /// the code run, and with `\* MERGEFORMAT` with those of the run of the stored result.
    fn value_format(&self, value: &Content) -> Option<CodeFormat> {
        let page_number = matches!(value, Content::PageNumber | Content::PageCount);
        if page_number && !merges_format(&self.code) {
            self.code_run
                .as_ref()
                .map(|code| CodeFormat::of(&code.props))
        } else {
            None
        }
    }

    /// The state of the field after its separator: a check box shows no result, a computed
    /// field waits for its value's place, and any other field keeps its stored result.
    fn result_state(&self, value: Option<Content>) -> FieldState {
        if self.check_box {
            FieldState::Replaced
        } else {
            value.map_or(FieldState::Kept, |value| {
                FieldState::Pending(Box::new(value))
            })
        }
    }

    /// The value of the field when layout computes it, with the field's stored result of
    /// `stored` where the value keeps it, such as a date's. `updates` says which fields Word
    /// updates in the story, `saved` is the picture of a save or print date without its own
    /// ([`computed_field`]), and `bookmarks` holds the names of the story's bookmarks. Call it
    /// once, when the field's code ends: the value of an `IF` field takes the parts of the
    /// code, which nothing reads after the code.
    fn take_value(
        &mut self,
        stored: &[String],
        (updates, saved): (Updates, Option<&str>),
        bookmarks: &BTreeSet<String>,
    ) -> Option<Content> {
        if let Some(entry) = self.drop_down.take()
            && field_code::kind(&self.code)
                .is_some_and(|kind| kind.eq_ignore_ascii_case(FORM_DROP_DOWN))
        {
            return Some(Content::Text(entry));
        }
        let mut value = computed_field(&self.code, saved)?;
        if let Content::NumberRef(field) = &value {
            // A field of text keeps its stored result unless its bookmark is missing, where
            // Word shows its error text instead.
            let text_shown = field.kind.is_none() && bookmarks.contains(&field.bookmark);
            if text_shown || self.locked || updates != Updates::References {
                return None;
            }
        }
        let stored = || stored.get(self.index).cloned().unwrap_or_default();
        match &mut value {
            Content::Date(date) => date.stored = stored(),
            Content::DocProperty(property) => property.stored = stored(),
            Content::StyleRef(style_ref) => style_ref.stored = stored(),
            Content::PageRef(page_ref) => {
                page_ref.stored = stored();
                page_ref.code.clone_from(&self.code_run);
            }
            Content::NumberRef(reference) => {
                reference.stored = stored();
                reference.code.clone_from(&self.code_run);
            }
            Content::If(field_if) => {
                field_if.parts = std::mem::take(&mut self.parts);
                field_if.stored = stored();
            }
            _ => {}
        }
        Some(value)
    }
}

impl Fields {
    /// The marks of the open fields in Word's text: the start of each, and the separator of
    /// each that is in its result.
    fn open_marks(&self) -> usize {
        self.open
            .iter()
            .map(|field| match field.state {
                FieldState::Code => TEXT_BUFFER_MARK_LENGTH,
                FieldState::Kept | FieldState::Pending(_) | FieldState::Replaced => {
                    2 * TEXT_BUFFER_MARK_LENGTH
                }
            })
            .sum()
    }

    /// The innermost open field that is still in its code.
    fn coding(&mut self) -> Option<&mut Field> {
        self.open
            .iter_mut()
            .rev()
            .find(|field| matches!(field.state, FieldState::Code))
    }

    fn push(&mut self, item: Content, out: &mut Vec<Content>) {
        let begins_too_deep =
            matches!(item, Content::FieldBegin) && self.open.len() >= MAX_FIELD_DEPTH;
        if begins_too_deep || self.too_deep_open > 0 {
            self.push_too_deep(item, out);
            return;
        }
        match item {
            Content::FieldBegin => {
                self.open.push(Field {
                    code: String::new(),
                    parts: Vec::new(),
                    index: self.begun,
                    state: FieldState::Code,
                    check_box: false,
                    drop_down: None,
                    locked: false,
                    code_rtl: None,
                    code_run: None,
                    linked: false,
                });
                self.begun += 1;
            }
            Content::FieldLock => {
                self.lock();
            }
            Content::FieldCode(code) => self.code(code),
            Content::CheckBox(_) => self.check_box(item, out),
            Content::DropDown(entry) => {
                if let Some(field) = self.open.last_mut() {
                    field.drop_down = Some(entry);
                }
            }
            Content::FieldSeparate => self.separate(out),
            Content::FieldEnd => self.end(out),
            other => self.result(other, out),
        }
    }

    /// Takes an item of a field that begins while [`MAX_FIELD_DEPTH`] fields are open, or of a
    /// field inside one. The reader does not read such a field as a field: it leaves out its
    /// marks and the text of its code, and reads its other content, such as its stored result,
    /// as content of the field around it.
    fn push_too_deep(&mut self, item: Content, out: &mut Vec<Content>) {
        match item {
            Content::FieldBegin => {
                self.too_deep_open += 1;
                self.too_deep = self.too_deep.saturating_add(1);
                // The field keeps its place in the order of the story's fields, by which the
                // later fields find their stored results.
                self.begun += 1;
            }
            Content::FieldEnd => self.too_deep_open = self.too_deep_open.saturating_sub(1),
            Content::FieldLock
            | Content::DropDown(_)
            | Content::FieldCode(_)
            | Content::FieldSeparate => {}
            other => self.result(other, out),
        }
    }

    /// Adds the text of a field code to the innermost open field when that field is in its
    /// code, or to the code of an outer field.
    fn code(&mut self, code: String) {
        let in_own_code = self
            .open
            .last()
            .is_some_and(|field| matches!(field.state, FieldState::Code));
        if in_own_code {
            let run_rtl = self.run_rtl;
            if let Some(field) = self.open.last_mut() {
                field.code_rtl = field.code_rtl.or(run_rtl);
                if field.code_run.is_none() {
                    field.code_run.clone_from(&self.run_code);
                }
                field.code.push_str(&code);
                field.parts.push(CodePart::Text(code));
            }
        } else if self.in_code() {
            // Some files write the stored result of a field nested in a code as
            // instruction text. It is the nested field's value there.
            self.code_content(Content::Text(code));
        }
    }

    /// Ends the code of the innermost field: it keeps its stored result or waits for its
    /// computed value's place.
    fn separate(&mut self, out: &mut Vec<Content>) {
        // An `IF` field with a stored result shows that result, except in a header or
        // footer. Where Word updates only the fields without a stored result, every
        // field with one shows it.
        let updates = self.updates;
        if let Some(field) = self.open.last_mut() {
            let stored = self
                .stored
                .get(field.index)
                .is_some_and(|text| !text.is_empty());
            let value = field
                .take_value(&self.stored, (updates, self.saved_date), &self.bookmarks)
                .filter(|value| updates.updates(value, stored));
            field.state = field.result_state(value);
        }
        // A field result that the story shows, stored or computed, starts a text
        // object.
        // The shown result of a field that links is a hyperlink's text.
        if let Some((field, outer)) = self.open.split_last_mut()
            && matches!(field.state, FieldState::Kept | FieldState::Pending(_))
            && shows(outer)
        {
            out.push(Content::FieldMark);
            if let Some(link) = Hyperlink::of_code(&field.code) {
                field.linked = true;
                self.links.push(LinkMark::Start(Box::new(link)));
            }
        }
    }

    /// Ends the innermost field and shows a computed value that has not taken its place yet.
    fn end(&mut self, out: &mut Vec<Content>) {
        let ended = self.open.pop();
        if let Some(field) = ended.as_ref().filter(|field| field.check_box)
            && let Some(code) = &field.code_run
        {
            self.check_box_formats
                .insert(field.index, CodeFormat::of(&code.props).with_own_color());
        }
        let shown = shows(&self.open);
        let mut linked = false;
        if let Some(field) = ended {
            linked = field.linked;
            linked |= self.show_value(field, shown, out);
        }
        if linked {
            self.links.push(LinkMark::End);
        }
        // The text after a field's end starts a text object.
        if shown {
            out.push(Content::FieldMark);
        }
    }

    /// Shows the computed value of `field`, which has just ended, when the value has not taken
    /// its place yet: a field without a separator, or with an empty result, still shows its
    /// value. In the code of another field, the value becomes part of that code. `shown` says
    /// whether the content around the field shows. It says whether the value of a field
    /// without a separator starts a hyperlink's text, which the field's end ends.
    fn show_value(&mut self, mut field: Field, shown: bool, out: &mut Vec<Content>) -> bool {
        let without_separator = matches!(field.state, FieldState::Code);
        let value = match std::mem::replace(&mut field.state, FieldState::Replaced) {
            FieldState::Code => field.take_value(
                &self.stored,
                (self.updates, self.saved_date),
                &self.bookmarks,
            ),
            FieldState::Pending(value) => Some(*value),
            FieldState::Kept | FieldState::Replaced => None,
        };
        let Some(value) = value else {
            return false;
        };
        let value_format = field.value_format(&value);
        if let Some(outer) = self.coding() {
            outer.parts.push(CodePart::Field(value));
            return false;
        }
        let direction = self.updates.result_direction(&value, field.code_rtl);
        self.result_rtl = direction.or(self.result_rtl);
        self.result_format = value_format.or(self.result_format.take());
        // The value of a field without a separator is its result, which starts a text object,
        // and a hyperlink's text when the field links.
        let mut linked = false;
        if without_separator && shown {
            out.push(Content::FieldMark);
            if let Some(link) = Hyperlink::of_code(&field.code) {
                self.links.push(LinkMark::Start(Box::new(link)));
                linked = true;
            }
        }
        out.push(value);
        linked
    }

    /// Retains the lock of the innermost field.
    fn lock(&mut self) {
        if let Some(field) = self.open.last_mut() {
            field.locked = true;
        }
    }

    /// Shows the box of a check box form field in the run that starts the field, unless the
    /// field lies in the code of another field, and marks the field.
    fn check_box(&mut self, item: Content, out: &mut Vec<Content>) {
        let nested = self
            .open
            .iter()
            .rev()
            .skip(1)
            .any(|field| matches!(field.state, FieldState::Code));
        if let Some(field) = self.open.last_mut() {
            field.check_box = true;
            if !nested {
                self.check_boxes.push((self.run, field.index));
                out.push(item);
            }
        }
    }

    /// Whether content now lies in the code of an open field, before its separator.
    fn in_code(&self) -> bool {
        self.open
            .iter()
            .any(|field| matches!(field.state, FieldState::Code))
    }

    /// Shows content of a stored result, or replaces it with a computed value. Content in the
    /// code of a field shows nothing, and its text, such as a non-breaking hyphen in a switch,
    /// belongs to the code.
    fn result(&mut self, item: Content, out: &mut Vec<Content>) {
        // A bookmark keeps its place, also in a field's code or in a result that a computed
        // value replaces.
        if matches!(item, Content::Bookmark(_)) {
            out.push(item);
            return;
        }
        if self.in_code() {
            self.code_content(item);
            return;
        }
        let updates = self.updates;
        let replacing = self
            .open
            .iter_mut()
            .find(|f| matches!(f.state, FieldState::Pending(_) | FieldState::Replaced));
        let Some(field) = replacing else {
            if matches!(item, Content::Text(_)) && self.open.iter().any(Field::is_form_text) {
                self.form_text = true;
            }
            out.push(item);
            return;
        };
        if let FieldState::Pending(value) =
            std::mem::replace(&mut field.state, FieldState::Replaced)
        {
            self.stored_characters += self
                .stored
                .get(field.index)
                .map_or(0, |text| text.encode_utf16().count());
            let direction = updates.result_direction(&value, field.code_rtl);
            self.result_rtl = direction.or(self.result_rtl);
            self.result_format = field.value_format(&value).or(self.result_format.take());
            out.push(*value);
        }
    }

    /// Takes content that lies in the code of a field. Text of the code itself joins the
    /// code. Inside the stored result of a field nested in the code, the stored text, or the
    /// computed value in its place, becomes part of the outer code.
    fn code_content(&mut self, item: Content) {
        let Some(last) = self.open.last_mut() else {
            return;
        };
        let part = match &mut last.state {
            FieldState::Code => {
                if let Content::Text(text) = &item {
                    last.code.push_str(text);
                    last.parts.push(CodePart::Text(text.clone()));
                }
                return;
            }
            FieldState::Kept => match item {
                Content::Text(text) => CodePart::Text(text),
                _ => return,
            },
            FieldState::Pending(_) => {
                let FieldState::Pending(value) =
                    std::mem::replace(&mut last.state, FieldState::Replaced)
                else {
                    return;
                };
                CodePart::Field(*value)
            }
            FieldState::Replaced => return,
        };
        if let Some(field) = self.coding() {
            field.parts.push(part);
        }
    }
}