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
//! `STYLEREF` fields: the text of the paragraphs and runs of each style on each page of the
//! body, and the text that a field in a header or footer takes from it.

use std::rc::Rc;

use crate::body::{Content, Paragraph, ParagraphId, StyleRef};
use crate::numbering::{Label, ReferenceKind};
use crate::styles::Styles;

use super::{Layout, decisions};

/// The text of one paragraph of the body, by style.
#[derive(Debug, Default)]
struct Styled {
    /// The paragraph style ID.
    style: Option<String>,
    /// The text of the paragraph.
    text: String,
    /// The character style ID and the text of each stretch of runs with one.
    runs: Vec<(String, String)>,
    /// The paragraph's number in its list, at its own level.
    number: Option<i64>,
    /// The paragraph number that a `STYLEREF` field with `\n` shows: the rendered pattern of
    /// the paragraph's level without trailing periods, as for a `REF` field with `\n`.
    pattern: Option<String>,
}

/// The styled text of the body, with the pages that each paragraph has lines on.
#[derive(Debug, Default)]
pub(super) struct StyledPages {
    paragraphs: Vec<Styled>,
    /// The page index and the paragraph index of each paragraph on each of its pages, in the
    /// order of the body.
    pages: Vec<(usize, usize)>,
}

impl StyledPages {
    /// The text that a `STYLEREF` field shows on page `page`: the text of the paragraph that
    /// [`Self::find`] finds, or with `\n` its paragraph number, which is 0 when the paragraph
    /// has no list number. None keeps the stored result: also a list number whose pattern
    /// gives no text.
    fn text(&self, styles: &Styles, field: &StyleRef, page: usize) -> Option<String> {
        let (index, text) = self.find(styles, field, page)?;
        if field.number {
            let paragraph = self.paragraphs.get(index)?;
            return match paragraph.number {
                None => Some("0".to_owned()),
                Some(_) => paragraph.pattern.clone(),
            };
        }
        Some(text.to_owned())
    }

    /// The paragraph that a `STYLEREF` field finds on page `page`, by its index, with its text
    /// of the style: the first text of the style on the page, or the last one with `\l`, or
    /// else the last one before the page, or else the first one after it.
    fn find(&self, styles: &Styles, field: &StyleRef, page: usize) -> Option<(usize, &str)> {
        let id = styles.id_of(&field.style);
        let found = |index: usize| -> Option<(usize, &str)> {
            let paragraph = self.paragraphs.get(index)?;
            if paragraph.style.as_deref() == Some(id) {
                return Some((index, paragraph.text.as_str()));
            }
            paragraph
                .runs
                .iter()
                .find(|(style, _)| style == id)
                .map(|(_, text)| (index, text.trim_matches([' ', '\u{a0}'])))
        };
        let on = |p: &&(usize, usize), wanted: fn(usize, usize) -> bool| wanted(p.0, page);
        let mut here = self
            .pages
            .iter()
            .filter(|p| on(p, |a, b| a == b))
            .filter_map(|p| found(p.1));
        let first = if field.last {
            here.next_back()
        } else {
            here.next()
        };
        first
            .or_else(|| {
                self.pages
                    .iter()
                    .rev()
                    .filter(|p| on(p, |a, b| a < b))
                    .find_map(|p| found(p.1))
            })
            .or_else(|| {
                self.pages
                    .iter()
                    .filter(|p| on(p, |a, b| a > b))
                    .find_map(|p| found(p.1))
            })
    }

    /// The chapter number on page `page`: the number of the first numbered paragraph of the
    /// heading style of `level` on the page, or else of the last one before it.
    fn chapter(&self, styles: &Styles, level: u8, page: usize) -> Option<i64> {
        let name = format!("heading {level}");
        let id = styles.id_of(&name);
        let number = |p: &(usize, usize)| {
            let paragraph = self.paragraphs.get(p.1)?;
            paragraph
                .number
                .filter(|_| paragraph.style.as_deref() == Some(id))
        };
        self.pages
            .iter()
            .filter(|p| p.0 == page)
            .find_map(number)
            .or_else(|| {
                self.pages
                    .iter()
                    .rev()
                    .filter(|p| p.0 < page)
                    .find_map(number)
            })
    }
}

