f-office-docx 0.3.0

DOCX model and Word's layout rules.
Documentation
use f_office_xml::{Document, Limits, NodeId};

use super::accept;
use crate::ns::W;

/// The part `<w:body>` + `body` + `</w:body>`.
fn parsed(body: &str) -> Document {
    let xml = format!(r#"<w:document xmlns:w="{W}"><w:body>{body}</w:body></w:document>"#);
    Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
}

/// The part `<w:body>` + `body` + `</w:body>` with every change accepted.
fn accepted(body: &str) -> Document {
    let mut doc = parsed(body);
    accept(
        &mut doc,
        crate::reader::settings::ReaderSettings::base()
            .with_insertions(crate::quirks::InsertionRevision::Author)
            .with_comments(crate::quirks::CommentBuffer::ReferenceMark),
    );
    doc
}

fn body(doc: &Document) -> NodeId {
    doc.child(doc.root().unwrap(), W, "body").unwrap()
}

/// The text of each paragraph of the body, with `|` where a table cell ends.
fn paragraphs(doc: &Document) -> Vec<String> {
    fn walk(doc: &Document, node: NodeId, out: &mut Vec<String>) {
        for child in doc.child_elements(node) {
            if doc.is(child, W, "p") {
                out.push(doc.text_content(child));
            } else {
                walk(doc, child, out);
                if doc.is(child, W, "tc") {
                    out.push("|".to_owned());
                }
            }
        }
    }
    let mut out = Vec::new();
    walk(doc, body(doc), &mut out);
    out
}

/// No element names.
const NONE: [&str; 0] = [];

fn names(doc: &Document, node: NodeId) -> Vec<String> {
    doc.child_elements(node)
        .filter_map(|child| doc.element(child).map(|e| e.name.local.to_owned()))
        .collect()
}

#[test]
fn keeps_inserted_text_and_drops_deleted_text() {
    let doc = accepted(
        r#"<w:p><w:r><w:t>Test </w:t></w:r><w:del w:author="A"><w:r><w:delText>test </w:delText></w:r></w:del><w:ins w:author="A"><w:r><w:t>abc </w:t></w:r></w:ins><w:moveFrom><w:r><w:t>away </w:t></w:r></w:moveFrom><w:moveTo><w:r><w:t>here </w:t></w:r></w:moveTo><w:r><w:t>test</w:t></w:r></w:p>"#,
    );
    assert_eq!(paragraphs(&doc), ["Test abc here test"]);
    let p = doc.child(body(&doc), W, "p").unwrap();
    assert_eq!(names(&doc, p), ["r", "r", "r", "r"]);
}

#[test]
fn notes_the_insertion_of_each_inserted_run() {
    // The runs of an insertion, also inside a hyperlink, and of moved-in content keep a number
    // of their change's author as a note, whatever the length of the change's id: two changes
    // of one author share it, another author's change gets another; the other runs get none.
    let doc = accepted(
        r#"<w:p><w:r><w:t>a</w:t></w:r><w:ins w:id="1778776725739" w:author="A"><w:r><w:t>b</w:t></w:r><w:hyperlink><w:r><w:t>c</w:t></w:r></w:hyperlink></w:ins><w:ins w:id="5" w:author="A"><w:r><w:t>d</w:t></w:r></w:ins><w:moveTo w:id="9" w:author="B"><w:r><w:t>e</w:t></w:r></w:moveTo></w:p>"#,
    );
    let p = doc.child(body(&doc), W, "p").unwrap();
    let note = |run| doc.attribute(run, Some(crate::ns::NOTE), "change");
    let runs: Vec<NodeId> = doc.child_elements(p).collect();
    let link = doc.child(runs[2], W, "r").unwrap();
    assert_eq!(note(runs[0]), None);
    assert!(note(runs[1]).is_some_and(|n| n.parse::<u32>().is_ok()));
    assert_eq!(note(link), note(runs[1]));
    assert_eq!(note(runs[3]), note(runs[1]));
    assert!(note(runs[4]).is_some());
    assert_ne!(note(runs[4]), note(runs[1]));
}

#[test]
fn makes_one_revision_of_the_insertions_of_one_author_or_of_one_author_and_minute() {
    // Three insertions of one author, the second 30 seconds after the first and the third a
    // minute after it, and one without a date.
    let insertions = r#"<w:p><w:ins w:id="1" w:author="A" w:date="2026-01-05T10:00:00Z"><w:r><w:t>a</w:t></w:r></w:ins><w:ins w:id="2" w:author="A" w:date="2026-01-05T10:00:30Z"><w:r><w:t>b</w:t></w:r></w:ins><w:ins w:id="3" w:author="A" w:date="2026-01-05T10:01:00Z"><w:r><w:t>c</w:t></w:r></w:ins><w:ins w:id="4" w:author="A"><w:r><w:t>d</w:t></w:r></w:ins></w:p>"#;
    let numbers = |revision| {
        let mut doc = parsed(insertions);
        accept(
            &mut doc,
            crate::reader::settings::ReaderSettings::base()
                .with_insertions(revision)
                .with_comments(crate::quirks::CommentBuffer::ReferenceMark),
        );
        let p = doc.child(body(&doc), W, "p").unwrap();
        doc.child_elements(p)
            .map(|run| {
                doc.attribute(run, Some(crate::ns::NOTE), "change")
                    .unwrap()
                    .to_owned()
            })
            .collect::<Vec<_>>()
    };
    // Which runs share their insertion's number with the run after them.
    let shared = |revision| {
        let numbers = numbers(revision);
        numbers
            .windows(2)
            .map(|pair| pair[0] == pair[1])
            .collect::<Vec<_>>()
    };
    assert_eq!(
        shared(crate::quirks::InsertionRevision::Author),
        [true, true, true]
    );
    assert_eq!(
        shared(crate::quirks::InsertionRevision::AuthorAndMinute),
        [true, false, false]
    );
}

#[test]
fn marks_the_run_after_deleted_runs_and_not_after_a_deleted_mark_alone() {
    // The first paragraph's mark is deleted, so the paragraphs join; the run after it holds
    // the mark's character in the buffers but follows no deleted run.
    let doc = accepted(&format!(
        r#"<w:p>{}<w:r><w:t>a</w:t></w:r><w:del w:id="1" w:author="A"><w:r><w:delText>x</w:delText></w:r></w:del><w:r><w:t>b</w:t></w:r><w:r><w:t>c</w:t></w:r></w:p><w:p><w:r><w:t>d</w:t></w:r></w:p>"#,
        deleted_mark("")
    ));
    let note = |run, name| doc.attribute(run, Some(crate::ns::NOTE), name).is_some();
    let runs: Vec<NodeId> = doc
        .child_elements(body(&doc))
        .flat_map(|p| doc.child_elements(p).collect::<Vec<_>>())
        .filter(|&node| doc.is(node, W, "r"))
        .collect();
    let removed: Vec<bool> = runs.iter().map(|&run| note(run, "removed")).collect();
    let buffered: Vec<bool> = runs.iter().map(|&run| note(run, "buffered")).collect();
    assert_eq!(removed, [false, true, false, false]);
    assert_eq!(buffered, [false, true, false, true]);
}

#[test]
fn drops_the_records_of_earlier_properties_and_the_marks_of_insertions() {
    let doc = accepted(
        r#"<w:p><w:pPr><w:jc w:val="center"/><w:rPr><w:ins w:author="A"/></w:rPr><w:pPrChange><w:pPr/></w:pPrChange></w:pPr><w:r><w:rPr><w:b/><w:rPrChange><w:rPr/></w:rPrChange></w:rPr><w:t>a</w:t></w:r></w:p>"#,
    );
    let p = doc.child(body(&doc), W, "p").unwrap();
    let ppr = doc.child(p, W, "pPr").unwrap();
    assert_eq!(names(&doc, ppr), ["jc", "rPr"]);
    assert_eq!(names(&doc, doc.child(ppr, W, "rPr").unwrap()), NONE);
    let rpr = doc.child(doc.child(p, W, "r").unwrap(), W, "rPr").unwrap();
    assert_eq!(names(&doc, rpr), ["b"]);
}

#[test]
fn joins_a_paragraph_whose_mark_is_deleted_to_the_next_one() {
    let deleted = r#"<w:rPr><w:del w:author="A"/></w:rPr>"#;
    let doc = accepted(&format!(
        r#"<w:p><w:pPr><w:jc w:val="center"/>{deleted}</w:pPr><w:r><w:t>one </w:t></w:r></w:p><w:bookmarkEnd w:id="0"/><w:p><w:pPr>{deleted}</w:pPr><w:r><w:t>two </w:t></w:r></w:p><w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>three</w:t></w:r></w:p>"#
    ));
    assert_eq!(paragraphs(&doc), ["one two three"]);
    let p = doc.child(body(&doc), W, "p").unwrap();
    let jc = doc.child(doc.child(p, W, "pPr").unwrap(), W, "jc").unwrap();
    assert_eq!(doc.attribute(jc, Some(W), "val"), Some("right"));
    assert_eq!(names(&doc, body(&doc)), ["bookmarkEnd", "p"]);
}

#[test]
fn drops_a_wholly_deleted_paragraph() {
    let doc = accepted(
        r#"<w:p><w:r><w:t>keep</w:t></w:r></w:p><w:p><w:pPr><w:rPr><w:del w:author="A"/></w:rPr></w:pPr><w:del w:author="A"><w:r><w:delText>gone</w:delText></w:r></w:del></w:p><w:p><w:r><w:t>next</w:t></w:r></w:p>"#,
    );
    assert_eq!(paragraphs(&doc), ["keep", "next"]);
}

#[test]
fn gives_a_deleted_mark_before_a_table_the_properties_of_its_first_paragraph() {
    let doc = accepted(
        r#"<w:p><w:pPr><w:jc w:val="center"/><w:rPr><w:del w:author="A"/></w:rPr></w:pPr><w:r><w:t>a</w:t></w:r></w:p><w:tbl><w:tr><w:trPr><w:del w:author="A"/></w:trPr><w:tc><w:p><w:pPr><w:jc w:val="both"/></w:pPr><w:r><w:t>gone</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:pPr><w:jc w:val="right"/><w:rPr><w:del w:author="A"/></w:rPr></w:pPr><w:r><w:t>b</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:pPr><w:jc w:val="center"/><w:rPr><w:del w:author="A"/></w:rPr></w:pPr><w:r><w:t>c</w:t></w:r></w:p>"#,
    );
    assert_eq!(paragraphs(&doc), ["a", "b", "|", "c"]);
    let jc = |paragraph: NodeId| {
        let jc = doc.child(doc.child(paragraph, W, "pPr").unwrap(), W, "jc");
        jc.and_then(|jc| doc.attribute(jc, Some(W), "val"))
    };
    let mut kept = doc
        .child_elements(body(&doc))
        .filter(|&c| doc.is(c, W, "p"));
    let (first, last) = (kept.next().unwrap(), kept.next().unwrap());
    assert_eq!(names(&doc, first), ["pPr", "r"]);
    assert_eq!(jc(first), Some("right"));
    assert_eq!(jc(last), Some("center"));
}

/// The properties of a paragraph with `props` whose mark is deleted.
fn deleted_mark(props: &str) -> String {
    format!(r#"<w:pPr>{props}<w:rPr><w:del w:author="A"/></w:rPr></w:pPr>"#)
}

/// A table of one deleted row, whose one cell holds `paragraph`.
fn deleted_table(paragraph: &str) -> String {
    format!(
        r#"<w:tbl><w:tr><w:trPr><w:del w:author="A"/></w:trPr><w:tc>{paragraph}</w:tc></w:tr></w:tbl>"#
    )
}

#[test]
fn does_not_join_across_a_deleted_table_and_drops_an_empty_paragraph_before_a_table() {
    let (deleted, gone) = (deleted_mark(""), deleted_table("<w:p/>"));
    let doc = accepted(&format!(
        r#"<w:p>{deleted}<w:r><w:t>one</w:t></w:r></w:p>{gone}<w:p><w:r><w:t>two</w:t></w:r></w:p><w:p>{deleted}<w:del w:author="A"><w:r><w:delText>no</w:delText></w:r></w:del><w:r><w:lastRenderedPageBreak/></w:r></w:p>{gone}<w:p><w:r><w:t>three</w:t></w:r></w:p>"#
    ));
    assert_eq!(paragraphs(&doc), ["one", "two", "three"]);
}

#[test]
fn drops_deleted_rows_and_empty_tables_and_keeps_deleted_cells() {
    let doc = accepted(
        r#"<w:tbl><w:tblPr/><w:tr><w:trPr><w:del w:author="A"/></w:trPr><w:tc><w:p><w:r><w:t>row</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:trPr><w:ins w:author="A"/></w:trPr><w:tc><w:tcPr><w:cellDel w:author="A"/></w:tcPr><w:p><w:r><w:t>cell</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:cellIns w:author="A"/><w:tcPrChange><w:tcPr/></w:tcPrChange></w:tcPr><w:p><w:r><w:t>new</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:tbl><w:tr><w:trPr><w:del w:author="A"/></w:trPr><w:tc><w:p/></w:tc></w:tr></w:tbl><w:p/>"#,
    );
    assert_eq!(paragraphs(&doc), ["cell", "|", "new", "|", ""]);
    let table = doc.child(body(&doc), W, "tbl").unwrap();
    let row = doc.child(table, W, "tr").unwrap();
    assert_eq!(names(&doc, doc.child(row, W, "trPr").unwrap()), NONE);
    for cell in doc.child_elements(row).filter(|&c| doc.is(c, W, "tc")) {
        assert_eq!(names(&doc, doc.child(cell, W, "tcPr").unwrap()), NONE);
    }
    assert_eq!(names(&doc, body(&doc)), ["tbl", "tbl", "p"]);
    let gone = doc.child_elements(body(&doc)).nth(1).unwrap();
    assert_eq!(names(&doc, gone), NONE);
}

#[test]
fn keeps_a_table_whose_rows_lie_in_content_controls_and_empties_one_whose_wrapped_rows_go() {
    let row =
        |text: &str| format!(r"<w:tr><w:tc><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:tc></w:tr>");
    let deleted = deleted_table("<w:p/>")
        .replace("<w:tbl>", "")
        .replace("</w:tbl>", "");
    let doc = accepted(&format!(
        r"<w:tbl><w:sdt><w:sdtPr/><w:sdtContent>{}</w:sdtContent></w:sdt></w:tbl><w:tbl><w:customXml>{}</w:customXml></w:tbl><w:tbl><w:sdt><w:sdtContent>{deleted}</w:sdtContent></w:sdt></w:tbl><w:p/>",
        row("control"),
        row("custom")
    ));
    assert_eq!(paragraphs(&doc), ["control", "|", "custom", "|", ""]);
    let gone = doc.child_elements(body(&doc)).nth(2).unwrap();
    assert_eq!(names(&doc, gone), NONE);
}

#[test]
fn gives_a_deleted_mark_before_a_deleted_table_the_properties_of_the_paragraph_after_it() {
    let deleted = deleted_mark(r#"<w:pBdr><w:bottom w:val="single"/></w:pBdr>"#);
    let right = deleted_mark(r#"<w:jc w:val="right"/>"#);
    let gone = deleted_table(&format!("<w:p>{right}</w:p>"));
    let doc = accepted(&format!(
        r#"<w:p>{deleted}<w:r><w:t>a</w:t></w:r></w:p><w:p>{deleted}</w:p>{gone}{gone}<w:p><w:pPr><w:spacing w:before="160"/><w:sectPr/></w:pPr></w:p><w:p><w:r><w:t>b</w:t></w:r></w:p>"#
    ));
    assert_eq!(paragraphs(&doc), ["a", "", "b"]);
    assert_eq!(names(&doc, body(&doc)), ["p", "tbl", "tbl", "p", "p"]);
    assert_eq!(first_properties(&doc), (vec!["spacing".to_owned()], None));
}

/// The names of the properties of the body's first paragraph, and its alignment.
fn first_properties(doc: &Document) -> (Vec<String>, Option<&str>) {
    let first = doc.child(body(doc), W, "p").unwrap();
    let props = doc.child(first, W, "pPr").unwrap();
    let jc = doc.child(props, W, "jc");
    (
        names(doc, props),
        jc.and_then(|jc| doc.attribute(jc, Some(W), "val")),
    )
}

#[test]
fn gives_a_deleted_mark_before_a_deleted_table_the_properties_of_a_kept_mark_in_its_rows() {
    let centered = deleted_mark(r#"<w:jc w:val="center"/>"#);
    let gone = deleted_table(
        r#"<w:p><w:pPr><w:jc w:val="both"/><w:pPrChange><w:pPr/></w:pPrChange></w:pPr></w:p>"#,
    );
    let doc = accepted(&format!(
        r#"<w:p>{centered}<w:r><w:t>a</w:t></w:r></w:p>{gone}<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#
    ));
    assert_eq!(paragraphs(&doc), ["a", "b"]);
    assert_eq!(
        first_properties(&doc),
        (vec!["jc".to_owned()], Some("both"))
    );
}

#[test]
fn accepts_changes_inside_text_boxes_and_leaves_other_namespaces() {
    let doc = accepted(
        r#"<w:p><w:r><x:del xmlns:x="urn:x"><w:txbxContent><w:p><w:del><w:r><w:delText>no</w:delText></w:r></w:del><w:r><w:t>box</w:t></w:r></w:p></w:txbxContent></x:del></w:r></w:p>"#,
    );
    assert_eq!(paragraphs(&doc), ["box"]);
}

#[test]
fn joins_a_long_chain_of_deleted_marks_without_a_walk_for_each() {
    // Two chains of 50,000 paragraphs: one joins a paragraph, one goes before a table.
    const CHAIN: usize = 50_000;
    let joins = deleted_mark("") + "<w:r><w:t>a</w:t></w:r></w:p>";
    let empty = deleted_mark("") + "</w:p>";
    let chains = format!(
        "{}<w:p><w:r><w:t>b</w:t></w:r></w:p>{}<w:tbl><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl>",
        format!("<w:p>{joins}").repeat(CHAIN),
        format!("<w:p>{empty}").repeat(CHAIN),
    );
    let mut doc = parsed(&chains);
    super::JOIN_STEPS.with(|steps| steps.set(0));
    accept(
        &mut doc,
        crate::reader::settings::ReaderSettings::base()
            .with_insertions(crate::quirks::InsertionRevision::Author)
            .with_comments(crate::quirks::CommentBuffer::ReferenceMark),
    );
    // Each paragraph of the chains takes at most three steps: the walk reads the block after it
    // once, a paragraph that joins moves its two children, and one before the table reads the
    // table. A walk for each paragraph would read about CHAIN² / 2 children.
    let steps = super::JOIN_STEPS.with(std::cell::Cell::get);
    assert!(steps <= 3 * 2 * CHAIN, "{steps} steps");
    assert_eq!(
        paragraphs(&doc),
        ["a".repeat(CHAIN) + "b", String::new(), "|".to_owned()]
    );
    assert_eq!(names(&doc, body(&doc)), ["p", "tbl"]);
}