docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Paragraph text projection.
//!
//! Word splits visible text across runs and inline containers. The projection
//! rebuilds the logical text of a paragraph and maps character offsets back to
//! the character data nodes they came from, so a template span can be resolved
//! without re-parsing XML.

use super::{Element, Node, Role, TextNode};

/// A character range resolved to one text node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ResolvedSlice {
    /// Child indices from the paragraph to the `w:t` element.
    pub(crate) element_path: Vec<usize>,
    /// Index of the character data node inside the `w:t` element.
    pub(crate) node_index: usize,
    /// Start offset within that node's decoded value.
    pub(crate) start: usize,
    /// End offset within that node's decoded value.
    pub(crate) end: usize,
}

/// One character data segment in the projection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Segment {
    /// Child indices from the paragraph to the `w:t` element.
    pub(crate) element_path: Vec<usize>,
    /// Index of the character data node inside the `w:t` element.
    pub(crate) node_index: usize,
    /// Start offset in the projection text.
    pub(crate) start: usize,
    /// End offset in the projection text.
    pub(crate) end: usize,
    /// Identity of the nearest inline container, if any.
    pub(crate) container: Option<usize>,
}

/// The logical text of a paragraph with an offset map.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Projection {
    text: String,
    segments: Vec<Segment>,
}

/// An error raised while resolving a span.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub(crate) enum ProjectionError {
    /// The span starts in one inline container and ends in another.
    #[error("text span crosses inline containers")]
    TextSpansContainers {
        /// The container identities the span touches.
        containers: Vec<Option<usize>>,
    },
}

impl Projection {
    /// The logical text of the paragraph.
    pub(crate) fn text(&self) -> &str {
        &self.text
    }

    /// The segments that make up the projection.
    pub(crate) fn segments(&self) -> &[Segment] {
        &self.segments
    }

    /// Resolve a character range to the text nodes it covers.
    ///
    /// Returns the covered sub ranges in document order. A range that crosses
    /// two different inline containers is rejected.
    pub(crate) fn resolve(
        &self,
        start: usize,
        end: usize,
    ) -> Result<Vec<ResolvedSlice>, ProjectionError> {
        let mut covered = Vec::new();
        let mut containers = Vec::new();

        for segment in &self.segments {
            if segment.start >= end || segment.end <= start {
                continue;
            }
            if !containers.contains(&segment.container) {
                containers.push(segment.container);
            }
            let slice_start = start.max(segment.start) - segment.start;
            let slice_end = end.min(segment.end) - segment.start;
            covered.push(ResolvedSlice {
                element_path: segment.element_path.clone(),
                node_index: segment.node_index,
                start: slice_start,
                end: slice_end,
            });
        }

        if containers.len() > 1 {
            return Err(ProjectionError::TextSpansContainers { containers });
        }

        Ok(covered)
    }
}

/// Build the projection for a paragraph element.
///
/// Walks runs and inline containers depth first. Only `w:t` character data is
/// projected; everything else is skipped.
pub(crate) fn project(paragraph: &Element) -> Projection {
    let mut builder = Builder {
        text: String::new(),
        segments: Vec::new(),
        containers: 0,
    };
    let mut path = Vec::new();
    builder.walk(paragraph, &mut path, None);
    Projection {
        text: builder.text,
        segments: builder.segments,
    }
}

struct Builder {
    text: String,
    segments: Vec<Segment>,
    containers: usize,
}

impl Builder {
    fn walk(&mut self, element: &Element, path: &mut Vec<usize>, container: Option<usize>) {
        for (index, child) in element.children().iter().enumerate() {
            let Node::Element(child) = child else {
                continue;
            };

            path.push(index);
            if child.role() == Role::Text {
                self.push_text(child, path, container);
            } else {
                let next_container = if child.role() == Role::InlineContainer {
                    let id = self.containers;
                    self.containers += 1;
                    Some(id)
                } else {
                    container
                };
                self.walk(child, path, next_container);
            }
            path.pop();
        }
    }

    fn push_text(&mut self, element: &Element, path: &[usize], container: Option<usize>) {
        for (node_index, child) in element.children().iter().enumerate() {
            let Node::Text(text) = child else {
                continue;
            };
            let start = self.text.len();
            self.text.push_str(text.value());
            let end = self.text.len();
            if start == end {
                continue;
            }
            self.segments.push(Segment {
                element_path: path.to_vec(),
                node_index,
                start,
                end,
                container,
            });
        }
    }
}