/// The text of a paragraph and of its runs with a character style, with `field_text` giving
/// the text of each field that the layout computes, as the paragraph's own lines show it.
fn styled(paragraph: &Paragraph, field_text: impl Fn(&Content) -> String) -> Styled {
    let mut out = Styled {
        style: paragraph.props.style.clone(),
        ..Styled::default()
    };
    // The character style of the last run with text. Text of another style, or of none, ends
    // a stretch.
    let mut previous: Option<&String> = None;
    for run in &paragraph.runs {
        let mut text = String::new();
        for content in &run.content {
            push_text(&mut text, content, &field_text);
        }
        out.text.push_str(&text);
        if let Some(style) = &run.style {
            match out.runs.last_mut() {
                Some((last, joined)) if last == style && previous == Some(style) => {
                    joined.push_str(&text);
                }
                _ => out.runs.push((style.clone(), text.clone())),
            }
        }
        if !text.is_empty() || run.style.is_some() {
            previous = run.style.as_ref();
        }
    }
    out
}

/// Adds to `text` what a `STYLEREF` field shows of one piece of a paragraph's content: its
/// text, the text of a field that the layout computes, a tab character for a tab and a line
/// feed for a line break, which the field's text keeps as a tab and a break. Positional tabs,
/// page and column breaks, check boxes, note references, pictures, drawings, equation marks and
/// the codes and marks of fields, bookmarks and comments add nothing.
fn push_text(text: &mut String, content: &Content, field_text: &impl Fn(&Content) -> String) {
    match content {
        Content::Text(piece) => text.push_str(piece),
        Content::Tab => text.push('\t'),
        Content::LineBreak | Content::ClearingBreak => text.push('\n'),
        Content::PageNumber
        | Content::PageCount
        | Content::Date(_)
        | Content::DocProperty(_)
        | Content::StyleRef(_)
        | Content::PageRef(_)
        | Content::NumberRef(_)
        | Content::If(_) => text.push_str(&field_text(content)),
        _ => {}
    }
}

impl Layout<'_> {
    /// Notes that a paragraph of the body, with the label of its list number, has a line on
    /// the page being filled.
    pub(super) fn note_styled(&mut self, paragraph: &Paragraph, label: Option<&Label>) {
        let number = label.map(|label| label.value);
        let page = self.output.pages.len();
        if let (Some(chapter), Some(number)) = (self.section.chapter, number) {
            let name = format!("heading {}", chapter.level);
            if paragraph.props.style.as_deref() == Some(self.styles.id_of(&name)) {
                self.output.chapter_number = Some(number);
            }
        }
        // The record is taken out while the text of the paragraph's computed fields is
        // computed, which reads the layout, and put back after.
        if let Some(mut record) = self.output.styled.take() {
            record.note(paragraph, page, || Styled {
                number,
                pattern: label
                    .and_then(|label| label.reference.reference(ReferenceKind::Pattern, None)),
                ..styled(paragraph, |content| self.field_text(content))
            });
            self.output.styled = Some(record);
        }
    }

    /// The chapter number that page numbers start with: in a header or footer, the number of
    /// the chapter heading of its page, and in the body, the number of the last chapter
    /// heading so far. `None` when the section has no chapter numbers or no numbered chapter
    /// heading is found.
    pub(super) fn chapter_prefix(&self) -> Option<String> {
        let chapter = self.section.chapter?;
        let number = match &self.style_page {
            Some((pages, page)) => pages.chapter(self.styles, chapter.level, *page),
            None => self.output.chapter_number,
        }?;
        Some(format!("{number}{}", chapter.separator.char()))
    }

    /// The text of a `STYLEREF` field in a header or footer, or its stored result elsewhere or
    /// when no text of the style is found. Where the quirks say so, a no-break space of the
    /// text taken from the page shows as a plain space, and the spaces at the end of a
    /// paragraph's text are left out.
    pub(super) fn style_ref_text(&self, field: &StyleRef) -> String {
        let found = self
            .style_page
            .as_ref()
            .and_then(|(pages, page)| pages.text(self.styles, field, *page));
        found.map_or_else(
            || field.stored.clone(),
            |text| decisions::style_ref_text(&self.context.quirks, text),
        )
    }

    /// Takes the record of styled text back to `record` and the number of the last chapter
    /// heading back to `chapter_number`, which a mark noted before a trial. The paragraphs of a
    /// trial that the layout takes back then leave no entry and no chapter number on the page
    /// that their lines left, so a header's `STYLEREF` field and a page number with its chapter
    /// show only what stays on the page.
    pub(super) fn back_to_styled(
        &mut self,
        record: Option<RecordMark>,
        chapter_number: Option<i64>,
    ) {
        if let (Some(kept), Some(record)) = (self.output.styled.as_mut(), record) {
            kept.rewind(record);
        }
        self.output.chapter_number = chapter_number;
    }
}

