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
//! The text buffers in which Word gathers the text of a document's runs.

use crate::body::{Block, Content, Paragraph, Run, field_code};
use crate::params::{
    HYPERLINK_FIELD_EXTRA_LENGTH, TEXT_BUFFER_FIRST_FILL, TEXT_BUFFER_LENGTH,
    TEXT_BUFFER_MARK_LENGTH,
};
use crate::reader::settings::ReaderSettings;

/// What the text buffers of a target count beside the text and the marks of the runs.
#[derive(Clone, Copy)]
pub struct Counting<'a> {
    /// The reader's settings, which say what a field, a hyperlink and a comment's reference
    /// take.
    pub settings: ReaderSettings,
    /// The characters of the target of a relationship of the body's part, by its ID.
    pub target: &'a dyn Fn(&str) -> usize,
}

/// Marks each run of `blocks` that starts a text buffer. Word gathers the text of the runs,
/// through the paragraphs and table cells in their order, in a buffer of
/// [`TEXT_BUFFER_LENGTH`] characters, whatever the properties of the runs. The end of a
/// paragraph, the end of a table cell and the end of a table row each count as a mark of
/// [`TEXT_BUFFER_MARK_LENGTH`]. A run that does not fit in the rest of the buffer starts a new
/// one, and a run longer than a buffer leaves an empty one behind it. On a target that counts
/// the marks of fields, the marks of the fields that are open after a run do not count toward
/// the buffer's length when the run is placed, and a buffer that a run starts holds again the
/// marks of the fields that are open all through the run. At the document's first
/// character the buffer already holds [`TEXT_BUFFER_FIRST_FILL`] characters. `counting` says
/// what else the target's Word holds in its text.
pub fn mark(blocks: &mut [Block], counting: &Counting<'_>) {
    let mut filled = TEXT_BUFFER_FIRST_FILL;
    mark_blocks(blocks, &mut filled, counting);
}

fn mark_blocks(blocks: &mut [Block], filled: &mut usize, counting: &Counting<'_>) {
    for block in blocks {
        match block {
            Block::Paragraph(paragraph) => mark_paragraph(paragraph, filled, counting),
            Block::Table(table) => {
                for row in &mut table.rows {
                    for cell in &mut row.cells {
                        mark_blocks(&mut cell.blocks, filled, counting);
                        // The end of a cell is a mark of its own, after the end of the
                        // cell's last paragraph.
                        *filled += TEXT_BUFFER_MARK_LENGTH;
                    }
                    // The end of a row is a mark of its own in Word's text.
                    *filled += TEXT_BUFFER_MARK_LENGTH;
                }
            }
        }
    }
}

fn mark_paragraph(paragraph: &mut Paragraph, filled: &mut usize, counting: &Counting<'_>) {
    // A buffer that a run without content starts starts a text object at the next text, and a
    // run longer than a buffer occupies a buffer of its own so the next text starts a new one.
    let mut carried = false;
    for run in &mut paragraph.runs {
        let text = run
            .content
            .iter()
            .any(|content| matches!(content, Content::Text(_)));
        if carried && text {
            run.starts_buffer = true;
            carried = false;
        }
        let length = buffer_only(run, counting)
            + run
                .content
                .iter()
                .map(|content| length_of(content, counting))
                .sum::<usize>();
        let (open, held) = open_marks(run, counting);
        if *filled + length > TEXT_BUFFER_LENGTH + open {
            run.starts_buffer = true;
            carried |= run.content.is_empty() || length > TEXT_BUFFER_LENGTH;
            *filled = held
                + if length > TEXT_BUFFER_LENGTH {
                    0
                } else {
                    length
                };
        } else {
            *filled += length;
        }
    }
    *filled += TEXT_BUFFER_MARK_LENGTH;
}

/// The buffer-only characters of a run (`Run::buffer_only`) that the target counts: the marks
/// and the code of the fields that the run held, and those of the field that Word makes of a
/// hyperlink with the characters of its address, on a target that counts them.
fn buffer_only(run: &Run, counting: &Counting<'_>) -> usize {
    counting
        .settings
        .buffer_only(&run.buffer_only, counting.target)
}

