Skip to content

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

Find/Change: Find Format (PR #1497's own change on main's Find/Change)

aiongg6561878d9f82
diff --git a/ROADMAP.md b/ROADMAP.md
index 52bfb0f3b..ed98bb2f1 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -464,6 +464,7 @@ Newest first.
- **2026-10-21** · Paragraph rules have InDesign's Type (solid, thick/thin stripes, dashed, dotted, straight hash, wavy, or a stroke style of the document), Gap Color and Gap Tint, and Keep In Frame (rule above); the Paragraph Rules page is laid out as InDesign's (Weight and Type, Color and Tint, Gap Color and Gap Tint, Width and Offset, Left and Right Indent). IDML reads and writes them (`RuleAboveType`, `RuleBelowGapColor`, `KeepRuleAboveInFrame`…). Found in the Learn Skills Daily course, chapter 20. No readiness percentage change.
- **2026-10-21** · New Character Style with text selected starts from what the text has of its own over its paragraph style, as InDesign's ("[None] + Bold + color"), and Apply Style to Selection gives the text the new style, with no override left. A new style's dialog is titled New Paragraph Style / New Character Style. `type.selectionAttrs` reports the text's own character attributes (`ownChars`). Found in the Learn Skills Daily course, chapter 22. No readiness percentage change.
- **2026-10-21** · New Paragraph Style with text selected starts from it, as InDesign's (Based On [No Paragraph Style], every setting of the text that differs) and Apply Style to Selection gives the paragraph the new style; General has Next Style and Reset To Base; Basic Character Formats is in two columns (Size | Leading, Kerning | Tracking, Case | Position). `style.paragraph.edit` honours `nextStyle` (it was ignored) and takes `resetToBase`. Found in the Learn Skills Daily course, chapter 20. No readiness percentage change.
+- **2026-10-21** · Find/Change has InDesign's Find Format: Specify Attributes opens Find Format Settings (the same Style Options and character sections as Change Format Settings), and only text with the format is found. With nothing in Find what, each stretch of text with the format is found, so Change All can restyle every word in a character style. `find.find`, `find.next` and `find.change` take `findFormat {charStyle?, paraStyle?, chars?}`. Found in the Learn Skills Daily course, chapter 22. No readiness percentage change.
- **2026-10-21** · Find/Change has InDesign's Change Format. Specify Attributes opens Change Format Settings: Style Options (the character and paragraph style to apply, [Any Style] for none), then Basic and Advanced Character Formats, Character Color, OpenType Features, Underline and Strikethrough Options. The box shows the format ("Character Style: eggs"), and Change All gives it to the changed text. With a Change Format and nothing in Change to, the found text stays and is only formatted, as InDesign's (an ⓘ beside Change to says so). `find.change` takes `charStyle` and `paraStyle`. Found in the Learn Skills Daily course, chapter 22. No readiness percentage change.
- **2026-10-21** · Preferences › Interface follows InDesign's: Appearance has a Color Theme swatch per interface theme (a click shows it at once, Cancel goes back) and Panels sets the Tools panel to a single or double column; UI Size moves to a UI Scaling section of its own. Interface held only UI Size, and the theme could be changed only from the Window menu. Found in the Learn Skills Daily course, chapter 26. No readiness percentage change.
- **2026-10-21** · Preferences › File Handling shows Number of Recent Items to Display as a whole number ("20"; it read "20.0"). Found in the Learn Skills Daily course, chapter 26. No readiness percentage change.
diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs
index aa6475f26..6c0be2cd9 100644
--- a/crates/engine/src/cmd/find.rs
+++ b/crates/engine/src/cmd/find.rs
@@ -1,12 +1,12 @@
//! Edit → Find/Change: plain text and GREP (regular expressions) with InDesign's metacharacters,
-//! optional formatting in the change, scoped to the document, a story or the selection.
+//! a Find Format and a Change Format, scoped to the document, a story or the selection.
use std::ops::Range;
use std::sync::{Arc, Weak};
use designcraft_compose::grep::{Grep, GrepOptions, translate_replacement};
use designcraft_doc::story::floor_char_boundary;
-use designcraft_doc::{CellAddr, Document, Selection, StoryId, TextSel};
+use designcraft_doc::{CellAddr, Document, Selection, Story, StoryId, Styles, TextSel};
use serde_json::{Value, json};
use super::{CommandSpec, bad, bool_or, cmd, has_doc, str_param};
@@ -61,18 +61,18 @@ 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?, 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?|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",
"Change All",
["Edit", "Find/Change"],
None,
- "{find, change, grep?, caseSensitive?, wholeWord?, scope?, story?, first?: bool (change only the first match), attrs?: {character attributes applied to changed text}, charStyle?: a character style applied to it, paraStyle?: a paragraph style applied to its paragraphs} → {count} — attrs, charStyle and paraStyle are the Change Format: with one and an empty change, the found text stays and is only formatted",
+ "{find, change, grep?, caseSensitive?, wholeWord?, scope?, 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), first?: bool (change only the first match), attrs?: {character attributes applied to changed text}, charStyle?: a character style applied to it, paraStyle?: a paragraph style applied to its paragraphs} → {count} — attrs, charStyle and paraStyle are the Change Format: with one and an empty change, the found text stays and is only formatted; with no find, change is literal text",
has_doc,
change
),
- cmd!(noundo "find.next", "Find Next", ["Edit"], Some("Cmd+Alt+F"), "{find, grep?, caseSensitive?, wholeWord?, scope?: document|story|selection, story?, change?|first?|attrs?|charStyle?|paraStyle?: ignored (find.change takes them; one request serves all three Find/Change commands)} — Selection starts at its original beginning; later calls advance within the scope", has_doc, find_next),
+ cmd!(noundo "find.next", "Find Next", ["Edit"], Some("Cmd+Alt+F"), "{find, grep?, caseSensitive?, wholeWord?, 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)} — Selection starts at its original beginning; later calls advance within the scope", has_doc, find_next),
]
}
@@ -108,6 +108,199 @@ fn build(p: &Value) -> Result<Grep> {
re.map_err(|e| bad("find", e))
}
+/// Find/Change's Find Format: the text a search finds must have it all through.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+struct FindFormat {
+ char_style: Option<String>,
+ para_style: Option<String>,
+ /// Resolved character attributes, as `type.selectionAttrs` reports them.
+ chars: serde_json::Map<String, Value>,
+}
+
+impl FindFormat {
+ fn from_params(p: &Value) -> Result<Option<Self>> {
+ let Some(f) = p.get("findFormat").filter(|f| !f.is_null()) else { return Ok(None) };
+ let o = f.as_object().ok_or_else(|| bad("find", "`findFormat` is an object"))?;
+ // A style is named; a null asks for none. Any other value is refused rather than
+ // searched without.
+ let name = |k: &str| match o.get(k) {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::String(n)) => Ok(Some(n.clone())),
+ Some(v) => Err(bad("find", format!("findFormat: `{k}` is a style name, not {v}"))),
+ };
+ let chars = match o.get("chars") {
+ None | Some(Value::Null) => None,
+ Some(Value::Object(m)) => Some(m),
+ Some(v) => return Err(bad("find", format!("findFormat: `chars` is an object of character attributes, not {v}"))),
+ };
+ // Only attributes text has, kept as the document writes them: `font_style` and
+ // `fontStyle`, or 12 and 12.0, then find the same text. A null asks for nothing.
+ let mut known = designcraft_doc::CharAttrs::default();
+ for (k, v) in chars.into_iter().flatten() {
+ known.set_json(k, v).map_err(|e| bad("find", format!("findFormat: {e}")))?;
+ }
+ let chars = match serde_json::to_value(&known) {
+ Ok(Value::Object(m)) => m,
+ _ => serde_json::Map::new(),
+ };
+ let f = Self { char_style: name("charStyle")?, para_style: name("paraStyle")?, chars };
+ Ok((f != Self::default()).then_some(f))
+ }
+
+ /// Styles the document doesn't have are refused, as `find.change` refuses them.
+ fn check(&self, styles: &Styles) -> Result<()> {
+ if let Some(n) = self.char_style.as_ref().filter(|n| styles.char_style(n).is_none()) {
+ return Err(bad("find", format!("no character style `{n}`")));
+ }
+ if let Some(n) = self.para_style.as_ref().filter(|n| styles.para(n).is_none()) {
+ return Err(bad("find", format!("no paragraph style `{n}`")));
+ }
+ Ok(())
+ }
+
+ /// The text in `r` of `story` that has the format, relative to `r.start`: the longest
+ /// stretches, each paragraph's apart (a paragraph's `\n` isn't in one).
+ fn spans(&self, styles: &Styles, story: &Story, r: &Range<usize>) -> Vec<Range<usize>> {
+ let mut out: Vec<Range<usize>> = Vec::new();
+ // Paragraphs and runs both go in text order: the runs before a paragraph are passed once.
+ let runs: Vec<_> = story.runs().collect();
+ let mut first = 0;
+ for (pi, pr) in story.para_ranges().into_iter().enumerate() {
+ let (a, b) = (pr.start.max(r.start), pr.end.min(r.end));
+ let Some(pf) = story.paras.get(pi) else { continue };
+ if a >= b || self.para_style.as_ref().is_some_and(|n| *n != pf.style) {
+ continue;
+ }
+ while runs.get(first).is_some_and(|(run, _)| run.end <= a) {
+ first += 1;
+ }
+ let base = (!self.chars.is_empty()).then(|| styles.resolve_para(pf).1);
+ for (run, cf) in runs[first..].iter().take_while(|(run, _)| run.start < b) {
+ let (x, y) = (run.start.max(a), run.end.min(b));
+ if x >= y || self.char_style.as_ref().is_some_and(|n| *n != cf.style) {
+ continue;
+ }
+ if let Some(base) = &base {
+ let cp = serde_json::to_value(styles.resolve_char(base, cf)).unwrap_or_default();
+ if !self.chars.iter().all(|(k, v)| cp.get(k).is_some_and(|c| same_value(c, v))) {
+ continue;
+ }
+ }
+ match out.last_mut() {
+ Some(last) if last.end == x - r.start => last.end = y - r.start,
+ _ => out.push(x - r.start..y - r.start),
+ }
+ }
+ }
+ out
+ }
+}
+
+/// Attribute values alike: numbers to within rounding (inside objects and lists too), the rest
+/// exactly.
+fn same_value(a: &Value, b: &Value) -> bool {
+ match (a, b) {
+ (Value::Number(_), Value::Number(_)) => match (a.as_f64(), b.as_f64()) {
+ (Some(x), Some(y)) => (x - y).abs() < 1e-6,
+ _ => a == b,
+ },
+ (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(a, b)| same_value(a, b)),
+ (Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| same_value(v, w))),
+ _ => a == b,
+ }
+}
+
+/// Whether match `m` lies in one of `spans`.
+fn within(spans: &[Range<usize>], m: &Range<usize>) -> bool {
+ spans.iter().any(|s| s.start <= m.start && m.end <= s.end)
+}
+
+/// What a search finds: the pattern's matches (with a Find Format, those whose text has it all
+/// through), or, with no pattern, the stretches of text with the Find Format.
+struct Search {
+ re: Option<Grep>,
+ format: Option<FindFormat>,
+}
+
+/// The search of a Find/Change request: an empty `find` needs a Find Format.
+fn search(p: &Value) -> Result<Search> {
+ let format = FindFormat::from_params(p)?;
+ if format.is_some() && str_param(p, "find") == Some("") {
+ return Ok(Search { re: None, format });
+ }
+ Ok(Search { re: Some(build(p)?), format })
+}
+
+impl Search {
+ fn check(&self, styles: &Styles) -> Result<()> {
+ self.format.as_ref().map_or(Ok(()), |f| f.check(styles))
+ }
+
+ /// Where the Find Format holds in target `r` of story `sid` (of its table cell `cell`, if any;
+ /// `None`: no Find Format).
+ fn spans(&self, d: &Document, sid: StoryId, cell: Option<CellAddr>, r: &Range<usize>) -> Option<Vec<Range<usize>>> {
+ let f = self.format.as_ref()?;
+ Some(d.text_story(sid, cell).map(|story| f.spans(&d.styles, story, r)).unwrap_or_default())
+ }
+
+ /// Up to `limit` matches in `text`, target `r` of story `sid` (offsets in `text`).
+ fn find_all(&self, d: &Document, sid: StoryId, cell: Option<CellAddr>, r: &Range<usize>, text: &str, limit: usize) -> Result<Vec<Range<usize>>> {
+ let spans = self.spans(d, sid, cell, r);
+ let Some(re) = &self.re else { return Ok(spans.unwrap_or_default().into_iter().take(limit).collect()) };
+ let Some(spans) = spans else { return re.find_all(text, limit).map_err(|e| bad("find", e)) };
+ Ok(re.find_all(text, usize::MAX).map_err(|e| bad("find", e))?.into_iter().filter(|m| within(&spans, m)).take(limit).collect())
+ }
+
+ /// The first match in `text` (target `r` of story `sid`) at or after byte `from`.
+ fn find_at(&self, d: &Document, sid: StoryId, cell: Option<CellAddr>, r: &Range<usize>, text: &str, from: usize) -> Result<Option<Range<usize>>> {
+ let spans = self.spans(d, sid, cell, r);
+ let Some(re) = &self.re else {
+ // From inside a stretch, the rest of it.
+ return Ok(spans.unwrap_or_default().into_iter().find(|s| s.end > from).map(|s| s.start.max(from)..s.end));
+ };
+ let mut at = from;
+ loop {
+ let Some(m) = re.find_at(text, at).map_err(|e| bad("find.next", e))? else { return Ok(None) };
+ if spans.as_ref().is_none_or(|s| within(s, &m)) {
+ return Ok(Some(m));
+ }
+ // On past it: its end, or a character on from an empty match.
+ at = if m.is_empty() { text.get(m.end..).and_then(|t| t.chars().next()).map_or(text.len() + 1, |c| m.end + c.len_utf8()) } else { m.end };
+ if at > text.len() {
+ return Ok(None);
+ }
+ }
+ }
+
+ /// 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)]
+ fn replacements(
+ &self,
+ d: &Document,
+ sid: StoryId,
+ cell: Option<CellAddr>,
+ r: &Range<usize>,
+ text: &str,
+ rep: &str,
+ grep: bool,
+ first_only: bool,
+ ) -> Result<Vec<(Range<usize>, String)>> {
+ let limit = if first_only { 1 } else { usize::MAX };
+ match (&self.re, self.spans(d, sid, cell, r)) {
+ (Some(re), None) if grep => re.replacements(text, rep, first_only).map_err(|e| bad("find.change", e)),
+ (Some(re), Some(spans)) if grep => Ok(re
+ .replacements(text, rep, false)
+ .map_err(|e| bad("find.change", e))?
+ .into_iter()
+ .filter(|(m, _)| within(&spans, m))
+ .take(limit)
+ .collect()),
+ _ => Ok(self.find_all(d, sid, cell, r, text, limit)?.into_iter().map(|m| (m, rep.to_string())).collect()),
+ }
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq)]
enum Domain {
Document,
@@ -140,6 +333,7 @@ struct Matcher {
grep: bool,
case_sensitive: bool,
whole_word: bool,
+ format: Option<FindFormat>,
}
impl Matcher {
@@ -149,6 +343,7 @@ impl Matcher {
grep: bool_or(p, "grep", false),
case_sensitive: bool_or(p, "caseSensitive", false),
whole_word: bool_or(p, "wholeWord", false),
+ format: FindFormat::from_params(p).ok().flatten(),
}
}
}
@@ -299,13 +494,14 @@ fn scope(s: &Session, p: &Value) -> Result<FindContext> {
const MAX_MATCHES: usize = 10_000;
fn find(s: &mut Session, p: &Value) -> Result<Value> {
- let re = build(p)?;
+ let re = search(p)?;
+ re.check(&s.doc()?.doc.styles)?;
let context = scope(s, p)?;
let st = s.doc()?;
let mut out = Vec::new();
for (sid, cell, r) in &context.targets {
let text = target_text(&st.doc, *sid, *cell, r)?;
- for m in re.find_all(text, MAX_MATCHES.saturating_sub(out.len())).map_err(|e| bad("find", e))? {
+ for m in re.find_all(&st.doc, *sid, *cell, r, text, MAX_MATCHES.saturating_sub(out.len()))? {
let mut hit = json!({"story": sid.0, "start": r.start + m.start, "end": r.start + m.end, "text": text.get(m)});
if let Some(c) = cell {
hit["cell"] = json!({"table": c.table, "row": c.row, "col": c.col});
@@ -349,9 +545,11 @@ fn char_overrides(attrs: Option<&Value>) -> Result<designcraft_doc::CharAttrs> {
}
fn change(s: &mut Session, p: &Value) -> Result<Value> {
- let re = build(p)?;
- let grep = bool_or(p, "grep", false);
- let rep = replacement(p);
+ let re = search(p)?;
+ re.check(&s.doc()?.doc.styles)?;
+ // With no pattern (a Find Format alone), the change is literal text.
+ let grep = bool_or(p, "grep", false) && re.re.is_some();
+ let rep = if re.re.is_some() { replacement(p) } else { metachars(str_param(p, "change").unwrap_or("")) };
let first_only = bool_or(p, "first", false);
let attrs = p.get("attrs").cloned();
let over = char_overrides(attrs.as_ref())?;
@@ -382,15 +580,11 @@ fn change(s: &mut Session, p: &Value) -> Result<Value> {
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)> = if grep {
- re.replacements(text, &rep, first_only)
- } else {
- re.find_all(text, if first_only { 1 } else { usize::MAX }).map(|ms| ms.into_iter().map(|m| (m, rep.clone())).collect())
- }
- .map_err(|e| bad("find.change", e))?
- .into_iter()
- .map(|(m, out)| (r.start + m.start..r.start + m.end, out))
- .collect();
+ 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 Some(st) = d.text_story_mut(sid, cell) else { continue };
for (range, new) in edits.iter().rev() {
let changed = if format_only {
@@ -432,7 +626,8 @@ fn change(s: &mut Session, p: &Value) -> Result<Value> {
}
fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
- let re = build(p)?;
+ let re = search(p)?;
+ re.check(&s.doc()?.doc.styles)?;
let mut context = scope(s, p)?;
let st = s.doc()?;
let mut hit = None;
@@ -442,7 +637,7 @@ fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
if text.get(from..).is_none() {
return Err(bad("find", "invalid UTF-8 search cursor"));
}
- if let Some(m) = re.find_at(text, from).map_err(|e| bad("find.next", e))? {
+ if let Some(m) = re.find_at(&st.doc, sid, cell, &r, text, from)? {
let (a, b) = (r.start + m.start, r.start + m.end);
// Match find_iter/captures_iter: suppress an empty match adjacent to the
// previous match's end, but keep adjacent nonempty matches.
diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs
index 5914c2e51..7de29f8ea 100644
--- a/crates/engine/src/cmd/find/tests.rs
+++ b/crates/engine/src/cmd/find/tests.rs
@@ -747,3 +747,118 @@ fn find_scope_revert_releases_context_with_same_document_uid() {
assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
assert!(s.execute("find.find", &p).is_err(), "revert's empty selection cannot inherit a previous range");
}
+
+#[test]
+fn change_format_styles_the_found_text_and_keeps_it() {
+ // The course's chapter 22: every lowercase "eggs" gets the character style "eggs", with
+ // Change to empty, so the words stay.
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let text = "Poached Eggs\nBreak eggs; cook until eggs are set.";
+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap();
+ let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
+ s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold", "fill": "C=15 M=100 Y=100 K=0"}})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap();
+ let undo = s.doc().unwrap().history.undo.len();
+ let r = s.execute("find.change", &json!({"find": "eggs", "change": "", "caseSensitive": true, "charStyle": "eggs"})).unwrap();
+ assert_eq!(r["count"], 2);
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
+ let style_at = |s: &Session, at: usize| s.doc().unwrap().doc.story(sid).unwrap().format_after(at).style.clone();
+ let story = s.doc().unwrap().doc.story(sid).unwrap().clone();
+ assert_eq!(story.text, text, "the words stay");
+ for at in [19, 36] {
+ assert_eq!(&story.text[at..at + 4], "eggs");
+ assert_eq!(style_at(&s, at), "eggs");
+ }
+ assert_eq!(style_at(&s, 8), designcraft_doc::NO_CHAR_STYLE, "case sensitive: not \"Eggs\"");
+ assert_eq!(style_at(&s, 25), designcraft_doc::NO_CHAR_STYLE, "only the found text");
+ // A paragraph style goes to the found text's paragraphs, with attributes over the text.
+ s.execute("find.change", &json!({"find": "cook", "change": "", "paraStyle": "Method", "attrs": {"underline": true}})).unwrap();
+ let story = s.doc().unwrap().doc.story(sid).unwrap().clone();
+ assert_eq!((story.paras[0].style.as_str(), story.paras[1].style.as_str()), (designcraft_doc::BASIC_PARAGRAPH, "Method"));
+ assert_eq!(story.format_after(25).over.underline, Some(true));
+ assert_eq!(story.format_after(19).style, "eggs", "the other text keeps its character style");
+ // Change to and a Change Format: the new text is formatted.
+ s.execute("find.change", &json!({"find": "set", "change": "firm", "charStyle": "eggs"})).unwrap();
+ assert_eq!(style_at(&s, s.doc().unwrap().doc.story(sid).unwrap().text.find("firm").unwrap()), "eggs");
+ // No such style: refused, nothing changed.
+ let before = s.doc().unwrap().doc.clone();
+ assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "charStyle": "Nope"})).is_err());
+ assert!(s.execute("find.change", &json!({"find": "eggs", "change": "", "paraStyle": "Nope"})).is_err());
+ assert_eq!(s.doc().unwrap().doc, before);
+ // With no Change Format, an empty Change to still deletes the found text.
+ s.execute("find.change", &json!({"find": "Break ", "change": ""})).unwrap();
+ assert!(!s.doc().unwrap().doc.story(sid).unwrap().text.contains("Break"));
+}
+
+#[test]
+fn a_find_format_finds_only_text_with_it() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r =
+ s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Break eggs; cook eggs.\nEggs and eggs"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ s.execute("style.character.create", &json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Method"})).unwrap();
+ for (a, b) in [(6, 10), (12, 16)] {
+ s.execute("text.select", &json!({"story": sid, "anchor": a, "focus": b})).unwrap();
+ s.execute("style.character.apply", &json!({"name": "eggs"})).unwrap();
+ }
+ s.execute("text.select", &json!({"story": sid, "anchor": 25, "focus": 25})).unwrap();
+ s.execute("style.paragraph.apply", &json!({"name": "Method"})).unwrap();
+ let found = |s: &mut Session, p: serde_json::Value| -> Vec<(u64, u64)> {
+ let m = s.execute("find.find", &p).unwrap();
+ m.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap(), m["end"].as_u64().unwrap())).collect()
+ };
+ // "eggs" where it has the character style: the first only.
+ assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs"}})), [(6, 10)]);
+ // Nothing in Find what: each stretch of text in the style.
+ assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})), [(6, 10), (12, 16)]);
+ // A paragraph style, and resolved attributes.
+ assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"paraStyle": "Method"}})), [(23, 27), (32, 36)]);
+ assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"fontStyle": "Bold"}}})), [(6, 10), (12, 16)]);
+ assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"size": 12}}})), [(0, 22), (23, 36)], "each paragraph apart");
+ // Find Next walks the stretches.
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();
+ let next = json!({"find": "", "findFormat": {"charStyle": "eggs"}});
+ assert_eq!(s.execute("find.next", &next).unwrap()["start"], 6);
+ assert_eq!(s.execute("find.next", &next).unwrap()["start"], 12);
+ // Equivalent spellings the attributes accept find the same text: a snake_case key, and a
+ // nested number written as an integer (14 pt leading on the second paragraph).
+ s.execute("text.select", &json!({"story": sid, "anchor": 23, "focus": 36})).unwrap();
+ s.execute("type.char", &json!({"leading": {"kind": "points", "value": 14.0}})).unwrap();
+ for (a, b) in [
+ (json!({"fontStyle": "Bold"}), json!({"font_style": "Bold"})),
+ (json!({"leading": {"kind": "points", "value": 14.0}}), json!({"leading": {"kind": "points", "value": 14}})),
+ ] {
+ let (a, b) = (json!({"find": "", "findFormat": {"chars": a}}), json!({"find": "", "findFormat": {"chars": b}}));
+ let all = found(&mut s, a.clone());
+ assert!(!all.is_empty(), "{a}");
+ assert_eq!(found(&mut s, b.clone()), all, "{b}");
+ for p in [&a, &b] {
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();
+ assert_eq!(s.execute("find.next", p).unwrap()["start"].as_u64(), Some(all[0].0), "{p}");
+ }
+ }
+ // A null attribute asks for nothing.
+ assert_eq!(found(&mut s, json!({"find": "eggs", "findFormat": {"charStyle": "eggs", "chars": {"size": null}}})), [(6, 10)]);
+ // With a Change Format: the text in the style goes back to [None], underlined.
+ let r = s
+ .execute(
+ "find.change",
+ &json!({"find": "", "change": "", "findFormat": {"charStyle": "eggs", "chars": {"font_style": "Bold"}}, "charStyle": "[None]", "attrs": {"underline": true}}),
+ )
+ .unwrap();
+ assert_eq!(r["count"], 2, "a snake_case attribute changes the same text");
+ assert!(found(&mut s, json!({"find": "", "findFormat": {"charStyle": "eggs"}})).is_empty());
+ assert_eq!(found(&mut s, json!({"find": "", "findFormat": {"chars": {"underline": true}}})), [(6, 10), (12, 16)]);
+ // Unknown styles and attributes are refused; an empty search needs a Find Format.
+ assert!(s.execute("find.find", &json!({"find": "", "findFormat": {"charStyle": "Nope"}})).is_err());
+ assert!(s.execute("find.next", &json!({"find": "eggs", "findFormat": {"paraStyle": "Nope"}})).is_err());
+ assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": {"chars": {"bogus": 1}}})).is_err());
+ // Malformed fields are refused, not searched without.
+ for f in [json!({"chars": [1]}), json!({"chars": 12}), json!({"charStyle": 3}), json!({"paraStyle": ["Body"]})] {
+ assert!(s.execute("find.find", &json!({"find": "eggs", "findFormat": f})).is_err(), "{f}");
+ }
+ assert!(s.execute("find.find", &json!({"find": ""})).is_err());
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 253deebd3..642f0d1cd 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -2644,9 +2644,21 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
});
ui.label(d.s("status"));
} else {
- let formatted = d.fields.get(CHANGE_FORMAT).and_then(Value::as_object).is_some_and(|f| !f.is_empty());
+ let (find_formatted, formatted) = (format_set(&d, FIND_FORMAT), format_set(&d, CHANGE_FORMAT));
egui::Grid::new("fc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Find what:"));
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Find what:"));
+ // InDesign's ⓘ: a Find Format narrows what is found.
+ if find_formatted {
+ info_icon(
+ ui,
+ crate::i18n::tr(
+ &app.ui.language,
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ ),
+ );
+ }
+ });
text_field_named(ui, &mut d, "find", 260.0, crate::i18n::tr(&app.ui.language, "Find what:"));
ui.end_row();
ui.horizontal(|ui| {
@@ -2685,7 +2697,8 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
check(ui, &mut d, "caseSensitive", crate::i18n::tr(&app.ui.language, "Case sensitive"));
check(ui, &mut d, "wholeWord", crate::i18n::tr(&app.ui.language, "Whole word"));
});
- change_format_box(&app.ui.language, ui, &mut d);
+ format_box(&app.ui.language, ui, &mut d, true);
+ format_box(&app.ui.language, ui, &mut d, false);
ui.horizontal(|ui| {
let params0 = find_change_params(&d);
let params = || params0.clone();
@@ -3278,7 +3291,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
crate::new_document::preview(app, &mut d, ctx);
}
if d.id == "findChange" && result.is_none() && d.fields.get(FORMAT_EDIT).is_some_and(Value::is_object) {
- change_format_settings(app, ctx, &mut d);
+ format_settings(app, ctx, &mut d);
}
app.ui.dialog = Some(d);
match result {
@@ -3446,6 +3459,10 @@ fn find_change_params(d: &Dialog) -> Value {
if let Some(story) = d.fields.get("story") {
p["story"] = story.clone();
}
+ // Find Format: only text with it is found (with nothing in Find what, all text with it).
+ if let Some(f) = d.fields.get(FIND_FORMAT).and_then(Value::as_object).filter(|f| !f.is_empty()) {
+ p["findFormat"] = Value::Object(f.clone());
+ }
// Change Format: find.change applies it to the changed text (the other commands ignore it).
if let Some(f) = d.fields.get(CHANGE_FORMAT) {
for key in ["charStyle", "paraStyle"] {
@@ -3460,14 +3477,21 @@ fn find_change_params(d: &Dialog) -> Value {
p
}
-/// Find/Change's Change Format ({charStyle?, paraStyle?, chars?}), as Change Format Settings set
-/// it; absent when there is none.
+/// Find/Change's Find Format and Change Format ({charStyle?, paraStyle?, chars?}), as their
+/// settings set them; absent when there is none.
+const FIND_FORMAT: &str = "findFormat";
const CHANGE_FORMAT: &str = "changeFormat";
-/// The fields of Change Format Settings while it is open (its section, `charStyle`, `paraStyle`
-/// and `c.<attr>`), until OK makes them the Change Format.
+/// The fields of Find or Change Format Settings while it is open (`for`: find|change, its
+/// section, `charStyle`, `paraStyle` and `c.<attr>`), until OK makes them the format.
const FORMAT_EDIT: &str = "formatEdit";
-/// The sections of Change Format Settings: Style Options, then those of Character Style Options.
+/// Whether the dialog has a Find (`FIND_FORMAT`) or Change Format.
+fn format_set(d: &Dialog, key: &str) -> bool {
+ d.fields.get(key).and_then(Value::as_object).is_some_and(|f| !f.is_empty())
+}
+
+/// The sections of Find and Change Format Settings: Style Options, then those of Character Style
+/// Options.
const FORMAT_SECTIONS: &[(&str, &str)] = &[
("style", "Style Options"),
("chars", "Basic Character Formats"),
@@ -3486,8 +3510,8 @@ fn info_icon(ui: &mut egui::Ui, tip: &str) {
resp.on_hover_text(tip);
}
-/// What the Change Format box shows: "Character Style: eggs + …".
-fn change_format_summary(lang: &str, format: Option<&Value>) -> String {
+/// What a Find or Change Format box shows: "Character Style: eggs + …".
+fn format_summary(lang: &str, format: Option<&Value>) -> String {
let Some(f) = format else { return String::new() };
let mut parts = Vec::new();
for (key, label) in [("charStyle", "Character Style:"), ("paraStyle", "Paragraph Style:")] {
@@ -3501,23 +3525,30 @@ fn change_format_summary(lang: &str, format: Option<&Value>) -> String {
parts.join(" + ")
}
-/// Find/Change's Change Format, as InDesign's: a box with what Change All also gives the changed
-/// text, a button that opens Change Format Settings and one that clears it.
-fn change_format_box(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) {
+/// Find/Change's Find Format (`find`) or Change Format, as InDesign's: a box with what the found
+/// text must have or what Change All also gives the changed text, a button that opens its
+/// settings and one that clears it.
+fn format_box(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, find: bool) {
+ let (key, label, specify) = if find {
+ (FIND_FORMAT, "Find Format:", "Specify attributes to find")
+ } else {
+ (CHANGE_FORMAT, "Change Format:", "Specify attributes to change")
+ };
ui.add_space(6.0);
- crate::rtl::label(ui, crate::i18n::tr(lang, "Change Format:"));
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
ui.horizontal_top(|ui| {
let t = crate::theme::Tokens::get(ui.ctx());
egui::Frame::new().fill(t.input).stroke(egui::Stroke::new(1.0, t.input_border)).inner_margin(6.0).show(ui, |ui| {
ui.set_width(340.0);
ui.set_min_height(40.0);
- let summary = change_format_summary(lang, d.fields.get(CHANGE_FORMAT));
+ let summary = format_summary(lang, d.fields.get(key));
ui.add(egui::Label::new(egui::RichText::new(summary).color(t.text)).wrap());
});
ui.vertical(|ui| {
- if crate::icons::button(ui, "find-format", 22.0, false, crate::i18n::tr(lang, "Specify attributes to change")).clicked() {
- let f = d.fields.get(CHANGE_FORMAT).cloned().unwrap_or_default();
+ if crate::icons::button(ui, "find-format", 22.0, false, crate::i18n::tr(lang, specify)).clicked() {
+ let f = d.fields.get(key).cloned().unwrap_or_default();
let mut edit = Map::new();
+ edit.insert("for".into(), json!(if find { "find" } else { "change" }));
edit.insert("section".into(), json!("style"));
for key in ["charStyle", "paraStyle"] {
if let Some(v) = f.get(key) {
@@ -3530,16 +3561,17 @@ fn change_format_box(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) {
d.fields.insert(FORMAT_EDIT.into(), Value::Object(edit));
}
if crate::icons::button(ui, "trash", 22.0, false, crate::i18n::tr(lang, "Clear specified attributes")).clicked() {
- d.fields.remove(CHANGE_FORMAT);
+ d.fields.remove(key);
}
});
});
}
-/// Find/Change › Change Format Settings, over Find/Change as InDesign's: Style Options (the
-/// character and paragraph style to apply, [Any Style] for none), then the character sections of
-/// Character Style Options with every field blank (left as it is). OK makes it the Change Format.
-fn change_format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dialog) {
+/// Find/Change › Find or Change Format Settings, over Find/Change as InDesign's: Style Options
+/// (the character and paragraph style the found text has or the changed text gets, [Any Style]
+/// for none), then the character sections of Character Style Options with every field blank (any
+/// value, or left as it is). OK makes it the Find or Change Format.
+fn format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dialog) {
let lang = app.ui.language.clone();
let Some(doc) = app.session.active().map(|st| st.doc.clone()) else {
d.fields.remove(FORMAT_EDIT);
@@ -3549,12 +3581,14 @@ fn change_format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dial
Dialog { id: "changeFormat".into(), fields: d.fields.get(FORMAT_EDIT).and_then(Value::as_object).cloned().unwrap_or_default(), unit: d.unit };
let base = json!({});
let cf = CharFields { base: &base, sparse: true };
+ let find = fd.s("for") == "find";
let popup_open = egui::Popup::is_any_open(ctx);
let mut result = None;
- let host = egui::Id::unique("change_format_settings");
+ let host = egui::Id::unique("format_settings");
crate::modal_drag::modal(ctx, host, host).backdrop_color(egui::Color32::TRANSPARENT).show(ctx, |ui| {
let title_top = ui.cursor().top();
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Change Format Settings")).font(semibold(16.0)));
+ let title = if find { "Find Format Settings" } else { "Change Format Settings" };
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, title)).font(semibold(16.0)));
let margin = egui::Frame::popup(ui.style()).inner_margin;
let title_row = egui::Rect::from_min_max(
egui::pos2(ui.max_rect().left() - margin.leftf(), title_top - margin.topf()),
@@ -3614,10 +3648,11 @@ fn change_format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dial
if !chars.is_empty() {
f.insert("chars".into(), Value::Object(chars));
}
+ let key = if find { FIND_FORMAT } else { CHANGE_FORMAT };
if f.is_empty() {
- d.fields.remove(CHANGE_FORMAT);
+ d.fields.remove(key);
} else {
- d.fields.insert(CHANGE_FORMAT.into(), Value::Object(f));
+ d.fields.insert(key.into(), Value::Object(f));
}
}
Some(false) => {
@@ -3629,8 +3664,8 @@ fn change_format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dial
}
}
-/// Change Format Settings › Style Options: the character and paragraph style the changed text
-/// gets ([Any Style]: as it is).
+/// Find or Change Format Settings › Style Options: the character and paragraph style the found
+/// text has or the changed text gets ([Any Style]: any, or as it is).
fn format_style_options(lang: &str, ui: &mut egui::Ui, fd: &mut Dialog, styles: &designcraft_doc::Styles) {
crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Style Options")).font(semibold(13.0)));
ui.add_space(6.0);
diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs
index 8a80198ea..d3f99b14e 100644
--- a/crates/ui-egui/src/dialogs/tests.rs
+++ b/crates/ui-egui/src/dialogs/tests.rs
@@ -3884,8 +3884,8 @@ fn find_change_gives_the_found_text_a_change_format() {
[8, 19, 36].map(|at| story.format_after(at).style.clone()),
[designcraft_doc::NO_CHAR_STYLE.to_string(), "eggs".into(), "eggs".into()]
);
- // The trash clears it.
- h.get_by_label("Clear specified attributes").click();
+ // The trash clears it (the second: the first is the Find Format's).
+ h.get_all_by_label("Clear specified attributes").nth(1).unwrap().click();
h.run_steps(3);
assert_eq!(field(&h, CHANGE_FORMAT), None);
assert!(h.query_by_label(TIP).is_none());
@@ -3899,8 +3899,72 @@ fn a_change_format_goes_with_change_all() {
d.fields.insert(CHANGE_FORMAT.into(), json!({"charStyle": "eggs", "paraStyle": "Method", "chars": {"underline": true}}));
let p = find_change_params(&d);
assert_eq!((p["charStyle"].clone(), p["paraStyle"].clone(), p["attrs"].clone()), (json!("eggs"), json!("Method"), json!({"underline": true})));
- assert_eq!(change_format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on");
+ assert_eq!(format_summary("en", d.fields.get(CHANGE_FORMAT)), "Character Style: eggs + Paragraph Style: Method + Underline: on");
assert!(find_change_params(&Dialog::new("findChange", json!({"find": "cook"}))).get("attrs").is_none());
+ // A Find Format goes with every search.
+ d.fields.insert(FIND_FORMAT.into(), json!({"paraStyle": "Method"}));
+ assert_eq!(find_change_params(&d)["findFormat"], json!({"paraStyle": "Method"}));
+}
+
+/// Find/Change › Find Format, as InDesign's: Find Format Settings sets the character style the
+/// found text must have, the box shows it with Find what's ⓘ, and Count counts only "eggs" in
+/// it; with nothing in Find what, Find Next finds the text in the style; the first trash clears
+/// it.
+#[test]
+fn find_format_finds_only_text_with_it() {
+ use egui_kittest::{Harness, kittest::Queryable};
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let f = app.run("frame.create", json!({"rect": [36, 36, 400, 300], "content": "text", "text": "Break eggs; cook eggs."})).unwrap();
+ app.run("style.character.create", json!({"name": "eggs", "chars": {"fontStyle": "Bold"}})).unwrap();
+ app.run("text.select", json!({"story": f["story"], "anchor": 6, "focus": 10})).unwrap();
+ app.run("style.character.apply", json!({"name": "eggs"})).unwrap();
+ app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap();
+ app.run("app.findChange", json!({})).unwrap();
+ if let Some(d) = app.ui.dialog.as_mut() {
+ d.fields.insert("find".into(), json!("eggs"));
+ }
+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let key = egui::Id::unique("find_format_test_fonts");
+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {
+ crate::theme::install_fonts(ui.ctx(), "");
+ ui.data_mut(|d| d.insert_temp(key, true));
+ return;
+ }
+ show(app, ui.ctx());
+ },
+ app,
+ );
+ h.run_steps(4);
+ const TIP: &str = "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it";
+ assert!(h.query_by_label("Find Format:").is_some() && h.query_by_label(TIP).is_none());
+ h.get_by_label("Specify attributes to find").click();
+ h.run_steps(3);
+ assert!(h.query_by_label("Find Format Settings").is_some());
+ h.get_all_by_value("[Any Style]").next().unwrap().click();
+ h.run_steps(3);
+ h.get_by_label("eggs").click();
+ h.run_steps(3);
+ h.get_all_by_label(" OK ").last().unwrap().click();
+ h.run_steps(3);
+ let field = |h: &Harness<'_, DesignApp>, k: &str| h.state().ui.dialog.as_ref().unwrap().fields.get(k).cloned();
+ assert_eq!((field(&h, FIND_FORMAT), field(&h, CHANGE_FORMAT)), (Some(json!({"charStyle": "eggs"})), None));
+ assert!(h.query_by_label("Character Style: eggs").is_some() && h.query_by_label(TIP).is_some());
+ h.get_by_label("Count").click();
+ h.run_steps(3);
+ assert_eq!(field(&h, "status"), Some(json!("1 match(es)")), "only the \"eggs\" in the style");
+ // Nothing in Find what: the text in the style.
+ h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("find".into(), json!(""));
+ h.run_steps(2);
+ h.get_by_label("Find Next").click();
+ h.run_steps(3);
+ let sel = h.state().session.doc().unwrap().selection.text.unwrap();
+ assert_eq!(sel.range(), 6..10);
+ // The first trash is the Find Format's.
+ h.get_all_by_label("Clear specified attributes").next().unwrap().click();
+ h.run_steps(3);
+ assert_eq!(field(&h, FIND_FORMAT), None);
}
/// The course's chapter 26: Preferences › Interface as InDesign's. A Color Theme swatch shows
diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs
index a2d19e1cd..79f28509f 100644
--- a/crates/ui-egui/src/i18n/ar.rs
+++ b/crates/ui-egui/src/i18n/ar.rs
@@ -39,6 +39,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("[Same style]", "[النمط نفسه]"),
("Reset To Base", "إعادة التعيين إلى الأساس"),
("Apply Style to Selection", "تطبيق النمط على التحديد"),
+ ("Find Format:", "البحث عن تنسيق:"),
+ ("Find Format Settings", "إعدادات البحث عن تنسيق"),
+ ("Specify attributes to find", "تحديد السمات المراد البحث عنها"),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ "مع تنسيق للبحث، يُعثر فقط على النص الذي يحمله؛ وإذا كان حقل «البحث عن» فارغًا، فعلى كل نص يحمله",
+ ),
("Change Format:", "تغيير التنسيق:"),
("Change Format Settings", "إعدادات تغيير التنسيق"),
("Style Options", "خيارات النمط"),
diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs
index fdb75d7b4..e9023b369 100644
--- a/crates/ui-egui/src/i18n/cs.rs
+++ b/crates/ui-egui/src/i18n/cs.rs
@@ -41,6 +41,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("[Same style]", "[Stejný styl]"),
("Reset To Base", "Obnovit podle základu"),
("Apply Style to Selection", "Použít styl na výběr"),
+ ("Find Format:", "Hledat formát:"),
+ ("Find Format Settings", "Nastavení hledání formátu"),
+ ("Specify attributes to find", "Určit atributy k hledání"),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ "S formátem hledání se najde jen text, který ho má; s prázdným polem „Najít“ veškerý text, který ho má",
+ ),
("Change Format:", "Změnit formát:"),
("Change Format Settings", "Nastavení změny formátu"),
("Style Options", "Volby stylu"),
diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs
index d71f2870d..180524863 100644
--- a/crates/ui-egui/src/i18n/it.rs
+++ b/crates/ui-egui/src/i18n/it.rs
@@ -37,6 +37,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("[Same style]", "[Stesso stile]"),
("Reset To Base", "Ripristina base"),
("Apply Style to Selection", "Applica stile alla selezione"),
+ ("Find Format:", "Trova formato:"),
+ ("Find Format Settings", "Impostazioni di ricerca formato"),
+ ("Specify attributes to find", "Specifica gli attributi da trovare"),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ "Con un formato di ricerca si trova solo il testo che lo ha; con «Trova» vuoto, tutto il testo che lo ha",
+ ),
("Change Format:", "Modifica formato:"),
("Change Format Settings", "Impostazioni di modifica formato"),
("Style Options", "Opzioni stile"),
diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs
index 5a68e37b0..2344a666c 100644
--- a/crates/ui-egui/src/i18n/ka.rs
+++ b/crates/ui-egui/src/i18n/ka.rs
@@ -40,6 +40,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("[Same style]", "[იგივე სტილი]"),
("Reset To Base", "საბაზოზე დაბრუნება"),
("Apply Style to Selection", "სტილის გამოყენება მონიშნულზე"),
+ ("Find Format:", "ფორმატის ძიება:"),
+ ("Find Format Settings", "ფორმატის ძიების პარამეტრები"),
+ ("Specify attributes to find", "საძიებო ატრიბუტების მითითება"),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ "ძიების ფორმატით მხოლოდ ის ტექსტი მოიძებნება, რომელსაც ის აქვს; ცარიელი „ძიება“ ველით — ყველა ასეთი ტექსტი",
+ ),
("Change Format:", "ფორმატის შეცვლა:"),
("Change Format Settings", "ფორმატის შეცვლის პარამეტრები"),
("Style Options", "სტილის პარამეტრები"),
diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs
index b536be8c7..252f82f74 100644
--- a/crates/ui-egui/src/i18n/pl.rs
+++ b/crates/ui-egui/src/i18n/pl.rs
@@ -39,6 +39,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("[Same style]", "[Ten sam styl]"),
("Reset To Base", "Przywróć bazowy"),
("Apply Style to Selection", "Zastosuj styl do zaznaczenia"),
+ ("Find Format:", "Znajdź format:"),
+ ("Find Format Settings", "Ustawienia wyszukiwania formatu"),
+ ("Specify attributes to find", "Określ atrybuty do znalezienia"),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ "Przy formacie wyszukiwania znajdowany jest tylko tekst, który go ma; przy pustym polu „Znajdź” — cały taki tekst",
+ ),
("Change Format:", "Zmień format:"),
("Change Format Settings", "Ustawienia zmiany formatu"),
("Style Options", "Opcje stylu"),
diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs
index 505b840ea..ccd3117e1 100644
--- a/crates/ui-egui/src/i18n/pt_br.rs
+++ b/crates/ui-egui/src/i18n/pt_br.rs
@@ -40,6 +40,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("[Same style]", "[Mesmo estilo]"),
("Reset To Base", "Redefinir para base"),
("Apply Style to Selection", "Aplicar estilo à seleção"),
+ ("Find Format:", "Localizar formato:"),
+ ("Find Format Settings", "Configurações de localização de formato"),
+ ("Specify attributes to find", "Especificar atributos a localizar"),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ "Com um formato de localização, só o texto que o tem é encontrado; com “Localizar” vazio, todo o texto que o tem",
+ ),
("Change Format:", "Alterar formato:"),
("Change Format Settings", "Configurações de alteração de formato"),
("Style Options", "Opções de estilo"),
diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs
index 6e8e49df2..a3271593e 100644
--- a/crates/ui-egui/src/i18n/ru.rs
+++ b/crates/ui-egui/src/i18n/ru.rs
@@ -43,6 +43,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("[Same style]", "[Тот же стиль]"),
("Reset To Base", "Сбросить до основы"),
("Apply Style to Selection", "Применить стиль к выделенному"),
+ ("Find Format:", "Найти формат:"),
+ ("Find Format Settings", "Параметры поиска формата"),
+ ("Specify attributes to find", "Задать атрибуты для поиска"),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ "С форматом поиска находится только текст с этим форматом; если поле «Найти» пусто — весь такой текст",
+ ),
("Change Format:", "Заменить формат:"),
("Change Format Settings", "Параметры замены формата"),
("Style Options", "Параметры стиля"),
diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs
index 93e83a382..ffc78fdfc 100644
--- a/crates/ui-egui/src/i18n/table.rs
+++ b/crates/ui-egui/src/i18n/table.rs
@@ -988,6 +988,31 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[
("Change All", ["Change All", "Tout remplacer", "Change All", "Change All", "全部更改"]),
("Change to:", ["Change to:", "Remplacer par :", "Change to:", "Change to:", "更改为:"]),
("Change Format:", ["Format ersetzen:", "Remplacer le format :", "Cambiar formato:", "置換形式 :", "更改格式:"]),
+ ("Find Format:", ["Format suchen:", "Rechercher le format :", "Buscar formato:", "検索形式 :", "查找格式:"]),
+ (
+ "Find Format Settings",
+ ["Einstellungen für Format suchen", "Paramètres de recherche de format", "Ajustes de búsqueda de formato", "検索形式の設定", "查找格式设置"],
+ ),
+ (
+ "Specify attributes to find",
+ [
+ "Zu suchende Attribute festlegen",
+ "Indiquer les attributs à rechercher",
+ "Especificar atributos que buscar",
+ "検索する属性を指定",
+ "指定要查找的属性",
+ ],
+ ),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ [
+ "Mit einem Suchformat wird nur Text gefunden, der es hat; bei leerem Feld „Suchen nach“ jeder Text, der es hat",
+ "Avec un format de recherche, seul le texte qui l’a est trouvé ; si « Rechercher » est vide, tout le texte qui l’a",
+ "Con un formato de búsqueda solo se encuentra el texto que lo tiene; con «Buscar» vacío, todo el texto que lo tiene",
+ "検索形式があるときは、その書式のテキストだけが見つかります。検索文字列が空のときは、その書式のテキストすべてが見つかります",
+ "设置了查找格式时,只查找具有该格式的文本;“查找内容”为空时,查找所有具有该格式的文本",
+ ],
+ ),
(
"Change Format Settings",
[
diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs
index 858e0912e..87b9ec847 100644
--- a/crates/ui-egui/src/i18n/uk.rs
+++ b/crates/ui-egui/src/i18n/uk.rs
@@ -38,6 +38,13 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("[Same style]", "[Той самий стиль]"),
("Reset To Base", "Скинути до основи"),
("Apply Style to Selection", "Застосувати стиль до виділеного"),
+ ("Find Format:", "Знайти формат:"),
+ ("Find Format Settings", "Параметри пошуку формату"),
+ ("Specify attributes to find", "Задати атрибути для пошуку"),
+ (
+ "With a Find Format, only text that has it is found; with nothing in Find what, all text that has it",
+ "З форматом пошуку знаходиться лише текст із цим форматом; якщо поле «Знайти» порожнє — увесь такий текст",
+ ),
("Change Format:", "Замінити формат:"),
("Change Format Settings", "Параметри заміни формату"),
("Style Options", "Параметри стилю"),
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index 228dc5231..7e65a1833 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -276,7 +276,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level
- FID2: IDML underline/strikethrough Text Color resets survive style inheritance and roundtrip. Raster and PDF paint underlines behind glyphs, retain strikethrough above, and center rules on their offsets; synthetic overlap tests cover both backends.
- Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels, gradients, composed text.
- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts and the Fill/Stroke proxy (D, X, Shift+X, / as `color.*` commands), document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), document grid (View ▸ Grids & Guides, ⌘', on the snap positions, behind or in front of items), Lock Guides (⌥⌘;) and Lock Column Guides (View ▸ Grids & Guides; Lock Column Guides is saved with the document and in IDML), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches (InDesign's header: Fill/Stroke proxy, Formatting Affects Container/Text, Tint, which reads 100 with nothing selected; a swatch goes to the fill or stroke in front; rows show InDesign's type columns: the crossed pencil on swatches that can't be edited, process or spot, and the colour mode; New Color Group / New Swatch / Delete Swatch row), Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.
-- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows, expandable groups and drag-and-drop reorder of layers and objects (the selection square moves the selection to another layer).
+- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP, with Find Format: text that has a character or paragraph style or character attributes), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows, expandable groups and drag-and-drop reorder of layers and objects (the selection square moves the selection to another layer).
- Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type; Option/Alt+Left/Right kerns at the caret or tracks a selection by the Kerning/Tracking increment, ×5 with Cmd/Ctrl; words move with Cmd+Left/Right on macOS and Ctrl+Left/Right elsewhere), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.
- PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`. File › Export PDF… now opens an "Export PDF" options dialog (General / Compression / Marks and Bleeds / Advanced) and remembers the last-used settings across exports and sessions.
- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories; attributes a file leaves unset take InDesign's defaults (Keep Lines Together at start/end of paragraph, 12 pt corners, paragraph rules in Text Color, auto-sizing from the centre, numbered lists restarting in each story, alternating table fills Black 20 % / None; a tint of −1 is the colour's own; frames take the fill, stroke, corners and Text Frame Options they don't write from their object style chain, then [None]) — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).