use super::*;
pub(super) fn build_replace_regex(query: &str, opts: SearchOpts) -> Option<Pattern> {
let q = as_typed(query);
if q.is_empty() {
return None;
}
let body = if opts.use_regex {
q.to_string()
} else {
regex::escape(q)
};
let mut pattern = String::new();
if !opts.case_sensitive {
pattern.push_str("(?i)");
}
pattern.push_str(&body);
Pattern::new(&pattern)
}
pub(super) fn replace_in_line(
line: &str,
matcher: &SearchMatcher,
full: Option<&Pattern>,
replacement: &str,
opts: SearchOpts,
) -> (String, usize) {
let mut out = String::with_capacity(line.len());
let mut last = 0;
let mut pos = 0;
let mut count = 0;
let mut prev_end: Option<usize> = None;
while pos <= line.len() {
let Ok(Some(m)) = matcher.find_at(line.as_bytes(), pos) else {
break;
};
let (start, end) = (m.start(), m.end());
if !line.is_char_boundary(start) || !line.is_char_boundary(end) {
break;
}
let adjacent_empty = start == end && prev_end == Some(start);
if !adjacent_empty {
out.push_str(&line[last..start]);
let expanded = full
.filter(|_| opts.use_regex)
.and_then(|re| re.expand_at(line, start, end, replacement))
.unwrap_or_else(|| replacement.to_string());
if opts.preserve_case {
out.push_str(&preserve_case(&line[start..end], &expanded));
} else {
out.push_str(&expanded);
}
count += 1;
last = end;
prev_end = Some(end);
}
pos = if start == end {
match line[end..].chars().next() {
Some(c) => end + c.len_utf8(),
None => break,
}
} else {
end
};
}
out.push_str(&line[last..]);
(out, count)
}
pub(super) fn count_in_line(line: &str, matcher: &SearchMatcher) -> usize {
replace_in_line(line, matcher, None, "", SearchOpts::default()).1
}
pub(super) fn trim_leading_context(lead: &str, avail: usize, need: usize) -> Option<String> {
use unicode_width::UnicodeWidthChar;
if lead.width() + need <= avail {
return None;
}
let keep = avail.saturating_sub(need) / 2;
let mut width = 0;
let mut start = lead.len();
for (i, c) in lead.char_indices().rev() {
width += c.width().unwrap_or(0);
if width > keep {
break;
}
start = i;
}
Some(lead[start..].to_string())
}
pub(super) fn brace_refs(
replacement: &str,
groups: usize,
is_group: impl Fn(&str) -> bool,
) -> String {
let is_name = |c: &char| c.is_ascii_alphanumeric() || *c == '_';
let mut out = String::with_capacity(replacement.len());
let mut rest = replacement;
while let Some(at) = rest.find('$') {
out.push_str(&rest[..at]);
let after = &rest[at + 1..];
let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len();
let name_len = after
.chars()
.take_while(is_name)
.map(char::len_utf8)
.sum::<usize>();
let braced = after
.strip_prefix('{')
.and_then(|b| b.find('}').map(|end| &b[..end]));
let (expansion, used) = if after.starts_with('$') {
(String::from("$$"), 1)
} else if after.starts_with('&') {
(String::from("${0}"), 1)
} else if digits > 0 {
numbered_ref(&after[..digits], groups)
} else if let Some(name) = braced {
let group = if !name.is_empty() && name.chars().all(|c| c.is_ascii_digit()) {
name.parse::<usize>().is_ok_and(|g| g < groups)
} else {
is_group(name)
};
if group {
(format!("${{{name}}}"), name.len() + 2)
} else {
(String::from("$$"), 0)
}
} else if name_len > 0 && is_group(&after[..name_len]) {
(format!("${{{}}}", &after[..name_len]), name_len)
} else {
(String::from("$$"), 0)
};
out.push_str(&expansion);
rest = &after[used..];
}
out.push_str(rest);
out
}
pub(super) fn numbered_ref(digits: &str, groups: usize) -> (String, usize) {
(1..=digits.len())
.rev()
.find(|&n| digits[..n].parse::<usize>().is_ok_and(|g| g < groups))
.map_or((String::from("$$"), 0), |n| {
(format!("${{{}}}", &digits[..n]), n)
})
}
pub fn replace_in_text(
content: &str,
query: &str,
replacement: &str,
opts: SearchOpts,
) -> Option<(String, usize)> {
let q = as_typed(query);
let matcher = build_matcher(q, opts)?;
let full = if opts.use_regex {
let case = if opts.case_sensitive { "" } else { "(?i)" };
Some(Pattern::new(&format!("{case}{q}"))?)
} else {
None
};
let mut out = String::with_capacity(content.len());
let mut count = 0;
for piece in content.split_inclusive('\n') {
let body = piece
.strip_suffix("\r\n")
.or_else(|| piece.strip_suffix('\n'))
.unwrap_or(piece);
let (line, n) = replace_in_line(body, &matcher, full.as_ref(), replacement, opts);
out.push_str(&line);
out.push_str(&piece[body.len()..]);
count += n;
}
Some((out, count))
}
pub fn preserve_case(matched: &str, replacement: &str) -> String {
if matched.is_empty() {
return replacement.to_string();
}
let splits = |sep: char| {
matched.contains(sep)
&& replacement.contains(sep)
&& matched.split(sep).count() == replacement.split(sep).count()
};
let (hyphens, underscores) = (splits('-'), splits('_'));
if hyphens != underscores {
let sep = if hyphens { '-' } else { '_' };
return matched
.split(sep)
.zip(replacement.split(sep))
.map(|(m, r)| preserve_case(m, r))
.collect::<Vec<_>>()
.join(&sep.to_string());
}
if matched.to_uppercase() == matched {
return replacement.to_uppercase();
}
if matched.to_lowercase() == matched {
return replacement.to_lowercase();
}
let (Some(first), Some(lead)) = (matched.chars().next(), replacement.chars().next()) else {
return replacement.to_string();
};
let rest = &replacement[lead.len_utf8()..];
if first.is_uppercase() {
lead.to_uppercase().chain(rest.chars()).collect()
} else if first.is_lowercase() {
lead.to_lowercase().chain(rest.chars()).collect()
} else {
replacement.to_string()
}
}
pub fn expand_replacement(
matched: &str,
query: &str,
replacement: &str,
opts: SearchOpts,
) -> String {
let expanded = match build_replace_regex(query, opts) {
Some(re) if opts.use_regex => re
.spans(matched)
.first()
.and_then(|&(start, end)| {
let expanded = re.expand_at(matched, start, end, replacement)?;
Some(format!(
"{}{expanded}{}",
&matched[..start],
&matched[end..]
))
})
.unwrap_or_else(|| matched.to_string()),
_ => replacement.to_string(),
};
if opts.preserve_case {
preserve_case(matched, &expanded)
} else {
expanded
}
}
pub fn replace_in_file(
path: &Path,
query: &str,
replacement: &str,
opts: SearchOpts,
) -> Option<usize> {
let content = std::fs::read_to_string(path).ok()?;
let (new_content, count) = replace_in_text(&content, query, replacement, opts)?;
if count == 0 {
return Some(0);
}
crate::prefs::replace_file_contents(path, new_content.as_bytes()).ok()?;
Some(count)
}
pub(super) fn is_whole_word_match(haystack: &str, start: usize, end: usize) -> bool {
let prev_ok = start == 0
|| haystack[..start]
.chars()
.last()
.map(|c| !is_word_char(c))
.unwrap_or(true);
let next_ok = end >= haystack.len()
|| haystack[end..]
.chars()
.next()
.map(|c| !is_word_char(c))
.unwrap_or(true);
prev_ok && next_ok
}
pub(super) fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
impl SearchPanel {
pub fn replace_all_on_disk(&self) -> usize {
let needle = as_typed(&self.query);
if needle.is_empty() {
return 0;
}
let mut seen: HashSet<PathBuf> = HashSet::new();
let mut total = 0usize;
for hit in &self.hits {
if !seen.insert(hit.path.clone()) {
continue;
}
if let Some(n) = replace_in_file(&hit.path, needle, &self.replace, self.opts) {
total += n;
}
}
total
}
pub fn count_replacements(&self, skip: &HashSet<PathBuf>) -> (usize, usize) {
let needle = as_typed(&self.query);
if needle.is_empty() {
return (0, 0);
}
let mut seen: HashSet<PathBuf> = HashSet::new();
let mut occurrences = 0usize;
let mut files = 0usize;
for hit in &self.hits {
if !seen.insert(hit.path.clone()) {
continue;
}
if skip.contains(&hit.path) {
continue;
}
let Ok(content) = std::fs::read_to_string(&hit.path) else {
continue;
};
if let Some((_, n)) = replace_in_text(&content, needle, &self.replace, self.opts)
&& n > 0
{
occurrences += n;
files += 1;
}
}
(occurrences, files)
}
pub fn replace_all_skipping(
&self,
skip: &HashSet<PathBuf>,
) -> (usize, Vec<PathBuf>, Vec<PathBuf>) {
let needle = as_typed(&self.query);
if needle.is_empty() {
return (0, Vec::new(), Vec::new());
}
let mut failed = Vec::new();
let mut seen: HashSet<PathBuf> = HashSet::new();
let mut total = 0usize;
let mut skipped = Vec::new();
for hit in &self.hits {
if !seen.insert(hit.path.clone()) {
continue;
}
if skip.contains(&hit.path) {
skipped.push(hit.path.clone());
continue;
}
match replace_in_file(&hit.path, needle, &self.replace, self.opts) {
Some(n) => total += n,
None => failed.push(hit.path.clone()),
}
}
(total, skipped, failed)
}
}