/// The record of styled text that a body layout keeps while it fills its pages.
#[derive(Debug, Default)]
pub(super) struct Record {
    styled: StyledPages,
    /// The paragraph whose lines are being placed, by its ID, to know a paragraph that goes on
    /// to the next page. A copy of the paragraph is the same paragraph, and another paragraph
    /// in the place in memory of a dropped copy is not.
    current: Option<ParagraphId>,
}

impl Record {
    /// Notes that a line of `paragraph` stands on page `page`. The paragraph whose lines the
    /// record noted last gets the page in its entry; another paragraph gets an entry of its
    /// own, which `entry` makes.
    fn note(&mut self, paragraph: &Paragraph, page: usize, entry: impl FnOnce() -> Styled) {
        let index = match self.styled.pages.last() {
            Some(&(_, last)) if self.current == Some(paragraph.id) => last,
            _ => {
                self.current = Some(paragraph.id);
                self.styled.paragraphs.push(entry());
                self.styled.paragraphs.len() - 1
            }
        };
        if self.styled.pages.last() != Some(&(page, index)) {
            self.styled.pages.push((page, index));
        }
    }

    /// What the record holds now, for a mark of the layout.
    pub(super) fn mark(&self) -> RecordMark {
        RecordMark {
            paragraphs: self.styled.paragraphs.len(),
            pages: self.styled.pages.len(),
            current: self.current,
        }
    }

    /// Forgets what the record noted after `mark`, as a trial that the layout takes back noted
    /// it. The record only adds entries to its two lists and changes none, so their lengths
    /// and the paragraph whose lines it placed last give back what it held.
    pub(super) fn rewind(&mut self, mark: RecordMark) {
        self.styled.paragraphs.truncate(mark.paragraphs);
        self.styled.pages.truncate(mark.pages);
        self.current = mark.current;
    }

    pub(super) fn finish(self) -> Rc<StyledPages> {
        Rc::new(self.styled)
    }
}

