f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
//! The XML that the named edits write, made from the bytes of the elements that they change:
//! a new paragraph, a style reference, the places in an element where new XML goes, and the
//! checks of a delete.

use std::collections::HashMap;
use std::ops::Range;

use f_office_xml::{Document, Limits as XmlLimits, NodeId};

use super::styles::Styles;
use super::{Main, NamedFault};
use crate::ns::{MC, W};

/// The ends of ranges that a deleted block must hold both of, by their start and end elements
/// (ECMA-376 Part 1, 17.13.6 and 17.16.1).
const RANGES: [(&str, &str); 3] = [
    ("w:bookmarkStart", "w:bookmarkEnd"),
    ("w:commentRangeStart", "w:commentRangeEnd"),
    ("w:permStart", "w:permEnd"),
];

/// The elements whose content is another story or an object, which the walks of a block's
/// runs leave out.
const OTHER_STORIES: [(&str, &str); 4] = [
    (W, "drawing"),
    (W, "pict"),
    (W, "object"),
    (MC, "AlternateContent"),
];

/// A new paragraph and the style that it names, if any.
pub(super) struct Built {
    /// The paragraph's XML.
    pub(super) xml: String,
    /// The ID of the style of its `w:pStyle`, if it has one.
    pub(super) style: Option<String>,
}

