use std::collections::HashSet;
use crate::changes::{Change, ChangeError, ChangeKind};
use crate::edit::ResolvedRevisions;
fn escape_critic(text: &str) -> String {
const DELIMITERS: [(&str, &str); 11] = [
("{++", "{\\++"),
("{--", "{\\--"),
("{~~", "{\\~~"),
("{>>", "{\\>>"),
("{==", "{\\=="),
("++}", "++\\}"),
("--}", "--\\}"),
("~~}", "~~\\}"),
("<<}", "<<\\}"),
("==}", "==\\}"),
("~>", "~\\>"),
];
if !text.contains(['{', '}', '~']) {
return text.to_string();
}
DELIMITERS
.iter()
.fold(text.to_string(), |text, (from, to)| text.replace(from, to))
}
fn quoted(text: &str) -> String {
serde_json::to_string(text).expect("a string serializes")
}
fn short_place(change: &Change) -> String {
change.paragraph.as_deref().map_or_else(
|| crate::ids::change_id(&change.id).map_or_else(|| "-".to_string(), |id| id.story),
crate::ids::short_paragraph,
)
}
fn pair_ref(first: &Change, second: &Change) -> Option<String> {
let a = crate::ids::change_id(&first.id)?;
let b = crate::ids::change_id(&second.id)?;
if a.story != b.story {
return None;
}
let combined = if a.story == "body" {
format!("r{}+{}", a.wid, b.wid)
} else {
format!("{}.r{}+{}", a.story, a.wid, b.wid)
};
matches!(
combined.parse::<crate::ids::ShortId>(),
Ok(crate::ids::ShortId::Change { .. })
)
.then_some(combined)
}
fn text_from_to(kind: ChangeKind, move_from: bool, text: &str, accepted: bool) -> (String, String) {
let escaped = escape_critic(text);
let is_insertion = match kind {
ChangeKind::Insertion => true,
ChangeKind::Deletion => false,
ChangeKind::Move => !move_from,
ChangeKind::Formatting | ChangeKind::Replacement => {
return (text.to_string(), text.to_string());
}
};
if is_insertion {
let from = format!("{{++{escaped}++}}");
let to = if accepted {
text.to_string()
} else {
String::new()
};
(from, to)
} else {
let from = format!("{{--{escaped}--}}");
let to = if accepted {
String::new()
} else {
text.to_string()
};
(from, to)
}
}
struct Line {
action: &'static str,
r#ref: String,
place: String,
from: String,
to: String,
}
impl Line {
fn render(&self) -> String {
format!(
"{} {} in {}: {} > {}",
self.action,
self.r#ref,
self.place,
quoted(&self.from),
quoted(&self.to)
)
}
}
fn is_substitution_pair(first: &Change, second: &Change) -> bool {
if first.paragraph != second.paragraph || first.paragraph.is_none() {
return false;
}
if first.target != "text" || second.target != "text" {
return false;
}
let kinds = (first.kind, second.kind);
if !matches!(
kinds,
(ChangeKind::Deletion, ChangeKind::Insertion)
| (ChangeKind::Insertion, ChangeKind::Deletion)
) {
return false;
}
if first.move_name.is_some() || second.move_name.is_some() {
return false;
}
let (Some(a), Some(b)) = (
crate::ids::change_id(&first.id),
crate::ids::change_id(&second.id),
) else {
return false;
};
a.story == b.story
}
fn adjacent_changes(source: &[u8]) -> Result<HashSet<(String, String)>, ChangeError> {
use crate::namespaces::W;
use crate::xmllinq::{Dom, NodeId};
fn flatten(dom: &Dom, node: NodeId, out: &mut Vec<NodeId>) {
for child in dom.elements(node, None) {
let name = dom.name(child);
match name.as_ref().map(|n| n.local_name()) {
Some("hyperlink" | "smartTag" | "customXml" | "fldSimple" | "bdo" | "dir") => {
flatten(dom, child, out);
}
Some("sdt") => {
if let Some(content) = dom.element(child, &W::sdt_content()) {
flatten(dom, content, out);
}
}
Some("pPr" | "proofErr") => {}
_ => out.push(child),
}
}
}
let normalized = crate::strict_translation::strict_to_transitional_docx(source)
.map_err(|e| ChangeError::Package(e.to_string()))?;
let package =
crate::opc::PartFs::open(&normalized).map_err(|e| ChangeError::Package(e.to_string()))?;
let main = package
.main_document_part()
.unwrap_or_else(|| "word/document.xml".into());
let mut adjacent = HashSet::new();
for part in package.parts().iter().filter(|part| part.ends_with(".xml")) {
let Some(xml) = package.part_string(part) else {
continue;
};
let mut dom = Dom::new();
let doc = dom.parse_xdocument(&xml);
let Some(root) = dom.root(doc) else { continue };
let story = if *part == main {
"body".into()
} else {
crate::ids::part_story(part)
};
for paragraph in dom.descendants(root, Some(&W::p())) {
let mut children = Vec::new();
flatten(&dom, paragraph, &mut children);
for pair in children.windows(2) {
if ((dom.name_is(pair[0], &W::ins()) && dom.name_is(pair[1], &W::del()))
|| (dom.name_is(pair[0], &W::del()) && dom.name_is(pair[1], &W::ins())))
&& let (Some(a), Some(b)) = (
dom.attribute(pair[0], &W::id()),
dom.attribute(pair[1], &W::id()),
)
{
adjacent.insert((
crate::ids::ChangeId::new(&story, a).short(),
crate::ids::ChangeId::new(&story, b).short(),
));
}
}
}
}
Ok(adjacent)
}
pub fn resolution_lines(
source: &[u8],
resolved: &ResolvedRevisions,
) -> Result<Vec<String>, ChangeError> {
let listed = crate::changes::list_changes(source)?;
let adjacent = adjacent_changes(source)?;
let accepted: HashSet<&str> = resolved.accepted.iter().map(String::as_str).collect();
let rejected: HashSet<&str> = resolved.rejected.iter().map(String::as_str).collect();
let mut ordered: Vec<(&Change, bool)> = Vec::new();
for change in &listed {
if accepted.contains(change.id.as_str()) {
ordered.push((change, true));
} else if rejected.contains(change.id.as_str()) {
ordered.push((change, false));
}
}
let mut lines = Vec::new();
let mut i = 0;
while i < ordered.len() {
let (first, accepted_first) = ordered[i];
if i + 1 < ordered.len() {
let (second, accepted_second) = ordered[i + 1];
if accepted_first == accepted_second
&& is_substitution_pair(first, second)
&& adjacent.contains(&(first.id.clone(), second.id.clone()))
&& let Some(combined) = pair_ref(first, second)
{
let pos = |id: &str| listed.iter().position(|c| c.id == id);
let consecutive = pos(&first.id)
.zip(pos(&second.id))
.is_some_and(|(a, b)| a + 1 == b || b + 1 == a);
if consecutive {
let (deletion, insertion) = if first.kind == ChangeKind::Deletion {
(first, second)
} else {
(second, first)
};
let from = format!(
"{{~~{}~>{}~~}}",
escape_critic(&deletion.text),
escape_critic(&insertion.text)
);
let to = if accepted_first {
insertion.text.clone()
} else {
deletion.text.clone()
};
lines.push(
Line {
action: if accepted_first {
"accepted"
} else {
"rejected"
},
r#ref: combined,
place: short_place(first),
from,
to,
}
.render(),
);
i += 2;
continue;
}
}
}
lines.push(single_line(first, accepted_first));
i += 1;
}
Ok(lines)
}
fn single_line(change: &Change, accepted: bool) -> String {
let action = if accepted { "accepted" } else { "rejected" };
let place = short_place(change);
let (from, to) = match change.target {
"paragraph_mark" => {
let is_insertion = match change.kind {
ChangeKind::Insertion => true,
ChangeKind::Deletion => false,
ChangeKind::Move => change.move_side != Some(crate::changes::MoveSide::From),
ChangeKind::Formatting | ChangeKind::Replacement => false,
};
if change.kind == ChangeKind::Formatting {
(change.text.clone(), change.text.clone())
} else if is_insertion {
let to = if accepted {
"\n\n".to_string()
} else {
String::new()
};
("{++\n\n++}".to_string(), to)
} else {
let to = if accepted {
String::new()
} else {
"\n\n".to_string()
};
("{--\n\n--}".to_string(), to)
}
}
"properties" => {
(change.text.clone(), change.text.clone())
}
_ => {
let move_from = change.move_side == Some(crate::changes::MoveSide::From);
text_from_to(change.kind, move_from, &change.text, accepted)
}
};
Line {
action,
r#ref: change.r#ref.clone(),
place,
from,
to,
}
.render()
}
pub fn resolution_text(source: &[u8], resolved: &ResolvedRevisions) -> Result<String, ChangeError> {
let mut out = String::new();
for line in resolution_lines(source, resolved)? {
out.push_str(&line);
out.push('\n');
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quoting_escapes_quotes_and_backslashes() {
assert_eq!(quoted("a\"b\\c"), "\"a\\\"b\\\\c\"");
}
#[test]
fn critic_escaping_mirrors_the_view() {
assert_eq!(escape_critic("{++x++}"), "{\\++x++\\}");
assert_eq!(escape_critic("a~>b"), "a~\\>b");
assert_eq!(escape_critic("plain"), "plain");
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod pairing_branch_tests {
use super::super::deeper_boundary_fixture::{Part, docx, docx_with};
use super::*;
const INS: &str = r#"<w:ins w:id="1" w:author="Bo" w:date="2026-01-01T00:00:00Z"><w:r><w:t>new</w:t></w:r></w:ins>"#;
const DEL: &str = r#"<w:del w:id="2" w:author="Bo" w:date="2026-01-01T00:00:00Z"><w:r><w:delText>old</w:delText></w:r></w:del>"#;
fn listed(source: &[u8]) -> Vec<Change> {
crate::changes::list_changes(source).unwrap()
}
#[test]
fn substitution_pairs_need_one_text_paragraph_story_and_no_move() {
let source = docx(&format!("<w:p><w:r><w:t>a </w:t></w:r>{INS}{DEL}</w:p>"));
let changes = listed(&source);
assert_eq!(changes.len(), 2);
let (ins, del) = (&changes[0], &changes[1]);
assert!(is_substitution_pair(ins, del));
assert!(is_substitution_pair(del, ins));
let mut loose = ins.clone();
loose.paragraph = None;
assert!(!is_substitution_pair(&loose, &loose.clone()));
let mut mark = del.clone();
mark.target = "paragraph_mark";
assert!(!is_substitution_pair(ins, &mark));
assert!(!is_substitution_pair(&mark, ins));
assert!(!is_substitution_pair(ins, ins));
let mut moved = del.clone();
moved.move_name = Some("m1".into());
assert!(!is_substitution_pair(ins, &moved));
assert!(!is_substitution_pair(&moved, ins));
let mut odd = del.clone();
odd.id = "not an id".into();
assert!(!is_substitution_pair(ins, &odd));
let mut other = del.clone();
other.id = "header1.r2".into();
assert!(!is_substitution_pair(ins, &other));
assert_eq!(pair_ref(ins, &other), None);
let mut header_ins = ins.clone();
header_ins.id = "header1.r1".into();
assert_eq!(
pair_ref(&header_ins, &other).as_deref(),
Some("header1.r1+2")
);
assert_eq!(pair_ref(ins, del).as_deref(), Some("r1+2"));
}
#[test]
fn adjacent_pairs_print_once_and_split_pairs_print_twice() {
let source = docx(&format!("<w:p><w:r><w:t>a </w:t></w:r>{INS}{DEL}</w:p>"));
let changes = listed(&source);
let ids: Vec<String> = changes.iter().map(|c| c.id.clone()).collect();
let accepted = ResolvedRevisions {
accepted: ids.clone(),
rejected: Vec::new(),
};
let lines = resolution_lines(&source, &accepted).unwrap();
assert_eq!(lines, [r#"accepted r1+2 in p0: "{~~old~>new~~}" > "new""#]);
let split = ResolvedRevisions {
accepted: vec![ids[0].clone()],
rejected: vec![ids[1].clone()],
};
let lines = resolution_lines(&source, &split).unwrap();
assert_eq!(lines.len(), 2, "{lines:?}");
assert!(lines[0].starts_with("accepted r1 in p0"), "{lines:?}");
assert!(lines[1].starts_with("rejected r2 in p0"), "{lines:?}");
let apart = docx(&format!("<w:p>{INS}<w:r><w:t> mid </w:t></w:r>{DEL}</w:p>"));
let lines = resolution_lines(&apart, &accepted).unwrap();
assert_eq!(lines.len(), 2, "{lines:?}");
let wrapped = docx(&format!(
r#"<w:p><w:hyperlink w:anchor="x">{INS}</w:hyperlink><w:sdt><w:sdtContent>{DEL}</w:sdtContent></w:sdt><w:proofErr w:type="spellStart"/></w:p>"#
));
let lines = resolution_lines(&wrapped, &accepted).unwrap();
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(lines[0].contains("r1+2"), "{lines:?}");
let idless = docx(&format!(
r#"<w:p><w:ins w:author="Bo"><w:r><w:t>x</w:t></w:r></w:ins>{DEL}</w:p>"#
));
let all: Vec<String> = listed(&idless).iter().map(|c| c.id.clone()).collect();
let lines = resolution_lines(
&idless,
&ResolvedRevisions {
accepted: all,
rejected: Vec::new(),
},
)
.unwrap();
assert_eq!(lines.len(), 2, "{lines:?}");
}
#[test]
fn header_changes_pair_inside_their_own_story() {
let header = format!(
r#"<w:hdr xmlns:w="{}"><w:p>{INS}{DEL}</w:p></w:hdr>"#,
crate::namespaces::W::URI
);
let source = docx_with(
"<w:p><w:r><w:t>body</w:t></w:r></w:p>",
&[Part {
name: "word/header1.xml",
content_type: "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
rel_type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",
xml: &header,
}],
);
let changes = listed(&source);
assert_eq!(changes.len(), 2, "{changes:?}");
let lines = resolution_lines(
&source,
&ResolvedRevisions {
accepted: Vec::new(),
rejected: changes.iter().map(|c| c.id.clone()).collect(),
},
)
.unwrap();
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(lines[0].starts_with("rejected header1.r1+2"), "{lines:?}");
assert!(lines[0].ends_with(r#""old""#), "{lines:?}");
}
}