f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The body's table of contents: the first `TOC` field of the body that is not a table of
//! figures, with the entries of its stored result, what its switches select, and the `TC` fields
//! of the body, read before the reader of fields replaces each field by its result.

use std::ops::RangeInclusive;

use super::field_code;
use super::{Block, Content, ParagraphId, all_paragraphs};
use crate::params::BODY_TEXT_OUTLINE_LEVEL;

/// The outline levels from 0 that a switch without a range of levels selects: all the levels of
/// headings, below the level of body text.
const ALL_LEVELS: RangeInclusive<u8> = 0..=BODY_TEXT_OUTLINE_LEVEL - 1;

/// The `TC` fields that `\f` without an identifier and without `\l` selects.
const ANY_ENTRY_FIELDS: EntryFields = EntryFields {
    identifier: None,
    levels: ALL_LEVELS,
};

/// The first `TOC` field of the body that is not a table of figures (no `\c` and no `\a`), as
/// an outline of the document reads it (**Table of contents**).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct TableOfContents {
    /// The entries of its stored result in order: each paragraph of the result that links to
    /// a bookmark.
    pub(crate) entries: Vec<StoredEntry>,
    /// What its switches select.
    pub(crate) switches: Switches,
    /// The `TC` fields of the body in order.
    pub(crate) entry_fields: Vec<EntryField>,
}

/// A paragraph of a table of contents' stored result that links to a bookmark: through the
/// bookmark of a `PAGEREF` field in it, or the `\l` bookmark of a `HYPERLINK` field.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StoredEntry {
    /// The ID of the entry paragraph's style, as the file writes it, which gives the entry's
    /// level (a style named `toc 1` to `toc 9`).
    pub(crate) style: Option<String>,
    /// The name of the bookmark that it links to.
    pub(crate) bookmark: String,
}

/// What the switches of a table of contents select, each with the level from 0 that it gives.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Switches {
    /// `\o` and `\u`: the range of outline levels whose paragraphs it lists, at their outline
    /// level; `\o` without a range and `\u` take all nine. A code without `\o`, `\u`, `\t`,
    /// `\f` and `\l` takes all nine too.
    pub(crate) outline_levels: Option<RangeInclusive<u8>>,
    /// `\t`: the names of the styles whose paragraphs it lists, each with the level it gives.
    pub(crate) styles: Vec<(String, u8)>,
    /// `\f` and `\l`: the `TC` fields that it lists.
    pub(crate) entry_fields: Option<EntryFields>,
}

/// The `TC` fields that a table of contents lists (`\f` and `\l`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct EntryFields {
    /// The identifier of `\f`: it lists the fields of that identifier, or, without one, the
    /// fields without an identifier or with `C`.
    pub(crate) identifier: Option<String>,
    /// The range of `\l`: the levels from 0 of the fields that it lists, all nine without it.
    pub(crate) levels: RangeInclusive<u8>,
}

impl EntryFields {
    /// Whether it lists the field `field`.
    pub(crate) fn lists(&self, field: &EntryField) -> bool {
        let identifier = field.identifier.as_deref().unwrap_or("C");
        let wanted = self.identifier.as_deref().unwrap_or("C");
        identifier.eq_ignore_ascii_case(wanted) && self.levels.contains(&field.level)
    }
}

/// A `TC` field of the body, which a table of contents with `\f` or `\l` lists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct EntryField {
    /// The paragraph that holds it.
    pub(crate) paragraph: ParagraphId,
    /// Its level from 0, from its `\l` (1 without it).
    pub(crate) level: u8,
    /// The identifier of its `\f`, if it has one.
    pub(crate) identifier: Option<String>,
}

/// A field that is open at the current content: its code, and whether its result has started.
#[derive(Default)]
struct Open {
    code: String,
    result: bool,
}

/// The reading of the body's fields in document order.
#[derive(Default)]
struct Reading {
    open: Vec<Open>,
    found: Option<TableOfContents>,
    /// While the result of the table of contents runs, the index of its field in `open`.
    toc_at: Option<usize>,
    entry_fields: Vec<EntryField>,
}