/// What the record of styled text held at a mark of the layout: the lengths of its two lists
/// and the paragraph whose lines it placed last ([`Record::mark`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RecordMark {
    paragraphs: usize,
    pages: usize,
    current: Option<ParagraphId>,
}

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

    use super::{Record, Styled, StyledPages};
    use crate::body::Paragraph;
    use crate::layout::testing::{
        find_all, lay_out_with_header, on_base_with, pass_with, with_layout,
    };
    use crate::ns::W;
    use crate::numbering::Numbering;
    use crate::quirks::{StyleRefNoBreakSpace, StyleRefTrailingSpaces};
    use crate::reader::PartReader;
    use crate::styles::Styles;

    #[test]
    fn finds_the_chapter_heading_on_a_page_or_before_it() {
        let xml = format!(
            r#"<w:styles xmlns:w="{W}"><w:style w:type="paragraph" w:styleId="H1"><w:name w:val="heading 1"/></w:style></w:styles>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let paragraph = |style: &str, number| Styled {
            style: Some(style.into()),
            number,
            ..Styled::default()
        };
        // Chapter 1 on page 0, a numbered paragraph of another style on page 1, chapter 2 on
        // page 2, and an unnumbered heading on pages 2 and 3.
        let pages = StyledPages {
            paragraphs: vec![
                paragraph("H1", Some(1)),
                paragraph("Body", Some(7)),
                paragraph("H1", Some(2)),
                paragraph("H1", None),
            ],
            pages: vec![(0, 0), (1, 1), (2, 2), (2, 3), (3, 3)],
        };
        let chapters: Vec<Option<i64>> =
            (0..4).map(|page| pages.chapter(&styles, 1, page)).collect();
        assert_eq!(chapters, [Some(1), Some(1), Some(2), Some(2)]);
        assert_eq!(pages.chapter(&styles, 2, 2), None);
    }

    #[test]
    fn gives_another_paragraph_in_the_place_of_the_last_one_an_entry_of_its_own() {
        let mut record = Record::default();
        // One place in memory holds a paragraph and then another one, as when the layout drops
        // the copy of an endnote and the copy of the next endnote takes its place.
        let mut place = Paragraph::empty();
        record.note(&place, 0, Styled::default);
        record.note(&place, 1, Styled::default);
        place = Paragraph::empty();
        record.note(&place, 1, Styled::default);
        assert_eq!(record.styled.paragraphs.len(), 2);
        assert_eq!(record.styled.pages, [(0, 0), (1, 0), (1, 1)]);
    }

    #[test]
    fn forgets_at_a_rewind_what_a_trial_noted_and_which_paragraph_it_placed_last() {
        let (text, heading) = (Paragraph::empty(), Paragraph::empty());
        let mut record = Record::default();
        record.note(&text, 0, Styled::default);
        // A trial places the heading on page 0, and the layout takes it back and places it on
        // page 1, as a chain of kept paragraphs and rows does when its rows do not fit.
        let mark = record.mark();
        record.note(&heading, 0, Styled::default);
        record.rewind(mark);
        record.note(&heading, 1, Styled::default);
        assert_eq!(record.styled.paragraphs.len(), 2);
        assert_eq!(record.styled.pages, [(0, 0), (1, 1)]);
    }

    #[test]
    fn a_rewind_of_the_layout_takes_back_the_styled_text_and_the_chapter_number_of_a_trial() {
        with_layout(|layout| {
            layout.output.styled = Some(Record::default());
            layout.note_styled(&Paragraph::empty(), None);
            let before = layout.output.styled.as_ref().map(Record::mark);
            let mark = layout.mark();
            // A trial places a chapter heading on the page, and the layout takes it back.
            layout.note_styled(&Paragraph::empty(), None);
            layout.output.chapter_number = Some(2);
            layout.rewind(&mark);
            assert_eq!(layout.output.styled.as_ref().map(Record::mark), before);
            assert_eq!(layout.output.chapter_number, None);
        });
    }

    #[test]
    fn takes_the_text_that_the_layout_gives_the_computed_fields_of_a_paragraph() {
        use crate::body::{Content, DocProperty, Run};
        let paragraph = Paragraph {
            runs: vec![Run {
                content: vec![
                    Content::Text("C1 ".into()),
                    Content::DocProperty(Box::new(DocProperty {
                        name: "P".into(),
                        picture: None,
                        stored: "P1".into(),
                    })),
                    Content::Text(" ".into()),
                    Content::PageNumber,
                    Content::Text(" C2".into()),
                ],
                ..Run::default()
            }],
            ..Paragraph::empty()
        };
        with_layout(|layout| {
            layout.output.styled = Some(Record::default());
            layout.note_styled(&paragraph, None);
            let record = layout.output.styled.take().unwrap();
            // The property that the document lacks shows its stored result, and the page
            // number shows the number of the page that the paragraph is on.
            assert_eq!(record.styled.paragraphs[0].text, "C1 P1 1 C2");
        });
    }

    #[test]
    fn gives_a_tab_for_a_tab_and_a_break_for_a_line_break_and_nothing_for_a_positional_tab() {
        use crate::body::{Content, Run};
        let content = vec![
            Content::Text("A".into()),
            Content::Tab,
            Content::Text("B".into()),
            Content::PositionTab {
                kind: crate::props::TabKind::Right,
                leader: None,
            },
            Content::Text("C".into()),
            Content::LineBreak,
            Content::Text("D".into()),
            Content::ColumnBreak,
            Content::Bookmark("x".into()),
            Content::Text("E".into()),
        ];
        let paragraph = Paragraph {
            runs: vec![Run {
                content,
                ..Run::default()
            }],
            ..Paragraph::empty()
        };
        let styled = super::styled(&paragraph, |_| String::new());
        assert_eq!(styled.text, "A\tBC\nDE");
    }

    #[test]
    fn leaves_out_the_spaces_around_text_of_a_character_style() {
        let xml = format!(r#"<w:styles xmlns:w="{W}"/>"#);
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let pages = StyledPages {
            paragraphs: vec![Styled {
                text: " 25.\tWord".into(),
                runs: vec![("Number".into(), " 25\u{a0}".into())],
                ..Styled::default()
            }],
            pages: vec![(0, 0)],
        };
        let field = crate::body::StyleRef {
            style: "Number".into(),
            last: false,
            number: false,
            stored: String::new(),
        };
        assert_eq!(pages.text(&styles, &field, 0).as_deref(), Some("25"));
    }

    #[test]
    fn gives_the_paragraph_number_zero_to_a_paragraph_without_a_list_number() {
        let xml = format!(r#"<w:styles xmlns:w="{W}"/>"#);
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
        let paragraph = |number, pattern: Option<&str>| Styled {
            text: "3.\tWord".into(),
            runs: vec![("Number".into(), "3".into())],
            number,
            pattern: pattern.map(Into::into),
            ..Styled::default()
        };
        let field = crate::body::StyleRef {
            style: "Number".into(),
            last: false,
            number: true,
            stored: "1".into(),
        };
        // A typed number: the field gives 0.
        let pages = StyledPages {
            paragraphs: vec![paragraph(None, None)],
            pages: vec![(0, 0)],
        };
        assert_eq!(pages.text(&styles, &field, 0).as_deref(), Some("0"));
        // A list number gives the pattern of its level.
        let pages = StyledPages {
            paragraphs: vec![paragraph(Some(5), Some("3.5"))],
            pages: vec![(0, 0)],
        };
        assert_eq!(pages.text(&styles, &field, 0).as_deref(), Some("3.5"));
        // A pattern without text keeps the stored result, which the caller shows for none.
        let pages = StyledPages {
            paragraphs: vec![paragraph(Some(5), None)],
            pages: vec![(0, 0)],
        };
        assert_eq!(pages.text(&styles, &field, 0), None);
        // Without `\n`, the text of the style.
        let field = crate::body::StyleRef {
            number: false,
            ..field
        };
        assert_eq!(pages.text(&styles, &field, 0).as_deref(), Some("3"));
    }

    #[test]
    fn ends_a_stretch_of_a_character_style_at_other_text() {
        let run = |style: Option<&str>, text: &str| crate::body::Run {
            style: style.map(Into::into),
            content: vec![crate::body::Content::Text(text.into())],
            ..crate::body::Run::default()
        };
        let paragraph = Paragraph {
            runs: vec![
                run(Some("Number"), "31"),
                run(None, ". Other text "),
                run(Some("Number"), "6"),
                run(Some("Number"), ".18"),
            ],
            ..Paragraph::empty()
        };
        let styled = super::styled(&paragraph, |_| String::new());
        let runs: Vec<&str> = styled.runs.iter().map(|(_, text)| text.as_str()).collect();
        assert_eq!(runs, ["31", "6.18"]);
    }

    #[test]
    fn lays_out_the_tab_and_the_line_break_of_the_paragraph_that_a_header_field_shows() {
        // The header shows the paragraph of the style "Ref": "a", a tab, "b", a line break and
        // "c". As in the body, "b" stands at the first default tab stop, and "c" starts a
        // second line at the margin.
        let style =
            r#"<w:style w:type="paragraph" w:styleId="Ref"><w:name w:val="Ref"/></w:style>"#;
        let header = r#"<w:p><w:r><w:t>H</w:t></w:r><w:fldSimple w:instr=" STYLEREF Ref "><w:r><w:t>Z</w:t></w:r></w:fldSimple></w:p>"#;
        let body = r#"<w:p><w:pPr><w:pStyle w:val="Ref"/></w:pPr><w:r><w:t>a</w:t><w:tab/><w:t>b</w:t><w:br/><w:t>c</w:t></w:r></w:p>"#;
        let list = lay_out_with_header(body, style, None, Some(header));
        // Each character once in the header and once in the body, the header's first.
        let places = |ch: char| {
            let mut found = find_all(&list, ch);
            found.sort_by_key(|&(page, _, y)| (page, y));
            assert_eq!(found.len(), 2, "{ch}");
            (found[0], found[1])
        };
        let ((_, h, h_y), (a, b, c)) = (
            find_all(&list, 'H')[0],
            (places('a'), places('b'), places('c')),
        );
        assert_eq!(find_all(&list, 'Z'), Vec::new());
        assert_eq!((a.0.2, b.0.2), (h_y, h_y));
        assert_eq!(b.0.1, b.1.1);
        assert_eq!((c.0.1, c.1.1), (h, a.1.1));
        assert!(c.0.2 > h_y);
        assert_eq!(c.0.2 - h_y, c.1.2 - a.1.2);
    }

    #[test]
    fn shows_a_no_break_space_of_the_page_s_text_as_a_plain_space_where_the_quirk_says_so() {
        // The header shows the paragraph of the style "Ref", whose two words a no-break space
        // joins. The body keeps its no-break space; the header keeps it only on `Kept`.
        let style =
            r#"<w:style w:type="paragraph" w:styleId="Ref"><w:name w:val="Ref"/></w:style>"#;
        let header = r#"<w:p><w:fldSimple w:instr=" STYLEREF Ref "><w:r><w:t>Z</w:t></w:r></w:fldSimple></w:p>"#;
        let body =
            "<w:p><w:pPr><w:pStyle w:val=\"Ref\"/></w:pPr><w:r><w:t>a\u{a0}b</w:t></w:r></w:p>";
        let spaces = |rule| {
            let target = on_base_with(|p| p.with_variant(rule));
            let pass = pass_with(
                body,
                (style, None),
                Some(header),
                Numbering::default(),
                target,
            );
            (
                find_all(&pass.list, '\u{a0}').len(),
                find_all(&pass.list, 'b').len(),
            )
        };
        assert_eq!(spaces(StyleRefNoBreakSpace::Kept), (2, 2));
        assert_eq!(spaces(StyleRefNoBreakSpace::Plain), (1, 2));
    }

    #[test]
    fn leaves_out_the_spaces_at_the_end_of_the_page_s_paragraph_where_the_quirk_says_so() {
        // The header shows the paragraph of the style "Ref", whose text ends in two spaces. The
        // body keeps them; the header keeps them only on `Kept`.
        let style =
            r#"<w:style w:type="paragraph" w:styleId="Ref"><w:name w:val="Ref"/></w:style>"#;
        let header = r#"<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:fldSimple w:instr=" STYLEREF Ref "><w:r><w:t>Z</w:t></w:r></w:fldSimple></w:p>"#;
        let body = r#"<w:p><w:pPr><w:pStyle w:val="Ref"/></w:pPr><w:r><w:t xml:space="preserve">ab  </w:t></w:r></w:p>"#;
        let glyphs = |rule| {
            let target = on_base_with(|p| p.with_variant(rule));
            let pass = pass_with(
                body,
                (style, None),
                Some(header),
                Numbering::default(),
                target,
            );
            (
                find_all(&pass.list, ' ').len(),
                find_all(&pass.list, 'b').len(),
            )
        };
        let (kept, dropped) = (
            glyphs(StyleRefTrailingSpaces::Kept),
            glyphs(StyleRefTrailingSpaces::Dropped),
        );
        assert_eq!((kept.1, dropped.1), (2, 2));
        assert_eq!(kept.0, dropped.0 + 2);
    }
}