f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The replaces of a paragraph's text: the text of its `w:t` elements, the elements between
//! them that a match may not cross, and the new `w:t` elements of the matches.

use std::ops::Range;

use f_office_xml::{Document, NodeId};

use super::build::{is_other_story, prefix, text_element};
use super::{NamedError, NamedFault, Splice};
use crate::ns::{M, W};

/// The elements that stand in the text as one character, which a match may not cross.
const ONE_CHARACTER: [(&str, char); 4] =
    [("tab", '\t'), ("ptab", '\t'), ("br", '\n'), ("cr", '\n')];

/// The elements that have no text in the paragraph, which a match may not cross.
const NO_TEXT: [&str; 10] = [
    "instrText",
    "fldChar",
    "sym",
    "footnoteReference",
    "endnoteReference",
    "commentReference",
    "noBreakHyphen",
    "softHyphen",
    "drawing",
    "object",
];

/// The elements that hold runs, whose edges a match may not cross: a match across a
/// hyperlink's edge would split the link.
const CONTAINERS: [&str; 5] = ["hyperlink", "sdt", "smartTag", "fldSimple", "customXml"];

/// The elements of a paragraph whose content is no text of it: properties.
const PROPERTIES: [&str; 4] = ["pPr", "rPr", "sdtPr", "sdtEndPr"];

/// One `w:t` element of a paragraph, with its text and the containers that hold it.
struct Piece {
    node: NodeId,
    /// Where its text starts in the paragraph's text, in bytes.
    start: usize,
    text: String,
    /// The containers that hold it, from the outermost.
    containers: Vec<NodeId>,
}

/// An element that a match may not cross, where it stands in the paragraph's text.
struct Stop {
    /// Where it stands, in bytes.
    at: usize,
    /// Whether it stands in the text as one character.
    width: usize,
    element: &'static str,
}

/// The text of a paragraph as the replaces see it.
#[derive(Default)]
struct Walk {
    text: String,
    pieces: Vec<Piece>,
    stops: Vec<Stop>,
    /// Whether the paragraph holds an equation, whose text the walk leaves out: the text block
    /// shows it as the reader reads the math, such as a matrix's entries one after the other,
    /// which is no text of a `w:t`.
    equations: bool,
}

impl Walk {
    /// The walk of the paragraph `paragraph`.
    fn of(doc: &Document, paragraph: NodeId) -> Self {
        let mut walk = Self::default();
        walk.visit(doc, paragraph, &mut Vec::new());
        walk
    }

    fn visit(&mut self, doc: &Document, node: NodeId, containers: &mut Vec<NodeId>) {
        for child in doc.child_elements(node) {
            self.visit_element(doc, child, containers);
        }
    }

    fn visit_element(&mut self, doc: &Document, node: NodeId, containers: &mut Vec<NodeId>) {
        let local = doc.element(node).map_or("", |element| element.name.local);
        if doc.is(node, W, "t") {
            let text = doc.text_content(node);
            self.pieces.push(Piece {
                node,
                start: self.text.len(),
                text: text.clone(),
                containers: containers.clone(),
            });
            self.text.push_str(&text);
        } else if let Some((element, character)) =
            ONE_CHARACTER.iter().find(|(name, _)| doc.is(node, W, name))
        {
            self.stop(element, character.len_utf8());
            self.text.push(*character);
        } else if let Some(element) = NO_TEXT.iter().find(|name| doc.is(node, W, name)) {
            self.stop(element, 0);
        } else if doc.is(node, M, "oMath") || doc.is(node, M, "oMathPara") {
            self.equations = true;
            self.stop("oMath", 0);
        } else if is_other_story(doc, node) {
            self.stop("w:drawing", 0);
        } else if PROPERTIES.iter().any(|name| doc.is(node, W, name)) {
        } else if CONTAINERS.contains(&local) && doc.is(node, W, local) {
            containers.push(node);
            self.visit(doc, node, containers);
            containers.pop();
        } else {
            self.visit(doc, node, containers);
        }
    }

    fn stop(&mut self, element: &'static str, width: usize) {
        let element = element_name(element);
        self.stops.push(Stop {
            at: self.text.len(),
            width,
            element,
        });
    }

    /// The range of the one match of `find`.
    fn find(&self, find: &str) -> Result<Range<usize>, NamedFault> {
        let starts: Vec<usize> = self.text.match_indices(find).map(|(at, _)| at).collect();
        match starts.as_slice() {
            [] if self.equations => Err(NamedFault::TextNotFoundOutsideEquations),
            [] => Err(NamedFault::TextNotFound),
            [start] => Ok(*start..start + find.len()),
            more => Err(NamedFault::TextAmbiguous { count: more.len() }),
        }
    }

    /// Checks that the match `range` crosses no stop and no container's edge.
    fn check(&self, range: &Range<usize>, doc: &Document) -> Result<(), NamedFault> {
        let crossed = self.stops.iter().find(|stop| {
            if stop.width == 0 {
                range.start < stop.at && stop.at < range.end
            } else {
                range.start <= stop.at && stop.at < range.end
            }
        });
        if let Some(stop) = crossed {
            return Err(NamedFault::MatchCrossesElement {
                element: stop.element,
            });
        }
        let mut touched = self.touched(range);
        let Some(first) = touched.next() else {
            return Ok(());
        };
        for piece in touched {
            if piece.containers != first.containers {
                let edge = first
                    .containers
                    .iter()
                    .zip(&piece.containers)
                    .find(|(a, b)| a != b)
                    .map(|(a, _)| *a)
                    .or_else(|| first.containers.last().copied())
                    .or_else(|| piece.containers.last().copied());
                let element = edge
                    .and_then(|node| doc.element(node))
                    .map_or("w:hyperlink", |element| element_name(element.name.local));
                return Err(NamedFault::MatchCrossesEdge { element });
            }
        }
        Ok(())
    }

