Compare commits

...
Author SHA1 Message Date
autocraft-bot[bot] 0c0182b587 Merge main (8d75a12b) into the pull request
Both conflicts are resolved. `edit.replaceAll` still replaces in the mai

Both conflicts are resolved. `edit.replaceAll` still replaces in the main text, headers, footers, footnotes, endnotes and text boxes, and in a protected document only in the editable regions. In each of those stories it now also applies the default branch's smart-quote behaviour: a quote typed in the replacement is curled, and matches that already read that way are skipped and not counted. The command's parameter help keeps both descriptions, and the tests keep the default branch's new tests plus this pull request's test.

`cargo fmt --check` and clippy for `wordcraft-engine` (all targets) pass. The engine library tests had 1769 passes and 3 failures. The Replace All, protection and smart-quote tests I checked in the log pass.

The 3 failures:
- `rerouting_many_pages_does_not_rescan_all_objects_per_connector` is a timing limit. It passed when run again with only the other two failing tests.
- `swiss_german_and_portugal_portuguese_keep_their_languages_rules` fails again on rerun, at "German hyphenates Zusammenarbeit".
- `page_down_and_up_never_stay_on_a_line_in_the_continuous_views` fails again on rerun, at Page Up in draft view.

Neither of the last two tests calls Replace All. I did not run them on the default branch alone, so I have not confirmed that they already fail there.