/// The new paragraph of an insert next to `node`, a paragraph when `paragraph` holds, else a
/// table, with the style `given` or the one that follows the paragraph's style, and one run
/// whose content `content` makes with the prefix of WordprocessingML, such as the text of
/// [`run_text`]: no run when it is empty.
pub(super) fn paragraph(
    main: &Main<'_>,
    styles: &Styles,
    (node, paragraph): (NodeId, bool),
    given: Option<String>,
    content: &dyn Fn(&str) -> String,
) -> Result<Built, NamedFault> {
    let w = prefix(main.doc, node)?;
    let doc = main.doc;
    let properties = paragraph.then(|| doc.child(node, W, "pPr")).flatten();
    let own = properties
        .and_then(|ppr| doc.child(ppr, W, "pStyle"))
        .and_then(|style| doc.attribute(style, Some(W), "val"))
        .map(str::to_owned)
        .or_else(|| {
            paragraph
                .then(|| styles.default_paragraph().map(str::to_owned))
                .flatten()
        });
    let followed = own
        .as_deref()
        .and_then(|own| styles.next(own))
        .map(str::to_owned)
        .or_else(|| own.clone());
    let style = given.or(followed);
    let kept = paragraph && style == own;
    let written = style.filter(|id| Some(id.as_str()) != styles.default_paragraph());
    let reference = written
        .as_deref()
        .map(|id| format!(r#"<{w}:pStyle {w}:val="{}"/>"#, escaped(id)));
    let copied = properties.map(|ppr| {
        copy_children(main, ppr, &|child| {
            ["pStyle", "sectPr", "pPrChange"]
                .iter()
                .any(|local| doc.is(child, W, local))
        })
    });
    let inner = format!(
        "{}{}",
        reference.unwrap_or_default(),
        copied.unwrap_or_default()
    );
    let ppr = if inner.is_empty() {
        String::new()
    } else {
        format!("<{w}:pPr>{inner}</{w}:pPr>")
    };
    let inner = content(&w);
    let run = if inner.is_empty() {
        String::new()
    } else {
        let formatting = kept
            .then(|| first_run_properties(main, node))
            .flatten()
            .unwrap_or_default();
        format!("<{w}:r>{formatting}{inner}</{w}:r>")
    };
    Ok(Built {
        xml: format!("<{w}:p>{ppr}{run}</{w}:p>"),
        style: written,
    })
}

/// The content of a run with `text`: a `w:t` for each piece between tabs, and a `w:tab` for
/// each tab.
pub(super) fn run_text(w: &str, text: &str) -> String {
    text.split('\t')
        .map(|piece| {
            if piece.is_empty() {
                String::new()
            } else {
                text_element(w, piece)
            }
        })
        .collect::<Vec<String>>()
        .join(&format!("<{w}:tab/>"))
}

/// A `w:t` element with `text`, which keeps its white space at its ends.
pub(super) fn text_element(w: &str, text: &str) -> String {
    if text.is_empty() {
        return format!("<{w}:t/>");
    }
    let space = if text.starts_with(char::is_whitespace) || text.ends_with(char::is_whitespace) {
        r#" xml:space="preserve""#
    } else {
        ""
    };
    format!("<{w}:t{space}>{}</{w}:t>", escaped(text))
}

/// The bytes of the run properties of the first run of the paragraph `node`, if it has them.
pub(super) fn first_run_properties(main: &Main<'_>, node: NodeId) -> Option<String> {
    let doc = main.doc;
    let mut stack = vec![node];
    while let Some(current) = stack.pop() {
        if doc.is(current, W, "r") {
            return doc
                .child(current, W, "rPr")
                .map(|rpr| main.text(main.span(rpr)));
        }
        if current != node && is_other_story(doc, current) {
            continue;
        }
        let children: Vec<NodeId> = doc.child_elements(current).collect();
        stack.extend(children.into_iter().rev());
    }
    None
}

/// Whether `node` is an element whose content is another story or an object.
pub(super) fn is_other_story(doc: &Document, node: NodeId) -> bool {
    OTHER_STORIES
        .iter()
        .any(|(namespace, local)| doc.is(node, namespace, local))
}

/// The bytes of the child nodes of `node` as written, without the child elements for which
/// `skip` holds.
pub(super) fn copy_children(
    main: &Main<'_>,
    node: NodeId,
    skip: &dyn Fn(NodeId) -> bool,
) -> String {
    let doc = main.doc;
    doc.children(node)
        .iter()
        .filter(|&&child| doc.element(child).is_none() || !skip(child))
        .map(|&child| main.text(main.span(child)))
        .collect()
}

/// The prefix of the WordprocessingML element `node`, which the new elements next to it or in
/// it take.
pub(super) fn prefix(doc: &Document, node: NodeId) -> Result<String, NamedFault> {
    doc.element(node)
        .and_then(|element| element.name.prefix.map(str::to_owned))
        .ok_or(NamedFault::NoPrefix)
}

/// Checks that `xml` parses as the content of the parent of `node`.
pub(super) fn check_fragment(main: &Main<'_>, node: NodeId, xml: &str) -> Result<(), NamedFault> {
    parses_in(main, main.parent(node), xml)
}

/// Checks that `xml` parses as the content of `node`.
pub(super) fn check_content(main: &Main<'_>, node: NodeId, xml: &str) -> Result<(), NamedFault> {
    parses_in(main, Some(node), xml)
}

/// Checks that `xml` parses with the namespaces in scope at `scope`.
fn parses_in(main: &Main<'_>, scope: Option<NodeId>, xml: &str) -> Result<(), NamedFault> {
    let scope = scope.map_or_else(Vec::new, |node| main.doc.namespaces_in_scope(node));
    Document::parse_fragment(xml.as_bytes(), &scope, &XmlLimits::default())
        .map(drop)
        .map_err(NamedFault::NewXml)
}

/// Whether the paragraph `node` ends a section: its `w:pPr` holds a `w:sectPr`.
pub(super) fn ends_section(doc: &Document, node: NodeId) -> bool {
    doc.child(node, W, "pPr")
        .and_then(|ppr| doc.child(ppr, W, "sectPr"))
        .is_some()
}

/// The start or end element of the first range of which `node` holds one end only.
pub(super) fn open_range(doc: &Document, node: NodeId) -> Option<&'static str> {
    open_range_in(doc, &[node])
}

/// The start or end element of the first range of which the elements `nodes` hold one end
/// only: a range of one kind and ID with a start but no end, or an end but no start, in the
/// order of the walk.
pub(super) fn open_range_in(doc: &Document, nodes: &[NodeId]) -> Option<&'static str> {
    let mut ends: Vec<RangeEnd> = Vec::new();
    let mut stack = nodes.to_vec();
    while let Some(current) = stack.pop() {
        ends.extend(range_end(doc, current));
        stack.extend(doc.child_elements(current));
    }
    // Whether each range, by its kind and ID, has a start and an end among the elements.
    let mut sides: HashMap<(usize, &str), (bool, bool)> = HashMap::new();
    for end in &ends {
        let (has_start, has_end) = sides.entry((end.range, end.id.as_str())).or_default();
        if end.start {
            *has_start = true;
        } else {
            *has_end = true;
        }
    }
    ends.iter()
        .find(|end| {
            let (has_start, has_end) = sides
                .get(&(end.range, end.id.as_str()))
                .copied()
                .unwrap_or_default();
            if end.start { !has_end } else { !has_start }
        })
        .map(|end| end.element)
}

/// One end of a range: the index of its kind in [`RANGES`], whether it is the start, its ID
/// and its element's name.
struct RangeEnd {
    range: usize,
    start: bool,
    id: String,
    element: &'static str,
}

/// The end of a range that `node` is, if it is one.
fn range_end(doc: &Document, node: NodeId) -> Option<RangeEnd> {
    RANGES.iter().enumerate().find_map(|(range, (start, end))| {
        [(*start, true), (*end, false)]
            .into_iter()
            .find(|(element, _)| doc.is(node, W, element.trim_start_matches("w:")))
            .map(|(element, is_start)| RangeEnd {
                range,
                start: is_start,
                id: doc.attribute(node, Some(W), "id").unwrap_or("").to_owned(),
                element,
            })
    })
}

/// Whether `node` holds the reference of a footnote or an endnote.
pub(super) fn holds_note_reference(doc: &Document, node: NodeId) -> bool {
    holds_note_reference_in(doc, &[node])
}