impl Reading {
    /// Reads one piece of content of the paragraph `paragraph`, and gives the bookmark that the
    /// entry of the table of contents in that paragraph links to, when the content names it.
    fn read(&mut self, content: &Content, paragraph: ParagraphId) -> Option<String> {
        match content {
            Content::FieldBegin => self.open.push(Open::default()),
            Content::FieldCode(text) => {
                if let Some(field) = self.open.last_mut().filter(|field| !field.result) {
                    field.code.push_str(text);
                }
            }
            Content::FieldSeparate => {
                if self.open.last().is_some_and(|field| !field.result) {
                    let linked = self.code_ends(paragraph, true);
                    if let Some(field) = self.open.last_mut() {
                        field.result = true;
                    }
                    return linked;
                }
            }
            Content::FieldEnd => {
                let without_result = self.open.last().is_some_and(|field| !field.result);
                let linked = if without_result {
                    self.code_ends(paragraph, false)
                } else {
                    None
                };
                self.open.pop();
                if self.toc_at == Some(self.open.len()) {
                    self.toc_at = None;
                }
                return linked;
            }
            _ => {}
        }
        None
    }

    /// Takes the code of the innermost field, which ends here, before its result when
    /// `separated`, and gives the bookmark that it links to when it is a link inside the
    /// result of the table of contents.
    fn code_ends(&mut self, paragraph: ParagraphId, separated: bool) -> Option<String> {
        let at = self.open.len().checked_sub(1)?;
        let code = self.open.get(at).map(|field| field.code.clone())?;
        let kind = field_code::kind(&code)?;
        if kind.eq_ignore_ascii_case("TOC") && self.found.is_none() && !lists_figures(&code) {
            self.found = Some(TableOfContents {
                switches: switches(&code),
                ..TableOfContents::default()
            });
            self.toc_at = separated.then_some(at);
            None
        } else if kind.eq_ignore_ascii_case("TC") {
            self.entry_fields.push(entry_field(&code, paragraph));
            None
        } else if self.toc_at.is_some_and(|toc| toc < at) {
            linked_bookmark(&code)
        } else {
            None
        }
    }
}

/// Whether the `TOC` field of the code `code` is a table of figures: it has `\c`, which lists
/// the captions of a sequence, or `\a`, which lists them without their labels.
fn lists_figures(code: &str) -> bool {
    field_code::words_after_kind(code).any(|word| word == "\\c" || word == "\\a")
}

/// The switches of the `TOC` field of the code `code` that select its entries, each with its
/// argument: a quoted argument, or the next word, unless that word is a switch.
fn switches(code: &str) -> Switches {
    let mut out = Switches::default();
    let mut own_levels = false;
    let mut fields: Option<EntryFields> = None;
    let mut rest = field_code::after_kind(code);
    loop {
        let word = field_code::quoted_argument(rest);
        if word.text.is_empty() && word.rest.trim().is_empty() {
            break;
        }
        rest = word.rest;
        let next = field_code::quoted_argument(rest);
        let argument = (!next.text.is_empty() && !next.text.starts_with('\\')).then_some(next);
        let mut take = || {
            argument.map(|argument| {
                rest = argument.rest;
                argument.text
            })
        };
        match word.text {
            "\\o" => out.outline_levels = Some(take().and_then(levels).unwrap_or(ALL_LEVELS)),
            "\\u" => own_levels = true,
            "\\t" => out.styles = take().map_or_default(style_levels),
            "\\f" => {
                let identifier = take().map(str::to_owned);
                fields.get_or_insert(ANY_ENTRY_FIELDS).identifier = identifier;
            }
            "\\l" => {
                let range = take().and_then(levels).unwrap_or(ALL_LEVELS);
                fields.get_or_insert(ANY_ENTRY_FIELDS).levels = range;
            }
            _ => {}
        }
    }
    if own_levels {
        out.outline_levels.get_or_insert(ALL_LEVELS);
    }
    out.entry_fields = fields;
    if out.outline_levels.is_none() && out.styles.is_empty() && out.entry_fields.is_none() {
        out.outline_levels = Some(ALL_LEVELS);
    }
    out
}

