diff --git a/crates/ide-host/src/ops/search.rs b/crates/ide-host/src/ops/search.rs index 176dd430b..ce118ee6d 100644 --- a/crates/ide-host/src/ops/search.rs +++ b/crates/ide-host/src/ops/search.rs @@ -22,6 +22,17 @@ pub fn literal_range(l: ide_language::Literal) -> ide_search::LiteralRange { ide_search::LiteralRange { start: l.start, end: l.end, kind } } +/// Comments and string literals of `text`, for the search context of Find and Replace in Files. +pub(crate) fn literals_of( + project: &crate::project::Project, + syntax: &ide_language::Syntax, + path: &Path, + text: &str, +) -> Option> { + let language = project.languages.detect(path, text.lines().next()); + Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect()) +} + /// Find in Files. Results stream through `on_event`; ends with `Done`. /// Cancel with `cancel_request(request)`. #[command(trust = always)] @@ -98,10 +109,7 @@ pub(crate) fn search_project( Some(ProjectFileSet::Test) => roots.is_test(rel), _ => true, }; - let literals = |path: &Path, text: &str| { - let language = project.languages.detect(path, text.lines().next()); - Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect()) - }; + let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text); let defaults = project.documents.file_defaults(); let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path)); let mut total = SearchSummary::default(); diff --git a/crates/ide-host/src/ops/search/commands.rs b/crates/ide-host/src/ops/search/commands.rs index dea2aa20e..c65a89482 100644 --- a/crates/ide-host/src/ops/search/commands.rs +++ b/crates/ide-host/src/ops/search/commands.rs @@ -75,9 +75,19 @@ pub async fn replace_in_files( let summary = tokio::task::spawn_blocking(move || { let targets = if all_in_scope { scope_targets(&project, &syntax, &query, targets, &cancel)? } else { targets }; let host = DocumentsHost(&project.documents); - ide_search::replace_files(&host, &query, &replacement, preserve_case, &targets, &cancel, &|e| { - let _ = events.send(e); - }) + let literals = |path: &Path, text: &str| super::literals_of(&project, &syntax, path, text); + ide_search::replace_files_in_context( + &host, + &query, + &replacement, + preserve_case, + &targets, + Some(&literals), + &cancel, + &|e| { + let _ = events.send(e); + }, + ) }) .await .map_err(|e| ide_core::IdeError::internal(e.to_string())); diff --git a/crates/ide-host/tests/replace_all.rs b/crates/ide-host/tests/replace_all.rs index 29c8fb3d2..8aaae9312 100644 --- a/crates/ide-host/tests/replace_all.rs +++ b/crates/ide-host/tests/replace_all.rs @@ -195,3 +195,56 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() { assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n"); 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)] +async fn replace_all_past_the_limit_keeps_to_the_search_context() { + use ide_search::SearchContext as C; + let comments = |word: &str| lines(2001, &format!("// {word}")); + let code = |name: &str, string: &str| format!("fn {name}() -> &'static str {{ \"{string}\" }}\n"); + let original = format!("{}{}", comments("tok"), code("tok", "tok")); + let cases = [ + (C::Any, format!("{}{}", comments("X"), code("X", "X"))), + (C::InComments, format!("{}{}", comments("X"), code("tok", "tok"))), + (C::InStringLiterals, format!("{}{}", comments("tok"), code("tok", "X"))), + (C::ExceptComments, format!("{}{}", comments("tok"), code("X", "X"))), + (C::ExceptStringLiterals, format!("{}{}", comments("X"), code("X", "tok"))), + (C::ExceptCommentsAndStringLiterals, format!("{}{}", comments("tok"), code("X", "tok"))), + ]; + for (context, expected) in cases { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("project"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join("lib.rs"), &original).unwrap(); + let host = Host::new(HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("data"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + }); + host.trust.decide(&root, true, false).unwrap(); + host.open_project("main", &root).unwrap(); + ops::search::replace_in_files( + &host, + "main", + RequestId::next(), + SearchQuery { context, ..query("tok", false) }, + "X".into(), + false, + vec![], + true, + ops::Channel::new(|_| {}), + ) + .await + .unwrap(); + assert_eq!(std::fs::read_to_string(root.join("lib.rs")).unwrap(), expected, "{context:?}"); + host.close_project("main"); + } +} diff --git a/crates/ide-search/src/engine.rs b/crates/ide-search/src/engine.rs index a15f76dae..6f5b0ec4d 100644 --- a/crates/ide-search/src/engine.rs +++ b/crates/ide-search/src/engine.rs @@ -6,8 +6,7 @@ use crate::mask::FileMask; use crate::pattern::ScopePattern; use crate::query::{Compiled, line_terminator}; use crate::{ - FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary, - TextSource, + FileMatches, LineMatch, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary, TextSource, }; use grep_regex::RegexMatcher; use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch}; @@ -462,12 +461,6 @@ impl<'a> FileSink<'a> { } } -/// Kind of the comment or string literal containing byte `pos` (`literals` sorted). -fn literal_at(literals: &[LiteralRange], pos: usize) -> Option { - let i = literals.partition_point(|l| l.start <= pos); - literals[..i].last().filter(|l| pos < l.end).map(|l| l.kind) -} - impl Sink for FileSink<'_> { type Error = io::Error; @@ -493,7 +486,7 @@ impl Sink for FileSink<'_> { }); if let Some((context, literals)) = self.context { let block_start = usize::try_from(m.absolute_byte_offset()).unwrap_or(usize::MAX); - found.retain(|&(a, _)| context.accepts(literal_at(literals, block_start.saturating_add(a)))); + found.retain(|&(a, _)| context.keeps(literals, block_start.saturating_add(a))); } let mut next = found.iter().copied().peekable(); diff --git a/crates/ide-search/src/lib.rs b/crates/ide-search/src/lib.rs index 5921784fe..1f240a10b 100644 --- a/crates/ide-search/src/lib.rs +++ b/crates/ide-search/src/lib.rs @@ -22,7 +22,7 @@ pub use mask::FileMask; pub use pattern::ScopePattern; pub use replace::{ ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview, - replace_files, replacement_edits, + replace_files, replace_files_in_context, replacement_edits, }; pub use words::{WordFiles, WordQuery, files_with_word}; @@ -99,8 +99,15 @@ impl SearchContext { } } + /// Whether a match starting at byte `at` is kept, given the file's sorted comments and + /// string literals. Find and Replace both filter with it, so they keep the same matches. + pub fn keeps(self, literals: &[LiteralRange], at: usize) -> bool { + let i = literals.partition_point(|l| l.start <= at); + self.accepts(literals[..i].last().filter(|l| at < l.end).map(|l| l.kind)) + } + /// Only matches inside comments / string literals: files without any are skipped. - fn needs_literals(self) -> bool { + pub(crate) fn needs_literals(self) -> bool { matches!(self, Self::InComments | Self::InStringLiterals) } } diff --git a/crates/ide-search/src/replace.rs b/crates/ide-search/src/replace.rs index 0800c29b4..06017af08 100644 --- a/crates/ide-search/src/replace.rs +++ b/crates/ide-search/src/replace.rs @@ -3,7 +3,7 @@ //! (the document layer in the app, so open editors update and each file is one //! undoable step). -use crate::{SearchQuery, iter, query}; +use crate::{LiteralRange, Literals, SearchContext, SearchQuery, iter, query}; use grep_matcher::{Captures, Matcher}; use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, TextEdit}; use serde::{Deserialize, Serialize}; @@ -128,10 +128,11 @@ pub fn replacement_edits( preserve: bool, only: Option<&[Pos]>, ) -> IdeResult> { - edits_except(text, query, replacement, preserve, only, None) + edits_except(text, query, replacement, preserve, only, None, None) } -/// [`replacement_edits`] leaving out the matches that start at `skip`. +/// [`replacement_edits`] leaving out the matches that start at `skip` and, given the text's +/// comments and string literals, those outside the query's [`crate::SearchContext`]. fn edits_except( text: &str, query: &SearchQuery, @@ -139,6 +140,7 @@ fn edits_except( preserve: bool, only: Option<&[Pos]>, skip: Option<&[Pos]>, + literals: Option<&[LiteralRange]>, ) -> IdeResult> { if query.pattern.is_empty() { return Ok(Vec::new()); @@ -156,7 +158,10 @@ fn edits_except( iter::for_each_captures(matcher, haystack, &mut caps, |caps| { let Some(m) = caps.get(0) else { return }; let start = lines.pos(m.start()); - if only.as_ref().is_some_and(|o| !o.contains(&start)) || skip.contains(&start) { + if only.as_ref().is_some_and(|o| !o.contains(&start)) + || skip.contains(&start) + || literals.is_some_and(|l| !query.context.keeps(l, m.start())) + { return; } let mut new_text = if query.is_regex { @@ -227,6 +232,23 @@ pub fn replace_files( cancel: &CancellationToken, on_event: &dyn Fn(ReplaceEvent), ) -> IdeResult { + replace_files_in_context(host, query, replacement, preserve, targets, None, cancel, on_event) +} + +/// [`replace_files`] honouring [`SearchQuery::context`] with the comments and string literals +/// `literals` finds, as [`crate::search_in_context`] does; without it every match is plain code. +#[allow(clippy::too_many_arguments)] +pub fn replace_files_in_context( + host: &dyn ReplaceHost, + query: &SearchQuery, + replacement: &str, + preserve: bool, + targets: &[ReplaceTarget], + literals: Option>, + cancel: &CancellationToken, + 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)?; @@ -244,8 +266,14 @@ pub fn replace_files( if only.is_some_and(|o| o.is_empty()) { continue; } - let result = - host.edit_file(&target.path, &mut |text| edits_except(text, query, replacement, preserve, only, skip)); + let result = host.edit_file(&target.path, &mut |text| { + let found = match literals.map(|l| l(&target.path, text)) { + // No syntax tree: nothing is in a comment or string, as in the search. + Some(None) if query.context.needs_literals() => return Ok(Vec::new()), + found => found.map(Option::unwrap_or_default), + }; + edits_except(text, query, replacement, preserve, only, skip, found.as_deref()) + }); match result { Ok(n) => { if n > 0 { diff --git a/crates/ide-search/tests/replace.rs b/crates/ide-search/tests/replace.rs index a67ae9623..a82977856 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::{ - ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, preview, replace_files, - replacement_edits, + LiteralKind, LiteralRange, ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, + preview, replace_files, replace_files_in_context, replacement_edits, }; use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -169,3 +169,46 @@ fn replace_files_respects_selected_matches_and_invalid_patterns() { let err = replace_files(&docs, ®ex("("), "x", false, &t, &CancellationToken::new(), &|_| {}).unwrap_err(); assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput); } + +/// `// …` comments and `"…"` strings of `.rs` files; other files have no syntax tree. +fn toy_literals(path: &Path, text: &str) -> Option> { + if path.extension().is_none_or(|e| e != "rs") { + return None; + } + let mut out = Vec::new(); + for (i, _) in text.match_indices("//") { + let end = text[i..].find('\n').map_or(text.len(), |n| i + n); + out.push(LiteralRange { start: i, end, kind: LiteralKind::Comment }); + } + let quotes: Vec = text.match_indices('"').map(|(i, _)| i).collect(); + for pair in quotes.chunks(2) { + if let [a, b] = pair { + out.push(LiteralRange { start: *a, end: b + 1, kind: LiteralKind::String }); + } + } + out.sort_by_key(|l| l.start); + Some(out) +} + +#[test] +fn replace_files_in_context_keeps_to_the_search_context() { + use ide_search::SearchContext as C; + let text = "foo(\"foo\"); // foo\nfoo\n"; + let plain = "foo // foo\n"; + let cases = [ + (C::Any, "x(\"x\"); // x\nx\n", "x // x\n"), + (C::InComments, "foo(\"foo\"); // x\nfoo\n", plain), + (C::InStringLiterals, "foo(\"x\"); // foo\nfoo\n", plain), + (C::ExceptComments, "x(\"x\"); // foo\nx\n", "x // x\n"), + (C::ExceptStringLiterals, "x(\"foo\"); // x\nx\n", "x // x\n"), + (C::ExceptCommentsAndStringLiterals, "x(\"foo\"); // foo\nx\n", "x // x\n"), + ]; + for (context, in_rs, in_txt) in cases { + let docs = FakeDocs::with(&[("a.rs", text), ("b.txt", plain)]); + let q = SearchQuery { context, ..query("foo") }; + let t = targets(&["a.rs", "b.txt"]); + replace_files_in_context(&docs, &q, "x", false, &t, Some(&toy_literals), &CancellationToken::new(), &|_| {}) + .unwrap(); + assert_eq!((docs.text("a.rs").as_str(), docs.text("b.txt").as_str()), (in_rs, in_txt), "{context:?}"); + } +}