/// Mutably borrow the character data node a resolved slice points at.
pub(crate) fn text_node_mut<'a>(
    paragraph: &'a mut Element,
    path: &[usize],
    node_index: usize,
) -> Option<&'a mut TextNode> {
    let mut current = paragraph;
    for index in path {
        current = current.children_mut().get_mut(*index)?.as_element_mut()?;
    }
    current.children_mut().get_mut(node_index)?.as_text_mut()
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use super::*;

    fn element(name: &str, role: Role, children: Vec<Node>) -> Element {
        Element::new(
            name.to_owned(),
            role,
            format!("<{name}>").into_bytes(),
            format!("</{name}>").into_bytes(),
            false,
            children,
        )
    }

    fn text(value: &str) -> Node {
        Node::Text(TextNode::original(
            value.as_bytes().to_vec(),
            value.to_owned(),
        ))
    }

    fn run(value: &str) -> Node {
        Node::Element(element(
            "w:r",
            Role::Run,
            vec![Node::Element(element("w:t", Role::Text, vec![text(value)]))],
        ))
    }

    fn paragraph(children: Vec<Node>) -> Element {
        element("w:p", Role::Paragraph, children)
    }

    #[test]
    fn projects_text_across_runs() {
        let p = paragraph(vec![run("Hello "), run("World")]);
        let projection = project(&p);
        assert_eq!(projection.text(), "Hello World");
        assert_eq!(projection.segments().len(), 2);
    }

    #[test]
    fn resolves_a_placeholder_split_across_runs() {
        let p = paragraph(vec![run("{{user."), run("name}}")]);
        let projection = project(&p);
        let start = projection.text().find("{{").unwrap();
        let end = projection.text().find("}}").unwrap() + 2;
        let slices = projection.resolve(start, end).unwrap();
        assert_eq!(slices.len(), 2);
        assert_eq!(slices[0].start, 0);
        assert_eq!(slices[0].end, 7);
        assert_eq!(slices[1].start, 0);
        assert_eq!(slices[1].end, 6);
    }

    #[test]
    fn resolves_a_partial_range_within_one_node() {
        let p = paragraph(vec![run("say {{name}} now")]);
        let projection = project(&p);
        let start = projection.text().find("{{").unwrap();
        let end = start + 8;
        let slices = projection.resolve(start, end).unwrap();
        assert_eq!(slices.len(), 1);
        assert_eq!(slices[0].start, 4);
        assert_eq!(slices[0].end, 12);
    }

    #[test]
    fn rejects_a_span_across_inline_containers() {
        let link = Node::Element(element(
            "w:hyperlink",
            Role::InlineContainer,
            vec![run("{{na")],
        ));
        let p = paragraph(vec![link, run("me}}")]);
        let projection = project(&p);
        let start = projection.text().find("{{").unwrap();
        let end = projection.text().find("}}").unwrap() + 2;
        let error = projection.resolve(start, end).unwrap_err();
        assert!(matches!(error, ProjectionError::TextSpansContainers { .. }));
    }

    #[test]
    fn accepts_a_span_inside_one_container() {
        let link = Node::Element(element(
            "w:hyperlink",
            Role::InlineContainer,
            vec![run("{{name}}")],
        ));
        let p = paragraph(vec![link]);
        let projection = project(&p);
        let start = projection.text().find("{{").unwrap();
        let end = projection.text().find("}}").unwrap() + 2;
        assert_eq!(projection.resolve(start, end).unwrap().len(), 1);
    }

    #[test]
    fn empty_paragraph_projects_to_empty_text() {
        let p = paragraph(vec![]);
        let projection = project(&p);
        assert_eq!(projection.text(), "");
        assert!(projection.segments().is_empty());
    }

    #[test]
    fn text_node_mut_reaches_the_right_node() {
        let mut p = paragraph(vec![run("Hello "), run("World")]);
        let projection = project(&p);
        let slices = projection.resolve(6, 11).unwrap();
        let slice = &slices[0];
        let node = text_node_mut(&mut p, &slice.element_path, slice.node_index).unwrap();
        node.set_value("there".to_owned());
        assert_eq!(project(&p).text(), "Hello there");
    }
}