/// The levels from 0 of a range of levels from 1 such as `1-3`, or of one level such as `2`;
/// none for a range that is not one of levels 1 to 9.
fn levels(range: &str) -> Option<RangeInclusive<u8>> {
    let (first, last) = range.split_once('-').unwrap_or((range, range));
    let level = |text: &str| {
        text.trim()
            .parse::<u8>()
            .ok()
            .filter(|level| (1..=BODY_TEXT_OUTLINE_LEVEL).contains(level))
    };
    let (first, last) = (level(first)?, level(last)?);
    (first <= last).then(|| first - 1..=last - 1)
}

/// The styles of a `\t` argument, such as `Style1,1,Style2,2`: pairs of a style name and its
/// level from 1, separated by commas or semicolons, each with its level from 0. A name without a
/// level takes level 1.
fn style_levels(argument: &str) -> Vec<(String, u8)> {
    let mut parts = argument.split([',', ';']).map(str::trim);
    let mut out = Vec::new();
    while let Some(name) = parts.next() {
        if name.is_empty() {
            continue;
        }
        let level = parts
            .next()
            .and_then(levels)
            .map_or(0, |range| *range.start());
        out.push((name.to_owned(), level));
    }
    out
}

/// The `TC` field of the code `code` in the paragraph `paragraph`, with its `\l` level and its
/// `\f` identifier.
fn entry_field(code: &str, paragraph: ParagraphId) -> EntryField {
    let mut field = EntryField {
        paragraph,
        level: 0,
        identifier: None,
    };
    let mut words = field_code::words_after_kind(code);
    while let Some(word) = words.next() {
        if word == "\\l" {
            if let Some(range) = words
                .next()
                .and_then(|level| levels(field_code::word_argument(level)))
            {
                field.level = *range.start();
            }
        } else if word == "\\f" {
            field.identifier = words
                .next()
                .map(field_code::word_argument)
                .filter(|identifier| !identifier.starts_with('\\'))
                .map(str::to_owned);
        }
    }
    field
}

/// The bookmark that a field of the code `code` links to: the bookmark of a `PAGEREF` field,
/// or the `\l` bookmark of a `HYPERLINK` field.
fn linked_bookmark(code: &str) -> Option<String> {
    let kind = field_code::kind(code)?;
    let mut words = field_code::words_after_kind(code);
    let name = if kind.eq_ignore_ascii_case("PAGEREF") {
        words.next()
    } else if kind.eq_ignore_ascii_case("HYPERLINK") {
        words.skip_while(|word| *word != "\\l").nth(1)
    } else {
        None
    }?;
    let name = field_code::word_argument(name);
    (!name.is_empty() && !name.starts_with('\\')).then(|| name.to_owned())
}

/// The body's table of contents in `blocks`, before the reader of fields replaces the fields,
/// with the `TC` fields of the body; none when the body has no `TOC` field that is not a table
/// of figures.
pub(crate) fn read(blocks: &[Block]) -> Option<TableOfContents> {
    let mut reading = Reading::default();
    let mut entries = Vec::new();
    for paragraph in all_paragraphs(blocks) {
        let mut linked = None;
        let mut in_result = reading.toc_at.is_some();
        for content in paragraph.runs.iter().flat_map(|run| &run.content) {
            let bookmark = reading.read(content, paragraph.id);
            if linked.is_none() {
                linked = bookmark;
            }
            in_result |= reading.toc_at.is_some();
        }
        if let Some(bookmark) = linked.filter(|_| in_result) {
            entries.push(StoredEntry {
                style: paragraph.props.style.clone(),
                bookmark,
            });
        }
    }
    let mut found = reading.found?;
    found.entries = entries;
    found.entry_fields = reading.entry_fields;
    Some(found)
}

#[cfg(test)]
mod tests;