    /// The pieces whose text the match `range` touches.
    fn touched<'w>(&'w self, range: &'w Range<usize>) -> impl Iterator<Item = &'w Piece> + 'w {
        self.pieces.iter().filter(move |piece| {
            piece.start < range.end && range.start < piece.start + piece.text.len()
        })
    }
}

/// One end of the match of a find value: the `w:t` element, the offset in its text in bytes,
/// and the length of its text.
#[derive(Clone, Copy, Debug)]
pub(super) struct MatchEnd {
    pub(super) node: NodeId,
    pub(super) offset: usize,
    pub(super) length: usize,
}

/// The start and the end of the one match of `find` in the text of the paragraph
/// `paragraph`, which crosses no element without text and no edge of a container, as a replace
/// finds it.
pub(super) fn match_ends(
    doc: &Document,
    paragraph: NodeId,
    find: &str,
) -> Result<(MatchEnd, MatchEnd), NamedFault> {
    if find.is_empty() {
        return Err(NamedFault::EmptyFind);
    }
    let walk = Walk::of(doc, paragraph);
    let range = walk.find(find)?;
    walk.check(&range, doc)?;
    let mut touched = walk.touched(&range);
    let first = touched.next().ok_or(NamedFault::TextNotFound)?;
    let last = touched.last().unwrap_or(first);
    let end = |piece: &Piece, at: usize| MatchEnd {
        node: piece.node,
        offset: at - piece.start,
        length: piece.text.len(),
    };
    Ok((end(first, range.start), end(last, range.end)))
}

/// The qualified name of a WordprocessingML element of the lists above, for a message.
fn element_name(local: &str) -> &'static str {
    const NAMES: [&str; 21] = [
        "w:tab",
        "w:ptab",
        "w:br",
        "w:cr",
        "w:instrText",
        "w:fldChar",
        "w:sym",
        "w:footnoteReference",
        "w:endnoteReference",
        "w:commentReference",
        "w:noBreakHyphen",
        "w:softHyphen",
        "w:drawing",
        "w:object",
        "w:hyperlink",
        "w:sdt",
        "w:smartTag",
        "w:fldSimple",
        "w:customXml",
        "w:t",
        "m:oMath",
    ];
    let local = local.trim_start_matches("w:");
    NAMES
        .iter()
        .find(|name| name.get(2..) == Some(local))
        .copied()
        .unwrap_or("w:drawing")
}

/// Checks that `text` holds no character that a `w:t` cannot hold: no control character but
/// a tab when `tabs` holds, and no character that XML 1.0 does not allow.
pub(super) fn check_characters(text: &str, tabs: bool) -> Result<(), NamedFault> {
    match text
        .chars()
        .find(|&c| (c.is_control() && !(tabs && c == '\t')) || matches!(c, '\u{FFFE}' | '\u{FFFF}'))
    {
        Some(c) => Err(NamedFault::BadCharacter(c)),
        None => Ok(()),
    }
}

/// The splices of the replaces `list` of the paragraph `paragraph`, each the index of its edit,
/// its find value and its new text.
pub(super) fn replace(
    doc: &Document,
    paragraph: NodeId,
    list: &[(usize, &str, &str)],
) -> Result<Vec<Splice>, NamedError> {
    let at = |edit: usize| {
        move |fault| NamedError {
            edit: Some(edit),
            fault,
        }
    };
    let walk = Walk::of(doc, paragraph);
    let mut matches: Vec<(Range<usize>, usize, &str)> = Vec::new();
    for &(edit, find, with) in list {
        let range = walk.find(find).map_err(at(edit))?;
        walk.check(&range, doc).map_err(at(edit))?;
        if let Some((_, other, _)) = matches
            .iter()
            .find(|(seen, _, _)| seen.start < range.end && range.start < seen.end)
        {
            return Err(NamedError {
                edit: Some(edit),
                fault: NamedFault::MatchesOverlap { other: *other },
            });
        }
        matches.push((range, edit, with));
    }
    matches.sort_by_key(|(range, _, _)| range.start);
    let w = prefix(doc, paragraph).map_err(at(list.first().map_or(0, |(edit, _, _)| *edit)))?;
    let mut splices = Vec::new();
    for piece in &walk.pieces {
        let end = piece.start + piece.text.len();
        let cuts: Vec<&(Range<usize>, usize, &str)> = matches
            .iter()
            .filter(|(range, _, _)| piece.start < range.end && range.start < end)
            .collect();
        let Some(first) = cuts.first() else {
            continue;
        };
        let mut text = String::new();
        let mut cursor = piece.start;
        for (range, _, with) in &cuts {
            let from = range.start.max(piece.start);
            text.push_str(
                piece
                    .text
                    .get(cursor - piece.start..from - piece.start)
                    .unwrap_or_default(),
            );
            if range.start >= piece.start {
                text.push_str(with);
            }
            cursor = range.end.min(end);
        }
        text.push_str(piece.text.get(cursor - piece.start..).unwrap_or_default());
        splices.push(Splice {
            edit: first.1,
            range: doc.span(piece.node).unwrap_or(0..0),
            xml: text_element(&w, &text),
        });
    }
    Ok(splices)
}