One rare case where the two features meet was found by reading the code and is left unchanged. In a protected document, suppose a skipped match in locked text directly touches a match in an editable region. A quote typed in the replacement would then be curled as if the locked match had also been replaced.
2026-12-03 20:44:21 +00:00
autocraft-bot[bot] b3302eeef3 Part 1: in a document protected as read only, comments only or forms, Re
Part 1: in a document protected as read only, comments only or forms, Replace All now keeps only the matches inside the editable regions, in every story. A placeholder repeated in a header, footer, footnote or text box, or in locked body text, is left alone instead of making the whole command fail. The editable matches are replaced as before. I added `editable_ranges` in cmd/protect.rs: exception ranges the author may edit for read only and comments, and the interiors of fillable controls for forms. `replace_all` in cmd/edit.rs filters each story's matches through it before the locked-content check and the replacement. I added the test `replace_all_in_a_protected_document_skips_protected_matches` in cmd/protect/tests.rs, with an editable body region and `[NAME]` in a header, a footnote and locked body text. I did not check that it fails without the fix. `cargo fmt --all --check` is clean. The six `replace_all` tests pass, including the new one. The full engine test run was 1215 passed and 2 failed. The failures are `page_down_and_up_never_stay_on_a_line_in_the_continuous_views` and `rerouting_many_pages_does_not_rescan_all_objects_per_connector`. Neither touches Replace All, and I did not re-run them on the base commit. `cargo clippy -p wordcraft-engine --all-targets -- -D warnings` stops on one existing needless-range-loop lint at cmd/table_draw.rs:768, which I did not touch. I did not run clippy without test targets. One behaviour change: matches in locked body text of a protected document are now skipped silently. Before, they made the whole command fail.
2026-12-02 19:34:24 +00:00
Dhruv 8e90f8f336 Replace All replaces in every story: headers, footers, footnotes, endnotes and text boxes (#3300) 2026-11-04 10:29:46 -06:00
4 changed files with 134 additions and 10 deletions
+40 -10
View File
@@ -161,7 +161,7 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"tab"?: "find|replace|goto" (default replace)}"#)
.pure(),
CommandSpec::new("edit.replaceAll", "Replace All", "Home › Editing › Replace", replace_all)
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted)"#),
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted); replaces in the main text, headers, footers, footnotes, endnotes and text boxes, wherever the caret is"#),
CommandSpec::new("edit.goto", "Go To", "Home › Editing › Find", goto)
.key("Mod+Alt+G / F5")
.params(r#"{"page"?: n, "pageBy"?: int (pages forward, negative back, from the caret's page), "bookmark"?: string (selects its text), "paragraph"?: n}; none opens Find and Replace on its Go To tab"#)
@@ -827,16 +827,47 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
}
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
/// the replacement (`^p`) splits the paragraph.
/// The stories Replace All covers, as in Word: the main text, then headers, footers, footnotes,
/// endnotes and text boxes. Comments keep their words.
fn replace_stories(s: &Session) -> Vec<StoryRef> {
use wordcraft_doc::PartKind;
let parts = s.doc.parts.iter().filter(|(_, p)| !matches!(p.kind, PartKind::Comment)).map(|(id, _)| StoryRef::Part(*id));
std::iter::once(StoryRef::Body).chain(parts).collect()
}
/// Every match in every story replaced (wherever the caret is), last first so earlier positions
/// stay valid (one undo step). A `\r` in the replacement (`^p`) splits the paragraph. Locked
/// content in any story stops it before anything changes.
fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
need_query(s, v)?;
read_opts(s, v);
let story = s.sel.focus.story;
// Matches already curled as the replacement would curl them are left and not counted (#7307).
let results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
let n = results.len();
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
let mut found = Vec::new();
// A protected document only lets the editable regions change: matches elsewhere (in a header,
// say) stay as they are, so they don't make the whole command fail.
let editable = super::protect::editable_ranges(s);
for story in replace_stories(s) {
// Matches already curled as the replacement would curl them are left and not counted (#7307).
let mut results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
if let Some(ranges) = &editable {
results.retain(|f| ranges.iter().any(|(from, to)| f.a.story == from.story && f.a >= *from && f.b <= *to));
}
if results.is_empty() {
continue;
}
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
found.push(results);
}
let n: usize = found.iter().map(Vec::len).sum();
// The main text comes last, so under Track Changes the caret ends where it did before.
for results in found.into_iter().rev() {
replace_found(s, results)?;
}
s.status = format!("All done. We made {n} replacements.");
Ok(json!({"replaced": n}))
}
/// Replace the matches of one story, last first.
fn replace_found(s: &mut Session, results: Vec<Found>) -> Result<(), CmdError> {
for Found { a, b, rep, .. } in results.into_iter().rev() {
let with = rep.unwrap_or_default();
if s.doc.settings.track_changes {
@@ -857,8 +888,7 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
}
}
}
s.status = format!("All done. We made {n} replacements.");
Ok(json!({"replaced": n}))
Ok(())
}
fn goto(s: &mut Session, v: &Value) -> CmdResult {
+21
View File
@@ -695,6 +695,27 @@ pub(crate) fn typing_pos(s: &Session, p: &Pos) -> Pos {
Pos { off, ..p.clone() }
}
/// The ranges, in any story, that a document protected as read only, comments only or forms
/// lets this author edit; `None` when the protection doesn't limit where edits may land. A command
/// that searches the whole document keeps only its matches inside them, so a match in protected
/// content (a header repeating a placeholder) is left alone instead of failing the command.
pub(crate) fn editable_ranges(s: &Session) -> Option<Vec<(Pos, Pos)>> {
match s.doc.settings.protection.as_deref()? {
"forms" => {
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
Some(
stories
.flat_map(|story| s.doc.control_ranges(story))
.filter(|r| r.control.lock.can_edit())
.map(|r| (r.content_start(), r.end))
.collect(),
)
}
"readOnly" | "comments" => Some(s.doc.perm_ranges().into_iter().filter(|r| editable_by(r, &s.author)).map(|r| (r.start, r.end)).collect()),
_ => None,
}
}
/// The first position in an editable range after `from` (wrapping round), for Find Next Region
/// I Can Edit; with it, the range's end. Filling in forms: the next fillable control's content.
pub fn next_region(s: &Session, from: &Pos) -> Option<(Pos, Pos)> {
+23
View File
@@ -32,6 +32,29 @@ fn read_only_with_an_exception_allows_edits_only_inside_it() {
assert_eq!(s.doc.settings.protection.as_deref(), Some("readOnly"));
}
/// Replace All covers every story, but in a protected document only the editable regions change:
/// the same placeholder in a header, a footnote or the locked body text is left as it is, and
/// the replacement in the editable region still goes through.
#[test]
fn replace_all_in_a_protected_document_skips_protected_matches() {
use wordcraft_doc::{CharProps, Paragraph, PartKind, para_block};
let mut s = Session::new(Document::from_text("Locked [NAME].\nFill [NAME] in."));
let header = s.doc.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("Header [NAME]", CharProps::default()))]);
let note = s.doc.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text(" Note [NAME]", CharProps::default()))]);
select(&mut s, "Fill [NAME] in.");
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
let r = s.run("edit.replaceAll", &json!({"text": "[NAME]", "with": "Jane"})).unwrap();
assert_eq!(r["replaced"], 1, "{r}");
let body = s.doc.plain_text(StoryRef::Body).replace(OBJ, "");
assert!(body.contains("Locked [NAME]."), "{body}");
assert!(body.contains("Fill Jane in."), "{body}");
for id in [header, note] {
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
assert!(s.doc.para_at(&first).unwrap().text.contains("[NAME]"));
}
}
/// An exception that starts a line: Home, Left and Down put the caret before its start
/// marker, and Enter and typing there go inside the exception. A caret after the end marker at
/// the end of the line goes back inside it too.
+50
View File
@@ -16220,3 +16220,53 @@ fn nested_group_text_box_survives_mutating_session_commands() {
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
}
}
/// #3300: Replace All, as in Word, replaces in the main text, headers, footers, footnotes,
/// endnotes and text boxes, wherever the caret is. Comments keep their words.
#[test]
fn replace_all_replaces_in_every_story() {
use wordcraft_doc::{CharProps, Paragraph, PartKind, StoryRef, para_block};
let story_text = |t: &Session, story: StoryRef| {
let first = wordcraft_doc::Pos::new(story, wordcraft_doc::Path::top(0), 0);
if story == StoryRef::Body { t.doc.plain_text(story) } else { t.doc.para_at(&first).map(|p| p.text.clone()).unwrap_or_default() }
};
let build = || {
let mut t = s();
run(&mut t, "document.setText", json!({"text": "Body: [NAME] and [NAME]."}));
// A text box the body shows (one nothing shows is pruned with the next command).
let boxed = run(&mut t, "insert.textBox", json!({"text": "Text box: [NAME]"}))["story"].as_u64().unwrap() as u32;
let mut add = |kind, text: &str| t.doc.add_part(kind, vec![para_block(Paragraph::with_text(text, CharProps::default()))]);
let ids = [
add(PartKind::Header, "Header: [NAME]"),
add(PartKind::Footer, "Footer: [NAME]"),
add(PartKind::Footnote, " Footnote: [NAME]"),
add(PartKind::Endnote, " Endnote: [NAME]"),
boxed,
add(PartKind::Comment, "Comment: [NAME]"),
];
(t, ids)
};
let (mut t, ids) = build();
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 7, "{r}");
assert_eq!(story_text(&t, StoryRef::Body), "Body: Jane and Jane.");
let texts: Vec<String> = ids.iter().map(|id| story_text(&t, StoryRef::Part(*id))).collect();
assert_eq!(texts, ["Header: Jane", "Footer: Jane", " Footnote: Jane", " Endnote: Jane", "Text box: Jane", "Comment: [NAME]"]);
// One undo step brings every story back.
run(&mut t, "edit.undo", json!({}));
assert_eq!(story_text(&t, StoryRef::Body), "Body: [NAME] and [NAME].");
assert_eq!(story_text(&t, StoryRef::Part(ids[0])), "Header: [NAME]");
assert_eq!(story_text(&t, StoryRef::Part(ids[2])), " Footnote: [NAME]");
// From the caret in a footnote the body is replaced too.
let (mut t, ids) = build();
t.sel = crate::session::Selection::caret(wordcraft_doc::Pos::new(StoryRef::Part(ids[2]), wordcraft_doc::Path::top(0), 0));
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 7, "{r}");
assert_eq!(story_text(&t, StoryRef::Body), "Body: Jane and Jane.");
// Under Track Changes the replacements are revisions in every story, and nothing breaks.
let (mut t, ids) = build();
run(&mut t, "review.trackChanges", json!({"enabled": true}));
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 7, "{r}");
assert!(story_text(&t, StoryRef::Part(ids[0])).contains("Jane"));
}