/// The marks of open fields that a run leaves out of a buffer's length and that a buffer it
/// starts holds again (`BufferOnly::open` and `BufferOnly::held`), on a target that counts
/// them.
fn open_marks(run: &Run, counting: &Counting<'_>) -> (usize, usize) {
    counting.settings.open_marks(&run.buffer_only)
}

/// The characters of the external address `target` in the code of the field that Word makes of
/// a hyperlink: the address as the relationship writes it, but for a fragment after `#`, which
/// becomes a switch with its value, ` \l "fragment"`.
pub(crate) fn address_characters(target: &str) -> usize {
    match target.split_once('#') {
        Some((address, fragment)) => {
            characters(address) + characters(&format!(" \\l \"{fragment}\""))
        }
        None => characters(target),
    }
}

/// The characters of `text` in Word's text: its UTF-16 code units.
pub(crate) fn characters(text: &str) -> usize {
    text.encode_utf16().count()
}

/// The characters of the marks and the code of the fields among `content`, which the reader
/// takes out of a run once it reads the fields: a mark of [`TEXT_BUFFER_MARK_LENGTH`] for each
/// field's start, separator and end, the code in UTF-16 code units, and
/// [`HYPERLINK_FIELD_EXTRA_LENGTH`] more for the code of a field that links
/// (`field_code::links`).
pub(crate) fn field_characters(content: &[Content]) -> usize {
    content
        .iter()
        .map(|item| match item {
            Content::FieldBegin | Content::FieldSeparate | Content::FieldEnd => {
                TEXT_BUFFER_MARK_LENGTH
            }
            Content::FieldCode(code) => {
                code.encode_utf16().count()
                    + usize::from(field_code::links(code)) * HYPERLINK_FIELD_EXTRA_LENGTH
            }
            _ => 0,
        })
        .sum()
}

/// The characters of a run's content in UTF-16 code units: its text and the code of a field,
/// nothing for a bookmark, a mark of [`TEXT_BUFFER_MARK_LENGTH`] or nothing for a comment's
/// anchor (its reference) as `counting` says, and a mark for each other piece of content, such
/// as a tab, a line break or a field's mark. Each kind of content is named, so that a new kind
/// does not compile until it is counted.
fn length_of(content: &Content, counting: &Counting<'_>) -> usize {
    match content {
        Content::CommentAnchor(_) => counting.settings.comment_anchor_length(),
        // A value that Word computes counts as its field's stored result, which the reader
        // leaves as buffer-only characters, on a target that counts the marks of fields.
        Content::PageNumber
        | Content::PageCount
        | Content::Date(_)
        | Content::DocProperty(_)
        | Content::StyleRef(_)
        | Content::PageRef(_)
        | Content::NumberRef(_)
        | Content::If(_) => counting.settings.computed_value_length(),
        Content::Text(text) | Content::FieldCode(text) => text.encode_utf16().count(),
        Content::Bookmark(_)
        | Content::FieldMark
        | Content::HyperlinkEdge
        | Content::ControlEdge
        | Content::RemovedEdge
        | Content::Stack(_)
        | Content::Grown(_)
        | Content::Radical(_)
        | Content::Accent(_)
        | Content::Matrix(_)
        | Content::MathBar(_)
        | Content::MathSlash(_)
        | Content::MathLimit(_)
        | Content::GroupChr(_)
        | Content::MathBox(_)
        | Content::Scripts(_)
        | Content::Advance(_)
        | Content::FieldLock
        | Content::DropDown(_) => 0,
        Content::Tab
        | Content::PositionTab { .. }
        | Content::LineBreak
        | Content::ClearingBreak
        | Content::PageBreak
        | Content::ColumnBreak
        | Content::FieldBegin
        | Content::CheckBox(_)
        | Content::FieldSeparate
        | Content::FieldEnd
        | Content::FootnoteReference(..)
        | Content::FootnoteMark
        | Content::EndnoteReference(..)
        | Content::EndnoteMark
        | Content::CommentMark
        | Content::Separator
        | Content::ContinuationSeparator
        | Content::Floating(_)
        | Content::Object { .. }
        | Content::Drawing(_) => TEXT_BUFFER_MARK_LENGTH,
    }
}

