diff --git a/crates/ide-host/src/ops/search/commands.rs b/crates/ide-host/src/ops/search/commands.rs index 0a7d934e2..6e9d9f7b3 100644 --- a/crates/ide-host/src/ops/search/commands.rs +++ b/crates/ide-host/src/ops/search/commands.rs @@ -149,10 +149,11 @@ pub async fn replace_preview( .map_err(|e| ide_core::IdeError::internal(e.to_string()))? } -/// Validates a query (e.g. regex syntax) while the user types. +/// Validates a query (e.g. regex syntax), and what Replace would insert, while the user types. #[command(trust = always)] -pub fn search_validate(query: SearchQuery) -> IdeResult<()> { - ide_search::validate_query(&query) +pub fn search_validate(query: SearchQuery, replacement: Option) -> IdeResult<()> { + ide_search::validate_query(&query)?; + replacement.map_or(Ok(()), |r| ide_search::validate_replacement(&query, &r)) } ide_command::domain!(search_commands: replace_in_files, replace_preview, search_validate); diff --git a/crates/ide-host/tests/replace_all.rs b/crates/ide-host/tests/replace_all.rs index ba15f2bf9..7f2d2f517 100644 --- a/crates/ide-host/tests/replace_all.rs +++ b/crates/ide-host/tests/replace_all.rs @@ -199,6 +199,54 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() { host.close_project("main"); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_replacement_with_an_unknown_group_changes_no_file() { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("project"); + std::fs::create_dir_all(&root).unwrap(); + let host = Host::new(common::host_config(&base)); + host.trust.decide(&root, true, false).unwrap(); + host.open_project("main", &root).unwrap(); + let names = ["a.txt", "b.txt"]; + for all_in_scope in [false, true] { + for name in names { + std::fs::write(root.join(name), "foo.old();\n").unwrap(); + } + let err = ops::search::replace_in_files( + &host, + "main", + RequestId::next(), + query(r"(\w+)\.old", true), + "$name".into(), + false, + names.map(|n| ReplaceTarget { path: root.join(n).into(), only: None, skip: None }).into(), + all_in_scope, + ops::Channel::new(|_| {}), + ) + .await + .unwrap_err(); + assert_eq!(err.message, "Invalid replacement: the pattern has no group name"); + for name in names { + assert_eq!(std::fs::read_to_string(root.join(name)).unwrap(), "foo.old();\n"); + } + } + let preview = ops::search::replace_preview( + &host, + "main", + query(r"(\w+)\.old", true), + "$2".into(), + false, + root.join("a.txt"), + None, + ); + assert_eq!(preview.await.unwrap_err().message, "Invalid replacement: the pattern has no group 2"); + assert!(ops::search::search_validate(query("a", true), Some("$1".into())).is_err()); + assert!(ops::search::search_validate(query("(a)", true), Some("$1_x".into())).is_ok()); + assert!(ops::search::search_validate(query("a", true), None).is_ok()); + host.close_project("main"); +} + /// Replace All past the limit replaces what the search lists: only the matches its Search /// Context keeps (comments, string literals or code), as below the limit. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/crates/ide-search/src/lib.rs b/crates/ide-search/src/lib.rs index 2bf5e6e32..52c137f8e 100644 --- a/crates/ide-search/src/lib.rs +++ b/crates/ide-search/src/lib.rs @@ -15,6 +15,7 @@ mod mask; mod pattern; mod query; mod replace; +mod template; mod words; pub use files::{ScopeFile, scope_files}; @@ -31,6 +32,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize}; use specta::Type; use std::path::Path; +use template::Template; #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -308,6 +310,14 @@ pub fn validate_query(query: &SearchQuery) -> IdeResult<()> { Ok(()) } +/// Checks the pattern and the groups `replacement` refers to without searching. +pub fn validate_replacement(query: &SearchQuery, replacement: &str) -> IdeResult<()> { + if !query.pattern.is_empty() { + Template::new(replacement, query.is_regex, &query::compile(query)?)?; + } + Ok(()) +} + /// Byte ranges of the matches of `query` in `text`, matched as [`search`] does. /// Unlike [`LineMatch`]es, a match spanning lines comes back whole. pub fn match_ranges(text: &str, query: &SearchQuery) -> IdeResult> { @@ -328,6 +338,8 @@ pub fn match_ranges(text: &str, query: &SearchQuery) -> IdeResult IdeResult<(String, u32)> { if query.pattern.is_empty() { @@ -336,7 +348,7 @@ pub fn replace_in_text(text: &str, query: &SearchQuery, replacement: &str) -> Id let compiled = query::compile(query)?; let matcher = &compiled.matcher; let haystack = text.as_bytes(); - let template = if query.is_regex { unescape_replacement(replacement) } else { replacement.to_owned() }; + let template = Template::new(replacement, query.is_regex, &compiled)?; let mut caps = matcher.new_captures().map_err(|e| IdeError::internal(e.to_string()))?; let mut out = Vec::with_capacity(text.len()); let mut count = 0u32; @@ -346,39 +358,9 @@ pub fn replace_in_text(text: &str, query: &SearchQuery, replacement: &str) -> Id out.extend_from_slice(&haystack[last..m.start()]); last = m.end(); count += 1; - if query.is_regex { - caps.interpolate(|name| matcher.capture_index(name), haystack, template.as_bytes(), &mut out); - } else { - out.extend_from_slice(template.as_bytes()); - } + template.expand(caps, haystack, &mut out); }); out.extend_from_slice(&haystack[last..]); let out = String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()); Ok((out, count)) } - -/// Translates IDEA-style escapes in a regex replacement template; `\$` -/// becomes `$$` so the interpolator emits a literal dollar. -pub(crate) fn unescape_replacement(replacement: &str) -> String { - let mut out = String::with_capacity(replacement.len()); - let mut chars = replacement.chars(); - while let Some(c) = chars.next() { - if c != '\\' { - out.push(c); - continue; - } - match chars.next() { - Some('n') => out.push('\n'), - Some('t') => out.push('\t'), - Some('r') => out.push('\r'), - Some('\\') => out.push('\\'), - Some('$') => out.push_str("$$"), - Some(other) => { - out.push('\\'); - out.push(other); - } - None => out.push('\\'), - } - } - out -} diff --git a/crates/ide-search/src/replace.rs b/crates/ide-search/src/replace.rs index b4aee657b..34dd75540 100644 --- a/crates/ide-search/src/replace.rs +++ b/crates/ide-search/src/replace.rs @@ -3,6 +3,7 @@ //! (the document layer in the app, so open editors update and each file is one //! undoable step). +use crate::template::Template; use crate::{LiteralRange, Literals, SearchContext, SearchQuery, iter, query}; use grep_matcher::{Captures, Matcher}; use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, TextEdit}; @@ -127,8 +128,8 @@ impl<'a> Lines<'a> { } /// The edits Replace makes in `text`, in document order. With `only`, just the -/// matches starting at those positions. Regex replacements support `$1`, -/// `${name}`, `$$` and IDEA's `\n` / `\t` escapes (see [`crate::replace_in_text`]). +/// matches starting at those positions. Regex replacements are templates +/// (see [`crate::replace_in_text`]). pub fn replacement_edits( text: &str, query: &SearchQuery, @@ -156,7 +157,7 @@ fn edits_except( let compiled = query::compile(query)?; let matcher = &compiled.matcher; let haystack = text.as_bytes(); - let template = if query.is_regex { crate::unescape_replacement(replacement) } else { replacement.to_owned() }; + let template = Template::new(replacement, query.is_regex, &compiled)?; let only: Option> = only.map(|o| o.iter().copied().collect()); let skip: HashSet = skip.unwrap_or_default().iter().copied().collect(); let lines = Lines::new(text); @@ -172,13 +173,9 @@ fn edits_except( { return; } - let mut new_text = if query.is_regex { - buf.clear(); - caps.interpolate(|name| matcher.capture_index(name), haystack, template.as_bytes(), &mut buf); - String::from_utf8_lossy(&buf).into_owned() - } else { - template.clone() - }; + buf.clear(); + template.expand(caps, haystack, &mut buf); + let mut new_text = String::from_utf8_lossy(&buf).into_owned(); if preserve { new_text = preserve_case(&text[m.start()..m.end()], &new_text); } @@ -257,10 +254,8 @@ pub fn replace_files_in_context( on_event: &dyn Fn(ReplaceEvent), ) -> IdeResult { let literals = literals.filter(|_| query.context != SearchContext::Any); - // Fail fast on an invalid pattern instead of once per file. - if !query.pattern.is_empty() { - query::compile(query)?; - } + // Fail fast on an invalid pattern or replacement instead of once per file. + crate::validate_replacement(query, replacement)?; let started = Instant::now(); let total = targets.len() as u32; let mut summary = ReplaceSummary::default(); diff --git a/crates/ide-search/src/template.rs b/crates/ide-search/src/template.rs new file mode 100644 index 000000000..b27a0f63a --- /dev/null +++ b/crates/ide-search/src/template.rs @@ -0,0 +1,128 @@ +//! Replacement templates of regex queries. The editor's Replace reads the same +//! grammar (`src/editor/core/cm/replacement.ts`). + +use crate::query::Compiled; +use grep_matcher::{Captures, Matcher}; +use grep_regex::{RegexCaptures, RegexMatcher}; +use ide_core::{IdeError, IdeResult}; + +enum Part { + Text(String), + Group(usize), +} + +pub(crate) struct Template(Vec); + +impl Template { + /// Reads `replacement`: a template for a regex query, else text inserted as written. + pub fn new(replacement: &str, is_regex: bool, compiled: &Compiled) -> IdeResult { + if is_regex { + Self::parse(replacement, &compiled.matcher) + } else { + Ok(Self(vec![Part::Text(replacement.to_owned())])) + } + } + + fn parse(replacement: &str, matcher: &RegexMatcher) -> IdeResult { + let mut parts = Vec::new(); + let mut text = String::new(); + let mut rest = replacement; + while let Some(at) = rest.find(['$', '\\']) { + text.push_str(&rest[..at]); + let escape = rest.as_bytes()[at] == b'\\'; + rest = &rest[at + 1..]; + if escape { + rest = unescape(rest, &mut text); + continue; + } + match rest.as_bytes().first() { + Some(b'$') => { + text.push('$'); + rest = &rest[1..]; + } + // Other tools read it as the whole match; taken as text it would end up in every file. + Some(b'&') => { + return Err(IdeError::invalid("Invalid replacement: use $0 for the whole match instead of $&")); + } + _ => match group_ref(rest, matcher)? { + Some((group, len)) => { + if !text.is_empty() { + parts.push(Part::Text(std::mem::take(&mut text))); + } + parts.push(Part::Group(group)); + rest = &rest[len..]; + } + None => text.push('$'), + }, + } + } + text.push_str(rest); + if !text.is_empty() { + parts.push(Part::Text(text)); + } + Ok(Self(parts)) + } + + /// Appends the replacement for the match in `caps`; a group that took no part in it is empty. + pub fn expand(&self, caps: &RegexCaptures, haystack: &[u8], out: &mut Vec) { + for part in &self.0 { + match part { + Part::Text(text) => out.extend_from_slice(text.as_bytes()), + Part::Group(i) => { + if let Some(m) = caps.get(*i) { + out.extend_from_slice(&haystack[m]); + } + } + } + } + } +} + +/// Reads what follows a backslash, returning the rest; an unknown escape keeps its backslash. +fn unescape<'a>(after: &'a str, text: &mut String) -> &'a str { + let c = match after.as_bytes().first() { + Some(b'n') => '\n', + Some(b't') => '\t', + Some(b'r') => '\r', + Some(b'\\') => '\\', + Some(b'$') => '$', + _ => { + text.push('\\'); + return after; + } + }; + text.push(c); + &after[1..] +} + +/// The group named after a `$` and the length of its reference; `None` when the `$` is text. +fn group_ref(after: &str, matcher: &RegexMatcher) -> IdeResult> { + let missing = |group: &str| IdeError::invalid(format!("Invalid replacement: the pattern has no group {group}")); + let word = |s: &str| s.bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b'_').count(); + let numbered = |n: &str| n.parse().ok().filter(|i| *i < matcher.capture_count()); + if let Some(inner) = after.strip_prefix('{') { + let len = word(inner); + let name = &inner[..len]; + if name.is_empty() || !inner[len..].starts_with('}') { + return Ok(None); + } + let group = numbered(name).or_else(|| matcher.capture_index(name)).ok_or_else(|| missing(name))?; + return Ok(Some((group, len + 2))); + } + let digits = after.bytes().take_while(u8::is_ascii_digit).count(); + if digits > 0 { + // `$10` is group 1 and a `0` when there is no group 10, as in IDEA. + let (group, len) = (1..=digits) + .map_while(|len| numbered(&after[..len]).map(|group| (group, len))) + .last() + .ok_or_else(|| missing(&after[..1]))?; + return Ok(Some((group, len))); + } + let len = word(after); + if len == 0 { + return Ok(None); + } + let name = &after[..len]; + let group = matcher.capture_index(name).ok_or_else(|| missing(name))?; + Ok(Some((group, len))) +} diff --git a/crates/ide-search/tests/replace.rs b/crates/ide-search/tests/replace.rs index 9e9ecbe22..4b44b9bf1 100644 --- a/crates/ide-search/tests/replace.rs +++ b/crates/ide-search/tests/replace.rs @@ -1,7 +1,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult, Pos, TextEdit}; use ide_search::{ LiteralKind, LiteralRange, ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, - preview, replace_files, replace_files_in_context, replacement_edits, + preview, replace_files, replace_files_in_context, replace_in_text, replacement_edits, validate_replacement, }; use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -100,6 +100,108 @@ fn regex_groups_and_escapes() { assert_eq!(p.after, "v=k"); } +/// Replaces through every entry point, which must agree. +fn replace_everywhere(text: &str, pattern: &str, template: &str) -> IdeResult { + let q = regex(pattern); + let docs = FakeDocs::with(&[("a", text)]); + let replaced = + replace_files(&docs, &q, template, false, &targets(&["a"]), &CancellationToken::new(), &|_| {}).map(|_| ()); + let preview = preview(text, &q, template, false, None).map(|p| p.after); + let in_text = replace_in_text(text, &q, template).map(|(out, _)| out); + let valid = validate_replacement(&q, template); + assert_eq!(valid.err().map(|e| e.message).as_ref(), preview.as_ref().err().map(|e| &e.message)); + match &preview { + Ok(after) => { + replaced.unwrap(); + assert_eq!((&docs.text("a"), &in_text.unwrap()), (after, after), "s/{pattern}/{template}/"); + } + Err(e) => { + assert_eq!(replaced.err().map(|e| e.message).as_ref(), Some(&e.message), "s/{pattern}/{template}/"); + assert_eq!(in_text.err().map(|e| e.message).as_ref(), Some(&e.message), "s/{pattern}/{template}/"); + assert_eq!(docs.text("a"), text, "s/{pattern}/{template}/"); + } + } + preview +} + +#[test] +fn regex_templates() { + let ten = "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)"; + let cases = [ + // `$n` takes digits only while the pattern has that group. + ("foo.old();", r"(\w+)\.old", "$1_new", "foo_new();"), + ("getName()", r"get(\w+)", "fetch$1Value", "fetchNameValue()"), + ("a", "(a)", "$10", "a0"), + ("a", "(a)", "$01", "a"), + ("abcdefghij", ten, "$10$1$11", "jaa1"), + ("ab", "a(b)", "<$0>", ""), + ("foo.old", r"(\w+)\.old", "${1}_new", "foo_new"), + ("k1", r"(?P\w)(?\d)", "$n_1-$key=${key}${n_1}", "1-k=k1"), + // A group that took no part in the match is empty. + ("a", "(a)(b)?", "[$2${2}$1]", "[a]"), + ("a", "(?Pa)|(?Pb)", "$x|$y", "a|"), + ("a", "(a)", r"$$1 \$1 \\$1", r"$1 $1 \a"), + ("a", "(a)", r"\n\t\r\w\", "\n\t\r\\w\\"), + // `$` that starts no reference is text. + ("a", "(a)", "US$ $", "US$ $"), + ("a", "(a)", "${ ${} ${x.y} ${1", "${ ${} ${x.y} ${1"), + ]; + for (text, pattern, template, expected) in cases { + assert_eq!(replace_everywhere(text, pattern, template).unwrap(), expected, "s/{pattern}/{template}/"); + } +} + +#[test] +fn unknown_groups_are_an_invalid_replacement() { + let cases = [ + ("$2", "2"), + ("$0$1$9x", "9"), + ("${2}", "2"), + ("${10}", "10"), + ("${99999999999999999999}", "99999999999999999999"), + ("$name", "name"), + ("$key_new", "key_new"), + ("${key_new}", "key_new"), + ("${1_new}", "1_new"), + ]; + for (template, group) in cases { + // The template is checked before any match is looked for. + for text in ["a a", "zzz"] { + let err = replace_everywhere(text, "(?Pa)", template).unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput, "{template}"); + assert_eq!(err.message, format!("Invalid replacement: the pattern has no group {group}"), "{template}"); + } + } + let err = replace_everywhere("a", "(a)", "<$&>").unwrap_err(); + assert_eq!(err.message, "Invalid replacement: use $0 for the whole match instead of $&"); +} + +#[test] +fn an_invalid_replacement_changes_no_file() { + let docs = FakeDocs::with(&[("a", "foo"), ("b", "foo")]); + let t = targets(&["a", "b"]); + let events = Mutex::new(0); + let err = replace_files(&docs, ®ex("(foo)"), "$2", false, &t, &CancellationToken::new(), &|_| { + *events.lock().unwrap() += 1; + }) + .unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput); + assert_eq!((docs.text("a").as_str(), docs.text("b").as_str()), ("foo", "foo")); + assert_eq!((docs.steps.lock().unwrap().len(), *events.lock().unwrap()), (0, 0)); +} + +#[test] +fn literal_replacements_are_written_as_is() { + let template = r"$1 ${x} $& $$ \n"; + assert_eq!(preview("foo", &query("foo"), template, false, None).unwrap().after, template); +} + +#[test] +fn preserve_case_applies_to_the_expanded_groups() { + let p = preview("getName GETNAME", ®ex("get(name)"), "fetch$1Value", true, None).unwrap(); + assert_eq!(p.after, "fetchNameValue FETCHNAMEVALUE"); +} + #[test] fn preserve_case_rules() { assert_eq!(preserve_case("FOO", "bar"), "BAR"); diff --git a/src/bindings.ts b/src/bindings.ts index 84f8be497..23b0afea9 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2282,8 +2282,8 @@ export const commands = { * Cancel with `cancel_request(request)`. */ searchStart: (request: RequestId, query: SearchQuery, onEvent: Channel) => typedError(__TAURI_INVOKE("search_start", { request, query, onEvent })), - /** Validates a query (e.g. regex syntax) while the user types. */ - searchValidate: (query: SearchQuery) => typedError(__TAURI_INVOKE("search_validate", { query })), + /** Validates a query (e.g. regex syntax), and what Replace would insert, while the user types. */ + searchValidate: (query: SearchQuery, replacement: string | null) => typedError(__TAURI_INVOKE("search_validate", { query, replacement })), /** * Replaces the project groups; returns them as saved (names trimmed and unique, each * project in one group, only recent projects). diff --git a/src/editor/core/cm/find.test.ts b/src/editor/core/cm/find.test.ts index 4ef8f50d6..48e7308a3 100644 --- a/src/editor/core/cm/find.test.ts +++ b/src/editor/core/cm/find.test.ts @@ -23,6 +23,7 @@ import { replaceNext, setFindScope, setFindOpen, + setQuery, setReplacePreview, type FindOptions, } from "./find"; @@ -208,6 +209,73 @@ describe("replacement preview", () => { }); }); +/** Same cases as `regex_templates` in `crates/ide-search/tests/replace.rs`. */ +describe("regex replacement templates", () => { + const ten = "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)"; + const cases: Array<[text: string, search: string, replace: string, expected: string]> = [ + ["foo.old();", "(\\w+)\\.old", "$1_new", "foo_new();"], + ["getName()", "get(\\w+)", "fetch$1Value", "fetchNameValue()"], + ["a", "(a)", "$10", "a0"], + ["a", "(a)", "$01", "a"], + ["abcdefghij", ten, "$10$1$11", "jaa1"], + ["ab", "a(b)", "<$0>", ""], + ["foo.old", "(\\w+)\\.old", "${1}_new", "foo_new"], + ["k1", "(?\\w)(?\\d)", "$n_1-$key=${key}${n_1}", "1-k=k1"], + ["a", "(a)(b)?", "[$2${2}$1]", "[a]"], + ["a", "(?a)|(?b)", "$x|$y", "a|"], + ["a", "(a)", "$$1 \\$1 \\\\$1", "$1 $1 \\a"], + ["a", "(a)", "\\n\\t\\w\\", "\n\t\\w\\"], + ["a", "(a)", "US$ $", "US$ $"], + ["a", "(a)", "${ ${} ${x.y} ${1", "${ ${} ${x.y} ${1"], + ]; + + it.each(cases)("%s s/%s/%s/", (text, search, replace, expected) => { + const options = { search, regexp: true, replace }; + const replaced = (run: (v: EditorView) => void, scope?: { from: number; to: number }) => { + const v = make(text, options, scope); + run(v); + return v.state.doc.toString(); + }; + const next = (v: EditorView) => { + findNext(v); + replaceNext(v); + }; + const scope = { from: 0, to: text.length }; + expect([replaced(replaceAll), replaced(replaceAll, scope), replaced(next), replaced(next, scope)]).toEqual( + Array.from({ length: 4 }, () => expected), + ); + }); + + it.each(["$2", "$0$1$9x", "${2}", "${99999999999999999999}", "$name", "$key_new", "${key_new}", "${1_new}", "<$&>"])( + "%s changes nothing", + (replace) => { + for (const scope of [undefined, { from: 0, to: 3 }]) { + const v = make("a a", { search: "(?a)", regexp: true, replace }, scope); + v.dispatch({ effects: [setFindOpen.of(true), setReplacePreview.of(false)] }); + findNext(v); + expect([replaceNext(v), replaceAll(v), replaceNext(v, true), replaceAll(v, true)]).toEqual( + Array.from({ length: 4 }, () => false), + ); + expect(v.state.doc.toString()).toBe("a a"); + expect(v.dom.querySelector('[aria-label="Replacement preview"]')).toBeNull(); + } + }, + ); + + it("switching Regex off takes the template as text", () => { + const v = make("a", { search: "a", regexp: true, replace: "\\n" }); + setQuery(v, { search: "a", caseSensitive: false, wholeWord: false, regexp: false, replace: "\\n" }); + replaceAll(v); + expect(v.state.doc.toString()).toBe("\\n"); + }); + + it("keeps the case of the expanded text", () => { + const v = make("GETNAME", { search: "get(name)", regexp: true, replace: "fetch$1Value" }); + replaceAll(v, true); + expect(v.state.doc.toString()).toBe("FETCHNAMEVALUE"); + }); +}); + describe("plain-text queries", () => { it("match regex syntax and line breaks literally, case-insensitively", () => { const v = make("a.b(c)[d]$ x A.B(C)[D]$ axb\nend\n1 + 1 = 2", { search: "a.b(c)[d]$" }); diff --git a/src/editor/core/cm/find.ts b/src/editor/core/cm/find.ts index f705c43f7..ca23e5e49 100644 --- a/src/editor/core/cm/find.ts +++ b/src/editor/core/cm/find.ts @@ -1,6 +1,6 @@ /** - * Find / Replace in file. Matching and replacement (incl. regex groups) use - * @codemirror/search's query + commands; the bar itself is a React component + * Find / Replace in file. Matching uses @codemirror/search's query + commands, with + * Replace in Files' regex templates (./replacement.ts); the bar itself is a React component * (view/FindBar.tsx). Highlighting is ours because CodeMirror only highlights * while its own panel is open. Match positions found by the bar's counter are * kept in `findMarks` for the overview lane. The search context (comments / @@ -42,6 +42,7 @@ import { tx } from "@/platform/i18n"; import type { LineMatch } from "@/platform/ipc"; import { contextAccepts, preserveCase, type SearchContext } from "@/platform/search"; import { literalKindAt, literalsExtension } from "./literals"; +import { expandReplacement, literalReplacement, parseReplacement, type Replacement } from "./replacement"; import styles from "./FindPreview.module.css"; export const setFindOpen = StateEffect.define(); @@ -255,22 +256,56 @@ export interface FindQueryOptions extends FindOptions { /** The characters a regular expression treats as syntax (`-` only inside a class, which never opens here). */ const REGEX_SYNTAX = /[\\^$.*+?()[\]{}|/]/g; +/** What CodeMirror's replace commands ask for each replacement text. */ +interface Replacer { + getReplacement(m: Match): string; +} + +const createReplacer = (SearchQuery.prototype as unknown as { create(this: SearchQuery): Replacer }).create; + +/** A query whose replacement is read as Replace in Files reads it, not by CodeMirror. */ +class FindQuery extends SearchQuery { + private parsed: Replacement | undefined; + + get replacement(): Replacement { + return (this.parsed ??= this.valid ? parseReplacement(this.replace, this.search) : { parts: [] }); + } + + create(): Replacer { + const replacer = createReplacer.call(this); + replacer.getReplacement = (m) => this.replacementFor(m); + return replacer; + } + + replacementFor(m: Match): string { + const { replacement } = this; + if (replacement.error !== undefined) throw new Error(replacement.error); + return expandReplacement(replacement.parts, m.match!); + } +} + export function makeQuery(o: FindQueryOptions) { // CodeMirror compares a plain-text query one character at a time; the same text as an escaped // regular expression runs on the engine's matcher, over 20× faster in a large file, so every - // keystroke in the bar stays responsive. Its replacement escapes `$` to stay literal too. - return new SearchQuery({ + // keystroke in the bar stays responsive. Its replacement is escaped to stay literal too. + return new FindQuery({ search: o.regexp ? o.search : o.search.replace(REGEX_SYNTAX, "\\$&"), - // Plain-text search and replace are literal (`\n` is not a newline), as in IDEA. + // Plain-text search is literal (`\n` is not a newline), as in IDEA. literal: !o.regexp, caseSensitive: o.caseSensitive, wholeWord: o.wholeWord, regexp: true, - replace: o.regexp ? o.replace : o.replace.replaceAll("$", "$$$$"), + replace: o.regexp ? o.replace : literalReplacement(o.replace), test: testFor(o.context ?? "any", !!o.inChanges), }); } +/** Why Replace can't use the replacement of `o`, or null. */ +export function replacementError(o: FindOptions): string | null { + if (!o.regexp || !o.search || !regexValid(o.search)) return null; + return parseReplacement(o.replace, o.search).error ?? null; +} + export function setQuery(view: EditorView, o: FindQueryOptions) { const q = makeQuery(o); if (q.eq(getSearchQuery(view.state))) return; @@ -333,13 +368,6 @@ function matchesIn(state: EditorState, limit = Infinity): Match[] { return out; } -/** The replacement text for a match (regex groups, `\n` in regex mode), as CodeMirror computes it. */ -export function replacementFor(query: SearchQuery, m: Match): string { - const impl = (query as unknown as { create?: () => { getReplacement(m: Match): string } }).create?.(); - if (impl) return impl.getReplacement(m); - return query.replace; -} - function selectMatch(view: EditorView, m: Match) { view.dispatch({ selection: EditorSelection.single(m.from, m.to), @@ -365,6 +393,12 @@ function step(view: EditorView, forward: boolean): boolean { */ const usableQuery = (view: EditorView) => getSearchQuery(view.state).valid; +/** The query Replace can use: not with a replacement that names a group the pattern lacks. */ +function replaceQuery(state: EditorState): FindQuery | null { + const query = getSearchQuery(state); + return query instanceof FindQuery && query.valid && query.replacement.error === undefined ? query : null; +} + export function findNext(view: EditorView): boolean { if (view.state.field(findScope, false)) return step(view, true); return usableQuery(view) && cmFindNext(view); @@ -395,16 +429,16 @@ export function findPrevious(view: EditorView): boolean { } /** The text replacing `m`, keeping its case when `preserve` is set. */ -function insertFor(state: EditorState, query: SearchQuery, m: Match, preserve: boolean): string { - const insert = replacementFor(query, m); +function insertFor(state: EditorState, query: FindQuery, m: Match, preserve: boolean): string { + const insert = query.replacementFor(m); return preserve ? preserveCase(state.sliceDoc(m.from, m.to), insert) : insert; } function previewAtSelection(state: EditorState, preserve: boolean): Tooltip | null { - const query = getSearchQuery(state); + const query = replaceQuery(state); const { from, to } = state.selection.main; const scope = state.field(findScope, false); - if (!query.valid || !query.regexp || state.readOnly || from === to) return null; + if (!query || state.readOnly || from === to) return null; if (scope && (from < scope.from || to > scope.to)) return null; // Replace Next starts at the selection in the unscoped CodeMirror path. The @@ -473,9 +507,10 @@ const replacePreview = StateField.define<{ preserve: boolean | null; tooltip: To /** Replaces the selected match (if it is one) and selects the next match. */ export function replaceNext(view: EditorView, preserve = false): boolean { const { state } = view; - if (!state.field(findScope, false) && !preserve) return usableQuery(view) && cmReplaceNext(view); + const query = replaceQuery(state); + if (!query) return false; + if (!state.field(findScope, false) && !preserve) return cmReplaceNext(view); if (state.readOnly) return false; - const query = getSearchQuery(state); const ms = matchesIn(state); const { from, to } = state.selection.main; const cur = ms.find((m) => m.from === from && m.to === to); @@ -494,9 +529,10 @@ export function replaceNext(view: EditorView, preserve = false): boolean { export function replaceAll(view: EditorView, preserve = false): boolean { const { state } = view; - if (!state.field(findScope, false) && !preserve) return usableQuery(view) && cmReplaceAll(view); + const query = replaceQuery(state); + if (!query) return false; + if (!state.field(findScope, false) && !preserve) return cmReplaceAll(view); if (state.readOnly) return false; - const query = getSearchQuery(state); const changes = matchesIn(state).map((m) => ({ from: m.from, to: m.to, diff --git a/src/editor/core/cm/replacement.ts b/src/editor/core/cm/replacement.ts new file mode 100644 index 000000000..72c8b5650 --- /dev/null +++ b/src/editor/core/cm/replacement.ts @@ -0,0 +1,74 @@ +/** + * Replacement templates of regex searches, read as Replace in Files does + * (`crates/ide-search/src/template.rs`): `$1`, `${1}`, `$name`, `${name}`, `$$` and the + * escapes `\n`, `\t`, `\r`, `\$` and `\\`; any other `$` or backslash is text. + */ +import { tx } from "@/platform/i18n"; + +type Part = string | { group: number | string }; + +export type Replacement = { parts: Part[]; error?: undefined } | { error: string }; + +interface Groups { + count: number; + names: ReadonlySet; +} + +function groupsOf(pattern: string): Groups { + // The added empty alternative always matches, and a match lists every group of the pattern. + const match = new RegExp(`${pattern}|`, "u").exec("")!; + return { count: match.length, names: new Set(Object.keys(match.groups ?? {})) }; +} + +const ESCAPES: Record = { n: "\n", t: "\t", r: "\r", $: "$", "\\": "\\" }; + +const TOKEN = /\\([ntr$\\])|\$(?:([$&])|\{(\w+)\}|(\d+)|([A-Za-z_]\w*))/g; + +/** The longest prefix of `digits` that numbers a group: `$10` is group 1 and a `0` without a group 10. */ +function numbered(digits: string, count: number): number { + let len = 1; + while (len < digits.length && +digits.slice(0, len + 1) < count) len++; + return len; +} + +/** Reads `template` for a valid `pattern`. */ +export function parseReplacement(template: string, pattern: string): Replacement { + const groups = groupsOf(pattern); + const parts: Part[] = []; + const missing = (group: string) => ({ error: tx`Invalid replacement: the pattern has no group ${group}` }); + let at = 0; + for (const m of template.matchAll(TOKEN)) { + const [token, escape, sign, braced, digits, name] = m; + parts.push(template.slice(at, m.index)); + at = m.index + token.length; + if (escape) parts.push(ESCAPES[escape]!); + else if (sign === "$") parts.push("$"); + else if (sign) return { error: tx("Invalid replacement: use $0 for the whole match instead of $&") }; + else if (digits) { + const len = numbered(digits, groups.count); + const group = digits.slice(0, len); + if (+group >= groups.count) return missing(group); + parts.push({ group: +group }, digits.slice(len)); + } else { + const ref = (braced ?? name)!; + const group = /^\d+$/.test(ref) ? +ref : ref; + if (typeof group === "number" ? group >= groups.count : !groups.names.has(group)) return missing(ref); + parts.push({ group }); + } + } + parts.push(template.slice(at)); + return { parts }; +} + +/** The text of a template for `match`; a group that took no part in it is empty. */ +export function expandReplacement(parts: readonly Part[], match: RegExpExecArray): string { + return parts + .map((p) => { + if (typeof p === "string") return p; + return (typeof p.group === "number" ? match[p.group] : match.groups?.[p.group]) ?? ""; + }) + .join(""); +} + +/** The template inserting `text` as written. */ +export const literalReplacement = (text: string) => text.replace(/[\\$]/g, "\\$&"); diff --git a/src/editor/core/view/FindBar.test.tsx b/src/editor/core/view/FindBar.test.tsx index 5b2144ac1..79581514b 100644 --- a/src/editor/core/view/FindBar.test.tsx +++ b/src/editor/core/view/FindBar.test.tsx @@ -61,9 +61,16 @@ function setup() { }), }; disposers.push(() => view.destroy(), registerEditorActions(), installKeyboardDispatcher()); - const panel = render( {}} />); + const bar = (replace: boolean) => ( + {}} /> + ); + const panel = render(bar(false)); disposers.push(panel.unmount); - return { view, field: screen.getByRole("textbox", { name: "Find" }) }; + return { + view, + field: screen.getByRole("textbox", { name: "Find" }), + rerender: (replace: boolean) => panel.rerender(bar(replace)), + }; } const setSearch = (field: HTMLElement, value: string) => fireEvent.change(field, { target: { value } }); @@ -158,6 +165,40 @@ describe("Find bar More actions", () => { }); }); +describe("Replace bar", () => { + it("reports a replacement with an unknown group and replaces nothing until it is fixed", () => { + const { view, rerender } = setup(); + rerender(true); + act(() => useFindOptions.setState({ search: "(o+)", regexp: true, replace: "${2}" })); + const field = screen.getByRole("textbox", { name: "Replace" }); + const all = screen.getByRole("button", { name: "Replace All" }); + expect(screen.getByText("Bad replacement")).toBeInTheDocument(); + expect(field).toHaveAttribute("aria-invalid", "true"); + expect(field).toHaveAttribute("title", "Invalid replacement: the pattern has no group 2"); + expect(all).toBeDisabled(); + fireEvent.keyDown(field, { key: "Enter", code: "Enter" }); + fireEvent.keyDown(field, { key: "a", code: "KeyA", altKey: true }); + expect(view.state.doc.toString()).toBe("foo\nFOO\nfoo"); + + fireEvent.change(field, { target: { value: "<$1_>" } }); + expect(screen.queryByText("Bad replacement")).not.toBeInTheDocument(); + expect(field).not.toHaveAttribute("aria-invalid"); + fireEvent.click(all); + expect(view.state.doc.toString()).toBe("f\nF\nf"); + }); + + it("ignores the replacement while only finding, or with a bad pattern", () => { + const { rerender } = setup(); + act(() => useFindOptions.setState({ search: "(o+)", regexp: true, replace: "$2" })); + expect(screen.queryByText("Bad replacement")).not.toBeInTheDocument(); + rerender(true); + expect(screen.getByText("Bad replacement")).toBeInTheDocument(); + act(() => useFindOptions.setState({ search: "(o+" })); + expect(screen.getByText("Bad regex")).toBeInTheDocument(); + expect(screen.getByRole("textbox", { name: "Replace" })).not.toHaveAttribute("aria-invalid"); + }); +}); + describe("Find bars on different editors", () => { function editor(id: string, doc: string) { const view = new EditorView({ diff --git a/src/editor/core/view/FindBar.tsx b/src/editor/core/view/FindBar.tsx index 6b31627cd..b4ee28836 100644 --- a/src/editor/core/view/FindBar.tsx +++ b/src/editor/core/view/FindBar.tsx @@ -27,6 +27,7 @@ import { regexValid, replaceAll, replaceNext, + replacementError, setFindMarks, setFindOpen, setFindScope, @@ -588,13 +589,16 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo const invalid = opts.regexp && !!opts.search && !regexValid(opts.search); const none = !!opts.search && !invalid && count?.total === 0; + const badReplacement = replace ? replacementError(opts) : null; const counter = invalid ? "Bad regex" - : !opts.search - ? "" - : !count || count.total === 0 - ? "0 results" - : `${count.current || "?"}/${count.total}${count.capped ? "+" : ""}`; + : badReplacement + ? tx("Bad replacement") + : !opts.search + ? "" + : !count || count.total === 0 + ? "0 results" + : `${count.current || "?"}/${count.total}${count.capped ? "+" : ""}`; const filterItems: MenuItem[] = [ { @@ -711,7 +715,11 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo />
- + {counter} setOpts({ replace: value })} placeholder="Replace" aria-label="Replace" + invalid={!!badReplacement} + title={badReplacement ?? undefined} multiline maxRows={3} onHistory={() => setHistoryMenu("replace")} @@ -768,7 +778,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo size="small" title={tx`Replace (${formatBinding("Alt+P")})`} onClick={doReplace} - disabled={!canReplace} + disabled={!canReplace || !!badReplacement} > Replace @@ -776,7 +786,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo size="small" title={tx`Replace All (${formatBinding("Alt+A")})`} onClick={doReplaceAll} - disabled={!canReplace} + disabled={!canReplace || !!badReplacement} > Replace All diff --git a/src/features/search/__tests__/findPopup.test.tsx b/src/features/search/__tests__/findPopup.test.tsx index ae6ab2cb5..c05c5d43d 100644 --- a/src/features/search/__tests__/findPopup.test.tsx +++ b/src/features/search/__tests__/findPopup.test.tsx @@ -41,8 +41,10 @@ vi.mock("../find/windowStore", async (orig) => ({ nextRequestId: () => 1, }), })); +const validateReplacement = vi.hoisted(() => vi.fn(async (_query: SearchQuery, _replacement: string) => {})); vi.mock("../find/replaceFlow", async (orig) => ({ ...(await orig()), + validateReplacement, startReplace: (r: ReplaceRequest) => { replaced.push(r); const replacements = r.targets.reduce((n, t) => n + (t.only?.length ?? 0), 0); @@ -97,6 +99,8 @@ beforeEach(() => { validation = null; search = null; confirmation = null; + validateReplacement.mockReset(); + validateReplacement.mockResolvedValue(undefined); useFindPopup.setState({ pattern: "", caseSensitive: false, @@ -472,6 +476,40 @@ describe("outdated popup results", () => { expect(replaced).toHaveLength(0); }); + it("reports an invalid regex replacement at the field and replaces nothing until it is fixed", async () => { + const message = "Invalid replacement: the pattern has no group 2"; + validateReplacement.mockImplementation(async (_query, replacement) => { + if (replacement === "$2") throw new Error(message); + }); + render(); + act(() => showFindPopup(true, { query: "(order)" })); + act(() => useFindPopup.setState({ replacement: "$2" })); + await settle(); + await settle(); + expect(validateReplacement).not.toHaveBeenCalled(); + + act(() => useFindPopup.setState({ isRegex: true })); + await settle(); + await settle(); + const replace = screen.getByLabelText("Replace with"); + expect(screen.getByText(message)).toBeInTheDocument(); + expect(replace).toHaveAttribute("aria-invalid", "true"); + expect(screen.getByRole("button", { name: "Replace All" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Replace" })).toBeDisabled(); + fireEvent.keyDown(field(), { key: "Enter" }); + fireEvent.keyDown(field(), { key: "a", code: "KeyA", altKey: true }); + await settle(); + expect([replaced, confirms]).toEqual([[], []]); + + fireEvent.change(replace, { target: { value: "$1_new" } }); + await settle(); + expect(screen.queryByText(message)).not.toBeInTheDocument(); + expect(replace).not.toHaveAttribute("aria-invalid"); + fireEvent.click(screen.getByRole("button", { name: "Replace All" })); + await settle(); + expect(replaced).toHaveLength(1); + }); + it("rejects Replace All if the query changes while confirmation is open", async () => { render(); act(() => showFindPopup(true, { query: "order" })); diff --git a/src/features/search/find/FindInFiles.tsx b/src/features/search/find/FindInFiles.tsx index 376aa62b9..115eab81a 100644 --- a/src/features/search/find/FindInFiles.tsx +++ b/src/features/search/find/FindInFiles.tsx @@ -94,6 +94,7 @@ import { type NamedScope, type ScopeTab, } from "./store"; +import { useReplacementError } from "./useReplacementError"; import { ipcFindDeps, openInFindWindow } from "./windowStore"; import styles from "./FindInFiles.module.css"; @@ -240,6 +241,11 @@ function FindInFilesDialog() { const queryKey = JSON.stringify(query); const stale = !!query && (state.stale || (state.query ? JSON.stringify(state.query) !== queryKey : !!s.pattern)); + // An invalid pattern is reported at the pattern only, so the replacement waits for a checked one. + const replacementError = useReplacementError( + s.replace && !stale && state.status !== "invalid" ? query : null, + s.replacement, + ); const currentQuery = useRef(queryKey); const [rerun, setRerun] = useState(0); useEffect( @@ -314,6 +320,7 @@ function FindInFilesDialog() { const canReplace = () => !!query && !stale && + !replacementError && !session.current.stale && currentQuery.current === queryKey && session.current.files === state.files; @@ -743,6 +750,7 @@ function FindInFilesDialog() { leadingIcon="replace" placeholder="Replace" aria-label="Replace with" + invalid={!!replacementError} className={styles.field} multiline maxRows={3} @@ -760,6 +768,7 @@ function FindInFilesDialog() { />
)} + {replacementError &&
{txt(replacementError)}
}
)}
- {!stale && previewMode && s.replace && selected ? ( + {!stale && previewMode && s.replace && selected && !replacementError ? ( -
diff --git a/src/features/search/find/ScopesDialog.tsx b/src/features/search/find/ScopesDialog.tsx index 64a3fb496..bd5215cf6 100644 --- a/src/features/search/find/ScopesDialog.tsx +++ b/src/features/search/find/ScopesDialog.tsx @@ -56,16 +56,19 @@ function usePatternError(pattern: string): string | null { const setError = (error: string | null) => alive && setChecked({ pattern, error }); const t = setTimeout(() => { call( - commands.searchValidate({ - pattern: "", - isRegex: false, - caseSensitive: false, - wholeWord: false, - include: [], - exclude: [], - scope: { kind: "pattern", pattern }, - maxMatches: 0, - }), + commands.searchValidate( + { + pattern: "", + isRegex: false, + caseSensitive: false, + wholeWord: false, + include: [], + exclude: [], + scope: { kind: "pattern", pattern }, + maxMatches: 0, + }, + null, + ), ).then( () => setError(null), (e: unknown) => setError(String((e as Error)?.message ?? e)), diff --git a/src/features/search/find/replaceFlow.ts b/src/features/search/find/replaceFlow.ts index aabf8a0fa..49e78bccc 100644 --- a/src/features/search/find/replaceFlow.ts +++ b/src/features/search/find/replaceFlow.ts @@ -241,6 +241,11 @@ export function loadReplacePreview( return call(commands.replacePreview(query, replacement, preserveCase, path, only)); } +/** Rejects when `replacement` can't be used with the query: a regex template naming a group it lacks. */ +export async function validateReplacement(query: SearchQuery, replacement: string): Promise { + await call(commands.searchValidate(query, replacement)); +} + export function summaryText(s: ReplaceSummary): string { const occ = `${s.replacements} occurrence${s.replacements === 1 ? "" : "s"}`; const files = `${s.files} file${s.files === 1 ? "" : "s"}`; diff --git a/src/features/search/find/useReplacementError.ts b/src/features/search/find/useReplacementError.ts new file mode 100644 index 000000000..3218af093 --- /dev/null +++ b/src/features/search/find/useReplacementError.ts @@ -0,0 +1,28 @@ +import { useEffect, useState } from "react"; +import type { SearchQuery } from "@/platform/ipc"; +import { validateReplacement } from "./replaceFlow"; + +const DEBOUNCE_MS = 100; + +/** The backend's complaint about a regex replacement (debounced), or null; no check without a `query`. */ +export function useReplacementError(query: SearchQuery | null, replacement: string): string | null { + const [checked, setChecked] = useState<{ key: string; error: string | null } | null>(null); + const key = query?.isRegex && query.pattern ? JSON.stringify([query, replacement]) : null; + useEffect(() => { + if (!query || !key) return; + let alive = true; + const setError = (error: string | null) => alive && setChecked({ key, error }); + const t = setTimeout(() => { + validateReplacement(query, replacement).then( + () => setError(null), + (e: unknown) => setError(String((e as Error)?.message ?? e)), + ); + }, DEBOUNCE_MS); + return () => { + alive = false; + clearTimeout(t); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps -- `key` stands for the query and the replacement + }, [key]); + return checked && checked.key === key ? checked.error : null; +} diff --git a/src/features/search/find/windowStore.ts b/src/features/search/find/windowStore.ts index 5446a20a5..78ccc3d73 100644 --- a/src/features/search/find/windowStore.ts +++ b/src/features/search/find/windowStore.ts @@ -34,7 +34,7 @@ export const useFindWindow = create(() => ({ tabs: [], active: export function ipcFindDeps(): FindDeps { return { - validate: (q) => call(commands.searchValidate(q)).then(() => undefined), + validate: (q) => call(commands.searchValidate(q, null)).then(() => undefined), start: streamSearch, cancel: cancelRequest, nextRequestId, diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 296419d98..23f57305b 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -356,6 +356,9 @@ "At breakpoint": "At breakpoint", "Replacement preview": "Replacement preview", "Empty replacement": "Empty replacement", + "Bad replacement": "Bad replacement", + "Invalid replacement: the pattern has no group {group}": "Invalid replacement: the pattern has no group {group}", + "Invalid replacement: use $0 for the whole match instead of $&": "Invalid replacement: use $0 for the whole match instead of $&", "Build and Run": "Build and Run", "Gradle runtime": "Gradle runtime", "Changelists": "Changelists", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 615af2acc..e744dd105 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -3360,6 +3360,9 @@ "Replace with": "替换为", "Replacement preview": "替换预览", "Empty replacement": "替换为空", + "Bad replacement": "替换内容无效", + "Invalid replacement: the pattern has no group {group}": "替换内容无效:模式中没有捕获组 {group}", + "Invalid replacement: use $0 for the whole match instead of $&": "替换内容无效:请用 $0 代替 $& 表示整个匹配", "Replacements": "替换项", "Reports errors and warnings from language servers.": "报告来自语言服务器的错误和警告。", "Repository": "仓库",