Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge branch 'find-change-find-format' into find-change-change-find

moppeeer6eb426621403
diff --cc crates/engine/src/cmd/find.rs
index 17ca69eaa,18b0b0342..a6950b1d4
--- a/crates/engine/src/cmd/find.rs
+++ b/crates/engine/src/cmd/find.rs
@@@ -61,7 -61,7 +61,7 @@@ pub fn specs() -> Vec<CommandSpec>
}
),
cmd!(query "find.find", "Find", ["Edit", "Find/Change"], None,
- "{find, grep?: bool, caseSensitive?: bool, wholeWord?: bool, scope?: document|story|selection, story?, findFormat?: {charStyle?, paraStyle?, chars?: resolved character attributes} (Find Format: only text with it all through; with an empty find, each stretch of text with it), change?|first?|found?|attrs?|charStyle?|paraStyle?: ignored (find.change takes them; one request serves all three Find/Change commands)} → matches [{story, start, end, text}]",
- "{find, grep?: bool, caseSensitive?: bool, wholeWord?: bool, scope?: document|story|selection, story?, findFormat?: {charStyle?, paraStyle?, chars?: resolved character attributes} (Find Format: only text with it all through; with an empty find, each stretch of text with it), change?|first?|attrs?|charStyle?|paraStyle?: ignored (find.change takes them; one request serves all three Find/Change commands)} → matches [{story, start, end, text, cell?: {table, row, col}}] (document scope also searches table cells; start/end then index the cell's text)",
++ "{find, grep?: bool, caseSensitive?: bool, wholeWord?: bool, scope?: document|story|selection, story?, findFormat?: {charStyle?, paraStyle?, chars?: resolved character attributes} (Find Format: only text with it all through; with an empty find, each stretch of text with it), change?|first?|found?|attrs?|charStyle?|paraStyle?: ignored (find.change takes them; one request serves all three Find/Change commands)} → matches [{story, start, end, text, cell?: {table, row, col}}] (document scope also searches table cells; start/end then index the cell's text)",
has_doc, find),
cmd!(
"find.change",
@@@ -271,33 -272,6 +272,34 @@@ impl Search
}
}
+ /// The edit Change makes when the selection `range` (offsets in `text`, target `r` of story
+ /// `sid`) is what Find Next found there, so the two commands agree on what a match is. With
+ /// no pattern: a selection inside one stretch with the Find Format (Find Next selects the rest
+ /// of a stretch from inside it). With a pattern: the match it makes from the selection's start
+ /// must be the selection, overlapping matches Find Next can select included.
+ #[allow(clippy::too_many_arguments)]
+ fn found_edit(
+ &self,
+ d: &Document,
+ sid: StoryId,
++ cell: Option<CellAddr>,
+ r: &Range<usize>,
+ text: &str,
+ range: &Range<usize>,
+ rep: &str,
+ grep: bool,
+ ) -> Result<Option<(Range<usize>, String)>> {
- let spans = self.spans(d, sid, r);
++ let spans = self.spans(d, sid, cell, r);
+ let Some(re) = &self.re else {
+ let inside = !range.is_empty() && spans.unwrap_or_default().iter().any(|s| s.start <= range.start && range.end <= s.end);
+ return Ok(inside.then(|| (range.clone(), rep.to_string())));
+ };
+ let found =
+ if grep { re.replacement_at(text, range.start, rep) } else { re.find_at(text, range.start).map(|m| m.map(|m| (m, rep.to_string()))) };
+ let found = found.map_err(|e| bad("find.change", e))?;
+ Ok(found.filter(|(m, _)| m == range && spans.as_ref().is_none_or(|s| within(s, m))))
+ }
+
/// The edits Change All makes in `text` (target `r` of story `sid`): `rep` expanded for each
/// GREP match, else `rep` itself.
#[allow(clippy::too_many_arguments)]
@@@ -400,25 -378,6 +406,29 @@@ impl FindContext
self.selection = st.selection.clone();
}
+ /// After Change put `new_len` bytes in place of `old` in story `sid`: the domain keeps the
+ /// changed text and the search goes on after it.
- fn after_change(&mut self, st: &DocState, sid: StoryId, old: &Range<usize>, new_len: usize) {
++ fn after_change(&mut self, st: &DocState, sid: StoryId, cell: Option<CellAddr>, old: &Range<usize>, new_len: usize) {
+ let moved = |x: usize| if x >= old.end { x - old.len() + new_len } else { x };
- for (tid, r) in &mut self.targets {
- if *tid == sid {
++ for (tid, tcell, r) in &mut self.targets {
++ if *tid == sid && *tcell == cell {
+ *r = moved(r.start)..moved(r.end);
+ }
+ }
+ self.offset = old.start + new_len;
+ self.last_match_end = Some(self.offset);
+ let at = self.offset;
- if let Some(i) = self.order.iter().position(|i| self.targets.get(*i).is_some_and(|(tid, r)| *tid == sid && r.start <= at && at <= r.end)) {
++ if let Some(i) = self
++ .order
++ .iter()
++ .position(|i| self.targets.get(*i).is_some_and(|(tid, tcell, r)| *tid == sid && *tcell == cell && r.start <= at && at <= r.end))
++ {
+ self.target = i;
+ }
+ self.document = Arc::downgrade(&st.doc);
+ self.acknowledge(st);
+ }
+
fn restart(&mut self, st: &DocState) -> Result<()> {
self.target = 0;
self.last_match_end = None;
@@@ -567,58 -545,20 +596,58 @@@ fn change(s: &mut Session, p: &Value) -
}
// InDesign: with a Change Format and nothing in Change to, the found text is only formatted.
let format_only = str_param(p, "change").unwrap_or("").is_empty() && (char_style.is_some() || para_style.is_some() || !over.is_empty());
- let targets = scope(s, p)?.targets;
- s.edit(|d, sel| {
+ let context = scope(s, p)?;
+ let targets = context.targets.clone();
+ // Change: only the text Find Next found, the selection, while it is still a match (as Find
+ // Next defines one), with its replacement.
+ let (found, found_out) = if bool_or(p, "found", false) {
+ let st = s.doc()?;
- let selected = st.selection.text.filter(|t| t.cell.is_none() && !t.is_caret()).map(|t| (t.story, t.range()));
- let hit = selected.and_then(|(sid, range)| {
- targets.iter().find_map(|(tid, r)| {
- if *tid != sid || range.start < r.start || r.end < range.end {
++ let selected = st.selection.text.filter(|t| st.selection.cells.is_none() && !t.is_caret()).map(|t| (t.story, t.cell, t.range()));
++ let hit = selected.and_then(|(sid, cell, range)| {
++ targets.iter().find_map(|(tid, tcell, r)| {
++ if *tid != sid || *tcell != cell || range.start < r.start || r.end < range.end {
+ return None;
+ }
- let text = target_text(&st.doc, *tid, r).ok()?;
++ let text = target_text(&st.doc, *tid, cell, r).ok()?;
+ let local = range.start - r.start..range.end - r.start;
- let (m, out) = re.found_edit(&st.doc, *tid, r, text, &local, &rep, grep).ok()??;
- Some(((sid, r.start + m.start..r.start + m.end), out))
++ let (m, out) = re.found_edit(&st.doc, *tid, cell, r, text, &local, &rep, grep).ok()??;
++ Some(((sid, cell, r.start + m.start..r.start + m.end), out))
+ })
+ });
+ match hit {
+ Some((hit, out)) => (Some(hit), Some(out)),
+ None => return Ok(json!({"count": 0})),
+ }
+ } else {
+ (None, None)
+ };
+ let (count, changed) = s.edit(|d, sel| {
let styles = d.styles.clone();
let mut count = 0usize;
+ let mut changed = None;
- for (sid, r) in targets {
- if found.as_ref().is_some_and(|(at, _)| *at != sid) {
+ for (sid, cell, r) in targets {
++ if found.as_ref().is_some_and(|(at, in_cell, _)| *at != sid || *in_cell != cell) {
+ continue;
+ }
- let Some(story) = d.story(sid) else { continue };
+ let Some(story) = d.text_story(sid, cell) else { continue };
// Collect matches first (positions refer to the original text), apply back to front.
let text = story.text.get(r.clone()).ok_or_else(|| bad("find", "invalid selection bounds or UTF-8 boundary"))?;
- let edits: Vec<(std::ops::Range<usize>, String)> = re
- .replacements(d, sid, cell, &r, text, &rep, grep, first_only)?
- .into_iter()
- .map(|(m, out)| (r.start + m.start..r.start + m.end, out))
- .collect();
+ let edits: Vec<(std::ops::Range<usize>, String)> = match (&found, &found_out) {
+ // Change: the found text alone, in the target it lies in.
- (Some((_, range)), Some(out)) => {
++ (Some((_, _, range)), Some(out)) => {
+ if r.start <= range.start && range.end <= r.end {
+ vec![(range.clone(), out.clone())]
+ } else {
+ Vec::new()
+ }
+ }
+ _ => re
- .replacements(d, sid, &r, text, &rep, grep, first_only)?
++ .replacements(d, sid, cell, &r, text, &rep, grep, first_only)?
+ .into_iter()
+ .map(|(m, out)| (r.start + m.start..r.start + m.end, out))
+ .collect(),
+ };
- let Some(st) = d.story_mut(sid) else { continue };
+ let Some(st) = d.text_story_mut(sid, cell) else { continue };
for (range, new) in edits.iter().rev() {
let changed = if format_only {
range.clone()
@@@ -652,29 -592,13 +681,29 @@@
}
(t.anchor, t.focus) = if t.anchor <= t.focus { (start, end) } else { (end, start) };
}
+ // Change leaves the changed text selected.
- if let Some((_, range)) = &found
++ if let Some((_, _, range)) = &found
+ && let Some((_, new)) = edits.first()
+ && let Some(t) = sel.text.as_mut()
+ {
+ let len = if format_only { range.len() } else { new.len() };
+ (t.anchor, t.focus) = (range.start, range.start + len);
+ changed = Some(len);
+ }
// `first` is the first match of the whole search, not of each story.
if first_only && count > 0 {
break;
}
}
- Ok(json!({"count": count}))
- })
+ Ok((count, changed))
+ })?;
+ // Change: Find Next goes on after the changed text, in the search's domain.
- if let (Some((sid, old)), Some(len)) = (&found, changed) {
++ if let (Some((sid, cell, old)), Some(len)) = (&found, changed) {
+ let mut context = context;
- context.after_change(s.doc()?, *sid, old, len);
++ context.after_change(s.doc()?, *sid, *cell, old, len);
+ s.find_context = Some(context);
+ }
+ Ok(json!({"count": count}))
}
fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
@@@ -1511,6 -1370,31 +1545,52 @@@ mod tests
assert_eq!(s.doc().unwrap().history.undo.len(), history);
}
+ #[test]
+ fn document_scope_searches_and_changes_table_cells() {
+ let (mut s, sid) = scope_session("Ore 12.15 here");
+ scope_select(&mut s, sid, 0, 0);
+ let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap();
+ s.execute("table.setCell", &json!({"row": 0, "col": 1, "text": "Ore 12.15"})).unwrap();
+ // The caret sits in the first cell, so Find Next goes to the second cell, then the story.
+ let p = json!({"find": "Ore 12.15", "scope": "document"});
+ let cell = designcraft_doc::CellAddr { table, row: 0, col: 1 };
+ assert_eq!(s.execute("find.next", &p).unwrap(), json!({"story": sid.0, "start": 0, "end": 9, "cell": {"table": table, "row": 0, "col": 1}}));
+ assert_eq!(s.doc().unwrap().selection.text.map(|t| (t.story, t.range(), t.cell)), Some((sid, 0..9, Some(cell))));
+ let next = s.execute("find.next", &p).unwrap();
+ assert!(next.get("start").is_some() && next.get("cell").is_none(), "{next}");
+ let hits = s.execute("find.find", &p).unwrap();
+ let hits = hits.as_array().unwrap();
+ assert_eq!(hits.len(), 2);
+ let in_cell: Vec<_> = hits.iter().filter(|h| h.get("cell").is_some()).collect();
+ assert_eq!(in_cell.len(), 1);
+ assert_eq!((in_cell[0]["cell"]["row"].as_u64(), in_cell[0]["cell"]["col"].as_u64()), (Some(0), Some(1)));
+ let n = s.execute("find.change", &json!({"find": "Ore 12.15", "change": "Ore 13.00", "scope": "document"})).unwrap();
+ assert_eq!(n["count"], 2);
+ assert!(s.execute("find.find", &json!({"find": "12.15", "scope": "document"})).unwrap().as_array().unwrap().is_empty());
+ assert_eq!(s.execute("find.find", &json!({"find": "13.00", "scope": "document"})).unwrap().as_array().unwrap().len(), 2);
+ }
+
++ /// Change (`found`) on text Find Next found in a table cell changes it there, leaves the
++ /// same text in the story alone, and Find Next goes on after it.
++ #[test]
++ fn change_changes_the_text_find_next_found_in_a_cell() {
++ let (mut s, sid) = scope_session("red here");
++ scope_select(&mut s, sid, 0, 0);
++ let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap();
++ s.execute("table.setCell", &json!({"row": 0, "col": 1, "text": "red"})).unwrap();
++ let p = json!({"find": "red", "change": "blue", "scope": "document"});
++ let hit = s.execute("find.next", &p).unwrap();
++ assert_eq!(hit["cell"], json!({"table": table, "row": 0, "col": 1}), "{hit}");
++ let mut change = p.clone();
++ change["found"] = json!(true);
++ assert_eq!(s.execute("find.change", &change).unwrap()["count"], 1);
++ let t = s.execute("table.get", &json!({"table": table})).unwrap();
++ assert_eq!(t["cells"][1]["text"], "blue");
++ assert!(s.doc().unwrap().doc.story(sid).unwrap().text.contains("red here"), "the story's red stays");
++ let next = s.execute("find.next", &p).unwrap();
++ assert!(next.get("cell").is_none() && next.get("start").is_some(), "on to the story: {next}");
++ }
++
fn child_scope_session(note: bool, child: &str) -> (Session, designcraft_doc::StoryId, designcraft_doc::TextSel) {
let (mut s, sid) = scope_session("red");
scope_select(&mut s, sid, 3, 3);