f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! The marks of a comment in the main document part (ECMA-376 Part 1, 17.13.4): the start and
//! the end of its range and the run of its reference, around the content of a paragraph or
//! around the one match of a find value. A mark that falls inside a run cuts the run in two,
//! each part with the run's properties.

use std::fmt::Write as _;
use std::ops::Range;

use f_office_xml::NodeId;

use super::build::{check_fragment, content_after, insert_last, prefix, text_element};
use super::text::{MatchEnd, match_ends};
use super::{Main, NamedFault};
use crate::ns::W;
use crate::text_blocks::Address;

/// Where a mark falls in its run.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Fall {
    /// Before the run's first content.
    Before,
    /// After the run's last content.
    After,
    /// Inside the run, which it cuts.
    Inside,
}

/// The splices of the marks of the comment `id` on the paragraph `paragraph` at `at`: around
/// its content, or around the one match of `find` with the rules of a replace.
pub(super) fn marks(
    main: &Main<'_>,
    (at, paragraph): (&Address, NodeId),
    id: i64,
    find: Option<&str>,
) -> Result<Vec<(Range<usize>, String)>, NamedFault> {
    let w = prefix(main.doc, paragraph)?;
    let start = format!(r#"<{w}:commentRangeStart {w}:id="{id}"/>"#);
    let end = format!(
        r#"<{w}:commentRangeEnd {w}:id="{id}"/><{w}:r><{w}:commentReference {w}:id="{id}"/></{w}:r>"#
    );
    let Some(find) = find else {
        return Ok(around_content(main, paragraph, &start, &end));
    };
    let (first, last) = match_ends(main.doc, paragraph, find)?;
    let run_of = |end: &MatchEnd| {
        main.parent(end.node)
            .filter(|&run| main.doc.is(run, W, "r"))
            .ok_or_else(|| NamedFault::NoElement(at.clone()))
    };
    let (start_run, end_run) = (run_of(&first)?, run_of(&last)?);
    if start_run == end_run {
        return in_run(main, start_run, &[(first, &start), (last, &end)]);
    }
    let mut splices = in_run(main, start_run, &[(first, &start)])?;
    splices.extend(in_run(main, end_run, &[(last, &end)])?);
    Ok(splices)
}

/// The marks around the content of `paragraph`, after its properties.
fn around_content(
    main: &Main<'_>,
    paragraph: NodeId,
    start: &str,
    end: &str,
) -> Vec<(Range<usize>, String)> {
    let span = main.span(paragraph);
    let properties = main
        .doc
        .child(paragraph, W, "pPr")
        .map(|ppr| main.span(ppr));
    match content_after(main.bytes, &span, properties) {
        Some(content) if content.is_empty() => {
            vec![(content.start..content.start, format!("{start}{end}"))]
        }
        Some(content) => vec![
            (content.start..content.start, start.to_owned()),
            (content.end..content.end, end.to_owned()),
        ],
        None => vec![insert_last(main.bytes, span, &format!("{start}{end}"))],
    }
}

/// The splices of the marks `cuts` in the run `run`, each at its end of the match: next to the
/// run when each falls before or after its content, else the run written again in parts.
fn in_run(
    main: &Main<'_>,
    run: NodeId,
    cuts: &[(MatchEnd, &str)],
) -> Result<Vec<(Range<usize>, String)>, NamedFault> {
    let doc = main.doc;
    let content: Vec<NodeId> = doc
        .child_elements(run)
        .filter(|&child| !doc.is(child, W, "rPr"))
        .collect();
    let fall = |end: &MatchEnd| {
        if end.offset == 0 && content.first() == Some(&end.node) {
            Fall::Before
        } else if end.offset == end.length && content.last() == Some(&end.node) {
            Fall::After
        } else {
            Fall::Inside
        }
    };
    let span = main.span(run);
    if cuts.iter().all(|(end, _)| fall(end) != Fall::Inside) {
        return Ok(cuts
            .iter()
            .map(|(end, xml)| {
                let point = if fall(end) == Fall::Before {
                    span.start
                } else {
                    span.end
                };
                (point..point, (*xml).to_owned())
            })
            .collect());
    }
    let w = prefix(doc, run)?;
    let properties = doc
        .child(run, W, "rPr")
        .map_or_default(|rpr| main.text(main.span(rpr)));
    let mut out = String::new();
    let mut current = String::new();
    let flush = |out: &mut String, current: &mut String| {
        if !current.is_empty() {
            let _ = write!(out, "<{w}:r>{properties}{current}</{w}:r>");
            current.clear();
        }
    };
    for child in content {
        let mut here: Vec<&(MatchEnd, &str)> =
            cuts.iter().filter(|(end, _)| end.node == child).collect();
        if here.is_empty() {
            current.push_str(&main.text(main.span(child)));
            continue;
        }
        here.sort_by_key(|(end, _)| end.offset);
        let text = doc.text_content(child);
        let mut cursor = 0;
        for (end, xml) in here {
            let piece = text.get(cursor..end.offset).unwrap_or_default();
            if !piece.is_empty() {
                current.push_str(&text_element(&w, piece));
            }
            flush(&mut out, &mut current);
            out.push_str(xml);
            cursor = end.offset;
        }
        let rest = text.get(cursor..).unwrap_or_default();
        if !rest.is_empty() {
            current.push_str(&text_element(&w, rest));
        }
    }
    flush(&mut out, &mut current);
    check_fragment(main, run, &out)?;
    Ok(vec![(span, out)])
}