use super::*;
pub(super) fn open_error(error: crate::inspect::InspectError) -> EditError {
match error {
crate::inspect::InspectError::Admission(refused) => {
err(refused.code(), None, refused.message)
}
other => err("INVALID_DOCUMENT", None, other.to_string()),
}
}
pub(super) fn selection_error(e: ChangeError, syntax: PlanSyntax, verb: &str) -> EditError {
match e {
ChangeError::UnknownChange(id) => err(
"UNKNOWN_CHANGE",
None,
syntax.selection_message(format_args!("no tracked change {id}")),
),
ChangeError::InvalidId(m) => err("INVALID_PLAN", None, format!("resolve_revisions: {m}")),
ambiguous @ ChangeError::Ambiguous { .. } => err(
"AMBIGUOUS_CHANGE",
None,
syntax.selection_message(ambiguous),
),
part @ ChangeError::PartOfChange { .. } => err(
"INCOMPLETE_CHANGE",
None,
syntax.incomplete_change(&part, verb),
),
ChangeError::Package(m) => err("INVALID_DOCUMENT", None, m),
exposed @ ChangeError::ExposedFinalMark { .. } => {
err("EXPOSED_FINAL_MARK", None, exposed.to_string())
}
}
}
pub(super) fn selected_ids(
listed: &[Change],
filter: Option<&ChangeFilter>,
syntax: PlanSyntax,
) -> Result<Vec<String>, EditError> {
let Some(filter) = filter else {
return Ok(Vec::new());
};
let selection_error = |e| selection_error(e, syntax, "");
let filter = &filter.normalized().map_err(selection_error)?;
filter.check(listed).map_err(selection_error)?;
let hit: Vec<&Change> = listed.iter().filter(|c| filter.matches(c)).collect();
Ok(listed
.iter()
.filter(|c| {
hit.iter()
.any(|h| h.id == c.id || h.move_name.is_some() && h.move_name == c.move_name)
})
.map(|c| c.id.clone())
.collect())
}
fn named_ids(listed: &[Change], filter: Option<&ChangeFilter>) -> Vec<String> {
let Some(filter) = filter.and_then(|f| f.normalized().ok()) else {
return Vec::new();
};
listed
.iter()
.filter(|c| filter.matches(c))
.map(|c| c.id.clone())
.collect()
}
pub(super) fn resolve_selected(
source: &[u8],
selection: Option<&ResolveRevisions>,
policy: RemovedAnchorComments,
syntax: PlanSyntax,
) -> Result<(Option<Vec<u8>>, ResolvedRevisions, AnchorChanges), EditError> {
let mut comments = AnchorChanges::default();
let mut resolved = ResolvedRevisions::default();
let Some(selection) = selection else {
return Ok((None, resolved, comments));
};
let change_err = |e| selection_error(e, syntax, "");
for (side, verb) in [
(selection.accept.as_ref(), "accept"),
(selection.reject.as_ref(), "reject"),
] {
if let Some(side) = side {
crate::changes::check_whole_changes(source, side)
.map_err(|e| selection_error(e, syntax, verb))?;
}
}
let listed = crate::changes::list_changes(source).map_err(change_err)?;
let accept = selected_ids(&listed, selection.accept.as_ref(), syntax)?;
let reject = if selection.reject_visible {
Vec::new()
} else {
selected_ids(&listed, selection.reject.as_ref(), syntax)?
};
if let Some(both) = accept.iter().find(|id| reject.contains(id)) {
return Err(err(
"REVISION_CONFLICT",
None,
format!("resolve_revisions selects {both} to accept and to reject"),
));
}
if accept.is_empty() && reject.is_empty() {
return Ok((None, resolved, comments));
}
let mut bytes = source.to_vec();
if !accept.is_empty() {
let (document, removed, kept) = crate::changes::resolve_for_edit(
&bytes,
&ChangeFilter::ids(accept.clone()),
crate::revision_processor::Resolution::Accept,
policy == RemovedAnchorComments::Keep,
)
.map_err(|e| selection_error(e, syntax, "accept"))?;
comments.extend(
removed,
kept,
crate::revision_processor::Resolution::Accept,
Some(&named_ids(&listed, selection.accept.as_ref())),
);
bytes = document;
resolved.accepted = accept;
}
let left = crate::changes::list_changes(&bytes).map_err(change_err)?;
let reject: Vec<String> = reject
.into_iter()
.filter(|id| left.iter().any(|c| &c.id == id))
.collect();
if !reject.is_empty() {
let (document, removed, kept) = crate::changes::resolve_for_edit(
&bytes,
&ChangeFilter::ids(reject.clone()),
crate::revision_processor::Resolution::Reject,
policy == RemovedAnchorComments::Keep,
)
.map_err(|e| selection_error(e, syntax, "reject"))?;
comments.extend(
removed,
kept,
crate::revision_processor::Resolution::Reject,
Some(&named_ids(&listed, selection.reject.as_ref())),
);
bytes = document;
resolved.rejected = reject;
}
Ok((Some(bytes), resolved, comments))
}
pub(super) struct Settled {
pub(super) base: Vec<u8>,
pub(super) opened: Opened,
pub(super) resolved_revisions: ResolvedRevisions,
pub(super) comment_changes: AnchorChanges,
pub(super) changed: bool,
}
pub(super) fn owns_change(author: Option<&str>, actor: &str) -> bool {
author.is_some_and(|name| !name.is_empty() && name == actor)
}
pub(super) fn change_not_yours(change: &Change) -> String {
let whose = match change.author.as_deref() {
Some(name) if !name.is_empty() => format!("{} is by {name:?}", change.id),
_ => format!("{} names no author", change.id),
};
let answer = match change.kind {
ChangeKind::Deletion => {
format!(
"answer it visibly (-p {} --restore), or comment on it",
change.id
)
}
ChangeKind::Insertion => {
format!("strike it (-p {} --strike), or comment on it", change.id)
}
_ => "comment on it (accepting or rejecting would erase their change)".to_string(),
};
format!("{whose}; {answer}")
}
pub(super) fn join_authors(authors: &[String], nameless: bool) -> String {
let mut parts: Vec<String> = authors.iter().map(|name| format!("{name:?}")).collect();
if nameless {
parts.push("one that names no author".to_string());
}
match parts.as_slice() {
[] => String::new(),
[one] => one.clone(),
[first, second] => format!("{first} and {second}"),
_ => {
let (last, rest) = parts.split_last().expect("at least three");
format!("{} and {last}", rest.join(", "))
}
}
}
pub(super) fn removes_content(change: &Change, accept: bool) -> bool {
matches!(
(accept, change.kind, change.move_side),
(true, ChangeKind::Deletion, _)
| (false, ChangeKind::Insertion, _)
| (true, ChangeKind::Move, Some(MoveSide::From))
| (false, ChangeKind::Move, Some(MoveSide::To))
)
}
pub(super) fn taken_along<'a>(listed: &'a [Change], root: &Change) -> Vec<&'a Change> {
let by_id: HashMap<&str, &Change> = listed.iter().map(|c| (c.id.as_str(), c)).collect();
let roots: HashSet<&str> = root.element_ids().collect();
listed
.iter()
.filter(|change| {
if roots.contains(change.id.as_str()) || change.id.starts_with(STYLES_STORY) {
return false;
}
let mut cursor = change.inside.as_deref();
let mut seen = HashSet::new();
while let Some(id) = cursor {
if !seen.insert(id) {
return false;
}
if roots.contains(id) {
return true;
}
cursor = by_id.get(id).and_then(|holder| holder.inside.as_deref());
}
false
})
.collect()
}
fn comment_not_yours(verb: &str, change_id: &str, comment_id: &str, author: &str) -> String {
let whose = if author.is_empty() {
format!("{comment_id}, which names no author")
} else {
format!("{comment_id}, which is by {author:?}")
};
format!("{verb} {change_id} would delete {whose}")
}
fn owns_comment(author: &str, actor: &str) -> bool {
!author.is_empty() && author == actor
}
fn replies_to(
record: &crate::comments::CommentRecord,
root: u32,
by_id: &HashMap<u32, &crate::comments::CommentRecord>,
) -> bool {
let mut cursor = record.parent;
let mut seen = HashSet::new();
while let Some(id) = cursor {
if !seen.insert(id) {
return false;
}
if id == root {
return true;
}
cursor = by_id.get(&id).and_then(|comment| comment.parent);
}
false
}
pub(super) fn guard_removed_comments(
source: &[u8],
actor: &str,
removals: &[(&Change, bool, Vec<&Change>)],
) -> Result<(), EditError> {
let mut held: Vec<(&str, &str, bool)> = Vec::new();
for (change, accepting, nested) in removals {
for id in change
.holds_comments
.iter()
.chain(nested.iter().flat_map(|inner| inner.holds_comments.iter()))
{
if held.iter().any(|(_, have, _)| *have == id) {
continue;
}
held.push((change.id.as_str(), id.as_str(), *accepting));
}
}
if held.is_empty() {
return Ok(());
}
let records = crate::comments::list_comments(source)
.map_err(|e| err("INVALID_DOCUMENT", None, e.to_string()))?;
let by_id: HashMap<u32, &crate::comments::CommentRecord> =
records.iter().map(|record| (record.id, record)).collect();
for (change_id, comment_id, accepting) in held {
let Some(root) = records.iter().find(|record| record.r#ref == comment_id) else {
continue;
};
let verb = if accepting { "accepting" } else { "rejecting" };
if !owns_comment(&root.author, actor) {
return Err(err(
"COMMENT_NOT_YOURS",
None,
comment_not_yours(verb, change_id, comment_id, &root.author),
));
}
for reply in &records {
if reply.id == root.id || !replies_to(reply, root.id, &by_id) {
continue;
}
if owns_comment(&reply.author, actor) {
continue;
}
return Err(err(
"COMMENT_NOT_YOURS",
None,
comment_not_yours(verb, change_id, &reply.r#ref, &reply.author),
));
}
}
Ok(())
}
pub(super) fn note_foreign(
change: &Change,
actor: &str,
authors: &mut Vec<String>,
nameless: &mut bool,
) {
if change.id.starts_with(STYLES_STORY) || owns_change(change.author.as_deref(), actor) {
return;
}
match change.author.as_deref() {
Some(name) if !name.is_empty() => {
if !authors.iter().any(|have: &String| have == name) {
authors.push(name.to_string());
}
}
_ => *nameless = true,
}
}
fn blocker_list(revisions: &[String]) -> String {
let shown = revisions
.iter()
.take(BLOCKERS_SHOWN)
.map(String::as_str)
.collect::<Vec<_>>()
.join(", ");
match revisions.len().saturating_sub(BLOCKERS_SHOWN) {
0 => shown,
rest => format!("{shown} and {rest} more"),
}
}
const BLOCKERS_SHOWN: usize = 20;
pub(super) fn settle(
source: &[u8],
plan: &EditPlan,
probe: Opened,
syntax: PlanSyntax,
) -> Result<Settled, EditError> {
let original = source;
if plan.others.keeps() {
let wholesale = match plan.existing_revisions {
ExistingRevisions::Accept => Some("accept"),
ExistingRevisions::Reject => Some("reject"),
ExistingRevisions::Keep | ExistingRevisions::Refuse => None,
};
guard_keep_others(
source,
&plan.author,
plan.resolve_revisions.as_ref(),
wholesale,
false,
syntax,
)?;
}
let (resolved_source, resolved_revisions, mut comment_changes) = resolve_selected(
source,
plan.resolve_revisions.as_ref(),
plan.removed_anchor_comments,
syntax,
)?;
let (source, probe) = match &resolved_source {
Some(bytes) => (bytes.as_slice(), Opened::open(bytes).map_err(open_error)?),
None => (source, probe),
};
let revisions: Vec<String> = crate::changes::changes_in(&probe.pkg)
.into_iter()
.filter(|c| !c.id.starts_with(STYLES_STORY))
.map(|c| c.id)
.collect();
let has_revisions = !revisions.is_empty();
let (base, opened, flattened) = match (has_revisions, plan.existing_revisions) {
(false, _) | (true, ExistingRevisions::Keep) => (source.to_vec(), probe, false),
(true, ExistingRevisions::Refuse) => {
return Err(err(
"EXISTING_REVISIONS",
None,
format!(
"the document already holds tracked changes; blockers: {}; {KEEP_REVISIONS}",
blocker_list(&revisions)
),
));
}
(true, policy) => {
let resolution = if policy == ExistingRevisions::Accept {
crate::revision_processor::Resolution::Accept
} else {
crate::revision_processor::Resolution::Reject
};
let (flattened, removed, kept) = crate::changes::resolve_for_edit(
source,
&ChangeFilter::default(),
resolution,
plan.removed_anchor_comments == RemovedAnchorComments::Keep,
)
.map_err(|e| err("INVALID_DOCUMENT", None, e.to_string()))?;
comment_changes.extend(removed, kept, resolution, None);
let reopened = Opened::open(&flattened).map_err(open_error)?;
(flattened, reopened, true)
}
};
let changed = resolved_source.is_some() || flattened;
if changed {
crate::changes::check_exposed_final_marks(original, &base)
.map_err(|e| selection_error(e, syntax, ""))?;
}
Ok(Settled {
base,
opened,
resolved_revisions,
comment_changes,
changed,
})
}
pub(super) struct Loaded {
pub(super) stories: Vec<StoryPart>,
pub(super) paragraph_nodes: Vec<NodeId>,
pub(super) paragraph_story: Vec<(usize, usize)>,
}
pub(super) fn load_stories(opened: &mut Opened) -> Result<Loaded, EditError> {
let mut stories = vec![StoryPart {
id: BODY_STORY.to_string(),
part: opened.main.clone(),
document: opened.document,
root: opened.body,
}];
for (id, _, part) in opened.story_parts() {
let invalid = |m: String| err("INVALID_DOCUMENT", None, format!("{part}: {m}"));
let xml = opened
.pkg
.part_string(&part)
.ok_or_else(|| invalid("missing part".into()))?;
crate::xmllinq::parse::validate_xml(&xml).map_err(|e| invalid(e.to_string()))?;
let document = opened.dom.parse_xdocument(&xml);
let root = opened
.dom
.root(document)
.ok_or_else(|| invalid("missing XML root".into()))?;
stories.push(StoryPart {
id,
part,
document,
root,
});
}
let mut paragraph_nodes = Vec::new();
let mut paragraph_story = Vec::new();
for (index, story) in stories.iter().enumerate() {
let nodes = if index == 0 {
crate::inspect::body_paragraph_nodes(&opened.dom, story.root)
} else {
crate::inspect::story_paragraph_nodes(&opened.dom, story.root)
};
for (local, node) in nodes.into_iter().enumerate() {
paragraph_nodes.push(node);
paragraph_story.push((index, local));
}
}
Ok(Loaded {
stories,
paragraph_nodes,
paragraph_story,
})
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod guard_branch_tests {
use super::super::deeper_boundary_fixture::docx;
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>added words</w:t></w:r></w:ins>"#;
fn run(source: &[u8], author: &str, ops: serde_json::Value) -> Vec<u8> {
let mut value = serde_json::json!({
"schema_version": 1,
"author": author,
"date": "2026-02-02T00:00:00Z",
"existing_revisions": "keep",
});
value["operations"] = ops;
let plan = EditPlan::from_json(&value.to_string()).unwrap();
apply_plan(source, &plan).unwrap().redline
}
fn threaded() -> Vec<u8> {
let source = docx(&format!(
"<w:p><w:r><w:t xml:space=\"preserve\">Lead </w:t></w:r>{INS}</w:p>"
));
let commented = run(
&source,
"Cy",
serde_json::json!([{"kind":"comment","paragraph":"p0","find":"added","text":"why?"}]),
);
let id = crate::comments::list_comments(&commented).unwrap()[0].id;
run(
&commented,
"Di",
serde_json::json!([{"kind":"reply_comment","comment_id":id,"text":"because"}]),
)
}
fn insertion(source: &[u8]) -> Change {
crate::changes::list_changes(source)
.unwrap()
.into_iter()
.find(|c| c.kind == ChangeKind::Insertion && c.author.as_deref() == Some("Bo"))
.expect("Bo's insertion")
}
#[test]
fn removing_a_thread_needs_its_root_and_every_reply_to_be_yours() {
let source = threaded();
let change = insertion(&source);
assert!(!change.holds_comments.is_empty(), "{change:?}");
let nested = vec![&change];
let removals = [(&change, false, nested)];
let e = guard_removed_comments(&source, "Di", &removals).unwrap_err();
assert_eq!(e.code, "COMMENT_NOT_YOURS");
assert!(
e.message.starts_with("rejecting r1 would delete c"),
"{}",
e.message
);
assert!(e.message.ends_with("which is by \"Cy\""), "{}", e.message);
let removals = [(&change, true, Vec::new())];
let e = guard_removed_comments(&source, "Cy", &removals).unwrap_err();
assert!(
e.message.starts_with("accepting r1 would delete c"),
"{}",
e.message
);
assert!(e.message.ends_with("which is by \"Di\""), "{}", e.message);
let mut ghost = change.clone();
ghost.holds_comments = vec!["c99".into()];
let removals = [(&ghost, true, Vec::new())];
assert!(guard_removed_comments(&source, "Zed", &removals).is_ok());
}
#[test]
fn a_thread_wholly_yours_is_removable() {
let source = docx(&format!("<w:p>{INS}</w:p>"));
let mine = run(
&source,
"Cy",
serde_json::json!([{"kind":"comment","paragraph":"p0","find":"added","text":"mine"}]),
);
let id = crate::comments::list_comments(&mine).unwrap()[0].id;
let mine = run(
&mine,
"Cy",
serde_json::json!([{"kind":"reply_comment","comment_id":id,"text":"still mine"}]),
);
let change = insertion(&mine);
let removals = [(&change, false, Vec::new())];
assert!(guard_removed_comments(&mine, "Cy", &removals).is_ok());
}
fn bare(id: &str, kind: ChangeKind, author: Option<&str>) -> Change {
let source = docx(&format!("<w:p>{INS}</w:p>"));
let mut change = insertion(&source);
change.id = id.into();
change.kind = kind;
change.author = author.map(str::to_string);
change
}
#[test]
fn foreign_authors_are_named_once_in_order_and_styles_are_no_one() {
let mut authors = Vec::new();
let mut nameless = false;
for change in [
bare("r1", ChangeKind::Insertion, Some("Bo")),
bare("r2", ChangeKind::Insertion, Some("Bo")),
bare("r3", ChangeKind::Deletion, Some("Me")),
bare("styles.r4", ChangeKind::Formatting, Some("Zed")),
bare("r5", ChangeKind::Deletion, Some("Cy")),
] {
note_foreign(&change, "Me", &mut authors, &mut nameless);
}
assert_eq!(authors, ["Bo", "Cy"]);
assert!(!nameless);
note_foreign(
&bare("r6", ChangeKind::Insertion, Some("")),
"Me",
&mut authors,
&mut nameless,
);
assert!(nameless);
assert_eq!(
join_authors(&authors, nameless),
r#""Bo", "Cy" and one that names no author"#
);
assert_eq!(join_authors(&[], true), "one that names no author");
assert_eq!(
join_authors(&["Bo".into()], true),
r#""Bo" and one that names no author"#
);
}
#[test]
fn refusal_sentences_name_the_author_or_its_absence() {
assert!(owns_change(Some("Me"), "Me"));
assert!(!owns_change(Some(""), ""));
assert!(!owns_change(None, "Me"));
assert_eq!(
change_not_yours(&bare("r1", ChangeKind::Insertion, Some(""))),
"r1 names no author; strike it (-p r1 --strike), or comment on it"
);
assert_eq!(
change_not_yours(&bare("r2", ChangeKind::Deletion, Some("Bo"))),
"r2 is by \"Bo\"; answer it visibly (-p r2 --restore), or comment on it"
);
assert_eq!(
comment_not_yours("accepting", "r1", "c3", ""),
"accepting r1 would delete c3, which names no author"
);
}
#[test]
fn taken_along_follows_inside_chains_and_stops_on_cycles() {
let root = bare("r1", ChangeKind::Insertion, Some("Bo"));
let mut child = bare("r2", ChangeKind::Deletion, Some("Cy"));
child.inside = Some("r1".into());
let mut grandchild = bare("r3", ChangeKind::Deletion, Some("Cy"));
grandchild.inside = Some("r2".into());
let mut style = bare("styles.r4", ChangeKind::Formatting, Some("Cy"));
style.inside = Some("r1".into());
let mut loop_a = bare("r5", ChangeKind::Deletion, None);
loop_a.inside = Some("r6".into());
let mut loop_b = bare("r6", ChangeKind::Deletion, None);
loop_b.inside = Some("r5".into());
let mut stray = bare("r7", ChangeKind::Deletion, None);
stray.inside = Some("r99".into());
let listed = vec![
root.clone(),
child,
grandchild,
style,
loop_a,
loop_b,
stray,
];
let along: Vec<&str> = taken_along(&listed, &root)
.iter()
.map(|c| c.id.as_str())
.collect();
assert_eq!(along, ["r2", "r3"]);
}
#[test]
fn an_unnormalizable_filter_names_nothing() {
let source = docx(&format!("<w:p>{INS}</w:p>"));
let listed = crate::changes::list_changes(&source).unwrap();
let replacement = ChangeFilter {
ids: None,
authors: None,
kinds: Some(vec![ChangeKind::Replacement]),
};
assert!(named_ids(&listed, Some(&replacement)).is_empty());
assert!(named_ids(&listed, None).is_empty());
assert_eq!(named_ids(&listed, Some(&ChangeFilter::default())), ["r1"]);
}
#[test]
fn a_visible_reject_settles_nothing_before_the_plan() {
let source = docx(&format!("<w:p>{INS}</w:p>"));
let selection = ResolveRevisions {
accept: None,
reject: Some(ChangeFilter::ids(vec!["r1".to_string()])),
reject_visible: true,
};
let (bytes, resolved, _) = resolve_selected(
&source,
Some(&selection),
RemovedAnchorComments::default(),
PlanSyntax::default(),
)
.unwrap();
assert!(bytes.is_none());
assert!(resolved.accepted.is_empty() && resolved.rejected.is_empty());
}
}