Skip to main content

f_office_docx/
text_blocks.rs

1//! The text blocks of the body: each paragraph and table, in the order of the document, with its
2//! address, its kind with its style and text, and the pages that its lines lie on, for a reader
3//! of the document such as `foffice read`.
4//!
5//! The body's blocks follow its XML one for one: each `w:p` and `w:tbl` among the block-level
6//! children, with block-level content controls, custom XML and the shown branch of alternate
7//! content in their place (`body::block_children`), gives one block, so an address names the
8//! same element in the file.
9
10use std::collections::HashMap;
11use std::fmt;
12use std::num::NonZeroUsize;
13use std::ops::{Range, RangeInclusive};
14use std::str::FromStr;
15
16use crate::body::toc::TableOfContents;
17use crate::body::{Block, Content, Paragraph, ParagraphId};
18use crate::layout::PlacedLine;
19use crate::params;
20use crate::styles::Styles;
21
22/// The text of a picture in the text of its paragraph.
23pub(crate) const PICTURE_MARKER: &str = "{PICTURE}";
24
25/// One step of an address: the story that it starts in, or the place of a block, a row, a cell
26/// or a text box among its kind, from 1.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
28#[non_exhaustive]
29pub enum AddressStep {
30    /// The header part of this number, in the order in which the sections first name the
31    /// header parts (`h`).
32    Header(NonZeroUsize),
33    /// The footer part of this number, in the order in which the sections first name the
34    /// footer parts (`f`).
35    Footer(NonZeroUsize),
36    /// The footnote of this number among the normal footnotes of its part, in the order of the
37    /// part (`n`).
38    Footnote(NonZeroUsize),
39    /// The endnote of this number among the normal endnotes of its part, in the order of the
40    /// part (`e`).
41    Endnote(NonZeroUsize),
42    /// The paragraph of this number among the paragraphs of its story, cell or text box (`p`).
43    Paragraph(NonZeroUsize),
44    /// The table of this number among the tables of its story, cell or text box (`t`).
45    Table(NonZeroUsize),
46    /// The row of this number of its table (`r`).
47    Row(NonZeroUsize),
48    /// The cell of this number of its row (`c`).
49    Cell(NonZeroUsize),
50    /// The text box of this number among the text boxes of its paragraph (`b`).
51    TextBox(NonZeroUsize),
52}
53
54impl AddressStep {
55    /// The letter that names the step's kind.
56    const fn letter(self) -> char {
57        match self {
58            Self::Header(_) => 'h',
59            Self::Footer(_) => 'f',
60            Self::Footnote(_) => 'n',
61            Self::Endnote(_) => 'e',
62            Self::Paragraph(_) => 'p',
63            Self::Table(_) => 't',
64            Self::Row(_) => 'r',
65            Self::Cell(_) => 'c',
66            Self::TextBox(_) => 'b',
67        }
68    }
69
70    /// The step's number, from 1.
71    const fn number(self) -> NonZeroUsize {
72        match self {
73            Self::Header(n)
74            | Self::Footer(n)
75            | Self::Footnote(n)
76            | Self::Endnote(n)
77            | Self::Paragraph(n)
78            | Self::Table(n)
79            | Self::Row(n)
80            | Self::Cell(n)
81            | Self::TextBox(n) => n,
82        }
83    }
84
85    /// Whether the step names a story other than the body.
86    const fn is_story(self) -> bool {
87        matches!(
88            self,
89            Self::Header(_) | Self::Footer(_) | Self::Footnote(_) | Self::Endnote(_)
90        )
91    }
92}
93
94/// The path by which a reader names an element of a story (**Address**):
95/// `p12` for the twelfth paragraph of the body, `t2/r4/c1/p1` for the first paragraph of the
96/// first cell of the fourth row of the second table, `t2/r4` for that row, `p5/b1/p2` for the
97/// second paragraph of the first text box of the fifth paragraph, and `h1/p3` for the third
98/// paragraph of the first header part. Its grammar is
99///
100/// ```text
101/// address = [ story "/" ] block
102/// story   = ( "h" | "f" | "n" | "e" ) number
103/// block   = "p" number [ "/b" number "/" block ]
104///         | "t" number [ "/r" number [ "/c" number [ "/" block ] ] ]
105/// number  = a decimal number from 1, without a sign or leading zeros
106/// ```
107///
108/// so that a value of this type always names a paragraph, a table, a row or a cell.
109#[derive(Clone, Debug, PartialEq, Eq, Hash)]
110pub struct Address {
111    steps: Vec<AddressStep>,
112}
113
114impl Address {
115    /// The steps from the body down to the element, never empty.
116    #[must_use]
117    pub fn steps(&self) -> &[AddressStep] {
118        &self.steps
119    }
120
121    /// Whether it names an element of the body outside text boxes.
122    #[must_use]
123    pub fn in_body(&self) -> bool {
124        !self
125            .steps
126            .iter()
127            .any(|step| step.is_story() || matches!(step, AddressStep::TextBox(_)))
128    }
129
130    /// The address of a block of a story or a cell that holds the steps of `self`, the block
131    /// itself named by `step`.
132    pub(crate) fn then(&self, step: AddressStep) -> Self {
133        let mut steps = self.steps.clone();
134        steps.push(step);
135        Self { steps }
136    }
137
138    /// The address of the block `step` of the body.
139    pub(crate) fn top(step: AddressStep) -> Self {
140        Self { steps: vec![step] }
141    }
142
143    /// The address of the block `step` of the cell `cell`, or of the body when `cell` is none.
144    pub(crate) fn within(cell: Option<&Self>, step: AddressStep) -> Self {
145        cell.map_or_else(|| Self::top(step), |cell| cell.then(step))
146    }
147
148    /// The address of the table that holds the row `self`, or none when `self` names no row.
149    pub(crate) fn table_of_row(&self) -> Option<Self> {
150        match self.steps.split_last() {
151            Some((AddressStep::Row(_), table)) if !table.is_empty() => Some(Self {
152                steps: table.to_vec(),
153            }),
154            _ => None,
155        }
156    }
157
158    /// The address of the row that holds the cell `self`, with the cell's number, or none when
159    /// `self` names no cell.
160    pub(crate) fn row_of_cell(&self) -> Option<(Self, NonZeroUsize)> {
161        match self.steps.split_last() {
162            Some((AddressStep::Cell(number), row)) => Some((
163                Self {
164                    steps: row.to_vec(),
165                },
166                *number,
167            )),
168            _ => None,
169        }
170    }
171
172    /// The steps of the cell or the body that holds the block, the row or the cell `self`:
173    /// every step but the last.
174    pub(crate) fn container(&self) -> &[AddressStep] {
175        self.steps
176            .split_last()
177            .map_or(&[], |(_, container)| container)
178    }
179}
180
181impl fmt::Display for Address {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        for (index, step) in self.steps.iter().enumerate() {
184            if index > 0 {
185                f.write_str("/")?;
186            }
187            write!(f, "{}{}", step.letter(), step.number())?;
188        }
189        Ok(())
190    }
191}
192
193/// Why a text does not read as an address. Each error's text names the fix.
194#[derive(Clone, Debug, PartialEq, Eq)]
195#[non_exhaustive]
196pub enum AddressError {
197    /// The text is empty.
198    Empty,
199    /// A step is not a letter of a step's kind followed by a number from 1.
200    Step {
201        /// The step.
202        step: String,
203    },
204    /// A step stands where the grammar does not allow its kind.
205    Order {
206        /// The step.
207        step: String,
208        /// What the grammar allows there.
209        expected: &'static str,
210    },
211    /// The text ends where the grammar needs another step.
212    Unfinished {
213        /// What the grammar needs there.
214        expected: &'static str,
215    },
216}
217
218impl fmt::Display for AddressError {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        match self {
221            Self::Empty => f.write_str(
222                "the address is empty: name a paragraph or a table, such as p12 or t2/r4/c1/p1",
223            ),
224            Self::Step { step } => write!(
225                f,
226                "`{step}` is not a step of an address: write h, f, n, e, p, t, r, c or b and a \
227                 number from 1, such as p12 or t2/r4/c1/p1"
228            ),
229            Self::Order { step, expected } => write!(
230                f,
231                "`{step}` cannot stand there: the address needs {expected}, as in t2/r4/c1/p1 \
232                 or h1/p3/b1/p1"
233            ),
234            Self::Unfinished { expected } => write!(
235                f,
236                "the address ends too soon: it needs {expected}, as in h1/p3/b1/p1"
237            ),
238        }
239    }
240}
241
242impl std::error::Error for AddressError {}
243
244/// What the grammar allows as the next step.
245#[derive(Clone, Copy, PartialEq, Eq)]
246enum Next {
247    /// A story or a block, at the start.
248    Start,
249    /// A paragraph or a table, after a story or a text box, which the address cannot end with.
250    Block,
251    /// A row, after a table, or the end.
252    Row,
253    /// A cell, after a row, or the end.
254    Cell,
255    /// A block, after a cell, or the end.
256    BlockInCell,
257    /// A text box, after a paragraph, or the end.
258    TextBox,
259}
260
261impl Next {
262    /// What an error says that the grammar allows.
263    const fn expected(self) -> &'static str {
264        match self {
265            Self::Start => "a story (h, f, n or e), a paragraph (p) or a table (t)",
266            Self::Block | Self::BlockInCell => "a paragraph (p) or a table (t)",
267            Self::Row => "a row (r) after a table",
268            Self::Cell => "a cell (c) after a row",
269            Self::TextBox => "a text box (b) or nothing after a paragraph",
270        }
271    }
272
273    /// What the grammar allows after `step`, or none when it does not allow `step` here.
274    const fn after(self, step: AddressStep) -> Option<Self> {
275        Some(match (self, step) {
276            (Self::Start, step) if step.is_story() => Self::Block,
277            (Self::Start | Self::Block | Self::BlockInCell, AddressStep::Paragraph(_)) => {
278                Self::TextBox
279            }
280            (Self::Start | Self::Block | Self::BlockInCell, AddressStep::Table(_)) => Self::Row,
281            (Self::TextBox, AddressStep::TextBox(_)) => Self::Block,
282            (Self::Row, AddressStep::Row(_)) => Self::Cell,
283            (Self::Cell, AddressStep::Cell(_)) => Self::BlockInCell,
284            _ => return None,
285        })
286    }
287}
288
289impl FromStr for Address {
290    type Err = AddressError;
291
292    fn from_str(text: &str) -> Result<Self, Self::Err> {
293        if text.is_empty() {
294            return Err(AddressError::Empty);
295        }
296        let mut steps = Vec::new();
297        let mut next = Next::Start;
298        for part in text.split('/') {
299            let step = read_step(part)?;
300            next = next.after(step).ok_or_else(|| AddressError::Order {
301                step: part.to_owned(),
302                expected: next.expected(),
303            })?;
304            steps.push(step);
305        }
306        if next == Next::Block {
307            return Err(AddressError::Unfinished {
308                expected: next.expected(),
309            });
310        }
311        Ok(Self { steps })
312    }
313}
314
315/// Reads one step: its kind's letter and a number from 1 without a sign or leading zeros.
316fn read_step(part: &str) -> Result<AddressStep, AddressError> {
317    let bad = || AddressError::Step {
318        step: part.to_owned(),
319    };
320    let mut chars = part.chars();
321    let kind = chars.next().ok_or_else(bad)?;
322    let digits = chars.as_str();
323    if digits.is_empty() || digits.starts_with('0') || !digits.bytes().all(|b| b.is_ascii_digit()) {
324        return Err(bad());
325    }
326    let number = digits.parse::<NonZeroUsize>().map_err(|_| bad())?;
327    Ok(match kind {
328        'h' => AddressStep::Header(number),
329        'f' => AddressStep::Footer(number),
330        'n' => AddressStep::Footnote(number),
331        'e' => AddressStep::Endnote(number),
332        'b' => AddressStep::TextBox(number),
333        'p' => AddressStep::Paragraph(number),
334        't' => AddressStep::Table(number),
335        'r' => AddressStep::Row(number),
336        'c' => AddressStep::Cell(number),
337        _ => return Err(bad()),
338    })
339}
340
341/// What a text block is.
342#[derive(Clone, Debug, PartialEq, Eq)]
343#[non_exhaustive]
344pub enum TextBlockKind {
345    /// A paragraph, with its style ID and its text.
346    Paragraph {
347        /// The ID of its paragraph style, as the file writes it, if it has one.
348        style: Option<String>,
349        /// Its text as a reader sees it in the file: the text of its runs, a tab as `\t`, a
350        /// line, page or column break as `\n`, a check box as ☐ or ☒, the stored result of a
351        /// field whose value Word may compute again, and a marker in braces for what has no
352        /// text of its own: `{PAGE}` and `{NUMPAGES}` for the page number and the page count,
353        /// `{FOOTNOTE}` and `{ENDNOTE}` for a note's reference, `{PICTURE}` and `{OBJECT}` for
354        /// an inline object, and `{DRAWING}` for a drawing. Field codes, bookmarks, comment
355        /// anchors and the marks of notes, comments and equations give no text.
356        text: String,
357    },
358    /// A table, with its number of rows. The paragraphs of its cells follow it as text blocks
359    /// of their own.
360    Table {
361        /// The number of rows.
362        rows: usize,
363    },
364}
365
366/// A paragraph or a table of the body, as a reader of the document lists it (**Text block**).
367#[derive(Clone, Debug, PartialEq, Eq)]
368#[non_exhaustive]
369pub struct TextBlock {
370    /// Where it is in the body.
371    pub address: Address,
372    /// What it is, with its style and text for a paragraph.
373    pub kind: TextBlockKind,
374    /// The indices of the pages that its lines lie on, from the first to the last, counted from
375    /// 0 as `f_office::Document::page` counts them, while its address counts from 1; for a
376    /// table, those of the lines of its cells. It is none when the layout placed no line of the
377    /// block: a paragraph whose mark and text are hidden, or a table none of whose cells has a
378    /// placed line.
379    pub page_indices: Option<RangeInclusive<usize>>,
380    /// The span of its element in the bytes of the main document part, where the reader found
381    /// it (**Source span**), or none for a block that F-Office made itself or
382    /// a part not in UTF-8. The edits of `foffice` find the element of an address with it.
383    pub source: Option<Range<usize>>,
384    /// For a table, the span of each row's element in the same way, in the order of the rows;
385    /// empty for a paragraph.
386    pub row_sources: Vec<Option<Range<usize>>>,
387    /// For a paragraph that is a heading, its outline level from 0 for the top level to 8: the
388    /// `w:outlineLvl` of its own properties, or else of its style and the styles that it is
389    /// based on. It is none for body text and for a table.
390    pub outline_level: Option<u8>,
391    /// For a paragraph that the body's table of contents lists, the level from 0 that it gives
392    /// the paragraph. The table of contents is the first `TOC` field of the body that is not a
393    /// table of figures (no `\c` and no `\a`). Its stored entries give the levels: each entry
394    /// that links to a bookmark (by a `PAGEREF` or a `HYPERLINK \l` field) lists the
395    /// paragraph that holds the bookmark's start, at the level of the entry's style (`toc 1`
396    /// gives 0). When no stored entry links to a paragraph, its switches give them: the
397    /// paragraphs of the styles of `\t`, those whose outline level lies in the range of `\o`
398    /// or `\u`, and those of the `TC` fields that `\f` and `\l` list. It is none for a
399    /// paragraph that the table of contents does not list, for a table, and for every block of a
400    /// body without one.
401    pub toc_level: Option<u8>,
402}
403
404/// Incremental page-span tracker for body [`TextBlock`] entries during Pass-1 streaming.
405pub(crate) struct IncrementalTextBlocks {
406    by_paragraph: HashMap<ParagraphId, Vec<usize>>,
407    spans: Vec<Option<RangeInclusive<usize>>>,
408}
409
410#[derive(Default)]
411struct BlockIndex {
412    enclosing: Vec<usize>,
413    by_paragraph: HashMap<ParagraphId, Vec<usize>>,
414}
415
416impl BlockIndex {
417    fn record_paragraph(&mut self, id: ParagraphId, block_idx: usize) {
418        let entry = self.by_paragraph.entry(id).or_default();
419        entry.push(block_idx);
420        entry.extend(self.enclosing.iter().copied());
421    }
422}
423
424impl IncrementalTextBlocks {
425    /// Builds the fixed body [`TextBlock`] skeleton (all `page_indices: None`) and an index
426    /// mapping each [`ParagraphId`] to every block index (paragraph and enclosing tables) whose
427    /// `page_indices` covers it.
428    #[must_use]
429    pub(crate) fn new(
430        blocks: &[Block],
431        (styles, toc): (&Styles, Option<&TableOfContents>),
432    ) -> (Vec<TextBlock>, Self) {
433        let levels = toc_levels::toc_levels(blocks, styles, toc);
434        let empty_pages = HashMap::new();
435        let mut out = Vec::new();
436        let mut index = BlockIndex::default();
437        add_blocks_indexed(
438            blocks,
439            None,
440            (&empty_pages, styles, &levels),
441            Some(&mut index),
442            &mut out,
443        );
444        let spans = vec![None; out.len()];
445        (
446            out,
447            Self {
448                by_paragraph: index.by_paragraph,
449                spans,
450            },
451        )
452    }
453
454    /// Updates tracked page spans from newly placed `lines` in `O(lines)` time, returning only
455    /// the `(block_index, page_indices)` entries that widened.
456    pub(crate) fn update(&mut self, lines: &[PlacedLine]) -> Vec<(usize, RangeInclusive<usize>)> {
457        let mut dirty: Vec<usize> = Vec::new();
458        for line in lines {
459            let Some(indices) = self.by_paragraph.get(&line.paragraph) else {
460                continue;
461            };
462            let page = line.page..=line.page;
463            for &idx in indices {
464                let Some(slot) = self.spans.get_mut(idx) else {
465                    continue;
466                };
467                let next = widen(slot.clone(), Some(&page));
468                if next != *slot {
469                    *slot = next;
470                    if !dirty.contains(&idx) {
471                        dirty.push(idx);
472                    }
473                }
474            }
475        }
476        dirty
477            .into_iter()
478            .filter_map(|idx| {
479                self.spans
480                    .get(idx)
481                    .and_then(Clone::clone)
482                    .map(|span| (idx, span))
483            })
484            .collect()
485    }
486}
487
488/// The text blocks of the body's `blocks`, in the order of the document, with the pages of the
489/// `lines` that the layout placed, the outline levels that the paragraphs take from their
490/// properties and `styles`, and the levels that the body's table of contents `toc` gives them.
491#[must_use]
492pub(crate) fn text_blocks(
493    blocks: &[Block],
494    lines: &[PlacedLine],
495    (styles, toc): (&Styles, Option<&TableOfContents>),
496) -> Vec<TextBlock> {
497    let mut pages: HashMap<ParagraphId, RangeInclusive<usize>> = HashMap::new();
498    for line in lines {
499        let page = line.page..=line.page;
500        let span = pages.remove(&line.paragraph);
501        if let Some(span) = widen(span, Some(&page)) {
502            pages.insert(line.paragraph, span);
503        }
504    }
505    let levels = toc_levels::toc_levels(blocks, styles, toc);
506    let mut out = Vec::new();
507    add_blocks_indexed(blocks, None, (&pages, styles, &levels), None, &mut out);
508    out
509}
510
511/// Adds the text blocks of `blocks`, the blocks of the body when `within` is none, or else of
512/// the cell at that address, and gives the pages that their lines lie on.
513fn add_blocks_indexed(
514    blocks: &[Block],
515    within: Option<&Address>,
516    context: (
517        &HashMap<ParagraphId, RangeInclusive<usize>>,
518        &Styles,
519        &HashMap<ParagraphId, u8>,
520    ),
521    mut index: Option<&mut BlockIndex>,
522    out: &mut Vec<TextBlock>,
523) -> Option<RangeInclusive<usize>> {
524    let (mut paragraphs, mut tables) = (0, 0);
525    let mut all = None;
526    for block in blocks {
527        let span = match block {
528            Block::Paragraph(paragraph) => {
529                paragraphs += 1;
530                push_paragraph_block(
531                    paragraph,
532                    within,
533                    paragraphs,
534                    context,
535                    index.as_deref_mut(),
536                    out,
537                )
538            }
539            Block::Table(table) => {
540                tables += 1;
541                push_table_block(table, within, tables, context, index.as_deref_mut(), out)
542            }
543        };
544        all = widen(all, span.as_ref());
545    }
546    all
547}
548
549fn push_paragraph_block(
550    paragraph: &Paragraph,
551    within: Option<&Address>,
552    ordinal: usize,
553    (pages, styles, levels): (
554        &HashMap<ParagraphId, RangeInclusive<usize>>,
555        &Styles,
556        &HashMap<ParagraphId, u8>,
557    ),
558    index: Option<&mut BlockIndex>,
559    out: &mut Vec<TextBlock>,
560) -> Option<RangeInclusive<usize>> {
561    let span = pages.get(&paragraph.id).cloned();
562    let block_idx = out.len();
563    if let Some(index) = index {
564        index.record_paragraph(paragraph.id, block_idx);
565    }
566    out.push(TextBlock {
567        address: Address::within(within, AddressStep::Paragraph(number(ordinal))),
568        kind: TextBlockKind::Paragraph {
569            style: paragraph.props.style.clone(),
570            text: paragraph_text(paragraph),
571        },
572        page_indices: span.clone(),
573        source: paragraph.source.range(),
574        row_sources: Vec::new(),
575        outline_level: outline_level(paragraph, styles),
576        toc_level: levels.get(&paragraph.id).copied(),
577    });
578    span
579}
580
581fn push_table_block(
582    table: &crate::table::Table,
583    within: Option<&Address>,
584    ordinal: usize,
585    context: (
586        &HashMap<ParagraphId, RangeInclusive<usize>>,
587        &Styles,
588        &HashMap<ParagraphId, u8>,
589    ),
590    mut index: Option<&mut BlockIndex>,
591    out: &mut Vec<TextBlock>,
592) -> Option<RangeInclusive<usize>> {
593    let table_address = Address::within(within, AddressStep::Table(number(ordinal)));
594    let at = out.len();
595    // Push the table block first so child indices remain stable without Vec::insert shifts.
596    out.push(TextBlock {
597        address: table_address.clone(),
598        kind: TextBlockKind::Table {
599            rows: table.rows.len(),
600        },
601        page_indices: None,
602        source: table.source.range(),
603        row_sources: table.rows.iter().map(|row| row.source.range()).collect(),
604        outline_level: None,
605        toc_level: None,
606    });
607    if let Some(index) = index.as_deref_mut() {
608        index.enclosing.push(at);
609    }
610    let mut span = None;
611    for (row_index, row) in table.rows.iter().enumerate() {
612        let row_address = table_address.then(AddressStep::Row(number(row_index + 1)));
613        for (cell_index, cell) in row.cells.iter().enumerate() {
614            let step = AddressStep::Cell(number(cell_index + 1));
615            let cell_span = add_blocks_indexed(
616                &cell.blocks,
617                Some(&row_address.then(step)),
618                context,
619                index.as_deref_mut(),
620                out,
621            );
622            span = widen(span, cell_span.as_ref());
623        }
624    }
625    if let Some(index) = index {
626        let _ = index.enclosing.pop();
627    }
628    if let Some(table_block) = out.get_mut(at) {
629        table_block.page_indices.clone_from(&span);
630    }
631    span
632}
633
634/// The outline level of `paragraph`, as [`TextBlock::outline_level`] says: none for the level
635/// of body text.
636pub(super) fn outline_level(paragraph: &Paragraph, styles: &Styles) -> Option<u8> {
637    let props = styles.paragraph_properties_without_list_level(&paragraph.props, None);
638    props
639        .outline_level
640        .filter(|level| *level < params::BODY_TEXT_OUTLINE_LEVEL)
641}
642
643/// The pages from the first of `pages` and `more` to the last, or those of the one that is
644/// given.
645fn widen(
646    pages: Option<RangeInclusive<usize>>,
647    more: Option<&RangeInclusive<usize>>,
648) -> Option<RangeInclusive<usize>> {
649    match (pages, more) {
650        (Some(a), Some(b)) => Some((*a.start()).min(*b.start())..=(*a.end()).max(*b.end())),
651        (a, b) => a.or_else(|| b.cloned()),
652    }
653}
654
655/// The number, from 1, of the block, row or cell that `count` blocks, rows or cells end, which
656/// is never 0.
657pub(crate) fn number(count: usize) -> NonZeroUsize {
658    NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
659}
660
661/// The text of a paragraph, as [`TextBlockKind::Paragraph`] says.
662#[must_use]
663fn paragraph_text(paragraph: &Paragraph) -> String {
664    let mut text = String::new();
665    for content in paragraph.runs.iter().flat_map(|run| &run.content) {
666        match content {
667            Content::Text(piece) => text.push_str(piece),
668            Content::Tab | Content::PositionTab { .. } => text.push('\t'),
669            Content::LineBreak
670            | Content::ClearingBreak
671            | Content::PageBreak
672            | Content::ColumnBreak => text.push('\n'),
673            Content::CheckBox(check_box) => {
674                text.push(if check_box.checked { '☒' } else { '☐' });
675            }
676            Content::PageNumber => text.push_str("{PAGE}"),
677            Content::PageCount => text.push_str("{NUMPAGES}"),
678            Content::Date(field) => text.push_str(&field.stored),
679            Content::DocProperty(field) => text.push_str(&field.stored),
680            Content::StyleRef(field) => text.push_str(&field.stored),
681            Content::PageRef(field) => text.push_str(&field.stored),
682            Content::NumberRef(field) => text.push_str(&field.stored),
683            Content::If(field) => text.push_str(&field.stored),
684            Content::FootnoteReference(..) => text.push_str("{FOOTNOTE}"),
685            Content::EndnoteReference(..) => text.push_str("{ENDNOTE}"),
686            Content::Object { picture, .. } => {
687                text.push_str(if picture.is_some() {
688                    PICTURE_MARKER
689                } else {
690                    "{OBJECT}"
691                });
692            }
693            Content::Drawing(_) | Content::Floating(_) => text.push_str("{DRAWING}"),
694            Content::FieldBegin
695            | Content::FieldLock
696            | Content::DropDown(_)
697            | Content::FieldCode(_)
698            | Content::FieldSeparate
699            | Content::FieldEnd
700            | Content::Bookmark(_)
701            | Content::FieldMark
702            | Content::HyperlinkEdge
703            | Content::ControlEdge
704            | Content::RemovedEdge
705            | Content::CommentAnchor(_)
706            | Content::FootnoteMark
707            | Content::EndnoteMark
708            | Content::CommentMark
709            | Content::Separator
710            | Content::ContinuationSeparator
711            | Content::Stack(_)
712            | Content::Grown(_)
713            | Content::Radical(_)
714            | Content::Accent(_)
715            | Content::Matrix(_)
716            | Content::MathBar(_)
717            | Content::MathSlash(_)
718            | Content::MathLimit(_)
719            | Content::GroupChr(_)
720            | Content::MathBox(_)
721            | Content::Scripts(_)
722            | Content::Advance(_) => {}
723        }
724    }
725    text
726}
727
728mod toc_levels;
729
730#[cfg(test)]
731mod tests;