/// Whether the elements `nodes` hold the reference of a footnote or an endnote.
pub(super) fn holds_note_reference_in(doc: &Document, nodes: &[NodeId]) -> bool {
    let mut stack = nodes.to_vec();
    while let Some(current) = stack.pop() {
        if doc.is(current, W, "footnoteReference") || doc.is(current, W, "endnoteReference") {
            return true;
        }
        stack.extend(doc.child_elements(current));
    }
    false
}

/// The splices that set the style of `node` to `id`: its `element` (`w:pStyle` or
/// `w:tblStyle`), the first child of its `properties` (`w:pPr` or `w:tblPr`).
pub(super) fn set_style(
    main: &Main<'_>,
    node: NodeId,
    properties: &str,
    element: &str,
    id: &str,
) -> Result<Vec<(Range<usize>, String)>, NamedFault> {
    let doc = main.doc;
    let w = prefix(doc, node)?;
    let reference = format!(r#"<{w}:{element} {w}:val="{}"/>"#, escaped(id));
    let Some(holder) = doc.child(node, W, properties) else {
        let wrapped = format!("<{w}:{properties}>{reference}</{w}:{properties}>");
        return Ok(vec![insert_first(main, node, &wrapped)]);
    };
    if let Some(old) = doc.child(holder, W, element) {
        return Ok(vec![(main.span(old), reference)]);
    }
    Ok(vec![insert_first(main, holder, &reference)])
}

/// The splice that puts `xml` first in the content of `node`: after its start tag, or in
/// place of an empty element, which becomes a start tag and an end tag around it.
fn insert_first(main: &Main<'_>, node: NodeId, xml: &str) -> (Range<usize>, String) {
    let span = main.span(node);
    if let Some(wrapped) = wrap_empty(main.bytes, &span, xml) {
        return (span, wrapped);
    }
    let end = start_tag_end(main.bytes, span.start);
    (end..end, xml.to_owned())
}

/// The splice that puts `xml` last in the content of the element whose span in `bytes` is
/// `span`: before its end tag, or in place of an empty element, which becomes a start tag and
/// an end tag around it.
pub(super) fn insert_last(bytes: &[u8], span: Range<usize>, xml: &str) -> (Range<usize>, String) {
    if let Some(wrapped) = wrap_empty(bytes, &span, xml) {
        return (span, wrapped);
    }
    let end = end_tag_start(bytes, &span);
    (end..end, xml.to_owned())
}

/// The content of the element whose span in `bytes` is `span`, after its child `after` when it
/// has one: from the end of that child, or of the start tag, to the start of the end tag; none
/// for an empty element, which has no end tag.
pub(super) fn content_after(
    bytes: &[u8],
    span: &Range<usize>,
    after: Option<Range<usize>>,
) -> Option<Range<usize>> {
    let open = start_tag_end(bytes, span.start);
    if open == span.end {
        return None;
    }
    let start = after.map_or(open, |child| child.end);
    Some(start..end_tag_start(bytes, span))
}

/// An empty element (`<w:p/>`) whose span in `bytes` is `span`, written again as a start tag
/// and an end tag around `xml`; none for an element with an end tag.
fn wrap_empty(bytes: &[u8], span: &Range<usize>, xml: &str) -> Option<String> {
    let end = start_tag_end(bytes, span.start);
    if end != span.end || bytes.get(end.saturating_sub(2)) != Some(&b'/') {
        return None;
    }
    let open = String::from_utf8_lossy(bytes.get(span.start..end - 2)?).into_owned();
    let name = open
        .trim_start_matches('<')
        .split(|c: char| c.is_whitespace())
        .next()
        .unwrap_or_default()
        .to_owned();
    Some(format!("{}>{xml}</{name}>", open.trim_end()))
}

/// The index of the `<` that starts the end tag of the element whose span in `bytes` is
/// `span`, which has one: the last `</` of the span, since no text holds a bare `<`.
fn end_tag_start(bytes: &[u8], span: &Range<usize>) -> usize {
    bytes
        .get(span.clone())
        .and_then(|element| element.windows(2).rposition(|pair| pair == b"</"))
        .map_or(span.end, |at| span.start + at)
}

/// The index after the `>` that ends the start tag at `start`, outside quoted attribute
/// values.
fn start_tag_end(bytes: &[u8], start: usize) -> usize {
    let mut quote = None;
    for (index, &byte) in bytes.iter().enumerate().skip(start) {
        match (quote, byte) {
            (None, b'"' | b'\'') => quote = Some(byte),
            (Some(open), _) if byte == open => quote = None,
            (None, b'>') => return index + 1,
            _ => {}
        }
    }
    bytes.len()
}

/// `text` with the characters that XML text and attribute values reserve written as
/// references.
pub(super) fn escaped(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
    out
}