#[cfg(test)]
mod tests {
    use crate::body::{Block, Body, Content, Paragraph, Run};
    use crate::quirks::{BodyFieldResults, CommentBuffer, FieldBuffer};
    use crate::reader::PartReader;
    use crate::reader::settings::ReaderSettings;
    use f_office_xml::{Document, Limits};

    /// A paragraph of runs of `x` with these lengths.
    fn paragraph(lengths: &[usize]) -> Block {
        Block::Paragraph(Paragraph {
            runs: lengths
                .iter()
                .map(|&length| Run {
                    content: vec![Content::Text("x".repeat(length))],
                    ..Run::default()
                })
                .collect(),
            ..Paragraph::empty()
        })
    }

    /// F-Office's count before the hyperlink rule, with no relationships.
    fn text_only() -> super::Counting<'static> {
        super::Counting {
            settings: ReaderSettings::base()
                .with_fields(FieldBuffer::ResultOnly)
                .with_comments(CommentBuffer::Nothing),
            target: &|_| 0,
        }
    }

    /// The runs of each paragraph that start a buffer.
    fn starts(blocks: &[Block]) -> Vec<Vec<usize>> {
        blocks
            .iter()
            .map(|block| match block {
                Block::Paragraph(paragraph) => paragraph
                    .runs
                    .iter()
                    .enumerate()
                    .filter_map(|(index, run)| run.starts_buffer.then_some(index))
                    .collect(),
                Block::Table(_) => Vec::new(),
            })
            .collect()
    }

    /// The run of the trailing paragraph that starts a buffer, in a document of a 600-character
    /// run, the markup `between`, and a trailing paragraph of a 430-character run followed by 82
    /// one-character runs.
    fn trailing_run_start(between: &str, counting: &super::Counting<'_>) -> Vec<usize> {
        let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
        let body = format!(
            "<w:p>{}</w:p>{between}<w:p>{}{}</w:p>",
            run(600),
            run(430),
            run(1).repeat(82)
        );
        read_starts(&body, counting).pop().unwrap()
    }

    /// `length` letters.
    fn text(length: usize) -> String {
        "x".repeat(length)
    }

    /// The runs that start a buffer in each paragraph of the body whose content is `body`.
    fn read_starts(body: &str, counting: &super::Counting<'_>) -> Vec<Vec<usize>> {
        let xml = format!(
            r#"<w:body xmlns:w="{}" xmlns:r="{}">{body}</w:body>"#,
            crate::ns::W,
            crate::ns::R,
        );
        let mut doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        // The tracked changes accepted, as a target that prints without markup reads them.
        crate::revisions::accept(
            &mut doc,
            counting
                .settings
                .with_insertions(crate::quirks::InsertionRevision::Author),
        );
        let mut body = Body::read(
            &mut PartReader::new(&doc),
            doc.root().unwrap(),
            (
                ReaderSettings::base()
                    .with_body_results(BodyFieldResults::ComputesFields)
                    .with_section_ends(crate::quirks::ContinuousSectionEnd::OnlyBlockKeepsLine),
                crate::mode::ModeRules::default(),
            ),
        );
        super::mark(&mut body.blocks, counting);
        starts(&body.blocks)
    }

    /// The characters that the paragraph of the content `case` takes in the buffer in which a
    /// trailing paragraph starts the next one: a document of a 600-character run, which leaves
    /// an empty buffer, the paragraph, and 512 one-character runs.
    fn count_after(case: &str, counting: &super::Counting<'_>) -> Option<usize> {
        count_after_blocks(&format!("<w:p>{case}</w:p>"), counting)
    }

    /// The characters that the blocks `blocks` take, as [`count_after`] counts those of one
    /// paragraph.
    fn count_after_blocks(blocks: &str, counting: &super::Counting<'_>) -> Option<usize> {
        let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
        let body = format!(
            "<w:p>{}</w:p>{blocks}<w:p>{}</w:p>",
            run(600),
            run(1).repeat(512)
        );
        let starts = read_starts(&body, counting);
        Some(511 - starts.last()?.first()?)
    }

    /// The counts that Word gives where a buffer starts inside a field or a hyperlink: a field
    /// keeps its open field marks out of the buffer's length, and a buffer that starts inside it
    /// holds them again.
    #[test]
    fn holds_the_open_marks_of_fields_again() {
        let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
        let mark = |kind: &str| format!(r#"<w:r><w:fldChar w:fldCharType="{kind}"/></w:r>"#);
        let code = |code: &str| {
            format!(r#"<w:r><w:instrText xml:space="preserve">{code}</w:instrText></w:r>"#)
        };
        let field = |code_runs: &str, result: &str| {
            format!(
                "{}{code_runs}{}{result}{}",
                mark("begin"),
                mark("separate"),
                mark("end")
            )
        };
        let addin = |length: usize| code(&format!(" ADDIN F {}", "b".repeat(length - 9)));
        let short = field(&addin(20), &run(3));
        let link = |length: usize| {
            format!(
                r#"{}<w:hyperlink w:anchor="none" w:history="1">{}{}</w:hyperlink>"#,
                run(length),
                run(3),
                run(40)
            )
        };
        let cases = [
            (run(488) + &field(&addin(20), &(run(3) + &run(40))), 43),
            (run(470) + &field(&addin(20), &(run(3) + &run(40))), 43),
            (run(500) + &short, 26),
            (run(489) + &short, 6),
            (run(486) + &short, 1),
            (run(475) + &field(&addin(20), &(run(3) + &short)), 29),
            (run(463) + &field(&addin(20), &(run(3) + &short)), 4),
            (field(&addin(700), &run(3)), 6),
            (link(495), 64),
            (link(470), 41),
        ];
        let counting = super::Counting {
            settings: ReaderSettings::base()
                .with_fields(FieldBuffer::MarksAndCode)
                .with_comments(CommentBuffer::Nothing),
            target: &|_| 0,
        };
        for (case, count) in cases {
            assert_eq!(count_after(&case, &counting), Some(count), "{case}");
        }
    }

    /// The counts that Word gives for the stored results of computed fields, for fields
    /// without a result or a separator, for references with and without the link switch, and
    /// for hyperlinks with a location or an address with a fragment.
    #[test]
    fn counts_stored_results_links_and_locations() {
        let ham = format!("<w:r><w:t>{}</w:t></w:r>", text(3));
        let mark = |kind: &str| format!(r#"<w:r><w:fldChar w:fldCharType="{kind}"/></w:r>"#);
        let complex = |code: &str, result: &str| {
            format!(
                r#"{}<w:r><w:instrText xml:space="preserve">{code}</w:instrText></w:r>{}<w:r><w:t>{result}</w:t></w:r>{}"#,
                mark("begin"),
                mark("separate"),
                mark("end")
            )
        };
        let simple = |code: &str, result: &str| {
            format!(r#"<w:fldSimple w:instr="{code}"><w:r><w:t>{result}</w:t></w:r></w:fldSimple>"#)
        };
        let marked = |field: String| {
            format!(
                r#"<w:bookmarkStart w:id="1" w:name="bk01"/>{ham}<w:bookmarkEnd w:id="1"/>{field}"#
            )
        };
        let cases = [
            (simple(" PAGE ", "99999"), 15),
            (r#"<w:fldSimple w:instr=" PAGE "/>"#.to_owned(), 10),
            (
                format!(
                    r#"{}<w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r>{}"#,
                    mark("begin"),
                    mark("end")
                ),
                9,
            ),
            (simple(" NUMPAGES ", "999"), 17),
            (
                simple(" DATE \\@ &quot;yyyy-MM-dd&quot; ", "2000-01-01"),
                36,
            ),
            (marked(complex(" PAGEREF bk01 \\h ", "99999")), 30),
            (marked(complex(" PAGEREF bk01 ", "99999")), 26),
            (marked(complex(" REF bk01 \\h ", "99999")), 26),
            (marked(complex(" REF bk01 ", "99999")), 22),
            (complex(" ADDIN \\h ", "Ham"), 17),
            (
                format!(
                    r#"<w:hyperlink w:anchor="none" w:docLocation="abcdefgh">{ham}</w:hyperlink>"#
                ),
                44,
            ),
            (
                format!(r#"<w:hyperlink r:id="rId9">{ham}</w:hyperlink>"#),
                42,
            ),
        ];
        let counting = super::Counting {
            settings: ReaderSettings::base()
                .with_fields(FieldBuffer::MarksAndCode)
                .with_comments(CommentBuffer::Nothing),
            target: &|id| {
                if id == "rId9" {
                    super::address_characters("http://a.b/#xy")
                } else {
                    0
                }
            },
        };
        for (case, count) in cases {
            assert_eq!(count_after(&case, &counting), Some(count), "{case}");
        }
        assert_eq!(super::address_characters("http://a.b/%7Eb"), 15);
    }

    /// The counts that Word gives for deleted text and a deleted paragraph mark, which a
    /// target that prints without markup accepts, and for inline and block content controls,
    /// also where a buffer starts inside a control.
    #[test]
    fn counts_deletions_and_content_controls() {
        let ham = format!("<w:r><w:t>{}</w:t></w:r>", text(3));
        let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
        let cases = [
            (
                format!(
                    r#"<w:p>{ham}<w:del w:id="1" w:author="a"><w:r><w:delText>{}</w:delText></w:r></w:del></w:p>"#,
                    text(5)
                ),
                9,
            ),
            (
                format!(
                    r#"<w:p><w:pPr><w:rPr><w:del w:id="1" w:author="a"/></w:rPr></w:pPr>{ham}</w:p><w:p/>"#
                ),
                5,
            ),
            (
                format!(
                    r#"<w:p><w:sdt><w:sdtPr><w:id w:val="1"/></w:sdtPr><w:sdtContent>{ham}</w:sdtContent></w:sdt></w:p>"#
                ),
                6,
            ),
            (
                format!(
                    r#"<w:sdt><w:sdtPr><w:id w:val="1"/></w:sdtPr><w:sdtContent><w:p>{ham}</w:p></w:sdtContent></w:sdt>"#
                ),
                6,
            ),
            (
                format!(
                    "<w:p>{}<w:sdt><w:sdtContent>{ham}{}</w:sdtContent></w:sdt></w:p>",
                    run(490),
                    run(40)
                ),
                42,
            ),
        ];
        let counting = super::Counting {
            settings: ReaderSettings::base()
                .with_fields(FieldBuffer::MarksAndCode)
                .with_comments(CommentBuffer::Nothing),
            target: &|_| 0,
        };
        for (case, count) in cases {
            assert_eq!(count_after_blocks(&case, &counting), Some(count), "{case}");
        }
    }

    #[test]
    fn starts_a_buffer_at_the_run_that_does_not_fit() {
        // The paragraphs of one document, in their order.
        let mut blocks = vec![
            paragraph(&[700]),
            paragraph(&[700]),
            paragraph(&[48, 256, 96]),
            paragraph(&[48, 256, 96]),
            paragraph(&[35, 256, 256, 127]),
            paragraph(&[35, 256, 256, 127]),
            paragraph(&[226, 256, 256, 73]),
            paragraph(&[226, 256, 256, 73]),
            paragraph(&[103, 97]),
            paragraph(&[103, 97]),
        ];
        super::mark(&mut blocks, &text_only());
        assert_eq!(
            starts(&blocks),
            [
                vec![0],
                vec![0],
                vec![],
                vec![1],
                vec![1, 3],
                vec![2],
                vec![0, 2],
                vec![0, 2],
                vec![1],
                vec![],
            ]
        );
    }

    #[test]
    fn counts_a_paragraph_end_as_one_character() {
        // The buffer holds 4 characters at the start: 4 + 507 + 1 fill it.
        let mut blocks = vec![paragraph(&[507]), paragraph(&[1]), paragraph(&[1])];
        super::mark(&mut blocks, &text_only());
        assert_eq!(starts(&blocks), [vec![], vec![0], vec![]]);
    }

    /// Two documents: a trailing paragraph alone, and one after paragraphs of 27, 46 and 18
    /// characters plus an empty one.
    #[test]
    fn starts_with_four_characters_in_the_buffer() {
        let trailing = |first: usize| {
            let mut lengths = vec![first];
            lengths.extend([1; 82]);
            paragraph(&lengths)
        };
        let mut blocks = vec![trailing(430)];
        super::mark(&mut blocks, &text_only());
        assert_eq!(starts(&blocks), [vec![508 - 430 + 1]]);
        let mut blocks = vec![
            paragraph(&[27]),
            paragraph(&[46]),
            paragraph(&[18]),
            paragraph(&[]),
            trailing(340),
        ];
        super::mark(&mut blocks, &text_only());
        assert_eq!(starts(&blocks).pop().unwrap(), [413 - 340 + 1]);
    }

    /// Verifies paragraph and table mark counts: the one-character run that starts a buffer is
    /// run 82 less the count.
    #[test]
    fn counts_the_marks_of_paragraphs_and_tables() {
        let cell = "<w:tc><w:p/></w:tc>";
        let cases = [
            (String::new(), 0),
            ("<w:p/>".to_owned(), 1),
            ("<w:p><w:r><w:t>Ham</w:t></w:r></w:p>".to_owned(), 4),
            (format!("<w:tbl><w:tr>{cell}</w:tr></w:tbl>"), 3),
            (format!("<w:tbl><w:tr>{cell}{cell}</w:tr></w:tbl>"), 5),
            (
                format!("<w:tbl><w:tr>{cell}{cell}</w:tr><w:tr>{cell}{cell}</w:tr></w:tbl>"),
                10,
            ),
            ("<w:p><w:r><w:tab/></w:r></w:p>".to_owned(), 2),
            ("<w:p><w:r><w:br/></w:r></w:p>".to_owned(), 2),
        ];
        for (between, count) in cases {
            assert_eq!(
                trailing_run_start(&between, &text_only()),
                [82 - count],
                "{between}"
            );
        }
    }

    /// The counts that Word gives for hyperlinks and fields on a target that counts a field's
    /// marks and code, and F-Office's count before the rule, which counts a field's result
    /// alone and a hyperlink's text alone.
    #[test]
    fn counts_fields_and_hyperlinks_as_the_quirk_says() {
        let link = |attributes: &str, runs: &str| {
            format!("<w:p><w:hyperlink {attributes}>{runs}</w:hyperlink></w:p>")
        };
        let ham = "<w:r><w:t>Ham</w:t></w:r>";
        let field = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> HYPERLINK \l "none" </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>Ham</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
        let page = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
        let simple_page =
            r#"<w:p><w:fldSimple w:instr=" PAGE "><w:r><w:t>1</w:t></w:r></w:fldSimple></w:p>"#;
        let cases = [
            (link(r#"w:anchor="a""#, ham), 27, 4),
            (link(r#"w:anchor="none""#, ham), 30, 4),
            (link(r#"w:anchor="abcdefghijklmnop""#, ham), 42, 4),
            (link(r#"r:id="rId9""#, ham), 34, 4),
            (link(r#"w:anchor="none" w:tooltip="tip""#, ham), 39, 4),
            (link(r#"w:anchor="none" w:history="1""#, ham), 27, 4),
            (link(r#"w:anchor="none" w:tgtFrame="_blank""#, ham), 42, 4),
            (
                link(
                    r#"w:anchor="none""#,
                    "<w:r><w:t>Ha</w:t></w:r><w:r><w:t>m</w:t></w:r>",
                ),
                30,
                4,
            ),
            (field.to_owned(), 29, 4),
            (page.to_owned(), 11, 2),
            (simple_page.to_owned(), 11, 2),
        ];
        // The address of `rId9` has 11 characters.
        let counting = super::Counting {
            settings: ReaderSettings::base()
                .with_fields(FieldBuffer::MarksAndCode)
                .with_comments(CommentBuffer::Nothing),
            target: &|id| if id == "rId9" { 11 } else { 0 },
        };
        for (between, field_count, text_count) in cases {
            assert_eq!(
                trailing_run_start(&between, &counting),
                [82 - field_count],
                "{between}"
            );
            assert_eq!(
                trailing_run_start(&between, &text_only()),
                [82 - text_count],
                "{between}"
            );
        }
    }

    /// A deleted run counts in the buffers as the same run counts live on Word for Windows: a
    /// comment's reference, a note's own mark and a separator a mark each, and alternate
    /// content only its shown branch.
    #[test]
    fn counts_a_deleted_run_as_the_same_run_live() {
        let counting = super::Counting {
            settings: ReaderSettings::base()
                .with_fields(FieldBuffer::MarksAndCode)
                .with_comments(CommentBuffer::ReferenceMark),
            target: &|_| 0,
        };
        let alternate = format!(
            r#"<mc:AlternateContent xmlns:mc="{}" xmlns:w14="{}"><mc:Choice Requires="w14"><w:t>ab</w:t></mc:Choice><mc:Fallback><w:t>abcde</w:t></mc:Fallback></mc:AlternateContent>"#,
            crate::ns::MC,
            crate::ns::W14,
        );
        let cases = [
            ("<w:t>abcde</w:t>".to_owned(), 6),
            (r#"<w:commentReference w:id="1"/>"#.to_owned(), 2),
            (
                r#"<w:t>ab</w:t><w:commentReference w:id="1"/>"#.to_owned(),
                4,
            ),
            ("<w:footnoteRef/>".to_owned(), 2),
            ("<w:annotationRef/>".to_owned(), 2),
            ("<w:separator/>".to_owned(), 2),
            ("<w:continuationSeparator/>".to_owned(), 2),
            (alternate, 3),
        ];
        for (content, count) in cases {
            let live = format!("<w:p><w:r>{content}</w:r></w:p>");
            let deleted =
                format!(r#"<w:p><w:del w:id="9" w:author="A"><w:r>{content}</w:r></w:del></w:p>"#);
            assert_eq!(trailing_run_start(&live, &counting), [82 - count], "{live}");
            assert_eq!(
                trailing_run_start(&deleted, &counting),
                [82 - count],
                "{deleted}"
            );
        }
    }

    /// The counts of Word for Windows: a comment's reference takes a mark of one character,
    /// the marks of its range nothing, beside 3 letters and the paragraph's end.
    #[test]
    fn counts_a_comment_reference_as_a_mark() {
        let counting = super::Counting {
            settings: text_only()
                .settings
                .with_comments(CommentBuffer::ReferenceMark),
            ..text_only()
        };
        let letters = "<w:r><w:t>Ham</w:t></w:r>";
        let reference = |id: u32| format!(r#"<w:r><w:commentReference w:id="{id}"/></w:r>"#);
        let range =
            format!(r#"<w:commentRangeStart w:id="1"/>{letters}<w:commentRangeEnd w:id="1"/>"#);
        for (case, word) in [
            (letters.to_owned(), 4),
            (format!("{range}{}", reference(1)), 5),
            (format!("{letters}{}", reference(1)), 5),
            (range.clone(), 4),
            (format!("{letters}{}{}", reference(1), reference(2)), 6),
        ] {
            assert_eq!(count_after(&case, &counting), Some(word), "{case}");
            // F-Office's count before the rule leaves the reference out.
            assert_eq!(count_after(&case, &text_only()), Some(4), "{case}");
        }
    }

    /// A run longer than `TEXT_BUFFER_LENGTH` (513+) occupies a buffer of its own and leaves the
    /// next buffer empty (`filled = 0`), so the next text run in the same paragraph starts a new
    /// buffer (including across an empty run) and fills from zero.
    #[test]
    fn run_after_oversized_run_starts_new_buffer_from_zero() {
        let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
        let counting = text_only();
        // 512 control and 513 boundary both mark the following run at index 1.
        assert_eq!(
            read_starts(&format!("<w:p>{}{}</w:p>", run(512), run(40)), &counting),
            vec![vec![0, 1]]
        );
        assert_eq!(
            read_starts(&format!("<w:p>{}{}</w:p>", run(513), run(40)), &counting),
            vec![vec![0, 1]]
        );
        // Mid-paragraph oversized run: oversized run (1) and following run (2) both start buffers.
        assert_eq!(
            read_starts(
                &format!("<w:p>{}{}{}{}</w:p>", run(40), run(600), run(40), run(100)),
                &counting
            ),
            vec![vec![1, 2]]
        );
        // Empty run between oversized run and next text carries the buffer start to index 2.
        assert_eq!(
            read_starts(
                &format!("<w:p>{}<w:r/>{}</w:p>", run(600), run(40)),
                &counting
            ),
            vec![vec![0, 2]]
        );
        // Fill probe after 600: 40 + 400 + 72 fit (512); the 73rd 1-char run (index 75) overflows.
        let body = format!(
            "<w:p>{}{}{}{}</w:p>",
            run(600),
            run(40),
            run(400),
            run(1).repeat(80)
        );
        assert_eq!(read_starts(&body, &counting), vec![vec![0, 1, 75]]);
    }
}