mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-03 22:40:27 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c0182b587 | ||
|
|
b3302eeef3 | ||
|
|
8e90f8f336 |
@@ -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 {
|
||||
|
||||
@@ -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)> {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user