From 0fef588e8abac132b1cfb4bd0e159f98ff7fa1e5 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 08:26:29 +0100 Subject: [PATCH 1/3] fix(comments): move a thread's replies with its root Since 0.17.0 a reply has its own range crossing its parent's (#434). The root moves of F-X279d moved only the root's range, so move_comment, move_comment_to_text and rdocx comment move left every reply on the old text, and removing that text then removed the replies with it. On 0.16.4 a reply had no range and followed its root. A root move now carries its thread on the same staged candidate. Once the root's range has moved, each reply with a complete range and reference leaves its old place and crosses its nearest anchored ancestor's new range through the reply authoring path, parents first and siblings in id order, so the markers are those reply_to writes. Its original reference run travels as the root's does. The selections run on the flushed candidate instead of fresh clones. A reply without markers, as 0.16 wrote them, follows through the thread metadata. A reply with any other anchor refuses the move before any edit, a reply that fails after the root moved refuses it naming the root and the reply, and a reply id still refuses, now naming its thread root. Moving a root onto its own range publishes nothing when every anchored reply already crosses it, and otherwise gathers the replies, which heals a thread that a 0.17.0 move split. Removal keeps its contract: a comment whose whole anchor goes is removed with its replies. Tests, regression_test comment_thread_operations_keep_every_reply_on_its_root_text, comment_thread_moves_carry_replies_across_story_owners and comment_thread_moves_heal_split_threads_and_refuse_untravelable_replies, comments unit issue446_root_moves_carry_crossing_replies_and_generic_pairing_strict which inverts the reply expectations of the F-X279d root move test, test_core issue446 thread move, CLI comment move with a reply Harness, unchanged, no sample moves a comment --- crates/rdocx-cli/src/main.rs | 2 +- crates/rdocx-cli/tests/integration.rs | 27 +- crates/rdocx-py/python/rdocx/_rdocx.pyi | 15 +- crates/rdocx-py/src/document.rs | 6 +- crates/rdocx-py/tests/test_core.py | 25 ++ crates/rdocx/src/comments.rs | 212 +++++++++-- crates/rdocx/src/document.rs | 14 +- crates/rdocx/tests/regression_test.rs | 485 ++++++++++++++++++++++++ docs/hld/03-architecture.md | 9 +- docs/hld/10-bindings-spec.md | 8 +- docs/hld/12-testing-strategy.md | 13 +- 11 files changed, 757 insertions(+), 59 deletions(-) diff --git a/crates/rdocx-cli/src/main.rs b/crates/rdocx-cli/src/main.rs index 18e8b1fbe..0e13d4250 100644 --- a/crates/rdocx-cli/src/main.rs +++ b/crates/rdocx-cli/src/main.rs @@ -541,7 +541,7 @@ enum CommentCommand { #[arg(long)] json: bool, }, - /// Move an existing root comment onto literal main-story text + /// Move an existing root comment and its replies onto literal main-story text Move { /// Path to the DOCX file file: PathBuf, diff --git a/crates/rdocx-cli/tests/integration.rs b/crates/rdocx-cli/tests/integration.rs index 214af4a9b..7a4f05e0b 100644 --- a/crates/rdocx-cli/tests/integration.rs +++ b/crates/rdocx-cli/tests/integration.rs @@ -5233,10 +5233,25 @@ fn comment_move_outputs_reopen_with_unchanged_thread() { Some("2026-10-08T12:00:00Z"), ) .unwrap(); - document.reply_to(id, "Ben", "Reply").unwrap(); + let reply = document.reply_to(id, "Ben", "Reply").unwrap(); document.resolve_comment(id, true).unwrap(); document.save(&input).unwrap(); let before = fs::read(&input).unwrap(); + let refused = cli(&[ + "comment", + "move", + path_text(&input), + &reply.to_string(), + "--text", + "TARGET", + "-o", + path_text(&output), + ]); + assert!( + !refused.status.success(), + "a reply moves with its root only" + ); + assert!(!output.exists()); let result = cli(&[ "comment", "move", @@ -5252,10 +5267,12 @@ fn comment_move_outputs_reopen_with_unchanged_thread() { ]); assert_success(&result, "move root comment"); let reopened = Document::open(&output).unwrap(); - assert_eq!( - reopened.comment_anchor_text(id).unwrap().as_deref(), - Some("TARGET") - ); + for moved in [id, reply] { + assert_eq!( + reopened.comment_anchor_text(moved).unwrap().as_deref(), + Some("TARGET") + ); + } assert_eq!(reopened.comments().len(), 2); assert_eq!(reopened.comments()[0].id(), id); assert_eq!(reopened.comments()[0].resolved(), Some(true)); diff --git a/crates/rdocx-py/python/rdocx/_rdocx.pyi b/crates/rdocx-py/python/rdocx/_rdocx.pyi index 590718274..28cf64936 100644 --- a/crates/rdocx-py/python/rdocx/_rdocx.pyi +++ b/crates/rdocx-py/python/rdocx/_rdocx.pyi @@ -1468,10 +1468,21 @@ class Document: date: str | None = None, ) -> int: ... def move_comment(self, id: int, range: StoryRunRange) -> None: - """Move an existing root thread to a checked current story range.""" + """Move an existing root thread to a checked current story range. + + Replies with their own range and reference move with the root and + cross its new range as ``reply_to`` writes them. Replies with no + marker at all follow through the thread. Any other reply anchor, such + as a reference without a range, refuses the move. A reply id is + refused: move its thread root. Moving a root onto its own range + brings back replies that a 0.17.0 move left behind. + """ ... def move_comment_to_text(self, id: int, anchor: str, *, occurrence: int = 0) -> None: - """Move an existing root thread onto a literal main-story occurrence.""" + """Move an existing root thread onto a literal main-story occurrence. + + Replies move with the root, as in ``move_comment``. + """ ... def reply_to( self, parent_id: int, *, author: str, text: str, date: str | None = None, initials: str | None = None diff --git a/crates/rdocx-py/src/document.rs b/crates/rdocx-py/src/document.rs index 3047f7d94..ab993f73d 100644 --- a/crates/rdocx-py/src/document.rs +++ b/crates/rdocx-py/src/document.rs @@ -16702,7 +16702,8 @@ impl PyDocument { Ok(id) } - /// Move a root comment to a checked current story range atomically. + /// Move a root comment and its replies to a checked current story range + /// atomically. fn move_comment( &mut self, id: i32, @@ -16731,7 +16732,8 @@ impl PyDocument { Ok(()) } - /// Move a root comment onto the selected literal main-story occurrence. + /// Move a root comment and its replies onto the selected literal + /// main-story occurrence. #[pyo3(signature = (id, anchor, *, occurrence = 0))] fn move_comment_to_text( &mut self, diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index d180c0174..18562eea8 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -5214,6 +5214,31 @@ def test_comment_moves_refuse_unknown_reply_and_invalid_ranges_atomically(): assert reopened.comments[0].anchor_text == "TARGET" +def test_issue446_moving_a_thread_carries_its_replies(): + import rdocx + + document = rdocx.Document() + document.add_paragraph("Keep the bearing positions here.") + document.add_paragraph("The bearing at pier 2 moved about 12 mm.") + root = document.add_comment_on_text("about 12 mm", author="R", text="Which reference?") + reply = document.reply_to(root, author="A", text="The 2019 survey marks.") + child = document.reply_to(reply, author="C", text="Which marks?") + document.move_comment_to_text(root, "bearing positions") + assert [(c.id, c.anchor_text) for c in document.comments] == [ + (root, "bearing positions"), + (reply, "bearing positions"), + (child, "bearing positions"), + ] + assert document.remove_content(document.find_content_index(document.paragraphs[1])) + assert [c.id for c in document.comments] == [root, reply, child] + before = document.to_bytes() + with pytest.raises(rdocx.RdocxError, match=f"thread root {root}"): + document.move_comment_to_text(reply, "bearing") + assert document.to_bytes() == before + reopened = rdocx.Document.from_bytes(before) + assert {c.anchor_text for c in reopened.comments} == {"bearing positions"} + + def test_scoped_replacement_count_guards_are_atomic(): import pickle import rdocx diff --git a/crates/rdocx/src/comments.rs b/crates/rdocx/src/comments.rs index 3aaf57324..fdbc9276a 100644 --- a/crates/rdocx/src/comments.rs +++ b/crates/rdocx/src/comments.rs @@ -859,13 +859,19 @@ impl Document { Ok(true) } - /// Move a checked pair to a new range in one story owner. - /// Move one existing root comment without changing its thread identity. - /// Unknown IDs, replies, incomplete anchors and unsupported destinations - /// are refused without publishing any change. + /// Move one existing root comment and its replies without changing their + /// thread identity. + /// + /// Each reply with its own range and reference crosses the root's new + /// range as [`Self::reply_to`] writes it. A reply without any marker + /// follows through the thread metadata. Unknown IDs, replies, incomplete + /// anchors, a reply anchor that cannot travel and unsupported + /// destinations are refused without publishing any change. Moving a root + /// onto its own range publishes nothing when every anchored reply already + /// crosses it, and otherwise brings the replies back onto it. pub fn move_comment(&mut self, id: i32, range: StoryRunRange) -> Result<()> { let selected = self.checked_movable_comment(id)?; - if self.comment_anchor(id)?.as_ref() == Some(&range) { + if self.thread_on_range(id, &range)? { self.story_range_paragraph_snapshot(&range.start.location)?; if range.end.location != range.start.location { self.story_range_paragraph_snapshot(&range.end.location)?; @@ -875,17 +881,20 @@ impl Document { self.move_story_range(&selected, range) } - /// Move an existing root comment onto a literal main-story occurrence. - /// Search and run splitting follow [`Self::add_comment_on_text`]. + /// Move an existing root comment and its replies onto a literal + /// main-story occurrence, as [`Self::move_comment`] does. Search and run + /// splitting follow [`Self::add_comment_on_text`]. pub fn move_comment_to_text(&mut self, id: i32, anchor: &str, occurrence: usize) -> Result<()> { let selected = self.checked_movable_comment(id)?; let mut candidate = self.clone_for_staging(); // The move reads the main part as its source authority, which an // in-place edit such as `add_comment` leaves behind the typed body. candidate.flush_to_package()?; + let replies = candidate.anchored_thread_replies(id)?; let reference = candidate.remove_comment_source_for_move(&selected)?; candidate.anchor_existing_comment_on_text(id, anchor, occurrence)?; candidate.restore_comment_reference_run(id, reference)?; + candidate.move_replies_with_root(id, &replies)?; candidate.flush_to_package()?; candidate.comment_ownership_at(&candidate.doc_part_name)?; let reopened = candidate.prepare_and_reopen_staged()?; @@ -893,18 +902,117 @@ impl Document { Ok(()) } + /// The anchored replies of `root`, parents first and siblings in id + /// order, each with the nearest anchored ancestor its range crosses. + /// Replying in that order writes the markers [`Self::reply_to`] writes. + /// A reply without any marker follows through thread metadata alone. + /// Any other reply anchor cannot travel with the thread and refuses + /// before an edit. `self` must be flushed. + fn anchored_thread_replies(&self, root: i32) -> Result> { + let ownership = self.comment_ownership_at(&self.doc_part_name)?; + let counts = CommentOwnership::marker_counts(&ownership.markers); + let mut replies = Vec::new(); + let mut parents = std::collections::VecDeque::from([(root, root)]); + while let Some((parent, anchored)) = parents.pop_front() { + for (&reply, _) in ownership + .parents + .iter() + .filter(|(_, found)| **found == Some(parent)) + { + match counts.get(&reply).copied().unwrap_or_default() { + [0, 0, 0] => parents.push_back((reply, anchored)), + [1, 1, 1] => { + replies.push((reply, anchored)); + parents.push_back((reply, reply)); + } + _ => { + return Err(Error::Other(format!( + "comment {root} cannot move: reply {reply} has an incomplete anchor" + ))); + } + } + } + } + Ok(replies) + } + + /// Bring each anchored reply onto its ancestor's current range on this + /// staged candidate, after the root moved. The original reference run + /// travels as the root's does. A failure names the root and the reply. + fn move_replies_with_root(&mut self, root: i32, replies: &[(i32, i32)]) -> Result<()> { + for &(reply, anchored) in replies { + let mut moved = || -> Result<()> { + self.flush_to_package()?; + let selected = self.checked_flushed_comment_source(reply, false)?; + let reference = self.remove_comment_source_for_move(&selected)?; + let (_, written) = self.anchor_reply_crossing(anchored, Some(reply))?; + // Anchoring rewrote that owner, so take its current identity. + let story = self + .stories()? + .into_iter() + .find(|story| { + story.kind() == written.kind() + && story.part_name() == written.part_name() + && story.owner_index() == written.owner_index() + }) + .ok_or_else(|| Error::Other("reply story disappeared".into()))?; + self.splice_comment_reference_run(&story, reply, reference) + }; + moved().map_err(|error| { + Error::Other(format!( + "comment {root} cannot move: reply {reply}: {error}" + )) + })?; + } + Ok(()) + } + + /// Whether `root` already has `range` and every anchored reply crosses + /// its ancestor's range, as [`Self::reply_to`] writes it. + fn thread_on_range(&self, root: i32, range: &StoryRunRange) -> Result { + let mut proof = self.clone_for_staging(); + proof.flush_to_package()?; + let read = CommentAnchorRead::from_prepared(&proof, None)?; + if read.project(root)?.0.as_ref() != Some(range) { + return Ok(false); + } + for (reply, anchored) in proof.anchored_thread_replies(root)? { + let (Some(reply), Some(anchored)) = (read.project(reply)?.0, read.project(anchored)?.0) + else { + return Ok(false); + }; + if reply.start != anchored.start || reply.end.location != anchored.end.location { + return Ok(false); + } + } + Ok(true) + } + pub(crate) fn checked_movable_comment(&self, id: i32) -> Result { + self.checked_comment_source(id, true) + } + + /// Select one comment's complete paired range and reference. `root` + /// refuses a reply, which only moves with its thread. + pub(crate) fn checked_comment_source(&self, id: i32, root: bool) -> Result { let mut proof = self.clone_for_staging(); proof.flush_to_package()?; - let ownership = proof.comment_ownership_at(&proof.doc_part_name)?; + proof.checked_flushed_comment_source(id, root) + } + + /// [`Self::checked_comment_source`] on a document whose package is + /// already flushed, such as a staged candidate. + fn checked_flushed_comment_source(&self, id: i32, root: bool) -> Result { + let ownership = self.comment_ownership_at(&self.doc_part_name)?; match ownership.parents.get(&id) { None => return Err(Error::Other(format!("unknown comment {id}"))), - Some(Some(_)) => { + Some(Some(_)) if root => { return Err(Error::Other(format!( - "comment {id} is a reply, not a movable root" + "comment {id} is a reply, not a movable root: it moves with its thread root {}", + ownership.thread_root(id) ))); } - Some(None) => {} + Some(_) => {} } let counts = CommentOwnership::marker_counts(&ownership.markers); if counts.get(&id) != Some(&[1, 1, 1]) { @@ -915,15 +1023,16 @@ impl Document { // This exact accepted projection also rejects hidden, reversed, // cross-story or unrepresentable endpoints rather than inventing one. // A range across table cells is read but placing it takes one owner. - let anchor = self - .comment_anchor(id)? + let anchor = CommentAnchorRead::from_prepared(self, Some(id))? + .project(id)? + .0 .ok_or_else(|| Error::Other(format!("comment {id} has no movable paired range")))?; if anchor.start.location.story() != anchor.end.location.story() { return Err(Error::Other(format!( "comment {id} range runs across story owners and cannot be moved" ))); } - let paragraphs = proof.story_range_located_paragraphs()?; + let paragraphs = self.story_range_located_paragraphs()?; let (mut located, identity_counts) = located_story_markers(¶graphs)?; located.retain(|(_, _, _, marker)| { matches!(marker.kind, StoryRangeKind::Comment { id: found } if found == id) @@ -959,7 +1068,9 @@ impl Document { let mut candidate = self.clone_for_staging(); // As in `move_comment_to_text`, bring the main part up to date. candidate.flush_to_package()?; + let replies = candidate.anchored_thread_replies(*id)?; candidate.move_comment_story_range(selected, &range, *id)?; + candidate.move_replies_with_root(*id, &replies)?; candidate.flush_to_package()?; candidate.comment_ownership_at(&candidate.doc_part_name)?; candidate.checked_movable_comment(*id)?; @@ -1953,7 +2064,7 @@ impl Document { .position(|item| item.id == parent_id) }) .ok_or_else(|| Error::Other(format!("comment id {parent_id} does not exist")))?; - let id = self.anchor_reply_to_parent(parent_id)?; + let (id, _) = self.anchor_reply_crossing(parent_id, None)?; self.prepare_comment_authoring()?; let existing_parent_para_id = last_para_id( &self @@ -2023,7 +2134,14 @@ impl Document { /// Reuse checked story endpoints, extending the reply through the parent's /// reference run. Physical start adjacency is then enforced in that same /// owner without moving or rewriting any intervening producer payload. - fn anchor_reply_to_parent(&mut self, parent_id: i32) -> Result { + /// A new reply reserves its id once the parent proves projectable, while + /// a reply moving with its thread keeps `existing`. Returns the reply id + /// and the story that now holds its markers. + fn anchor_reply_crossing( + &mut self, + parent_id: i32, + existing: Option, + ) -> Result<(i32, crate::StoryId)> { let no_range = || Error::Other(format!("comment id {parent_id} has no range to reply to")); self.flush_to_package()?; #[cfg(test)] @@ -2034,7 +2152,10 @@ impl Document { drop(read); #[cfg(test)] drop(parent_read_phase); - let id = self.identifiers.reserve_comment_id()?; + let id = match existing { + Some(id) => id, + None => self.identifiers.reserve_comment_id()?, + }; self.anchor_story_range( &StoryRunRange { start: parent.start, @@ -2076,7 +2197,7 @@ impl Document { xml.splice(destination..destination, marker); self.write_story_part(story.part_name(), xml)?; } - Ok(id) + Ok((id, story)) } /// Set or clear the resolved state for a comment. @@ -3062,6 +3183,19 @@ impl CommentOwnership { } } } + + /// The root of `id`'s thread, following defined parents. A malformed + /// parent cycle stops once every definition was visited. + fn thread_root(&self, id: i32) -> i32 { + let mut root = id; + for _ in 0..self.parents.len() { + match self.parents.get(&root) { + Some(Some(parent)) if self.parents.contains_key(parent) => root = *parent, + _ => break, + } + } + root + } } // One actual prepared-source read shared by anchor projection and reply checks. @@ -4829,8 +4963,10 @@ mod tests { .collect() } + /// Issue 446: a root move carries every reply range with it, in the + /// crossing order `reply_to` writes, as Word does when the text moves. #[test] - fn issue434_root_moves_keep_crossing_replies_and_generic_pairing_strict() { + fn issue446_root_moves_carry_crossing_replies_and_generic_pairing_strict() { for reply_count in [1, 3] { let mut document = Document::new(); document.add_paragraph("SOURCE"); @@ -4848,6 +4984,8 @@ mod tests { } document.resolve_comment(root, true).unwrap(); assert!(document.story_ranges().is_err()); + let part = document.doc_part_name.clone(); + let authored = issue434_reply_markers(&mut document, &part); document.flush_to_package().unwrap(); let comments_part = document.comments_part_name.clone().unwrap(); let extended_part = document.comments_extended_part_name.clone().unwrap(); @@ -4865,21 +5003,21 @@ mod tests { }, }; document.move_comment(root, target.clone()).unwrap(); - assert_eq!( - document.comment_anchor_text(root).unwrap().as_deref(), - Some("TARGET TARGET") - ); - for reply in &replies { + for id in std::iter::once(root).chain(replies.iter().copied()) { assert_eq!( - document.comment_anchor_text(*reply).unwrap().as_deref(), - Some("SOURCE") + document.comment_anchor_text(id).unwrap().as_deref(), + Some("TARGET TARGET") ); } + assert_eq!(issue434_reply_markers(&mut document, &part), authored); document.move_comment_to_text(root, "TARGET", 1).unwrap(); - assert_eq!( - document.comment_anchor_text(root).unwrap().as_deref(), - Some("TARGET") - ); + for id in std::iter::once(root).chain(replies.iter().copied()) { + assert_eq!( + document.comment_anchor_text(id).unwrap().as_deref(), + Some("TARGET") + ); + } + assert_eq!(issue434_reply_markers(&mut document, &part), authored); let before = document.to_bytes().unwrap(); assert_eq!( document.package.get_part(&comments_part).unwrap(), @@ -4899,18 +5037,12 @@ mod tests { invalid.end.run_index = usize::MAX; assert!(document.move_comment(root, invalid).is_err()); assert_eq!(document.to_bytes().unwrap(), before); - if reply_count > 1 { - assert!(document.story_ranges().is_err()); - } + assert!(document.story_ranges().is_err()); let reopened = Document::from_bytes(&before).unwrap(); - assert_eq!( - reopened.comment_anchor_text(root).unwrap().as_deref(), - Some("TARGET") - ); - for reply in replies { + for id in std::iter::once(root).chain(replies) { assert_eq!( - reopened.comment_anchor_text(reply).unwrap().as_deref(), - Some("SOURCE") + reopened.comment_anchor_text(id).unwrap().as_deref(), + Some("TARGET") ); } } diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index 7f024a7ac..1239dcfa7 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -31825,7 +31825,19 @@ impl Document { reference: Vec, ) -> Result<()> { let selected = self.checked_movable_comment(id)?; - let (source, owner) = self.story_source_and_owner(selected.range().end.location.story())?; + self.splice_comment_reference_run(selected.range().end.location.story(), id, reference) + } + + /// Replace the reference run that anchoring synthesized for comment `id` + /// in `story` with the original one. A reply moving with its thread names + /// the story its reply authoring wrote, without another selection. + pub(crate) fn splice_comment_reference_run( + &mut self, + story: &crate::StoryId, + id: i32, + reference: Vec, + ) -> Result<()> { + let (source, owner) = self.story_source_and_owner(story)?; let part = source.part_name.clone(); let span = comment_reference_run_span(source.xml.as_ref(), &owner.full, id)?; let mut xml = source.xml.into_owned(); diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 52ba847e8..8e3ff6702 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -61751,6 +61751,491 @@ fn comment_removal_dangling_reference_comparison_keeps_existing_lifecycle() { assert!(!xml.contains(r#"commentReference w:id="8""#)); } +/// A root on "about 12 mm" with a reply, a sibling reply and a reply to the +/// reply, each authored with its own crossing range and reference. +fn issue446_thread() -> (Document, i32, i32) { + let mut document = Document::new(); + document.add_paragraph("Keep the bearing positions here."); + document.add_paragraph("The bearing at pier 2 moved about 12 mm."); + document.add_paragraph("Tail paragraph."); + let root = document + .add_comment_on_text("about 12 mm", 0, "R", None, "Which reference?", None) + .unwrap(); + let reply = document + .reply_to(root, "A", "The 2019 survey marks.") + .unwrap(); + document.reply_to(root, "S", "Sibling").unwrap(); + document.reply_to(reply, "C", "Child").unwrap(); + (document, root, reply) +} + +/// Every listed comment keeps one range start, one range end and one +/// reference of its own in the saved package, and each reply shows its +/// thread root's text. No marker outlives its comment. Returns the number of +/// listed comments. +fn issue446_threads_whole(document: &mut Document, label: &str) -> usize { + let bytes = document.to_bytes().unwrap(); + let package = oxml_opc::OpcPackage::from_reader(std::io::Cursor::new(bytes)).unwrap(); + let parts = package + .parts + .values() + .map(|xml| String::from_utf8_lossy(xml).into_owned()) + .collect::>(); + let comments = document.comments(); + let parents = comments + .iter() + .map(|comment| (comment.id(), comment.parent_id())) + .collect::>(); + for comment in &comments { + let id = comment.id(); + for marker in ["commentRangeStart", "commentRangeEnd", "commentReference"] { + let tag = format!(""); + let count = parts + .iter() + .map(|xml| xml.matches(&tag).count()) + .sum::(); + assert_eq!(count, 1, "{label}: comment {id} has {count} {marker}"); + } + let mut root = id; + while let Some(parent) = parents[&root] { + assert!( + parents.contains_key(&parent), + "{label}: comment {root} lost its parent {parent}" + ); + root = parent; + } + assert_eq!( + document.comment_anchor_text(id).unwrap(), + document.comment_anchor_text(root).unwrap(), + "{label}: comment {id} left its thread root {root}" + ); + } + for marker in ["commentRangeStart", "commentRangeEnd", "commentReference"] { + let count = parts + .iter() + .map(|xml| xml.matches(&format!("(); + assert_eq!(count, comments.len(), "{label}: orphan {marker}"); + } + comments.len() +} + +/// Issue 446: a comment thread acts as one unit. Every operation keeps each +/// reply's own range and reference on its root's text, removes the whole +/// thread with that text, or refuses without changing the document. +#[test] +fn comment_thread_operations_keep_every_reply_on_its_root_text() { + #[derive(Debug, Clone, Copy, PartialEq)] + enum Expected { + Kept(&'static str), + Removed, + Refused, + } + type Operation = fn(&mut Document, i32) -> rdocx::Result<()>; + fn body_location(document: &Document, index: usize) -> ContentLocation { + let body = f254_story(document, StoryKind::Body); + document.story_items(&body).unwrap()[index] + .location() + .clone() + } + let operations: [(&str, Operation, Expected); 15] = [ + ( + "move_comment_to_text", + |document, root| document.move_comment_to_text(root, "bearing positions", 0), + Expected::Kept("bearing positions"), + ), + ( + "move_comment_to_text in the same paragraph", + |document, root| document.move_comment_to_text(root, "The bearing", 0), + Expected::Kept("The bearing"), + ), + ( + "move_comment", + |document, root| { + let location = document.paragraph_story_location(0)?.unwrap(); + document.move_comment( + root, + StoryRunRange { + start: StoryRunPosition { + location: location.clone(), + run_index: 0, + }, + end: StoryRunPosition { + location, + run_index: 1, + }, + }, + ) + }, + Expected::Kept("Keep the bearing positions here."), + ), + ( + "move, then remove the old text", + |document, root| { + document.move_comment_to_text(root, "Tail", 0)?; + document.try_remove_content(1).map(|_| ()) + }, + Expected::Kept("Tail"), + ), + ( + "remove_content", + |document, _| document.try_remove_content(1).map(|_| ()), + Expected::Removed, + ), + ( + "remove_content_range", + |document, _| document.remove_content_range(1, 3).map(|_| ()), + Expected::Removed, + ), + ( + "remove_content_at", + |document, _| { + let location = body_location(document, 1); + document.remove_content_at(&location).map(|_| ()) + }, + Expected::Refused, + ), + ( + "Paragraph::set_text", + |document, _| document.paragraph_mut(1).unwrap().set_text("Replaced."), + Expected::Kept("Replaced."), + ), + ( + "try_replace_text over the anchor", + |document, _| { + document + .try_replace_text("about 12 mm", "fifteen") + .map(|_| ()) + }, + Expected::Kept("fifteen"), + ), + ( + "clone_content", + |document, _| { + let (source, destination) = + (body_location(document, 1), body_location(document, 2)); + document.clone_content(&source, &destination) + }, + Expected::Kept("about 12 mm"), + ), + ( + "move_content", + |document, _| { + let (source, destination) = + (body_location(document, 1), body_location(document, 0)); + document.move_content(&source, &destination) + }, + Expected::Kept("about 12 mm"), + ), + ( + "compare, then accept the deletion", + |document, _| { + let mut edited = Document::new(); + edited.add_paragraph("Keep the bearing positions here."); + edited.add_paragraph("Tail paragraph."); + document.compare(&edited, "X", "2026-11-09T00:00:00Z")?; + document.accept_all().map(|_| ()) + }, + Expected::Removed, + ), + ( + "compare, then reject the deletion", + |document, _| { + let mut edited = Document::new(); + edited.add_paragraph("Keep the bearing positions here."); + edited.add_paragraph("Tail paragraph."); + document.compare(&edited, "X", "2026-11-09T00:00:00Z")?; + document.reject_all().map(|_| ()) + }, + Expected::Kept("about 12 mm"), + ), + ( + "import_fragment of the whole body, as Python insert_document does", + |document, _| { + let mut host = Document::new(); + host.add_paragraph("Host."); + let start = document.direct_body_item_location(0)?.unwrap(); + let end = ContentLocation::end(start.story().clone()); + let fragment = DocumentFragment::from_range(document, &start, &end, false)?; + let destination = ContentLocation::end(f254_story(&host, StoryKind::Body)); + host.import_fragment( + &destination, + &fragment, + FragmentConflictPolicy::for_insert_document(None), + )?; + *document = host; + Ok(()) + }, + Expected::Kept("about 12 mm"), + ), + ( + "save and reopen", + |document, _| { + *document = Document::from_bytes(&document.to_bytes()?)?; + Ok(()) + }, + Expected::Kept("about 12 mm"), + ), + ]; + for (label, operation, expected) in operations { + let (mut document, root, _) = issue446_thread(); + let before = document.to_bytes().unwrap(); + let result = operation(&mut document, root); + match expected { + Expected::Refused => { + assert!(result.is_err(), "{label}: refusal expected"); + assert_eq!(document.to_bytes().unwrap(), before, "{label}"); + continue; + } + _ => result.unwrap_or_else(|error| panic!("{label}: {error}")), + } + let count = issue446_threads_whole(&mut document, label); + let mut reopened = Document::from_bytes(&document.to_bytes().unwrap()).unwrap(); + assert_eq!( + issue446_threads_whole(&mut reopened, label), + count, + "{label}" + ); + match expected { + Expected::Kept(text) => { + assert_eq!(count, 4, "{label}: a reply was lost"); + let root = document + .comments() + .iter() + .find(|comment| comment.parent_id().is_none()) + .unwrap() + .id(); + assert_eq!( + document.comment_anchor_text(root).unwrap().as_deref(), + Some(text), + "{label}" + ); + } + _ => assert_eq!(count, 0, "{label}: a reply outlived its thread"), + } + } +} + +/// Issue 446: a root move carries its replies out of, and back into, every +/// supported story owner. +#[test] +fn comment_thread_moves_carry_replies_across_story_owners() { + for kind in [ + StoryKind::TableCell, + StoryKind::Header, + StoryKind::Footer, + StoryKind::Footnote, + StoryKind::TextBox, + ] { + let mut document = Document::new(); + document.add_paragraph("body target"); + let zero = Length::pt(0.0); + document + .add_text_box_to_story( + &f254_story(&document, rdocx::StoryKind::Body), + "box anchor", + rdocx::TextBoxOptions { + width: Length::pt(144.0), + height: Length::pt(54.0), + anchor: rdocx::PictureAnchor { + horizontal_relative_from: rdocx::DrawingHorizontalRelativeFrom::Column, + horizontal_offset: zero, + horizontal_alignment: None, + vertical_relative_from: rdocx::DrawingVerticalRelativeFrom::Paragraph, + vertical_offset: zero, + vertical_alignment: None, + wrap: rdocx::DrawingWrap::TopAndBottom, + distance_top: zero, + distance_bottom: zero, + distance_left: zero, + distance_right: zero, + relative_height: 1, + behind_text: false, + }, + rotation_degrees: 0.0, + text_direction: rdocx::TextBoxDirection::Horizontal, + fill_color: None, + }, + ) + .unwrap(); + document + .add_table(1, 1) + .cell(0, 0) + .unwrap() + .set_text("cell anchor"); + document.set_header("header anchor"); + document.set_footer("footer anchor"); + document.add_footnote("note anchor"); + let paragraph = |document: &Document, kind| { + let story = f254_story(document, kind); + let location = document + .story_items(&story) + .unwrap() + .into_iter() + .find(|item| item.kind() == StoryItemKind::Paragraph) + .unwrap() + .location() + .clone(); + StoryRunRange { + start: StoryRunPosition { + location: location.clone(), + run_index: 0, + }, + end: StoryRunPosition { + location, + run_index: 1, + }, + } + }; + let root = document + .add_story_comment(paragraph(&document, kind), "Ada", None, "root") + .unwrap(); + let reply = document.reply_to(root, "Ben", "reply").unwrap(); + document.reply_to(reply, "Cyd", "child").unwrap(); + let label = format!("{kind:?}"); + let source = document.comment_anchor_text(root).unwrap(); + assert_eq!(issue446_threads_whole(&mut document, &label), 3); + let target = paragraph(&document, StoryKind::Body); + document.move_comment(root, target).unwrap(); + assert_eq!(issue446_threads_whole(&mut document, &label), 3); + assert_eq!( + document.comment_anchor_text(reply).unwrap().as_deref(), + Some("body target"), + "{label}" + ); + let back = paragraph(&document, kind); + document.move_comment(root, back).unwrap(); + let mut reopened = Document::from_bytes(&document.to_bytes().unwrap()).unwrap(); + assert_eq!(issue446_threads_whole(&mut reopened, &label), 3); + assert_eq!( + reopened.comment_anchor_text(reply).unwrap(), + source, + "{label}" + ); + reopened.validate_comment_ownership().unwrap(); + } +} + +/// Rewrite the saved main part of a fresh `issue446_thread`. +fn issue446_edited_thread(edit: impl Fn(String, i32, i32) -> String) -> (Document, i32, i32) { + let (mut document, root, reply) = issue446_thread(); + let bytes = document.to_bytes().unwrap(); + let mut package = oxml_opc::OpcPackage::from_reader(std::io::Cursor::new(bytes)).unwrap(); + let xml = String::from_utf8(package.get_part("/word/document.xml").unwrap().to_vec()).unwrap(); + let edited = edit(xml.clone(), root, reply); + assert_ne!(edited, xml, "the fixture edit must apply"); + package.set_part("/word/document.xml", edited.into_bytes()); + let mut output = std::io::Cursor::new(Vec::new()); + package.write_to(&mut output).unwrap(); + (Document::from_bytes(output.get_ref()).unwrap(), root, reply) +} + +/// Issue 446: 0.17.0 moved roots without their replies. Moving the root +/// onto its own range brings them back, so removing the text they were left +/// on keeps them, and a second such move publishes nothing. A reply without +/// any marker follows through thread metadata. A reference-only reply +/// refuses the move before any edit, and a reply that fails once the root +/// has moved in the candidate refuses it with the document unchanged. +#[test] +fn comment_thread_moves_heal_split_threads_and_refuse_untravelable_replies() { + let (mut diverged, root, reply) = issue446_edited_thread(|xml, root, _| { + let reference = format!(""); + let start = format!(""); + let end = format!(""); + xml.replace(&reference, "") + .replace(&start, "") + .replace(&end, "") + .replacen( + "Keep the bearing positions here.", + &format!( + "{start}Keep the bearing positions here.{end}{reference}" + ), + 1, + ) + }); + assert_eq!( + diverged.comment_anchor_text(reply).unwrap().as_deref(), + Some("about 12 mm") + ); + let own = diverged.comment_anchor(root).unwrap().unwrap(); + diverged.move_comment(root, own).unwrap(); + assert_eq!( + diverged.comment_anchor_text(root).unwrap().as_deref(), + Some("Keep the bearing positions here.") + ); + assert_eq!(issue446_threads_whole(&mut diverged, "healed"), 4); + let healed = diverged.to_bytes().unwrap(); + let own = diverged.comment_anchor(root).unwrap().unwrap(); + diverged.move_comment(root, own).unwrap(); + assert_eq!( + diverged.to_bytes().unwrap(), + healed, + "a second move is a no-op" + ); + assert!(diverged.try_remove_content(1).unwrap()); + assert_eq!(issue446_threads_whole(&mut diverged, "healed"), 4); + assert_eq!( + diverged.comment_anchor_text(reply).unwrap().as_deref(), + Some("Keep the bearing positions here.") + ); + + let (mut legacy, root, reply) = issue446_edited_thread(|xml, _, reply| { + xml.replace(&format!(""), "") + .replace(&format!(""), "") + .replace( + &format!(""), + "", + ) + }); + legacy.move_comment_to_text(root, "Tail", 0).unwrap(); + assert_eq!( + legacy.comment_anchor_text(root).unwrap().as_deref(), + Some("Tail") + ); + assert_eq!(legacy.comment_anchor_text(reply).unwrap(), None); + assert_eq!(legacy.comments().len(), 4); + assert!(legacy.try_remove_content(1).unwrap()); + assert_eq!(legacy.comments().len(), 4); + + let (mut point, root, reply) = issue446_edited_thread(|xml, _, reply| { + xml.replace(&format!(""), "") + .replace(&format!(""), "") + }); + let before = point.to_bytes().unwrap(); + let error = point + .move_comment_to_text(root, "Tail", 0) + .unwrap_err() + .to_string(); + assert!(error.contains(&format!("reply {reply}")), "{error}"); + assert_eq!(point.to_bytes().unwrap(), before); + let error = point + .move_comment_to_text(reply, "Tail", 0) + .unwrap_err() + .to_string(); + assert!(error.contains(&format!("thread root {root}")), "{error}"); + assert_eq!(point.to_bytes().unwrap(), before); + + let (mut tracked, root, reply) = issue446_edited_thread(|xml, _, reply| { + let reference = format!(""); + xml.replace( + &reference, + &format!( + "{reference}" + ), + ) + }); + let before = tracked.to_bytes().unwrap(); + let error = tracked + .move_comment_to_text(root, "Tail", 0) + .unwrap_err() + .to_string(); + assert!( + error.starts_with(&format!("comment {root} cannot move: reply {reply}: ")), + "{error}" + ); + assert_eq!(tracked.to_bytes().unwrap(), before); +} + #[test] fn comment_anchor_helper_matches_accepted_story_spans() { // Existing helper fallback must not substitute deleted/foreign text for accepted display. diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 491226411..efc1eb5c5 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -2677,8 +2677,13 @@ boundaries rebase after removal. Only newly empty pure Google marker controls are pruned. `move_comment_to_text` shares the existing recursive literal finder and splitter without allocating a temporary thread. Root moves select that comment's qualified markers with their original source -ordinals, preserving crossing reply anchors. Generic paired-range operations -retain their strict nesting checks. +ordinals. Each reply with a complete range and reference then leaves its old +position and crosses its nearest anchored ancestor's new range through the +reply authoring path, parents first and siblings in id order, so the markers +match what `reply_to` writes. Its original reference run travels as the +root's does. A reply without markers follows through thread metadata. Any +other reply anchor, or a reply id, refuses the move atomically. Generic +paired-range operations retain their strict nesting checks. Rich comment query restores main-part namespace context once through the existing strict declaration replay. Paired XML events prove that names, non-namespace attributes and payload remain identical, yielding exact physical boundary correspondence. The mapped canonical and restored story-owner inventories must be bijective in physical spans, kind and owner index before canonical paragraph paths receive actual namespace scopes. Additional or reinterpreted owners refuse instead of redirecting a query. The existing checked paragraph span traversal serves both discovery and projection, with paragraph scopes inventoried in a bounded pass. Canonical locations, fingerprints and accepted run indices remain authoritative. Imported paragraph and block-local alias fields retain rich A7B, source-byte purity and usable move/reopen endpoints. Comment destination anchoring replays retained declarations before replacing package authority, while other anchor kinds keep their existing path. Redundant declaration replay is omitted only for a unique exact owner whose complete non-namespace event payload and local declarations match, with identical resolved element and attribute namespace facts throughout that owner. Redundant child declarations on a transported reference do not require global replay to reinterpret its shape. This owner-local proof permits unrelated modeled source normalization. Needed declarations still use the unchanged strict replay. The private pre-removal endpoint probe validates the caller's exact accepted endpoints without publishing destination namespace context, while the real Comment destination always preserves that authority before replacing source. Same-owner modeled alias plus local raw-field fixtures that already fail initial save remain outside this correction. Supported controls include separate unrelated root-bound modeled aliases and normalized properties in the same package. `StoryRunPosition` and `StoryRunRange` add checked `ContentLocation` ownership for body and table-cell paragraphs without changing `RunPosition`. A body diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index c5493ba53..6dad9fff6 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -2447,8 +2447,12 @@ views and document revisions remain unchanged on refusal, while a successful add or reply publishes once. Untouched imported comment parts remain unchanged. Native `move_comment(id, StoryRunRange)` and `move_comment_to_text(id, anchor, -occurrence)` move an existing root thread without changing its numeric id or -metadata. Python exposes `move_comment(id, range)` and +occurrence)` move an existing root thread without changing its numeric ids or +metadata. Replies with their own range and reference move with the root and +cross its new range as `reply_to` writes them. Replies with no marker at all +follow through the thread metadata. Any other reply anchor, such as a +reference without a range, refuses the move. Moving a root onto its own range +brings back replies left elsewhere. Python exposes `move_comment(id, range)` and `move_comment_to_text(id, anchor, *, occurrence=0)`, advancing the document revision exactly once after successful package publication. Refusals retain bytes and revisions. `rdocx comment move --text diff --git a/docs/hld/12-testing-strategy.md b/docs/hld/12-testing-strategy.md index 8c0ca6f86..30c459e2f 100644 --- a/docs/hld/12-testing-strategy.md +++ b/docs/hld/12-testing-strategy.md @@ -4378,10 +4378,15 @@ Word, or full verify gate. Issue 289 is covered by block-control paragraph endpo Existing native entrypoints pin thread and companion continuity, same-paragraph accepted-boundary rebasing, cross-story placement, block-control destinations -and exact mixed-reference source retention. Google marker wrappers prune only -when their raw skeleton contains no unrelated payload. Namespace aliases and -foreign lookalikes remain distinct. Incomplete, duplicate, reversed, point, -orphan, reply, unknown and stale sources refuse without publication. Oxml +and exact mixed-reference source retention. One operation table checks that +every reply keeps its own range and reference on its root's text through +moves, removals, text edits, clones, comparison and import, and that a root +move onto its own range gathers replies a 0.17.0 move split. Google marker +wrappers prune only when their raw skeleton contains no unrelated payload. +Namespace aliases and foreign lookalikes remain distinct. Incomplete, +duplicate, reversed, point, orphan, reply, unknown and stale sources refuse +without publication, and so does a reply anchor that cannot travel with its +thread. Oxml carrier tests cover paired and empty references, qualified attributes, multiple references, property insertion, typed replacement, removal, splitting and segment serialization. Python runtime and typing cover revision invalidation From 939f421e7e614ef508ee36e71139c9ed43d507f4 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 08:26:29 +0100 Subject: [PATCH 2/3] fix(table): consume cells by one rule in spans, omissions and merges Table::set_cell_grid_span_checked and set_row_grid_omissions consumed a cell only when its paragraph equaled an empty one and its properties held a width alone, while Table::merge_cells drops a lone paragraph whatever its paragraph properties and identity attributes (#432 case 4). So set_cell_grid_span refused a cell whose only paragraph was right aligned, or carried the w14:paraId Word writes, that Cell.merge consumed. The three now share cell_is_consumable. Its content is one paragraph that only paragraph formatting or root identity attributes tell from an empty one. A tracked paragraph mark, a tracked paragraph property or numbering change and section properties count as content, so a merge now keeps such a paragraph where it dropped it, and a span or an omission refuses. The cell has no opaque cell, cell-property or border XML and no vertical merge ownership. Modeled formatting such as shading goes with the cell, as merge_cells and Word's merge already do. Spans and omissions also keep refusing a legacy hMerge cell, which merge_cells never reaches since its column-edit topology check refuses such a table. Spans and omissions now remove and restore cells through the row helpers that merge_cells uses, so row-level bookmark and permission markers keep their cell boundaries instead of being lost or moved to another cell. A restored cell goes before the markers that followed the span or closed the row, so a removal round trips. set_cell_vertical_merge only writes the property and removes no cell, so it keeps its own validation. Tests, table unit issue446_every_cell_consuming_edit_shares_one_rule over fifteen cell contents and five entry points, legacy hMerge cells and row-level markers through span, omissions and their restoration, test_formatting_tables issue446 grid span and merge Harness, unchanged, samples use the unchecked span builder --- .../rdocx-py/tests/test_formatting_tables.py | 29 ++ crates/rdocx/src/table.rs | 451 +++++++++++++++--- docs/hld/04-opc-and-packaging.md | 5 +- docs/hld/10-bindings-spec.md | 25 +- 4 files changed, 444 insertions(+), 66 deletions(-) diff --git a/crates/rdocx-py/tests/test_formatting_tables.py b/crates/rdocx-py/tests/test_formatting_tables.py index 46e476ffa..4191bc70d 100644 --- a/crates/rdocx-py/tests/test_formatting_tables.py +++ b/crates/rdocx-py/tests/test_formatting_tables.py @@ -570,6 +570,35 @@ def test_cells_merge_through_the_checked_table_operations(): assert reopened.cell(1, -1).vertical_merge is None +def test_issue446_grid_span_and_merge_consume_the_same_cells(): + from rdocx import WD_ALIGN_PARAGRAPH, Document, RdocxError + + for operation in ("grid span", "merge"): + document = Document() + table = document.add_table(1, 3, style="Table Grid") + table.cell(0, 0).text = "Total" + table.cell(0, 1).paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT + if operation == "grid span": + document.tables[0].set_cell_grid_span(0, 0, 2) + else: + document.tables[0].cell(0, 0).merge(document.tables[0].cell(0, 1)) + table = document.tables[0] + assert [cell.text for cell in table.rows[0].cells] == ["Total", ""], operation + assert [cell.grid_span for cell in table.rows[0].cells] == [2, 1], operation + assert len(table.cell(0, 0).paragraphs) == 1, operation + + document = Document() + table = document.add_table(1, 2) + table.cell(0, 0).text = "Total" + table.cell(0, 1).text = "kept" + before = document.to_bytes() + with pytest.raises(RdocxError, match="nonempty cell"): + document.tables[0].set_cell_grid_span(0, 0, 2) + assert document.to_bytes() == before + document.tables[0].cell(0, 0).merge(document.tables[0].cell(0, 1)) + assert [p.text for p in document.tables[0].cell(0, 0).paragraphs] == ["Total", "kept"] + + def test_table_acceptance_workflow_writes_the_native_body(): # table_acceptance_workflow_writes_the_body_the_python_binding_pins in # crates/rdocx/tests/integration_test.rs pins the same body for the native diff --git a/crates/rdocx/src/table.rs b/crates/rdocx/src/table.rs index 87a9b84ab..5ad0bf6a8 100644 --- a/crates/rdocx/src/table.rs +++ b/crates/rdocx/src/table.rs @@ -674,25 +674,67 @@ pub(crate) fn validate_table_topology(table: &CT_Tbl) -> Result<()> { Ok(()) } -fn cell_is_discardable_for_grid_edit(cell: &CT_Tc) -> bool { - let empty_content = matches!( - cell.content.as_slice(), - [CellContent::Paragraph(paragraph)] if paragraph == &CT_P::new() - ); - let width_only = cell.properties.as_ref().is_none_or(|properties| { - properties.grid_span.is_none() - && properties.h_merge.is_none() - && properties.v_merge.is_none() - && properties.borders.is_none() - && properties.shading.is_none() - && properties.v_align.is_none() - && properties.no_wrap.is_none() - && properties.cell_margin.is_none() - && properties.text_direction.is_none() - && properties.cnf_style.is_none() - && properties.extra_xml.is_empty() - }); - empty_content && cell.extra_xml.is_empty() && width_only +/// Whether the cell holds one paragraph with nothing in it. Paragraph +/// formatting, which includes the mark's run formatting, and root identity +/// attributes such as `w14:paraId` or `w:rsidR` are not content. Review and +/// section state in the paragraph properties is: a tracked paragraph mark, a +/// tracked property or numbering change and section properties would vanish +/// with the cell. +fn cell_content_is_lone_empty(cell: &CT_Tc) -> bool { + match cell.content.as_slice() { + [CellContent::Paragraph(paragraph)] => { + if paragraph.properties.as_ref().is_some_and(|properties| { + properties.sect_pr.is_some() + || properties.change.is_some() + || !properties.revision_xml.is_empty() + || properties.numbering_revision.is_some() + || !properties.numbering_revision_xml.is_empty() + || properties.rpr.as_ref().is_some_and(|mark| { + !mark.revision_markers.is_empty() || mark.change.is_some() + }) + }) { + return false; + } + let mut payload = paragraph.clone(); + payload.properties = None; + payload + .extra_xml + .retain(|(position, raw)| !CT_P::raw_is_root_attributes(*position, raw)); + payload == CT_P::new() + } + _ => false, + } +} + +/// Whether an edit may drop the cell's own metadata: no opaque cell, +/// cell-property or border XML and no vertical merge ownership. Modeled +/// formatting such as shading goes with the cell, as in Word's merge. +fn cell_metadata_is_discardable(cell: &CT_Tc) -> bool { + cell.extra_xml.is_empty() + && cell.properties.as_ref().is_none_or(|properties| { + properties.extra_xml.is_empty() + && properties + .borders + .as_ref() + .is_none_or(|borders| borders.extra_xml.is_empty()) + && properties.v_merge.is_none() + }) +} + +/// The one rule for every edit that consumes a cell: merging it into a +/// neighbour, spanning over it or omitting it from a row edge. A merge +/// refuses a cell whose metadata cannot go and keeps the content of a cell +/// whose content is not a lone empty paragraph. A span or an omission +/// refuses either. They also refuse a legacy `w:hMerge` cell, whose partners +/// would dangle, which a merge never reaches: its column-edit topology check +/// refuses any table that holds one. +fn cell_is_consumable(cell: &CT_Tc) -> bool { + cell_content_is_lone_empty(cell) + && cell_metadata_is_discardable(cell) + && cell + .properties + .as_ref() + .is_none_or(|properties| properties.h_merge.is_none()) } fn empty_grid_cell(width: i32) -> CT_Tc { @@ -875,6 +917,18 @@ fn insert_row_cell(row: &mut CT_Row, index: usize, cell: CT_Tc) { row.cells.insert(index, cell); } +/// Insert `cell` at boundary `index` after the preserved row children there. +/// A cell restored out of a span or at the row end goes before the children +/// that followed the span or closed the row, so a removal round trips. +fn insert_row_cell_after_children(row: &mut CT_Row, index: usize, cell: CT_Tc) { + for (position, _) in &mut row.extra_xml { + if *position != usize::MAX && *position >= index { + *position += 1; + } + } + row.cells.insert(index, cell); +} + /// Remove direct cell `index`. Preserved row children before it move to the /// next cell boundary. fn remove_row_cell(row: &mut CT_Row, index: usize) { @@ -1189,18 +1243,21 @@ impl<'a> Table<'a> { return Err(Error::Other("merge rectangle has no cells".into())); } for (offset, cell) in self.inner.rows[row].cells[first..=last].iter().enumerate() { - if !cell.extra_xml.is_empty() - || (offset > 0 - && cell.properties.as_ref().is_some_and(|p| { - !p.extra_xml.is_empty() - || p.borders.as_ref().is_some_and(|b| !b.extra_xml.is_empty()) - })) - || cell - .properties - .as_ref() - .is_some_and(|p| p.v_merge.is_some()) - { - return Err(Error::Other("merge cannot discard opaque cell metadata or existing vertical merge ownership".into())); + // A row's first cell keeps its properties, the others go. + let refused = if offset > 0 { + !cell_metadata_is_discardable(cell) + } else { + !cell.extra_xml.is_empty() + || cell + .properties + .as_ref() + .is_some_and(|p| p.v_merge.is_some()) + }; + if refused { + return Err(Error::Other( + "merge cannot discard opaque cell metadata or existing merge ownership" + .into(), + )); } } selected.push((first, last)); @@ -1210,18 +1267,8 @@ impl<'a> Table<'a> { let mut all_lone_empty = true; for (offset, (first, last)) in selected.iter().enumerate() { for cell in &candidate.rows[top + offset].cells[*first..=*last] { - let lone_empty = match cell.content.as_slice() { - [CellContent::Paragraph(paragraph)] => { - let mut payload = paragraph.clone(); - payload.properties = None; - payload.extra_xml.retain(|(position, raw)| { - !CT_P::raw_is_root_attributes(*position, raw) - }); - payload == CT_P::new() - } - _ => false, - }; - if !lone_empty { + // The metadata half of `cell_is_consumable` was checked above. + if !cell_content_is_lone_empty(cell) { all_lone_empty = false; content.extend(cell.content.clone()); } @@ -1815,7 +1862,8 @@ impl<'a> Table<'a> { /// Set the leading and trailing grid omissions for one row. /// - /// Increasing an omission removes only untouched empty edge cells. + /// Increasing an omission removes only edge cells that + /// `cell_is_consumable` admits. /// Decreasing it inserts empty cells with the corresponding grid widths. /// The complete table is validated before the candidate replaces the live /// value. @@ -1872,16 +1920,16 @@ impl<'a> Table<'a> { let cell = row.cells.first().ok_or_else(|| { Error::Other("table row has no leading cell to omit".to_owned()) })?; - if !cell_is_discardable_for_grid_edit(cell) { + if !cell_is_consumable(cell) { return Err(Error::Other( "table row cannot omit a nonempty leading cell".to_owned(), )); } - row.cells.remove(0); + remove_row_cell(row, 0); } } else { for column in (target_before..current_before).rev() { - row.cells.insert(0, empty_grid_cell(grid_widths[column])); + insert_row_cell(row, 0, empty_grid_cell(grid_widths[column])); } } @@ -1890,18 +1938,18 @@ impl<'a> Table<'a> { let cell = row.cells.last().ok_or_else(|| { Error::Other("table row has no trailing cell to omit".to_owned()) })?; - if !cell_is_discardable_for_grid_edit(cell) { + if !cell_is_consumable(cell) { return Err(Error::Other( "table row cannot omit a nonempty trailing cell".to_owned(), )); } - row.cells.pop(); + remove_row_cell(row, row.cells.len() - 1); } } else { let first_column = grid_widths.len() - current_after; let last_column = grid_widths.len() - target_after; for width in &grid_widths[first_column..last_column] { - row.cells.push(empty_grid_cell(*width)); + insert_row_cell_after_children(row, row.cells.len(), empty_grid_cell(*width)); } } @@ -1913,8 +1961,9 @@ impl<'a> Table<'a> { Ok(()) } - /// Set one cell's horizontal grid span and reconcile untouched cells that - /// enter or leave the span. + /// Set one cell's horizontal grid span. A widening span consumes only + /// cells that `cell_is_consumable` admits, and a narrowing one restores + /// empty cells. pub fn set_cell_grid_span_checked( &mut self, row_index: usize, @@ -1970,7 +2019,7 @@ impl<'a> Table<'a> { let next = row.cells.get(cell_index + 1).ok_or_else(|| { Error::Other("horizontal merge exceeds the row grid".to_owned()) })?; - if !cell_is_discardable_for_grid_edit(next) { + if !cell_is_consumable(next) { return Err(Error::Other( "horizontal merge cannot consume a nonempty cell".to_owned(), )); @@ -1988,12 +2037,15 @@ impl<'a> Table<'a> { "horizontal merge cuts through an existing span".to_owned(), )); } - row.cells.remove(cell_index + 1); + remove_row_cell(row, cell_index + 1); } } else if desired < current { for (offset, width) in grid_widths[(start + desired)..end].iter().enumerate() { - row.cells - .insert(cell_index + 1 + offset, empty_grid_cell(*width)); + insert_row_cell_after_children( + row, + cell_index + 1 + offset, + empty_grid_cell(*width), + ); } } let properties = row.cells[cell_index] @@ -3770,6 +3822,293 @@ mod tests { } } + fn issue446_row(xml: &str) -> CT_Row { + let xml = format!( + r#"{xml}"# + ); + let document = rdocx_oxml::CT_Document::from_xml(xml.as_bytes()).unwrap(); + let rdocx_oxml::document::BodyContent::Table(mut table) = + document.body.content.into_iter().next().unwrap() + else { + panic!("table fixture") + }; + table.rows.remove(0) + } + + fn issue446_cell(xml: &str) -> CT_Tc { + issue446_row(xml).cells.remove(0) + } + + /// Row-level markers and cell texts in physical order. + fn issue446_row_order(row: &CT_Row) -> Vec { + let mut order = Vec::new(); + for index in 0..=row.cells.len() { + for (_, raw) in row.extra_xml.iter().filter(|(at, _)| *at == index) { + let raw = String::from_utf8_lossy(raw); + let name = raw.trim_start_matches('<').split([' ', '/', '>']).next(); + order.push(name.unwrap_or_default().to_owned()); + } + if let Some(cell) = row.cells.get(index) { + let mut text = String::new(); + for content in &cell.content { + if let CellContent::Paragraph(paragraph) = content { + text.push_str(¶graph.text()); + } + } + order.push(text); + } + } + order + } + + /// Issue 446: every edit that consumes a cell applies one rule. A cell + /// that only paragraph properties, identity attributes or modeled cell + /// formatting distinguish from an empty one is consumed. Any other + /// content is never lost: a merge keeps it, a span or omission refuses. + /// Opaque cell XML refuses everywhere. + #[test] + fn issue446_every_cell_consuming_edit_shares_one_rule() { + #[derive(Debug, Clone, Copy, PartialEq)] + enum Expected { + Consumed, + Content, + Refused, + } + use Expected::*; + let rows = [ + ("empty", "", Consumed), + ( + "paragraph properties", + r#""#, + Consumed, + ), + ( + "paragraph mark run properties", + "", + Consumed, + ), + ( + "identity attributes", + r#""#, + Consumed, + ), + ( + "modeled cell formatting", + r#""#, + Consumed, + ), + ( + "empty run with properties", + "", + Content, + ), + ( + "bookmark only", + r#""#, + Content, + ), + ( + "comment anchor", + r#""#, + Content, + ), + ( + "text", + "kept", + Content, + ), + ("two empty paragraphs", "", Content), + ( + "tracked inserted paragraph mark", + r#""#, + Content, + ), + ( + "tracked deleted paragraph mark", + r#""#, + Content, + ), + ( + "tracked paragraph property change", + r#""#, + Content, + ), + ( + "section properties", + r#""#, + Content, + ), + ( + "opaque cell XML", + r#""#, + Refused, + ), + ]; + let total = issue432_paragraph("Total"); + let mut failures = Vec::new(); + for (label, xml, expected) in rows { + let consumed = issue446_cell(xml); + for entry in [ + "merge across", + "merge down", + "grid span", + "omit leading", + "omit trailing", + ] { + let vertical = entry == "merge down"; + let mut document = crate::Document::new(); + let mut table = + document.add_table(if vertical { 2 } else { 1 }, if vertical { 1 } else { 2 }); + let (kept, gone) = match entry { + "merge down" => ((0, 0), (1, 0)), + "omit leading" => ((0, 1), (0, 0)), + _ => ((0, 0), (0, 1)), + }; + table.inner.rows[kept.0].cells[kept.1].content = + vec![CellContent::Paragraph(total.clone())]; + table.inner.rows[gone.0].cells[gone.1] = consumed.clone(); + let before = table.inner.clone(); + let result = match entry { + "merge across" | "merge down" => table.merge_cells(kept, gone).map(|_| ()), + "grid span" => table.set_cell_grid_span_checked(0, 0, Some(2)), + "omit leading" => table.set_row_grid_omissions(0, Some(1), None), + _ => table.set_row_grid_omissions(0, None, Some(1)), + }; + let merge = entry.starts_with("merge"); + let survivor = + &table.inner.rows[0].cells[if entry == "omit leading" { 0 } else { kept.1 }]; + let outcome = match (&result, expected) { + (Err(_), Refused) | (Err(_), Content) if !merge || expected == Refused => { + *table.inner == before + } + (Ok(()), Consumed) => { + survivor.content == vec![CellContent::Paragraph(total.clone())] + && table + .inner + .rows + .iter() + .map(|row| row.cells.len()) + .sum::() + == if vertical { 2 } else { 1 } + } + (Ok(()), Content) if merge => { + survivor.content + == [ + vec![CellContent::Paragraph(total.clone())], + consumed.content.clone(), + ] + .concat() + } + _ => false, + }; + if !outcome { + failures.push(format!("{label} / {entry}: {expected:?} got {result:?}")); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); + // A span or an omission never drops a legacy horizontal merge cell, + // whose partners would dangle. A merge refuses any table holding one + // in its column-edit topology check, before any cell rule. + let legacy = + issue446_cell(r#""#); + for entry in ["merge across", "grid span", "omit trailing"] { + let mut document = crate::Document::new(); + let mut table = document.add_table(1, 2); + table.inner.rows[0].cells[1] = legacy.clone(); + let before = table.inner.clone(); + let result = match entry { + "merge across" => table.merge_cells((0, 0), (0, 1)).map(|_| ()), + "grid span" => table.set_cell_grid_span_checked(0, 0, Some(2)), + _ => table.set_row_grid_omissions(0, None, Some(1)), + }; + assert!(result.is_err(), "{entry}"); + assert_eq!(*table.inner, before, "{entry}"); + } + // Row-level range markers keep their cell boundaries when a span or + // an omission removes a Word-shaped empty cell or restores one. + let text = |value: &str| format!("{value}"); + let empty = r#""#; + let start = r#""#; + let mark = r#""#; + let end = r#""#; + for (entry, cells, expected) in [ + ( + "grid span", + format!("{start}{}{empty}{mark}{}{end}", text("Total"), text("end")), + vec![ + "w:permStart", + "Total", + "w:bookmarkStart", + "end", + "w:permEnd", + ], + ), + ( + "omit trailing", + format!("{start}{}{}{empty}{end}", text("Total"), text("end")), + vec!["w:permStart", "Total", "end", "w:permEnd"], + ), + ( + "omit leading", + format!("{start}{empty}{mark}{}{}{end}", text("Total"), text("end")), + vec![ + "w:permStart", + "w:bookmarkStart", + "Total", + "end", + "w:permEnd", + ], + ), + ] { + let mut document = crate::Document::new(); + let mut table = document.add_table(1, 3); + table.inner.rows[0] = issue446_row(&cells); + match entry { + "grid span" => table.set_cell_grid_span_checked(0, 0, Some(2)).unwrap(), + "omit trailing" => table.set_row_grid_omissions(0, None, Some(1)).unwrap(), + _ => table.set_row_grid_omissions(0, Some(1), None).unwrap(), + } + assert_eq!( + issue446_row_order(&table.inner.rows[0]), + expected, + "{entry}" + ); + // Restoring the cell round trips, except that markers at the row + // start stay leading. + match entry { + "grid span" => table.set_cell_grid_span_checked(0, 0, None).unwrap(), + _ => table.set_row_grid_omissions(0, None, None).unwrap(), + } + let restored = match entry { + "grid span" => { + vec![ + "w:permStart", + "Total", + "", + "w:bookmarkStart", + "end", + "w:permEnd", + ] + } + "omit trailing" => vec!["w:permStart", "Total", "end", "", "w:permEnd"], + _ => vec![ + "w:permStart", + "w:bookmarkStart", + "", + "Total", + "end", + "w:permEnd", + ], + }; + assert_eq!( + issue446_row_order(&table.inner.rows[0]), + restored, + "{entry} restore" + ); + } + } + #[test] fn issue432_added_cells_preserve_mark_priority_and_split_defaults() { for empty_source in [false, true] { diff --git a/docs/hld/04-opc-and-packaging.md b/docs/hld/04-opc-and-packaging.md index 818eb06f8..b1a72e7f1 100644 --- a/docs/hld/04-opc-and-packaging.md +++ b/docs/hld/04-opc-and-packaging.md @@ -1574,8 +1574,9 @@ split toggles including explicit false and removal, alignment, conditional regions, and leading or trailing grid omissions. Checked cell authoring covers width, borders, margins, shading, vertical alignment, text direction, conditional regions, wrapping, horizontal spans, vertical merges, and nested -tables. Topology-changing operations clone the complete table, reconcile only -untouched empty cells, validate positive grid widths, exact row coverage, and +tables. Topology-changing operations clone the complete table, consume only +cells that the shared consumable-cell rule admits, validate positive grid +widths, exact row coverage, and immediately adjacent vertical merge ranges, then replace the live table. Existing direct table rows clone and remove through a staged `Document` diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index 6dad9fff6..6b47556c5 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -630,7 +630,8 @@ document order, including those inside block content controls, so the handle is resolved from the inserted body position rather than assumed. Cells merge through the checked table operations, never through the unchecked cell span setter. `Table.set_cell_grid_span(row, col, span)` spans columns and absorbs -or restores untouched empty cells, and `None` or `1` removes the span. +the cells `Cell.merge` would drop or restores empty cells, and `None` or `1` +removes the span. `Table.set_cell_vertical_merge(row, col, merge)` writes `restart`, `continue` or `None` after validating the whole merge topology. Both take the possibly negative indexes `Table.cell` takes. A grid span that absorbs or restores @@ -2400,13 +2401,21 @@ lookalikes retain exact opaque XML and remain unmodeled. Typed serialization keeps the existing cell-property schema order and unsupported sibling slots. Operations whose validity depends on neighbouring cells live on `Table` and -take checked row and cell indexes. Grid omissions reconcile only untouched -empty edge cells. Horizontal spans consume or restore only untouched empty -cells. Vertical continuations require an equal grid range in the immediately -preceding row. Each operation validates a cloned complete table before -publication. These are additive pre-1.0 native APIs. WASM and CLI gain no row -or cell methods. Python binds the checked row and cell setters and the span -and vertical merge operations, as described under the Python API shape. +take checked row and cell indexes. Grid omissions, horizontal spans and +`Cell.merge` share one rule for a consumed cell: its content is one paragraph +that only paragraph properties or identity attributes distinguish from an +empty one, with no tracked mark, tracked property or numbering change and +no section properties, and it carries no opaque cell XML and no vertical +merge ownership. Its modeled formatting goes with it. Spans and omissions +refuse any other cell, and also a legacy horizontal merge cell. A merge +refuses a cell whose metadata cannot go and keeps any other content. Spans +and omissions keep row-level markers at their cell boundaries, and restore +empty cells. Vertical continuations require an equal grid range in the +immediately preceding row. +Each operation validates a cloned complete table before publication. These +are additive pre-1.0 native APIs. WASM and CLI gain no row or cell methods. +Python binds the checked row and cell setters and the span and vertical merge +operations, as described under the Python API shape. Row cloning and removal depend on package-wide identities, so the additive native operations live on `Document` as `clone_table_row(table, source, From 77c101edd5a8394daf9a993aaa0154285cdb7e4d Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 08:29:42 +0100 Subject: [PATCH 3/3] record the archive measurements The rdocx and rdocx-cli archives grow with the issue 446 changes and their tests, on main eb980e94. They are the only crates whose member bytes change. Both rows take the measurement date 2026-11-16. Tests, python3 scripts/readme_doctests.py Harness, unchanged, measurements only --- README.md | 2 +- crates/rdocx-cli/README.md | 2 +- scripts/readme_doctests.py | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 0f39a02a2..8ec7cca53 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ The archive row uses `cargo package --locked --allow-dirty --no-verify` with all | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx | 4,501,789 compressed bytes, 56,396,845 member bytes, 37 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-09 | +| Crates.io archive: rdocx | 4,511,214 compressed bytes, 56,437,697 member bytes, 37 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-16 | | Large-document layout throughput | minimum 250 pages/s, observed 31,019.1 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | | Large-document layout peak allocation | maximum 64 MiB, observed 29.03 MiB | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | peak live allocation | 2026-09-19 | | Large-document PDF throughput | minimum 1,000 pages/s, observed 60,058.0 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 deterministic layout pages | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | diff --git a/crates/rdocx-cli/README.md b/crates/rdocx-cli/README.md index dfda4eb84..f9838de38 100644 --- a/crates/rdocx-cli/README.md +++ b/crates/rdocx-cli/README.md @@ -48,7 +48,7 @@ The archive row uses `cargo package --locked --allow-dirty --no-verify` with all | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx-cli | 126,182 compressed bytes, 593,817 member bytes, 8 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx-cli` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-07 | +| Crates.io archive: rdocx-cli | 126,250 compressed bytes, 594,231 member bytes, 8 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx-cli` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-16 | ## Use it when diff --git a/scripts/readme_doctests.py b/scripts/readme_doctests.py index bf17a18d9..1cde40192 100644 --- a/scripts/readme_doctests.py +++ b/scripts/readme_doctests.py @@ -376,8 +376,8 @@ class ReadmeCase: "oxml-opc": "2026-11-06", "oxml-pdf": "2026-11-06", "oxml-sml": "2026-11-06", - "rdocx": "2026-11-09", - "rdocx-cli": "2026-11-07", + "rdocx": "2026-11-16", + "rdocx-cli": "2026-11-16", "rdocx-html": "2026-11-06", "rdocx-layout": "2026-11-09", "rdocx-opc": "2026-11-06", @@ -402,8 +402,8 @@ class ReadmeCase: "oxml-opc": (119_252, 486_417, 12), "oxml-pdf": (102_219, 478_926, 14), "oxml-sml": (24_956, 115_575, 6), - "rdocx": (4_501_789, 56_396_845, 37), - "rdocx-cli": (126_182, 593_817, 8), + "rdocx": (4_511_214, 56_437_697, 37), + "rdocx-cli": (126_250, 594_231, 8), "rdocx-html": (29_407, 118_370, 11), "rdocx-layout": (463_844, 2_543_127, 15), "rdocx-opc": (3_943, 10_694, 6),