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/// The text blocks of the body's `blocks`, in the order of the document, with the pages of the
405/// `lines` that the layout placed, the outline levels that the paragraphs take from their
406/// properties and `styles`, and the levels that the body's table of contents `toc` gives them.
407#[must_use]
408pub(crate) fn text_blocks(
409    blocks: &[Block],
410    lines: &[PlacedLine],
411    (styles, toc): (&Styles, Option<&TableOfContents>),
412) -> Vec<TextBlock> {
413    let mut pages: HashMap<ParagraphId, RangeInclusive<usize>> = HashMap::new();
414    for line in lines {
415        let page = line.page..=line.page;
416        let span = pages.remove(&line.paragraph);
417        if let Some(span) = widen(span, Some(&page)) {
418            pages.insert(line.paragraph, span);
419        }
420    }
421    let levels = toc_levels::toc_levels(blocks, styles, toc);
422    let mut out = Vec::new();
423    add_blocks(blocks, None, (&pages, styles, &levels), &mut out);
424    out
425}
426
427/// Adds the text blocks of `blocks`, the blocks of the body when `within` is none, or else of
428/// the cell at that address, and gives the pages that their lines lie on.
429fn add_blocks(
430    blocks: &[Block],
431    within: Option<&Address>,
432    (pages, styles, levels): (
433        &HashMap<ParagraphId, RangeInclusive<usize>>,
434        &Styles,
435        &HashMap<ParagraphId, u8>,
436    ),
437    out: &mut Vec<TextBlock>,
438) -> Option<RangeInclusive<usize>> {
439    let (mut paragraphs, mut tables) = (0, 0);
440    let mut all = None;
441    for block in blocks {
442        let (block_address, kind, span, source, (outline_level, toc_level)) = match block {
443            Block::Paragraph(paragraph) => {
444                paragraphs += 1;
445                let kind = TextBlockKind::Paragraph {
446                    style: paragraph.props.style.clone(),
447                    text: paragraph_text(paragraph),
448                };
449                let step = AddressStep::Paragraph(number(paragraphs));
450                let source = paragraph.source.range();
451                let address = Address::within(within, step);
452                (
453                    address,
454                    kind,
455                    pages.get(&paragraph.id).cloned(),
456                    source,
457                    (
458                        outline_level(paragraph, styles),
459                        levels.get(&paragraph.id).copied(),
460                    ),
461                )
462            }
463            Block::Table(table) => {
464                tables += 1;
465                let table_address = Address::within(within, AddressStep::Table(number(tables)));
466                let at = out.len();
467                let mut span = None;
468                for (row_index, row) in table.rows.iter().enumerate() {
469                    let row_address = table_address.then(AddressStep::Row(number(row_index + 1)));
470                    for (cell_index, cell) in row.cells.iter().enumerate() {
471                        let step = AddressStep::Cell(number(cell_index + 1));
472                        let cell_span = add_blocks(
473                            &cell.blocks,
474                            Some(&row_address.then(step)),
475                            (pages, styles, levels),
476                            out,
477                        );
478                        span = widen(span, cell_span.as_ref());
479                    }
480                }
481                let kind = TextBlockKind::Table {
482                    rows: table.rows.len(),
483                };
484                // The table comes before the blocks of its cells.
485                out.insert(
486                    at,
487                    TextBlock {
488                        address: table_address,
489                        kind,
490                        page_indices: span.clone(),
491                        source: table.source.range(),
492                        row_sources: table.rows.iter().map(|row| row.source.range()).collect(),
493                        outline_level: None,
494                        toc_level: None,
495                    },
496                );
497                all = widen(all, span.as_ref());
498                continue;
499            }
500        };
501        all = widen(all, span.as_ref());
502        out.push(TextBlock {
503            address: block_address,
504            kind,
505            page_indices: span,
506            source,
507            row_sources: Vec::new(),
508            outline_level,
509            toc_level,
510        });
511    }
512    all
513}
514
515/// The outline level of `paragraph`, as [`TextBlock::outline_level`] says: none for the level
516/// of body text.
517pub(super) fn outline_level(paragraph: &Paragraph, styles: &Styles) -> Option<u8> {
518    let props = styles.paragraph_properties_without_list_level(&paragraph.props, None);
519    props
520        .outline_level
521        .filter(|level| *level < params::BODY_TEXT_OUTLINE_LEVEL)
522}
523
524/// The pages from the first of `pages` and `more` to the last, or those of the one that is
525/// given.
526fn widen(
527    pages: Option<RangeInclusive<usize>>,
528    more: Option<&RangeInclusive<usize>>,
529) -> Option<RangeInclusive<usize>> {
530    match (pages, more) {
531        (Some(a), Some(b)) => Some((*a.start()).min(*b.start())..=(*a.end()).max(*b.end())),
532        (a, b) => a.or_else(|| b.cloned()),
533    }
534}
535
536/// The number, from 1, of the block, row or cell that `count` blocks, rows or cells end, which
537/// is never 0.
538pub(crate) fn number(count: usize) -> NonZeroUsize {
539    NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
540}
541
542/// The text of a paragraph, as [`TextBlockKind::Paragraph`] says.
543#[must_use]
544fn paragraph_text(paragraph: &Paragraph) -> String {
545    let mut text = String::new();
546    for content in paragraph.runs.iter().flat_map(|run| &run.content) {
547        match content {
548            Content::Text(piece) => text.push_str(piece),
549            Content::Tab | Content::PositionTab { .. } => text.push('\t'),
550            Content::LineBreak
551            | Content::ClearingBreak
552            | Content::PageBreak
553            | Content::ColumnBreak => text.push('\n'),
554            Content::CheckBox(check_box) => {
555                text.push(if check_box.checked { '☒' } else { '☐' });
556            }
557            Content::PageNumber => text.push_str("{PAGE}"),
558            Content::PageCount => text.push_str("{NUMPAGES}"),
559            Content::Date(field) => text.push_str(&field.stored),
560            Content::DocProperty(field) => text.push_str(&field.stored),
561            Content::StyleRef(field) => text.push_str(&field.stored),
562            Content::PageRef(field) => text.push_str(&field.stored),
563            Content::NumberRef(field) => text.push_str(&field.stored),
564            Content::If(field) => text.push_str(&field.stored),
565            Content::FootnoteReference(..) => text.push_str("{FOOTNOTE}"),
566            Content::EndnoteReference(..) => text.push_str("{ENDNOTE}"),
567            Content::Object { picture, .. } => {
568                text.push_str(if picture.is_some() {
569                    PICTURE_MARKER
570                } else {
571                    "{OBJECT}"
572                });
573            }
574            Content::Drawing(_) | Content::Floating(_) => text.push_str("{DRAWING}"),
575            Content::FieldBegin
576            | Content::FieldLock
577            | Content::DropDown(_)
578            | Content::FieldCode(_)
579            | Content::FieldSeparate
580            | Content::FieldEnd
581            | Content::Bookmark(_)
582            | Content::FieldMark
583            | Content::HyperlinkEdge
584            | Content::ControlEdge
585            | Content::RemovedEdge
586            | Content::CommentAnchor(_)
587            | Content::FootnoteMark
588            | Content::EndnoteMark
589            | Content::CommentMark
590            | Content::Separator
591            | Content::ContinuationSeparator
592            | Content::Stack(_)
593            | Content::Grown(_)
594            | Content::Radical(_)
595            | Content::Accent(_)
596            | Content::Matrix(_)
597            | Content::MathBar(_)
598            | Content::MathSlash(_)
599            | Content::MathLimit(_)
600            | Content::GroupChr(_)
601            | Content::MathBox(_)
602            | Content::Scripts(_)
603            | Content::Advance(_) => {}
604        }
605    }
606    text
607}
608
609mod toc_levels;
610
611#[cfg(test)]
612mod tests;