use globset::{Glob, GlobSet, GlobSetBuilder};
use grep_regex::{RegexMatcher, RegexMatcherBuilder};
use grep_searcher::{BinaryDetection, MmapChoice, Searcher, SearcherBuilder, Sink, SinkMatch};
use ignore::{WalkBuilder, WalkState};
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Widget},
};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
const MAX_LINE_LEN: usize = 200;
const FIELD_FILL_LIFT_IDLE: u8 = 0x14;
const FIELD_FILL_LIFT_FOCUS: u8 = 0x22;
const FIELD_BAR_IDLE: Color = Color::Rgb(0x2b, 0x31, 0x3b);
fn lift_bg((r, g, b): (u8, u8, u8), d: u8) -> Color {
Color::Rgb(
r.saturating_add(d),
g.saturating_add(d),
b.saturating_add(d),
)
}
fn draw_field_divider(buf: &mut Buffer, x0: u16, x1: u16, y: u16, theme: crate::theme::Theme) {
let style = Style::default().fg(theme.ui(FIELD_BAR_IDLE));
for x in x0..=x1 {
buf.set_string(x, y, "─", style);
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SearchHit {
pub path: PathBuf,
pub line_no: usize,
pub line_text: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct SearchOpts {
pub case_sensitive: bool,
pub whole_word: bool,
pub use_regex: bool,
}
fn build_matcher(query: &str, opts: SearchOpts) -> Option<RegexMatcher> {
if query.is_empty() {
return None;
}
let mut b = RegexMatcherBuilder::new();
b.case_insensitive(!opts.case_sensitive);
b.word(opts.whole_word);
b.fixed_strings(!opts.use_regex);
b.build(query).ok()
}
fn build_searcher() -> Searcher {
SearcherBuilder::new()
.line_number(true)
.binary_detection(BinaryDetection::quit(b'\x00'))
.memory_map(MmapChoice::never())
.build()
}
#[derive(Clone, Debug, Default)]
pub struct PathFilter {
include: Option<GlobSet>,
exclude: Option<GlobSet>,
}
fn build_glob_set(raw: &str) -> Option<GlobSet> {
let mut builder = GlobSetBuilder::new();
let mut any = false;
for part in raw.split(',') {
let pat = part.trim();
if pat.is_empty() {
continue;
}
let expanded = if pat.contains('/') {
pat.to_string()
} else {
format!("**/{pat}")
};
if let Ok(g) = Glob::new(&expanded) {
builder.add(g);
any = true;
}
}
if !any {
return None;
}
builder.build().ok()
}
impl PathFilter {
pub fn new(include: &str, exclude: &str) -> Self {
Self {
include: build_glob_set(include),
exclude: build_glob_set(exclude),
}
}
pub fn is_empty(&self) -> bool {
self.include.is_none() && self.exclude.is_none()
}
pub fn allows(&self, root: &Path, path: &Path) -> bool {
let rel = path.strip_prefix(root).unwrap_or(path);
if let Some(inc) = &self.include
&& !inc.is_match(rel)
{
return false;
}
if let Some(exc) = &self.exclude
&& exc.is_match(rel)
{
return false;
}
true
}
}
struct HitSink<'a> {
path: PathBuf,
batch: &'a mut Vec<SearchHit>,
cancel: Option<Arc<AtomicBool>>,
}
impl<'a> Sink for HitSink<'a> {
type Error = std::io::Error;
fn matched(
&mut self,
_searcher: &Searcher,
mat: &SinkMatch<'_>,
) -> Result<bool, std::io::Error> {
if let Some(c) = self.cancel.as_ref()
&& c.load(Ordering::Relaxed)
{
return Ok(false);
}
let line_no = mat.line_number().unwrap_or(0) as usize;
let line_str = std::str::from_utf8(mat.bytes()).unwrap_or("");
let stripped = line_str.trim_end_matches(['\r', '\n']);
let trimmed = stripped.trim_start();
let cut = if trimmed.chars().count() > MAX_LINE_LEN {
trimmed.chars().take(MAX_LINE_LEN).collect()
} else {
trimmed.to_string()
};
self.batch.push(SearchHit {
path: self.path.clone(),
line_no,
line_text: cut,
});
Ok(true)
}
}
pub fn search_workspace_streaming<F>(
root: &Path,
query: &str,
opts: SearchOpts,
cancel: &Arc<AtomicBool>,
on_batch: F,
) where
F: FnMut(Vec<SearchHit>) + Send + Clone,
{
search_workspace_streaming_skipping(root, query, opts, cancel, &HashSet::new(), on_batch);
}
pub fn search_workspace_streaming_skipping<F>(
root: &Path,
query: &str,
opts: SearchOpts,
cancel: &Arc<AtomicBool>,
skip: &HashSet<PathBuf>,
on_batch: F,
) where
F: FnMut(Vec<SearchHit>) + Send + Clone,
{
search_workspace_streaming_filtered(
root,
query,
opts,
cancel,
skip,
&PathFilter::default(),
on_batch,
);
}
pub fn search_workspace_streaming_filtered<F>(
root: &Path,
query: &str,
opts: SearchOpts,
cancel: &Arc<AtomicBool>,
skip: &HashSet<PathBuf>,
filter: &PathFilter,
on_batch: F,
) where
F: FnMut(Vec<SearchHit>) + Send + Clone,
{
let q = query.trim();
if q.is_empty() {
return;
}
let Some(matcher) = build_matcher(q, opts) else {
return;
};
let walker = WalkBuilder::new(root)
.git_ignore(true)
.hidden(true)
.build_parallel();
let root = root.to_path_buf();
walker.run(|| {
let matcher = matcher.clone();
let cancel = cancel.clone();
let skip = skip.clone();
let filter = filter.clone();
let root = root.clone();
let mut on_batch = on_batch.clone();
Box::new(move |entry| {
if cancel.load(Ordering::Relaxed) {
return WalkState::Quit;
}
let entry = match entry {
Ok(e) => e,
Err(_) => return WalkState::Continue,
};
if !entry.file_type().is_some_and(|t| t.is_file()) {
return WalkState::Continue;
}
let path = entry.path();
if !filter.is_empty() && !filter.allows(&root, path) {
return WalkState::Continue;
}
if !skip.is_empty() && path.canonicalize().is_ok_and(|canon| skip.contains(&canon)) {
return WalkState::Continue;
}
let mut batch: Vec<SearchHit> = Vec::new();
{
let mut sink = HitSink {
path: path.to_path_buf(),
batch: &mut batch,
cancel: Some(cancel.clone()),
};
let mut searcher = build_searcher();
let _ = searcher.search_path(&matcher, path, &mut sink);
}
if !batch.is_empty() {
on_batch(batch);
}
WalkState::Continue
})
});
}
pub fn search_workspace(root: &Path, query: &str, opts: SearchOpts) -> Vec<SearchHit> {
let cancel = Arc::new(AtomicBool::new(false));
let collected: Arc<std::sync::Mutex<Vec<SearchHit>>> =
Arc::new(std::sync::Mutex::new(Vec::new()));
let collected_for_cb = collected.clone();
search_workspace_streaming(root, query, opts, &cancel, move |batch| {
if let Ok(mut g) = collected_for_cb.lock() {
g.extend(batch);
}
});
Arc::try_unwrap(collected)
.map(|m| m.into_inner().unwrap_or_default())
.unwrap_or_default()
}
pub fn line_may_match(line: &str, needle: &str, opts: SearchOpts) -> bool {
if needle.is_empty() || opts.use_regex {
return true;
}
if !line.is_ascii() || !needle.is_ascii() {
return true;
}
if opts.case_sensitive {
return line.contains(needle);
}
let (hay, pat) = (line.as_bytes(), needle.as_bytes());
if pat.len() > hay.len() {
return false;
}
hay.windows(pat.len()).any(|w| w.eq_ignore_ascii_case(pat))
}
pub fn split_for_highlight(line: &str, needle: &str, opts: SearchOpts) -> Vec<(String, bool)> {
if needle.is_empty() {
return vec![(line.to_string(), false)];
}
if opts.use_regex {
return split_for_highlight_regex(line, needle, opts);
}
let (haystack, search_for): (String, String) = if opts.case_sensitive {
(line.to_string(), needle.to_string())
} else {
(line.to_lowercase(), needle.to_lowercase())
};
let shifts = |t: &str| {
t.chars()
.any(|c| c.to_lowercase().map(char::len_utf8).sum::<usize>() != c.len_utf8())
};
if !opts.case_sensitive && (shifts(line) || shifts(needle)) {
let literal = SearchOpts {
use_regex: true,
..opts
};
return split_for_highlight_regex(line, ®ex::escape(needle), literal);
}
if search_for.is_empty() {
return vec![(line.to_string(), false)];
}
let mut out: Vec<(String, bool)> = Vec::new();
let mut last = 0usize;
let mut start = 0usize;
while let Some(rel) = haystack[start..].find(&search_for) {
let abs = start + rel;
let end = abs + search_for.len();
if opts.whole_word && !is_whole_word_match(&haystack, abs, end) {
start = end;
continue;
}
if abs > last {
out.push((line[last..abs].to_string(), false));
}
out.push((line[abs..end].to_string(), true));
last = end;
start = end;
}
if last < line.len() {
out.push((line[last..].to_string(), false));
}
if out.is_empty() {
out.push((line.to_string(), false));
}
out
}
fn split_for_highlight_regex(line: &str, needle: &str, opts: SearchOpts) -> Vec<(String, bool)> {
let mut pattern = String::new();
if !opts.case_sensitive {
pattern.push_str("(?i)");
}
if opts.whole_word {
pattern.push_str("\\b(?:");
pattern.push_str(needle);
pattern.push_str(")\\b");
} else {
pattern.push_str(needle);
}
let re = match regex::Regex::new(&pattern) {
Ok(r) => r,
Err(_) => return vec![(line.to_string(), false)],
};
let mut out: Vec<(String, bool)> = Vec::new();
let mut last = 0usize;
for m in re.find_iter(line) {
if m.start() > last {
out.push((line[last..m.start()].to_string(), false));
}
if m.end() == m.start() {
out.push((String::new(), true));
last = m.end();
continue;
}
out.push((line[m.start()..m.end()].to_string(), true));
last = m.end();
}
if last < line.len() {
out.push((line[last..].to_string(), false));
}
if out.is_empty() {
out.push((line.to_string(), false));
}
out
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SearchEvent {
Hits(String, SearchOpts, Vec<SearchHit>),
Done(String, SearchOpts),
}
#[derive(Clone, Debug)]
pub enum SearchRequest {
Query(String, SearchOpts),
SetRoot(PathBuf),
SetRoots(Vec<PathBuf>),
SetDirtyBuffers(Vec<(PathBuf, String)>),
SetFilter(String, String),
}
const SEARCH_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(200);
pub fn search_worker_loop(
root: PathBuf,
rx: std::sync::mpsc::Receiver<SearchRequest>,
tx: std::sync::mpsc::Sender<SearchEvent>,
) {
let mut roots: Vec<PathBuf> = vec![root];
use std::sync::mpsc::RecvTimeoutError;
let mut current: Option<(std::thread::JoinHandle<()>, Arc<AtomicBool>)> = None;
let mut dirty: Vec<(PathBuf, String)> = Vec::new();
let mut filter = PathFilter::default();
while let Ok(mut latest) = rx.recv() {
if let Some((handle, cancel)) = current.take() {
cancel.store(true, Ordering::Relaxed);
let _ = handle.join();
}
match latest {
SearchRequest::SetRoot(new_root) => {
roots = vec![new_root];
continue;
}
SearchRequest::SetRoots(new_roots) if !new_roots.is_empty() => {
roots = new_roots;
continue;
}
SearchRequest::SetRoots(_) => continue,
SearchRequest::SetDirtyBuffers(buffers) => {
dirty = buffers;
continue;
}
SearchRequest::SetFilter(ref include, ref exclude) => {
filter = PathFilter::new(include, exclude);
continue;
}
SearchRequest::Query(..) => {}
}
loop {
match rx.recv_timeout(SEARCH_DEBOUNCE) {
Ok(SearchRequest::SetRoot(new_root)) => roots = vec![new_root],
Ok(SearchRequest::SetRoots(new_roots)) if !new_roots.is_empty() => {
roots = new_roots
}
Ok(SearchRequest::SetRoots(_)) => {}
Ok(SearchRequest::SetDirtyBuffers(buffers)) => dirty = buffers,
Ok(SearchRequest::SetFilter(include, exclude)) => {
filter = PathFilter::new(&include, &exclude)
}
Ok(newer) => latest = newer,
Err(RecvTimeoutError::Timeout) => break,
Err(RecvTimeoutError::Disconnected) => return,
}
}
let SearchRequest::Query(query, opts) = latest else {
continue;
};
if query.trim().is_empty() {
if tx.send(SearchEvent::Done(query, opts)).is_err() {
return;
}
continue;
}
let cancel = Arc::new(AtomicBool::new(false));
let cancel_for_thread = cancel.clone();
let tx_for_thread = tx.clone();
let roots_for_thread = roots.clone();
let query_for_thread = query.clone();
let dirty_for_thread = dirty.clone();
let filter_for_thread = filter.clone();
let handle = std::thread::spawn(move || {
let q_for_emit = query_for_thread.clone();
let tx_for_emit = tx_for_thread.clone();
let mut skip: HashSet<PathBuf> = HashSet::new();
let mut buf_hits: Vec<SearchHit> = Vec::new();
for (path, content) in &dirty_for_thread {
if let Ok(canon) = path.canonicalize() {
skip.insert(canon);
}
let owner = roots_for_thread
.iter()
.find(|r| path.starts_with(r))
.unwrap_or(&roots_for_thread[0]);
if !filter_for_thread.is_empty() && !filter_for_thread.allows(owner, path) {
continue;
}
collect_matches_in_text(path, content, &query_for_thread, opts, &mut buf_hits);
}
if !buf_hits.is_empty() {
let _ = tx_for_emit.send(SearchEvent::Hits(q_for_emit.clone(), opts, buf_hits));
}
for scan_root in &roots_for_thread {
if cancel_for_thread.load(Ordering::Relaxed) {
break;
}
let tx_for_root = tx_for_emit.clone();
let q_for_root = q_for_emit.clone();
search_workspace_streaming_filtered(
scan_root,
&query_for_thread,
opts,
&cancel_for_thread,
&skip,
&filter_for_thread,
move |batch| {
let _ =
tx_for_root.send(SearchEvent::Hits(q_for_root.clone(), opts, batch));
},
);
}
let _ = tx_for_thread.send(SearchEvent::Done(query_for_thread, opts));
});
current = Some((handle, cancel));
}
if let Some((handle, cancel)) = current.take() {
cancel.store(true, Ordering::Relaxed);
let _ = handle.join();
}
}
pub fn collect_matches_in_text(
path: &Path,
content: &str,
query: &str,
opts: SearchOpts,
out: &mut Vec<SearchHit>,
) {
let q = query.trim();
if q.is_empty() {
return;
}
let Some(matcher) = build_matcher(q, opts) else {
return;
};
let mut sink = HitSink {
path: path.to_path_buf(),
batch: out,
cancel: None,
};
let mut searcher = SearcherBuilder::new()
.line_number(true)
.binary_detection(BinaryDetection::quit(b'\x00'))
.build();
let _ = searcher.search_slice(&matcher, content.as_bytes(), &mut sink);
}
fn build_replace_regex(query: &str, opts: SearchOpts) -> Option<regex::Regex> {
let q = query.trim();
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);
regex::Regex::new(&pattern).ok()
}
fn replace_in_line(
line: &str,
matcher: &RegexMatcher,
full: Option<®ex::Regex>,
replacement: &str,
opts: SearchOpts,
) -> (String, usize) {
use grep_matcher::Matcher;
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 caps = full.and_then(|re| {
re.captures_at(line, start)
.filter(|c| {
c.get(0)
.is_some_and(|m| (m.start(), m.end()) == (start, end))
})
.or_else(|| {
re.captures(&line[start..end])
.filter(|c| c.get(0).is_some_and(|m| m.range() == (0..end - start)))
})
});
match caps {
Some(caps) if opts.use_regex => {
let mut expanded = String::new();
caps.expand(&brace_group_refs(replacement), &mut expanded);
out.push_str(&expanded);
}
_ => out.push_str(replacement),
}
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 fn brace_group_refs(replacement: &str) -> String {
let mut out = String::with_capacity(replacement.len());
let mut chars = replacement.chars().peekable();
while let Some(c) = chars.next() {
if c != '$' {
out.push(c);
continue;
}
if chars.peek() == Some(&'$') {
chars.next();
out.push_str("$$");
continue;
}
let mut digits = String::new();
while let Some(&d) = chars.peek().filter(|d| d.is_ascii_digit()) {
digits.push(d);
chars.next();
}
if digits.is_empty() {
out.push('$');
} else {
out.push_str(&format!("${{{digits}}}"));
}
}
out
}
pub fn replace_in_text(
content: &str,
query: &str,
replacement: &str,
opts: SearchOpts,
) -> Option<(String, usize)> {
let q = query.trim();
let matcher = build_matcher(q, opts)?;
let full = if opts.use_regex {
let case = if opts.case_sensitive { "" } else { "(?i)" };
Some(regex::Regex::new(&format!("{case}{q}")).ok()?)
} 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 expand_replacement(
matched: &str,
query: &str,
replacement: &str,
opts: SearchOpts,
) -> String {
let Some(re) = build_replace_regex(query, opts) else {
return replacement.to_string();
};
if opts.use_regex {
re.replace(matched, brace_group_refs(replacement).as_str())
.into_owned()
} else {
replacement.to_string()
}
}
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);
}
#[cfg(unix)]
let in_place = std::fs::metadata(path).is_ok_and(|m| {
use std::os::unix::fs::MetadataExt;
m.nlink() > 1 || m.uid() != unsafe { libc::geteuid() }
});
#[cfg(not(unix))]
let in_place = false;
if !in_place {
let name = path.file_name()?.to_string_lossy();
let tmp = path.with_file_name(format!(".{name}.croft-replace-{}", std::process::id()));
match crate::prefs::write_keeping_mode(&tmp, path, new_content.as_bytes()) {
Ok(()) => {
if std::fs::rename(&tmp, path).is_ok() {
return Some(count);
}
let _ = std::fs::remove_file(&tmp);
return None;
}
Err(e) => {
use std::io::ErrorKind;
if !matches!(
e.kind(),
ErrorKind::PermissionDenied | ErrorKind::AlreadyExists
) {
let _ = std::fs::remove_file(&tmp);
return None;
}
}
}
}
std::fs::write(path, new_content).ok()?;
Some(count)
}
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
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
pub struct SearchPanel {
pub query: String,
pub hits: Vec<SearchHit>,
pub selected: usize,
pub scroll: usize,
pub focused: bool,
pub focus_gradient: bool,
pub theme: crate::theme::Theme,
pub last_inner: Rect,
pub last_area: Rect,
pub root: PathBuf,
pub roots: Vec<PathBuf>,
pub opts: SearchOpts,
pub toggle_case_x: u16,
pub toggle_word_x: u16,
pub toggle_regex_x: u16,
pub toggle_y: u16,
pub paste_button_x: u16,
pub paste_button_y: u16,
pub paste_button_w: u16,
pub selection: Option<(usize, usize)>,
pub last_scrollbar: Rect,
pub hover_pointer: Option<(u16, u16)>,
pub replace: String,
pub include: String,
pub exclude: String,
pub replace_open: bool,
pub details_open: bool,
pub field: SearchField,
pub complete: bool,
pub field_selection: Option<(usize, usize)>,
pub chevron_x: u16,
pub chevron_y: u16,
pub replace_all_x: u16,
pub replace_all_y: u16,
pub ellipsis_x: u16,
pub ellipsis_y: u16,
pub refresh_x: u16,
pub refresh_y: u16,
pub clear_x: u16,
pub clear_y: u16,
pub query_input_rect: Rect,
pub replace_input_rect: Rect,
pub include_input_rect: Rect,
pub exclude_input_rect: Rect,
pub results_start_offset: u16,
caret_cell: Option<(u16, u16)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum SearchField {
#[default]
Query,
Replace,
Include,
Exclude,
}
impl SearchPanel {
pub fn new(root: PathBuf) -> Self {
Self {
roots: vec![root.clone()],
query: String::new(),
hits: Vec::new(),
selected: 0,
scroll: 0,
focused: false,
focus_gradient: false,
theme: crate::theme::Theme::default(),
last_inner: Rect::default(),
last_area: Rect::default(),
root,
opts: SearchOpts::default(),
toggle_case_x: 0,
toggle_word_x: 0,
toggle_regex_x: 0,
toggle_y: 0,
paste_button_x: 0,
paste_button_y: 0,
paste_button_w: 0,
selection: None,
last_scrollbar: Rect::default(),
hover_pointer: None,
replace: String::new(),
include: String::new(),
exclude: String::new(),
replace_open: false,
details_open: false,
field: SearchField::Query,
complete: false,
field_selection: None,
chevron_x: 0,
chevron_y: 0,
replace_all_x: 0,
replace_all_y: 0,
ellipsis_x: 0,
ellipsis_y: 0,
refresh_x: 0,
refresh_y: 0,
clear_x: 0,
clear_y: 0,
query_input_rect: Rect::default(),
replace_input_rect: Rect::default(),
include_input_rect: Rect::default(),
exclude_input_rect: Rect::default(),
results_start_offset: 5,
caret_cell: None,
}
}
pub fn cursor_screen_pos(&self) -> Option<(u16, u16)> {
if !self.focused {
return None;
}
self.caret_cell
}
pub fn paste_button_at(&self, col: u16, row: u16) -> bool {
if self.paste_button_w == 0 || row != self.paste_button_y {
return false;
}
col >= self.paste_button_x && col < self.paste_button_x + self.paste_button_w
}
pub fn selection_range(&self) -> Option<(usize, usize)> {
self.selection
.map(|(a, b)| if a <= b { (a, b) } else { (b, a) })
}
pub fn seed(&mut self, query: String, include: String, exclude: String) {
self.query = query;
self.include = include;
self.exclude = exclude;
self.field = SearchField::Query;
self.selection = None;
self.field_selection = None;
}
pub fn select_all_query(&mut self) {
if self.query.is_empty() {
self.selection = None;
} else {
self.selection = Some((0, self.query.len()));
}
}
pub fn clear_selection(&mut self) {
self.selection = None;
}
pub fn delete_selection(&mut self) -> bool {
let Some((a, b)) = self.selection_range() else {
return false;
};
if a == b {
self.selection = None;
return false;
}
self.query.replace_range(a..b, "");
self.selection = None;
true
}
pub fn selection_text(&self) -> String {
match self.selection_range() {
Some((a, b)) if a < b => self.query[a..b].to_string(),
_ => String::new(),
}
}
pub fn insert_str_into_query(&mut self, s: &str) {
self.delete_selection();
for c in s.chars() {
if c != '\n' && c != '\r' {
self.query.push(c);
}
}
}
fn active_text_mut(&mut self) -> &mut String {
match self.field {
SearchField::Query => &mut self.query,
SearchField::Replace => &mut self.replace,
SearchField::Include => &mut self.include,
SearchField::Exclude => &mut self.exclude,
}
}
pub fn active_text(&self) -> &str {
match self.field {
SearchField::Query => &self.query,
SearchField::Replace => &self.replace,
SearchField::Include => &self.include,
SearchField::Exclude => &self.exclude,
}
}
pub fn active_text_mut_clear(&mut self) {
self.active_text_mut().clear();
}
pub fn clear_active_selection(&mut self) {
self.set_active_selection(None);
}
fn active_selection(&self) -> Option<(usize, usize)> {
let sel = match self.field {
SearchField::Query => self.selection,
_ => self.field_selection,
};
sel.map(|(a, b)| if a <= b { (a, b) } else { (b, a) })
}
fn set_active_selection(&mut self, sel: Option<(usize, usize)>) {
match self.field {
SearchField::Query => self.selection = sel,
_ => self.field_selection = sel,
}
}
pub fn type_char(&mut self, c: char) {
if c == '\n' || c == '\r' {
return;
}
self.delete_active_selection();
self.active_text_mut().push(c);
}
pub fn backspace(&mut self) -> bool {
if self.delete_active_selection() {
return true;
}
self.active_text_mut().pop().is_some()
}
pub fn insert_str(&mut self, s: &str) {
self.delete_active_selection();
let text = self.active_text_mut();
for c in s.chars() {
if c != '\n' && c != '\r' {
text.push(c);
}
}
}
pub fn select_all_active(&mut self) {
let len = self.active_text().len();
if len == 0 {
self.set_active_selection(None);
} else {
self.set_active_selection(Some((0, len)));
}
}
fn delete_active_selection(&mut self) -> bool {
let Some((a, b)) = self.active_selection() else {
return false;
};
if a == b {
self.set_active_selection(None);
return false;
}
self.active_text_mut().replace_range(a..b, "");
self.set_active_selection(None);
true
}
pub fn active_selection_text(&self) -> String {
match self.active_selection() {
Some((a, b)) if a < b => self.active_text()[a..b].to_string(),
_ => String::new(),
}
}
pub fn focus_next_field(&mut self) {
let order = self.visible_fields();
let pos = order.iter().position(|f| *f == self.field).unwrap_or(0);
let next = order[(pos + 1) % order.len()];
self.focus_field(next);
}
pub fn focus_field(&mut self, field: SearchField) {
if self.field != field {
self.set_active_selection(None);
self.field = field;
}
}
fn visible_fields(&self) -> Vec<SearchField> {
let mut v = vec![SearchField::Query];
if self.replace_open {
v.push(SearchField::Replace);
}
if self.details_open {
v.push(SearchField::Include);
v.push(SearchField::Exclude);
}
v
}
pub fn toggle_replace(&mut self) {
self.replace_open = !self.replace_open;
if self.replace_open {
self.focus_field(SearchField::Replace);
} else if self.field == SearchField::Replace {
self.focus_field(SearchField::Query);
}
}
pub fn toggle_details(&mut self) {
self.details_open = !self.details_open;
if !self.details_open && matches!(self.field, SearchField::Include | SearchField::Exclude) {
self.focus_field(SearchField::Query);
}
}
pub fn path_filter(&self) -> PathFilter {
PathFilter::new(&self.include, &self.exclude)
}
pub fn chevron_at(&self, col: u16, row: u16) -> bool {
row == self.chevron_y && col == self.chevron_x
}
pub fn ellipsis_at(&self, col: u16, row: u16) -> bool {
self.ellipsis_x != 0 && row == self.ellipsis_y && col == self.ellipsis_x
}
pub fn replace_all_at(&self, col: u16, row: u16) -> bool {
self.replace_all_x != 0 && row == self.replace_all_y && col == self.replace_all_x
}
pub fn refresh_at(&self, col: u16, row: u16) -> bool {
self.refresh_x != 0 && row == self.refresh_y && col == self.refresh_x
}
pub fn clear_at(&self, col: u16, row: u16) -> bool {
self.clear_x != 0 && row == self.clear_y && col == self.clear_x
}
pub fn tooltip_at(&self, col: u16, row: u16) -> Option<&'static str> {
if self.refresh_at(col, row) {
return Some("Refresh");
}
if self.clear_at(col, row) {
return Some("Clear Search Results");
}
if self.chevron_at(col, row) {
return Some(if self.replace_open {
"Collapse Replace"
} else {
"Toggle Replace"
});
}
if self.ellipsis_at(col, row) {
return Some("Toggle Search Details");
}
if self.replace_all_at(col, row) {
return Some("Replace All");
}
if let Some(toggle) = self.toggle_at(col, row) {
return Some(match toggle {
SearchToggle::CaseSensitive => "Match Case",
SearchToggle::WholeWord => "Match Whole Word",
SearchToggle::UseRegex => "Use Regular Expression",
});
}
None
}
pub fn clear_all(&mut self) {
self.query.clear();
self.replace.clear();
self.hits.clear();
self.selected = 0;
self.scroll = 0;
self.selection = None;
self.field_selection = None;
}
pub fn field_at(&self, col: u16, row: u16) -> Option<SearchField> {
let on = |r: Rect| r.width != 0 && row == r.y && col >= r.x && col < r.x + r.width;
if on(self.query_input_rect) {
return Some(SearchField::Query);
}
if on(self.replace_input_rect) {
return Some(SearchField::Replace);
}
if on(self.include_input_rect) {
return Some(SearchField::Include);
}
if on(self.exclude_input_rect) {
return Some(SearchField::Exclude);
}
None
}
pub fn replace_all_on_disk(&self) -> usize {
let needle = self.query.trim();
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 = self.query.trim();
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 = self.query.trim();
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)
}
pub fn run_query(&mut self) {
self.hits = search_workspace(&self.root, &self.query, self.opts);
self.selected = 0;
self.scroll = 0;
}
pub fn toggle_at(&self, col: u16, row: u16) -> Option<SearchToggle> {
if row != self.toggle_y {
return None;
}
for (start, kind) in [
(self.toggle_case_x, SearchToggle::CaseSensitive),
(self.toggle_word_x, SearchToggle::WholeWord),
(self.toggle_regex_x, SearchToggle::UseRegex),
] {
if start != 0 && col >= start && col < start + 2 {
return Some(kind);
}
}
None
}
pub fn move_up(&mut self) {
if self.selected > 0 {
self.selected -= 1;
}
self.ensure_selected_visible();
}
pub fn move_down(&mut self) {
if self.selected + 1 < self.hits.len() {
self.selected += 1;
}
self.ensure_selected_visible();
}
fn ensure_selected_visible(&mut self) {
let viewport = self.results_viewport_height();
if viewport == 0 {
return;
}
if self.selected < self.scroll {
self.scroll = self.selected;
} else if self.selected >= self.scroll + viewport {
self.scroll = self.selected + 1 - viewport;
}
}
pub fn scroll_up(&mut self, rows: usize) {
self.scroll = self.scroll.saturating_sub(rows);
}
pub fn scroll_down(&mut self, rows: usize) {
let viewport = self.results_viewport_height();
let max_scroll = self.hits.len().saturating_sub(viewport);
self.scroll = self.scroll.saturating_add(rows).min(max_scroll);
}
pub fn scroll_to_bar_y(&mut self, y: u16) -> bool {
let viewport = self.results_viewport_height();
let Some(metrics) = crate::widgets::scrollbar::vertical_metrics(
self.last_scrollbar,
self.hits.len(),
viewport,
self.scroll,
) else {
return false;
};
let new_scroll = crate::widgets::scrollbar::scroll_for_y(metrics, y);
let max_scroll = self.hits.len().saturating_sub(viewport);
self.scroll = new_scroll.min(max_scroll);
true
}
fn results_viewport_height(&self) -> usize {
let inner = self.last_inner;
if inner.height == 0 {
return 0;
}
let results_top = self.results_start_offset;
if inner.height <= results_top {
return 0;
}
(inner.height - results_top) as usize
}
pub fn selected_hit(&self) -> Option<&SearchHit> {
self.hits.get(self.selected)
}
pub fn hit_at_y(&self, y: u16) -> Option<usize> {
let inner = self.last_inner;
let results_start = inner.y + self.results_start_offset;
if y < results_start || y >= inner.y + inner.height {
return None;
}
let row_in_results = (y - results_start) as usize;
let idx = self.scroll + row_in_results;
if idx < self.hits.len() {
Some(idx)
} else {
None
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SearchToggle {
CaseSensitive,
WholeWord,
UseRegex,
}
struct FieldArgs<'a> {
bar_x: u16,
y: u16,
fill_right: u16,
lead_glyph: Option<&'a str>,
text: &'a str,
placeholder: &'a str,
selection: Option<(usize, usize)>,
field_focused: bool,
accent: Color,
bg: (u8, u8, u8),
reserve_right: u16,
}
fn render_field(
buf: &mut Buffer,
args: FieldArgs,
theme: crate::theme::Theme,
caret_out: &mut Option<(u16, u16)>,
) -> Rect {
if args.fill_right <= args.bar_x {
return Rect {
x: args.bar_x,
y: args.y,
width: 0,
height: 1,
};
}
let bar_color = if args.field_focused {
args.accent
} else {
theme.ui(FIELD_BAR_IDLE)
};
buf.set_string(args.bar_x, args.y, "▏", Style::default().fg(bar_color));
let fill_x = args.bar_x + 1;
let lift = if args.field_focused {
FIELD_FILL_LIFT_FOCUS
} else {
FIELD_FILL_LIFT_IDLE
};
let fill = lift_bg(args.bg, lift);
let fill_style = Style::default().bg(fill);
for x in fill_x..=args.fill_right {
buf[(x, args.y)].set_symbol(" ").set_style(fill_style);
}
let lead_w: u16 = if args.lead_glyph.is_some() { 2 } else { 0 };
if let Some(g) = args.lead_glyph {
let lead_color = if args.field_focused {
args.accent
} else {
theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4))
};
buf.set_string(fill_x, args.y, g, Style::default().fg(lead_color).bg(fill));
}
let text_x = fill_x + lead_w;
let text_right = args.fill_right.saturating_sub(args.reserve_right);
let text_w = text_right.saturating_sub(text_x).saturating_add(1);
let mut spans: Vec<Span> = Vec::with_capacity(4);
if args.text.is_empty() {
spans.push(Span::styled(
args.placeholder.to_string(),
Style::default()
.fg(theme.ui(Color::Rgb(0x6c, 0x7d, 0x9c)))
.bg(fill)
.add_modifier(Modifier::ITALIC),
));
} else {
let plain = Style::default().fg(theme.ui(Color::White)).bg(fill);
let selected = Style::default()
.fg(theme.ui(Color::White))
.bg(theme.ui(Color::Rgb(0x26, 0x4f, 0x78)));
match args.selection {
Some((a, b)) if a < b => {
if a > 0 {
spans.push(Span::styled(args.text[..a].to_string(), plain));
}
spans.push(Span::styled(args.text[a..b].to_string(), selected));
if b < args.text.len() {
spans.push(Span::styled(args.text[b..].to_string(), plain));
}
}
_ => spans.push(Span::styled(args.text.to_string(), plain)),
}
}
if text_w > 0 {
buf.set_line(text_x, args.y, &Line::from(spans), text_w);
}
if args.field_focused && text_w > 0 {
let off = (args.text.chars().count() as u16).min(text_w.saturating_sub(1));
*caret_out = Some((text_x + off, args.y));
}
Rect {
x: args.bar_x,
y: args.y,
width: text_right.saturating_sub(args.bar_x).saturating_add(1),
height: 1,
}
}
impl Widget for &mut SearchPanel {
fn render(self, area: Rect, buf: &mut Buffer) {
let focus_blue = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
let accent = if self.focus_gradient {
crate::gradient::rgb_color(crate::gradient::INNER_ACCENT)
} else {
focus_blue
};
let outer_style = if self.focused {
Style::default().fg(focus_blue)
} else {
Style::default().fg(Color::DarkGray)
};
let outer = Block::default()
.borders(Borders::ALL)
.border_style(outer_style);
let inner = outer.inner(area);
outer.render(area, buf);
if self.focused && self.focus_gradient {
crate::gradient::paint_gradient_box(buf, area);
}
self.last_area = area;
self.last_inner = inner;
self.caret_cell = None;
if inner.height == 0 || inner.width == 0 {
return;
}
buf.set_string(
inner.x,
inner.y,
"SEARCH",
Style::default()
.fg(self.theme.ui(Color::Rgb(0xb0, 0xb8, 0xc8)))
.add_modifier(Modifier::BOLD),
);
self.refresh_x = 0;
self.refresh_y = inner.y;
self.clear_x = 0;
self.clear_y = inner.y;
if inner.width > 16 {
let clear_x = inner.x + inner.width - 1;
let refresh_x = clear_x - 3;
for (x, glyph) in [
(refresh_x, crate::icons::SEARCH_REFRESH),
(clear_x, crate::icons::SEARCH_CLEAR_ALL),
] {
let hot = self
.hover_pointer
.is_some_and(|(px, py)| py == inner.y && px == x);
let color = if hot {
accent
} else {
self.theme.ui(Color::Rgb(0x8b, 0x94, 0xa4))
};
buf.set_string(x, inner.y, glyph.to_string(), Style::default().fg(color));
}
self.refresh_x = refresh_x;
self.clear_x = clear_x;
}
if inner.height < 4 || inner.width < 8 {
return;
}
let bg = self.theme.editor_bg_rgb();
let chevron_x = inner.x;
let bar_x = inner.x + 2; let inner_right = inner.x + inner.width - 1; let content_y = inner.y + 2;
let ellipsis_x = inner_right;
let query_fill_right = ellipsis_x.saturating_sub(2);
let regex_x = query_fill_right.saturating_sub(2); let word_x = regex_x.saturating_sub(3);
let case_x = word_x.saturating_sub(3);
let query_reserve = query_fill_right.saturating_sub(case_x).saturating_add(1);
let chevron_color = if self.focused {
accent
} else {
Color::DarkGray
};
let chevron_glyph = if self.replace_open {
crate::icons::CHEVRON_OPEN
} else {
crate::icons::CHEVRON_CLOSED
};
buf.set_string(
chevron_x,
content_y,
chevron_glyph.to_string(),
Style::default()
.fg(chevron_color)
.add_modifier(Modifier::BOLD),
);
self.chevron_x = chevron_x;
self.chevron_y = content_y;
let mut caret: Option<(u16, u16)> = None;
let query_focused = self.focused && self.field == SearchField::Query;
self.query_input_rect = render_field(
buf,
FieldArgs {
bar_x,
y: content_y,
fill_right: query_fill_right,
lead_glyph: Some("\u{ea6d}"),
text: &self.query,
placeholder: "Search",
selection: self.selection_range(),
field_focused: query_focused,
accent,
bg,
reserve_right: query_reserve,
},
self.theme,
&mut caret,
);
self.paste_button_x = 0;
self.paste_button_y = content_y;
self.paste_button_w = 0;
let toggle_fill = lift_bg(
bg,
if query_focused {
FIELD_FILL_LIFT_FOCUS
} else {
FIELD_FILL_LIFT_IDLE
},
);
let active_style = Style::default()
.fg(Color::White)
.bg(crate::gradient::rgb_color(crate::gradient::POPUP_SEL_BG))
.add_modifier(Modifier::BOLD);
let inactive_style = Style::default()
.fg(self.theme.ui(Color::Rgb(0x79, 0x82, 0x8f)))
.bg(toggle_fill);
self.toggle_y = content_y;
self.toggle_case_x = case_x;
self.toggle_word_x = word_x;
self.toggle_regex_x = regex_x;
for (x, glyph, active) in [
(case_x, "Aa", self.opts.case_sensitive),
(word_x, "ab", self.opts.whole_word),
(regex_x, ".*", self.opts.use_regex),
] {
let style = if active { active_style } else { inactive_style };
buf.set_string(x, content_y, glyph, style);
}
let ellipsis_style = if self.details_open {
Style::default().fg(accent).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(self.theme.ui(Color::Rgb(0x79, 0x82, 0x8f)))
};
buf.set_string(
ellipsis_x,
content_y,
crate::icons::SEARCH_ELLIPSIS.to_string(),
ellipsis_style,
);
self.ellipsis_x = ellipsis_x;
self.ellipsis_y = content_y;
let mut next_y = content_y + 1;
self.replace_input_rect = Rect::default();
self.replace_all_x = 0;
self.replace_all_y = 0;
if self.replace_open && next_y + 1 < inner.y + inner.height {
draw_field_divider(buf, bar_x, query_fill_right, next_y, self.theme);
next_y += 1;
let replace_all_x = inner_right;
let replace_fill_right = replace_all_x.saturating_sub(2).max(bar_x + 1);
let replace_focused = self.focused && self.field == SearchField::Replace;
self.replace_input_rect = render_field(
buf,
FieldArgs {
bar_x,
y: next_y,
fill_right: replace_fill_right,
lead_glyph: Some(&crate::icons::SEARCH_REPLACE.to_string()),
text: &self.replace,
placeholder: "Replace (Tab switches)",
selection: if self.field == SearchField::Replace {
self.active_selection()
} else {
None
},
field_focused: replace_focused,
accent,
bg,
reserve_right: 0,
},
self.theme,
&mut caret,
);
buf.set_string(
replace_all_x,
next_y,
crate::icons::SEARCH_REPLACE_ALL.to_string(),
Style::default().fg(if self.focused {
accent
} else {
self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4))
}),
);
self.replace_all_x = replace_all_x;
self.replace_all_y = next_y;
next_y += 1;
}
self.include_input_rect = Rect::default();
self.exclude_input_rect = Rect::default();
if self.details_open {
let detail_fill_right = inner_right.saturating_sub(1).max(bar_x + 1);
let caption_style = Style::default().fg(self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4)));
if next_y + 2 < inner.y + inner.height {
draw_field_divider(buf, bar_x, detail_fill_right, next_y, self.theme);
next_y += 1;
buf.set_string(bar_x, next_y, "files to include", caption_style);
next_y += 1;
let inc_focused = self.focused && self.field == SearchField::Include;
self.include_input_rect = render_field(
buf,
FieldArgs {
bar_x,
y: next_y,
fill_right: detail_fill_right,
lead_glyph: None,
text: &self.include,
placeholder: "e.g. src/**/*.rs",
selection: if self.field == SearchField::Include {
self.active_selection()
} else {
None
},
field_focused: inc_focused,
accent,
bg,
reserve_right: 0,
},
self.theme,
&mut caret,
);
next_y += 1;
}
if next_y + 2 < inner.y + inner.height {
draw_field_divider(buf, bar_x, detail_fill_right, next_y, self.theme);
next_y += 1;
buf.set_string(bar_x, next_y, "files to exclude", caption_style);
next_y += 1;
let exc_focused = self.focused && self.field == SearchField::Exclude;
self.exclude_input_rect = render_field(
buf,
FieldArgs {
bar_x,
y: next_y,
fill_right: detail_fill_right,
lead_glyph: None,
text: &self.exclude,
placeholder: "e.g. target, dist",
selection: if self.field == SearchField::Exclude {
self.active_selection()
} else {
None
},
field_focused: exc_focused,
accent,
bg,
reserve_right: 0,
},
self.theme,
&mut caret,
);
next_y += 1;
}
}
self.caret_cell = caret;
let separator_y = next_y;
if separator_y < inner.y + inner.height {
let sep_style = Style::default().fg(self.theme.ui(Color::Rgb(0x40, 0x48, 0x58)));
for x in inner.x..inner.x + inner.width {
buf.set_string(x, separator_y, "─", sep_style);
}
}
let caption_y = separator_y + 1;
let results_start_y = caption_y + 1;
self.results_start_offset = results_start_y.saturating_sub(inner.y);
if caption_y < inner.y + inner.height && !self.query.trim().is_empty() {
let count = self.hits.len();
let header = format!("{count} match{}", if count == 1 { "" } else { "es" });
let caption = Line::from(Span::styled(
header,
Style::default()
.fg(self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4)))
.add_modifier(Modifier::ITALIC),
));
buf.set_line(inner.x, caption_y, &caption, inner.width);
}
self.last_scrollbar = Rect::default();
if results_start_y >= inner.y + inner.height {
return;
}
let visible = (inner.y + inner.height - results_start_y) as usize;
if visible == 0 {
return;
}
let max_scroll = self.hits.len().saturating_sub(visible);
if self.scroll > max_scroll {
self.scroll = max_scroll;
}
let scrollbar_area = Rect {
x: inner.x + inner.width.saturating_sub(1),
y: results_start_y,
width: 1,
height: inner.y + inner.height - results_start_y,
};
let scrollbar_metrics = crate::widgets::scrollbar::vertical_metrics(
scrollbar_area,
self.hits.len(),
visible,
self.scroll,
);
if let Some(metrics) = scrollbar_metrics {
self.last_scrollbar = metrics.area;
}
let row_width = inner
.width
.saturating_sub(u16::from(scrollbar_metrics.is_some()));
let end = (self.scroll + visible).min(self.hits.len());
for (row_idx, hit_idx) in (self.scroll..end).enumerate() {
let y = results_start_y + row_idx as u16;
let hit = &self.hits[hit_idx];
let row_rect = Rect {
x: inner.x,
y,
width: row_width,
height: 1,
};
if hit_idx != self.selected
&& let Some(bg) =
crate::widgets::hover::row_hover_bg(row_rect, self.hover_pointer, self.theme)
{
let fill = Style::default().bg(bg);
for rx in 0..row_width {
buf[(inner.x + rx, y)].set_symbol(" ").set_style(fill);
}
}
let path_display = hit
.path
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| {
let owner = self
.roots
.iter()
.filter(|r| hit.path.starts_with(r))
.max_by_key(|r| r.components().count());
match owner {
Some(r) if self.roots.len() > 1 => {
let idx = self.roots.iter().position(|x| x == r).unwrap_or(0);
let name =
crate::workspace::root_display_labels(&self.roots).swap_remove(idx);
format!(
"{name}/{}",
hit.path
.strip_prefix(r)
.unwrap_or(hit.path.as_path())
.display()
)
}
Some(r) => hit
.path
.strip_prefix(r)
.unwrap_or(hit.path.as_path())
.display()
.to_string(),
None => hit.path.display().to_string(),
}
});
let header_style = if hit_idx == self.selected {
if self.focus_gradient {
Style::default()
.fg(Color::White)
.bg(crate::gradient::rgb_color(crate::gradient::POPUP_SEL_BG))
.add_modifier(Modifier::BOLD)
} else {
Style::default()
.fg(Color::Black)
.bg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)))
.add_modifier(Modifier::BOLD)
}
} else {
Style::default().fg(self.theme.ui(Color::White))
};
let needle = self.query.trim();
let highlight_style = Style::default()
.fg(Color::Black)
.bg(self.theme.ui(Color::Rgb(0xff, 0xd7, 0x4a)))
.add_modifier(Modifier::BOLD);
let plain_style = Style::default().fg(self.theme.ui(Color::Gray));
let mut spans: Vec<Span> = vec![
Span::styled(format!(" {path_display}"), header_style),
Span::styled(
format!(":{}: ", hit.line_no),
Style::default().fg(self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))),
),
];
let preview = self.replace_open && !self.replace.is_empty();
for (chunk, is_match) in split_for_highlight(&hit.line_text, needle, self.opts) {
if is_match && preview {
let new_text = expand_replacement(&chunk, needle, &self.replace, self.opts);
spans.push(Span::styled(
chunk,
Style::default()
.fg(self.theme.ui(Color::Rgb(0x8b, 0x93, 0xa5)))
.add_modifier(Modifier::CROSSED_OUT),
));
spans.push(Span::styled(
new_text,
Style::default()
.fg(self.theme.ui(Color::Rgb(0xb6, 0xee, 0xc4)))
.add_modifier(Modifier::BOLD),
));
continue;
}
spans.push(Span::styled(
chunk,
if is_match {
highlight_style
} else {
plain_style
},
));
}
let line = Line::from(spans);
buf.set_line(inner.x, y, &line, row_width);
}
if let Some(metrics) = scrollbar_metrics {
crate::widgets::scrollbar::render_vertical(buf, metrics, self.focused, self.theme);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn workspace_regex_replace_honours_line_anchors_and_group_suffixes() {
let opts = SearchOpts {
use_regex: true,
..SearchOpts::default()
};
assert_eq!(
replace_in_text("foo\nfoo\n", "^foo", "x", opts),
Some((String::from("x\nx\n"), 2))
);
assert_eq!(
replace_in_text("a foo\r\nb foo\r\n", "foo$", "x", opts),
Some((String::from("a x\r\nb x\r\n"), 2))
);
assert_eq!(
replace_in_text("foo", "(foo)", "$1_old", opts).map(|r| r.0),
Some(String::from("foo_old"))
);
}
use std::fs;
use tempfile::TempDir;
fn write(p: &Path, s: &str) {
fs::write(p, s).unwrap();
}
#[test]
fn collect_matches_substring_case_insensitive() {
let mut out = Vec::new();
let content = "Hello World\nfoo bar\nHELLO again\nno match here";
collect_matches_in_text(
Path::new("a.txt"),
content,
"hello",
SearchOpts::default(),
&mut out,
);
assert_eq!(out.len(), 2);
assert_eq!(out[0].line_no, 1);
assert_eq!(out[0].line_text, "Hello World");
assert_eq!(out[1].line_no, 3);
assert_eq!(out[1].line_text, "HELLO again");
}
#[test]
fn collect_matches_truncates_very_long_lines() {
let mut out = Vec::new();
let long_line = "x".repeat(MAX_LINE_LEN + 50) + "needle";
collect_matches_in_text(
Path::new("a.txt"),
&long_line,
"needle",
SearchOpts::default(),
&mut out,
);
assert_eq!(out.len(), 1);
assert!(!out[0].line_text.contains('…'));
assert_eq!(out[0].line_text.chars().count(), MAX_LINE_LEN);
}
#[test]
fn search_workspace_finds_matches_across_files() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "alpha\nbeta\nbananas\n");
write(&tmp.path().join("b.rs"), "fn beta() {}\nlet bananas = 1;\n");
let hits = search_workspace(tmp.path(), "bananas", SearchOpts::default());
assert_eq!(hits.len(), 2);
let names: Vec<String> = hits
.iter()
.map(|h| h.path.file_name().unwrap().to_string_lossy().into_owned())
.collect();
assert!(names.contains(&"a.txt".to_string()));
assert!(names.contains(&"b.rs".to_string()));
}
#[test]
fn search_workspace_returns_empty_for_blank_query() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "anything");
assert!(search_workspace(tmp.path(), "", SearchOpts::default()).is_empty());
assert!(search_workspace(tmp.path(), " ", SearchOpts::default()).is_empty());
}
#[test]
fn search_workspace_skips_binary_or_unreadable_files() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("text.txt"), "hello world");
std::fs::write(tmp.path().join("blob.bin"), [0u8, 159, 146, 150]).unwrap();
let hits = search_workspace(tmp.path(), "hello", SearchOpts::default());
assert_eq!(hits.len(), 1);
assert!(hits[0].path.ends_with("text.txt"));
}
#[test]
fn search_workspace_returns_every_match_with_no_arbitrary_cap() {
let tmp = TempDir::new().unwrap();
for i in 0..5 {
let many = (0..100).map(|_| "needle\n").collect::<String>();
write(&tmp.path().join(format!("f{i}.txt")), &many);
}
let hits = search_workspace(tmp.path(), "needle", SearchOpts::default());
assert_eq!(
hits.len(),
500,
"engine must surface every match - silent truncation is unacceptable"
);
}
#[test]
fn search_panel_run_query_populates_hits_and_resets_selection() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("x.txt"), "one\ntwo\nthree\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "two".into();
panel.run_query();
assert_eq!(panel.hits.len(), 1);
assert_eq!(panel.selected, 0);
}
const INPUT_TYPED_COL: u16 = 5;
const INPUT_CONTENT_ROW: u16 = 2;
#[test]
fn cursor_sits_at_input_start_when_query_empty_and_focused() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let inner_x = panel.last_inner.x;
let inner_y = panel.last_inner.y;
assert_eq!(
panel.cursor_screen_pos(),
Some((inner_x + INPUT_TYPED_COL, inner_y + INPUT_CONTENT_ROW)),
"caret must sit at the start of the input content area when the query is empty"
);
}
#[test]
fn cursor_sits_after_typed_text_when_query_non_empty_and_focused() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
panel.query = String::from("foo");
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let inner_x = panel.last_inner.x;
let inner_y = panel.last_inner.y;
assert_eq!(
panel.cursor_screen_pos(),
Some((inner_x + INPUT_TYPED_COL + 3, inner_y + INPUT_CONTENT_ROW)),
"caret must sit immediately after the typed query"
);
}
fn buffer_to_string(buf: &Buffer) -> String {
let mut out = String::new();
for y in buf.area.y..buf.area.y + buf.area.height {
for x in buf.area.x..buf.area.x + buf.area.width {
out.push_str(buf[(x, y)].symbol());
}
out.push('\n');
}
out
}
#[test]
fn header_row_says_search_in_upper_case() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let inner_x = panel.last_inner.x;
let inner_y = panel.last_inner.y;
let mut header = String::new();
for x in inner_x..inner_x + 8 {
header.push_str(buf[(x, inner_y)].symbol());
}
assert!(
header.starts_with("SEARCH"),
"first inner row must start with the uppercase SEARCH header; got: {header:?}"
);
let mut top_border = String::new();
for x in area.x..area.x + area.width {
top_border.push_str(buf[(x, area.y)].symbol());
}
assert!(
!top_border.contains("SEARCH"),
"outer border row must not carry a SEARCH title chip: {top_border:?}"
);
}
#[test]
fn input_box_renders_a_thin_focused_border_three_rows_tall() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
dump.contains('┌') || dump.contains('╭'),
"input box must have a top-left corner; got buffer:\n{dump}"
);
assert!(
dump.contains('└') || dump.contains('╰'),
"input box must have a bottom-left corner so the border reads as a 3-row box, not a single rule:\n{dump}"
);
}
#[test]
fn rendering_at_narrow_widths_does_not_panic() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
for width in 0u16..40 {
for height in 0u16..20 {
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
let area = Rect {
x: 0,
y: 0,
width,
height,
};
if area.width == 0 || area.height == 0 {
continue;
}
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
}
}
}
#[test]
fn asterisk_keeps_breathing_room_against_the_outer_right_border() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let inner = panel.last_inner;
let regex_end = panel.toggle_regex_x + 1;
let inner_right = inner.x + inner.width - 1;
let right_gap = inner_right.saturating_sub(regex_end);
assert!(
right_gap >= 1,
"asterisk must not sit flush against the outer right border (right_gap={right_gap})"
);
}
#[test]
fn input_row_carries_a_chevron_and_pipe_separated_toggles() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 10,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
dump.contains('▸'),
"collapsed panel must show a right-pointing expand chevron on the left:\n{dump}"
);
panel.toggle_replace();
let mut buf2 = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf2);
let dump2 = buffer_to_string(&buf2);
assert!(
dump2.contains('▾'),
"expanded panel must flip the chevron to a down-arrow:\n{dump2}"
);
assert!(
dump.contains("Aa") && dump.contains("ab") && dump.contains(".*"),
"all three toggle glyphs must render:\n{dump}"
);
let pipes = dump.matches('│').count();
assert!(
pipes >= 2,
"at least two pipe separators must sit between the three toggles; got {pipes} pipes in:\n{dump}"
);
}
#[test]
fn results_start_below_the_input_box_with_a_separator_in_between() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "needle\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = String::from("needle");
panel.run_query();
assert_eq!(panel.hits.len(), 1);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 14,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let dump = buffer_to_string(&buf);
let row_with_needle = dump
.lines()
.position(|l| l.contains("needle") && l.contains("a.txt"))
.expect("result row with needle must render");
assert!(
row_with_needle >= 5,
"result row must sit below the input box (expected row >= 5, got {row_with_needle}):\n{dump}"
);
}
#[test]
fn search_panel_does_not_render_paste_button_in_input_row() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 5,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
assert_eq!(
panel.paste_button_w, 0,
"paste button should not reserve cells"
);
let mut collected = String::new();
for x in area.x..area.x + area.width {
collected.push_str(buf[(x, 1)].symbol());
}
assert!(
!collected.to_lowercase().contains("paste"),
"input row should not visibly contain a Paste button, got: {collected:?}"
);
}
#[test]
fn paste_button_at_returns_false_when_button_hidden() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 5,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
assert_eq!(panel.paste_button_w, 0);
assert!(!panel.paste_button_at(0, 1));
assert!(!panel.paste_button_at(40, 1));
}
#[test]
fn split_highlight_returns_whole_line_when_needle_empty() {
let segs = split_for_highlight("hello world", "", SearchOpts::default());
assert_eq!(segs, vec![(String::from("hello world"), false)]);
}
#[test]
fn split_highlight_returns_whole_line_when_no_match() {
let segs = split_for_highlight("hello world", "xyz", SearchOpts::default());
assert_eq!(segs, vec![(String::from("hello world"), false)]);
}
#[test]
fn split_highlight_marks_each_match_run_case_insensitive() {
let segs = split_for_highlight(
"The Quick brown fox jumps over the QUICK fence",
"quick",
SearchOpts::default(),
);
let matches: Vec<&String> = segs
.iter()
.filter_map(|(s, m)| if *m { Some(s) } else { None })
.collect();
assert_eq!(matches.len(), 2);
assert_eq!(matches[0], "Quick");
assert_eq!(matches[1], "QUICK");
let joined: String = segs.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(joined, "The Quick brown fox jumps over the QUICK fence");
}
#[test]
fn split_highlight_handles_match_at_start_and_end() {
let segs = split_for_highlight("foo bar foo", "foo", SearchOpts::default());
let joined: String = segs.iter().map(|(s, _)| s.as_str()).collect();
assert_eq!(joined, "foo bar foo");
assert_eq!(
segs.first().map(|(_, m)| *m),
Some(true),
"first seg is match"
);
assert_eq!(
segs.last().map(|(_, m)| *m),
Some(true),
"last seg is match"
);
}
fn collect_until_done(
rx: &std::sync::mpsc::Receiver<SearchEvent>,
deadline: std::time::Duration,
) -> (Option<String>, Vec<SearchHit>, bool) {
let until = std::time::Instant::now() + deadline;
let mut last_q: Option<String> = None;
let mut hits: Vec<SearchHit> = Vec::new();
let mut saw_done = false;
while std::time::Instant::now() < until {
let remaining = until.saturating_duration_since(std::time::Instant::now());
match rx.recv_timeout(remaining.max(std::time::Duration::from_millis(50))) {
Ok(SearchEvent::Hits(q, _, batch)) => {
last_q = Some(q);
hits.extend(batch);
}
Ok(SearchEvent::Done(q, _)) => {
last_q = Some(q);
saw_done = true;
break;
}
Err(_) => break,
}
}
(last_q, hits, saw_done)
}
#[test]
fn search_worker_loop_searches_dirty_buffer_and_skips_stale_disk_copy() {
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("a.txt");
write(&path, "oldname\n");
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let root = tmp.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(root, q_rx, e_tx));
q_tx.send(SearchRequest::SetDirtyBuffers(vec![(
path.clone(),
"newname\n".into(),
)]))
.unwrap();
q_tx.send(SearchRequest::Query(
"newname".into(),
SearchOpts::default(),
))
.unwrap();
let (_, hits, done) = collect_until_done(&e_rx, std::time::Duration::from_secs(2));
assert!(done);
assert_eq!(hits.len(), 1, "the unsaved buffer's new name must be found");
assert_eq!(hits[0].line_text, "newname");
q_tx.send(SearchRequest::Query(
"oldname".into(),
SearchOpts::default(),
))
.unwrap();
let (_, stale, done2) = collect_until_done(&e_rx, std::time::Duration::from_secs(2));
assert!(done2);
assert_eq!(
stale.len(),
0,
"the stale on-disk copy of a dirty file must be skipped"
);
drop(q_tx);
join.join().unwrap();
}
#[test]
fn search_worker_loop_returns_hits_for_a_typed_query() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "one\nneedle\nthree\n");
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let root = tmp.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(root, q_rx, e_tx));
q_tx.send(SearchRequest::Query("needle".into(), SearchOpts::default()))
.unwrap();
let (q, hits, done) = collect_until_done(&e_rx, std::time::Duration::from_secs(2));
assert_eq!(q.as_deref(), Some("needle"));
assert_eq!(hits.len(), 1);
assert!(done, "worker must terminate the stream with a Done event");
drop(q_tx);
join.join().unwrap();
}
#[test]
fn search_worker_loop_streams_per_file_batches_for_a_typed_query() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "needle\n");
write(&tmp.path().join("b.txt"), "needle\nneedle\n");
write(&tmp.path().join("c.txt"), "needle\n");
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let root = tmp.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(root, q_rx, e_tx));
q_tx.send(SearchRequest::Query("needle".into(), SearchOpts::default()))
.unwrap();
let mut total = 0usize;
let mut hits_events = 0usize;
let mut done_events = 0usize;
let until = std::time::Instant::now() + std::time::Duration::from_secs(3);
while std::time::Instant::now() < until {
match e_rx.recv_timeout(std::time::Duration::from_millis(500)) {
Ok(SearchEvent::Hits(_, _, batch)) => {
hits_events += 1;
total += batch.len();
}
Ok(SearchEvent::Done(_, _)) => {
done_events += 1;
break;
}
Err(_) => break,
}
}
drop(q_tx);
join.join().unwrap();
assert_eq!(total, 4, "every match across all files must arrive");
assert!(
hits_events >= 3,
"expected per-file batches, got {hits_events}"
);
assert_eq!(done_events, 1, "exactly one Done sentinel per request");
}
#[test]
fn search_worker_loop_coalesces_a_burst_of_keystrokes() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "alpha one beta\nzeta\n");
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let root = tmp.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(root, q_rx, e_tx));
q_tx.send(SearchRequest::Query("o".into(), SearchOpts::default()))
.unwrap();
q_tx.send(SearchRequest::Query("on".into(), SearchOpts::default()))
.unwrap();
q_tx.send(SearchRequest::Query("one".into(), SearchOpts::default()))
.unwrap();
let (q, hits, done) = collect_until_done(&e_rx, std::time::Duration::from_secs(2));
assert_eq!(
q.as_deref(),
Some("one"),
"coalesce must drop intermediate prefixes"
);
assert_eq!(hits.len(), 1);
assert!(done);
drop(q_tx);
join.join().unwrap();
}
#[test]
fn search_worker_loop_resets_debounce_on_each_keystroke() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "alpha one beta\nzeta\n");
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let root = tmp.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(root, q_rx, e_tx));
q_tx.send(SearchRequest::Query("o".into(), SearchOpts::default()))
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(100));
q_tx.send(SearchRequest::Query("on".into(), SearchOpts::default()))
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(100));
q_tx.send(SearchRequest::Query("one".into(), SearchOpts::default()))
.unwrap();
let mut dones: Vec<String> = Vec::new();
let until = std::time::Instant::now() + std::time::Duration::from_secs(2);
while std::time::Instant::now() < until {
if let Ok(SearchEvent::Done(q, _)) =
e_rx.recv_timeout(std::time::Duration::from_millis(200))
{
dones.push(q)
}
}
drop(q_tx);
join.join().unwrap();
assert_eq!(
dones,
vec!["one".to_string()],
"exactly one search should have fired - for the trailing query - not one per keystroke"
);
}
#[test]
fn search_worker_loop_cancels_in_flight_scan_when_a_new_request_arrives() {
let tmp = TempDir::new().unwrap();
for i in 0..200 {
let many = (0..20000)
.map(|n| format!("ccc line {n}\n"))
.collect::<String>();
write(&tmp.path().join(format!("f{i}.txt")), &many);
}
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let root = tmp.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(root, q_rx, e_tx));
q_tx.send(SearchRequest::Query("c".into(), SearchOpts::default()))
.unwrap();
let mut c_hits = 0usize;
let staging = std::time::Instant::now() + std::time::Duration::from_secs(30);
while c_hits == 0 && std::time::Instant::now() < staging {
if let Ok(SearchEvent::Hits(q, _, hits)) =
e_rx.recv_timeout(std::time::Duration::from_millis(100))
&& q == "c"
{
c_hits += hits.len();
}
}
assert!(
c_hits > 0,
"staging: the \"c\" scan never started streaming"
);
q_tx.send(SearchRequest::Query(
"zzznoneatall".into(),
SearchOpts::default(),
))
.unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
let mut second_done = false;
while std::time::Instant::now() < deadline {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
match e_rx.recv_timeout(remaining.max(std::time::Duration::from_millis(50))) {
Ok(SearchEvent::Hits(q, _, hits)) if q == "c" => c_hits += hits.len(),
Ok(SearchEvent::Done(q, _)) if q == "zzznoneatall" => {
second_done = true;
break;
}
_ => {}
}
}
drop(q_tx);
join.join().unwrap();
assert!(
second_done,
"worker must emit Done for the new query after cancelling the in-flight scan"
);
assert!(
c_hits < 4_000_000,
"the in-flight scan must be cancelled, not run to completion; it streamed all {c_hits} matches"
);
}
#[test]
fn search_worker_loop_short_circuits_empty_queries() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "anything\n");
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let root = tmp.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(root, q_rx, e_tx));
q_tx.send(SearchRequest::Query("".into(), SearchOpts::default()))
.unwrap();
let (q, hits, done) = collect_until_done(&e_rx, std::time::Duration::from_secs(2));
assert_eq!(q.as_deref(), Some(""));
assert!(hits.is_empty());
assert!(done, "empty query still emits a Done sentinel");
drop(q_tx);
join.join().unwrap();
}
#[test]
fn search_worker_loop_targets_the_directory_set_by_the_latest_set_root() {
let dir_a = TempDir::new().unwrap();
write(&dir_a.path().join("a.txt"), "alpha only\n");
let dir_b = TempDir::new().unwrap();
write(&dir_b.path().join("b.txt"), "the needle is here\n");
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let start_root = dir_a.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(start_root, q_rx, e_tx));
q_tx.send(SearchRequest::SetRoot(dir_b.path().to_path_buf()))
.unwrap();
q_tx.send(SearchRequest::Query("needle".into(), SearchOpts::default()))
.unwrap();
let (q, hits, done) = collect_until_done(&e_rx, std::time::Duration::from_secs(2));
assert_eq!(q.as_deref(), Some("needle"));
assert_eq!(
hits.len(),
1,
"after SetRoot, the worker must search the new directory, not the one captured at spawn"
);
assert!(
hits[0].path.starts_with(dir_b.path()),
"the hit must come from the directory the Explorer now points at"
);
assert!(done);
drop(q_tx);
join.join().unwrap();
}
#[test]
fn search_opts_default_matches_legacy_case_insensitive_substring() {
let mut out = Vec::new();
let opts = SearchOpts::default();
collect_matches_in_text(
Path::new("a.txt"),
"Hello World\nfoo bar\nHELLO again\nno match",
"hello",
opts,
&mut out,
);
assert_eq!(out.len(), 2, "default opts mirror the original behaviour");
}
#[test]
fn search_opts_case_sensitive_excludes_different_case() {
let mut out = Vec::new();
let opts = SearchOpts {
case_sensitive: true,
..Default::default()
};
collect_matches_in_text(
Path::new("a.txt"),
"Hello World\nhello again\nHELLO loud",
"hello",
opts,
&mut out,
);
assert_eq!(out.len(), 1);
assert_eq!(out[0].line_text, "hello again");
}
#[test]
fn search_opts_whole_word_excludes_partial_matches() {
let mut out = Vec::new();
let opts = SearchOpts {
whole_word: true,
..Default::default()
};
collect_matches_in_text(
Path::new("a.txt"),
"cat sat\ncategory animal\ncat\nbobcat sleeps",
"cat",
opts,
&mut out,
);
let texts: Vec<&str> = out.iter().map(|h| h.line_text.as_str()).collect();
assert_eq!(texts, vec!["cat sat", "cat"]);
}
#[test]
fn search_opts_regex_finds_pattern_class() {
let mut out = Vec::new();
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
collect_matches_in_text(
Path::new("a.txt"),
"let x = 42;\nlet y = abc;\nlet z = 13;\nno number",
r"\d+",
opts,
&mut out,
);
let texts: Vec<&str> = out.iter().map(|h| h.line_text.as_str()).collect();
assert_eq!(texts, vec!["let x = 42;", "let z = 13;"]);
}
#[test]
fn search_opts_regex_honours_case_sensitive_flag() {
let mut out = Vec::new();
let opts = SearchOpts {
use_regex: true,
case_sensitive: true,
..Default::default()
};
collect_matches_in_text(Path::new("a.txt"), "Foo\nfoo\nFOO", r"foo", opts, &mut out);
let texts: Vec<&str> = out.iter().map(|h| h.line_text.as_str()).collect();
assert_eq!(texts, vec!["foo"], "regex must respect case-sensitive flag");
}
#[test]
fn search_opts_invalid_regex_returns_empty_quietly() {
let mut out = Vec::new();
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
collect_matches_in_text(
Path::new("a.txt"),
"anything\nat all",
r"[unclosed",
opts,
&mut out,
);
assert!(
out.is_empty(),
"invalid regex must not crash, just yield no hits"
);
}
#[test]
fn toggle_at_maps_a_click_on_each_glyph_to_the_right_kind() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let y = panel.toggle_y;
assert_eq!(
panel.toggle_at(panel.toggle_case_x, y),
Some(SearchToggle::CaseSensitive)
);
assert_eq!(
panel.toggle_at(panel.toggle_case_x + 1, y),
Some(SearchToggle::CaseSensitive)
);
assert_eq!(
panel.toggle_at(panel.toggle_word_x, y),
Some(SearchToggle::WholeWord)
);
assert_eq!(
panel.toggle_at(panel.toggle_regex_x + 1, y),
Some(SearchToggle::UseRegex)
);
assert_eq!(panel.toggle_at(panel.toggle_case_x, y + 1), None);
assert_eq!(panel.toggle_at(0, y), None);
}
#[test]
fn tooltip_at_labels_each_actionable_control_and_skips_inert_cells() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 12,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let y = panel.toggle_y;
assert_eq!(panel.tooltip_at(panel.toggle_case_x, y), Some("Match Case"));
assert_eq!(
panel.tooltip_at(panel.toggle_word_x, y),
Some("Match Whole Word")
);
assert_eq!(
panel.tooltip_at(panel.toggle_regex_x, y),
Some("Use Regular Expression")
);
assert_eq!(
panel.tooltip_at(panel.refresh_x, panel.refresh_y),
Some("Refresh")
);
assert_eq!(
panel.tooltip_at(panel.clear_x, panel.clear_y),
Some("Clear Search Results")
);
assert_eq!(
panel.tooltip_at(panel.chevron_x, panel.chevron_y),
Some("Toggle Replace"),
"the chevron reads as expand while the Replace row is collapsed"
);
assert_eq!(panel.tooltip_at(panel.toggle_case_x, y + 5), None);
}
#[test]
fn search_panel_navigation_clamps() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("x.txt"), "a needle\nb needle\nc needle\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "needle".into();
panel.run_query();
assert_eq!(panel.hits.len(), 3);
panel.move_up();
assert_eq!(panel.selected, 0);
panel.move_down();
panel.move_down();
panel.move_down(); assert_eq!(panel.selected, 2);
}
fn make_panel_with_hits(tmp: &TempDir, n: usize) -> SearchPanel {
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "needle".into();
panel.hits = (0..n)
.map(|i| SearchHit {
path: tmp.path().join("a.txt"),
line_no: i + 1,
line_text: format!("line {i}"),
})
.collect();
panel
}
#[test]
fn hovering_an_unselected_result_row_lifts_it() {
let tmp = TempDir::new().unwrap();
let mut panel = make_panel_with_hits(&tmp, 20);
panel.focus_gradient = false; panel.theme = crate::theme::Theme::DARK_BLUE;
panel.selected = 0;
panel.scroll = 0;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let row_y = area.y + 1 + 7 + 1;
panel.hover_pointer = Some((area.x + 1, row_y));
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
assert_eq!(
buf[(area.x + 1, row_y)].bg,
Color::Rgb(0x2b, 0x31, 0x42),
"the hovered unselected result row wears the Croft Dark hover lift"
);
}
#[test]
fn render_preserves_user_scroll_when_selected_is_at_top() {
let tmp = TempDir::new().unwrap();
let mut panel = make_panel_with_hits(&tmp, 100);
panel.selected = 0;
panel.scroll = 30;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
assert_eq!(
panel.scroll, 30,
"render must not pull scroll back to selected when the user has wheeled away"
);
}
#[test]
fn appending_streamed_hits_does_not_reset_user_scroll() {
let tmp = TempDir::new().unwrap();
let mut panel = make_panel_with_hits(&tmp, 80);
panel.selected = 0;
panel.scroll = 30;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = ratatui::buffer::Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let extra: Vec<SearchHit> = (80..130)
.map(|i| SearchHit {
path: tmp.path().join("a.txt"),
line_no: i + 1,
line_text: format!("line {i}"),
})
.collect();
panel.hits.extend(extra);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
assert_eq!(
panel.scroll, 30,
"streaming hits must not reset the user's scroll offset"
);
}
#[test]
fn move_down_past_bottom_of_viewport_advances_scroll_to_keep_selection_visible() {
let tmp = TempDir::new().unwrap();
let mut panel = make_panel_with_hits(&tmp, 100);
panel.last_inner = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
panel.selected = 24;
panel.scroll = 0;
panel.move_down();
assert_eq!(panel.selected, 25);
assert_eq!(
panel.scroll, 1,
"arrow-down past the bottom row must scroll to keep selection visible"
);
}
#[test]
fn move_up_above_top_of_viewport_retreats_scroll_to_keep_selection_visible() {
let tmp = TempDir::new().unwrap();
let mut panel = make_panel_with_hits(&tmp, 100);
panel.last_inner = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
panel.selected = 50;
panel.scroll = 50;
panel.move_up();
assert_eq!(panel.selected, 49);
assert_eq!(
panel.scroll, 49,
"arrow-up above the first visible row must scroll back to keep selection visible"
);
}
#[test]
fn scroll_down_via_wheel_does_not_change_selection() {
let tmp = TempDir::new().unwrap();
let mut panel = make_panel_with_hits(&tmp, 100);
panel.last_inner = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
panel.selected = 0;
panel.scroll = 0;
panel.scroll_down(20);
assert_eq!(panel.selected, 0, "wheel-scrolling must not move selection");
assert_eq!(panel.scroll, 20);
}
#[test]
fn path_filter_empty_allows_everything() {
let f = PathFilter::new("", "");
assert!(f.is_empty());
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/src/main.rs")));
assert!(f.allows(root, Path::new("/proj/a/b/c.py")));
}
#[test]
fn path_filter_include_bare_glob_matches_at_any_depth() {
let f = PathFilter::new("*.rs", "");
assert!(!f.is_empty());
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/main.rs")));
assert!(f.allows(root, Path::new("/proj/src/deep/mod.rs")));
assert!(!f.allows(root, Path::new("/proj/src/app.py")));
}
#[test]
fn path_filter_include_with_multiple_comma_separated_globs() {
let f = PathFilter::new("*.rs, *.toml", "");
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/main.rs")));
assert!(f.allows(root, Path::new("/proj/Cargo.toml")));
assert!(!f.allows(root, Path::new("/proj/notes.md")));
}
#[test]
fn path_filter_exclude_drops_matching_files() {
let f = PathFilter::new("", "*.lock");
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/main.rs")));
assert!(!f.allows(root, Path::new("/proj/Cargo.lock")));
}
#[test]
fn path_filter_exclude_beats_include_for_overlapping_paths() {
let f = PathFilter::new("*.rs", "target/**");
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/src/main.rs")));
assert!(!f.allows(root, Path::new("/proj/target/debug/build.rs")));
}
#[test]
fn path_filter_directory_glob_matches_relative_to_root() {
let f = PathFilter::new("src/**", "");
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/src/a/b.rs")));
assert!(!f.allows(root, Path::new("/proj/tests/c.rs")));
}
#[test]
fn search_streaming_filtered_honours_include_glob() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("keep.rs"), "needle here\n");
write(&tmp.path().join("drop.txt"), "needle here too\n");
let cancel = Arc::new(AtomicBool::new(false));
let filter = PathFilter::new("*.rs", "");
let collected = Arc::new(std::sync::Mutex::new(Vec::new()));
let c2 = collected.clone();
search_workspace_streaming_filtered(
tmp.path(),
"needle",
SearchOpts::default(),
&cancel,
&HashSet::new(),
&filter,
move |batch| c2.lock().unwrap().extend(batch),
);
let hits = Arc::try_unwrap(collected).unwrap().into_inner().unwrap();
assert_eq!(
hits.len(),
1,
"only the .rs file should match the include glob"
);
assert!(hits[0].path.ends_with("keep.rs"));
}
#[test]
fn search_streaming_filtered_honours_exclude_glob() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.rs"), "needle\n");
write(&tmp.path().join("b.rs"), "needle\n");
let cancel = Arc::new(AtomicBool::new(false));
let filter = PathFilter::new("", "b.rs");
let collected = Arc::new(std::sync::Mutex::new(Vec::new()));
let c2 = collected.clone();
search_workspace_streaming_filtered(
tmp.path(),
"needle",
SearchOpts::default(),
&cancel,
&HashSet::new(),
&filter,
move |batch| c2.lock().unwrap().extend(batch),
);
let hits = Arc::try_unwrap(collected).unwrap().into_inner().unwrap();
assert_eq!(hits.len(), 1);
assert!(hits[0].path.ends_with("a.rs"), "b.rs must be excluded");
}
#[test]
fn search_worker_loop_applies_set_filter_to_subsequent_query() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("keep.rs"), "needle\n");
write(&tmp.path().join("skip.md"), "needle\n");
let (q_tx, q_rx) = std::sync::mpsc::channel::<SearchRequest>();
let (e_tx, e_rx) = std::sync::mpsc::channel::<SearchEvent>();
let root = tmp.path().to_path_buf();
let join = std::thread::spawn(move || search_worker_loop(root, q_rx, e_tx));
q_tx.send(SearchRequest::SetFilter("*.rs".into(), String::new()))
.unwrap();
q_tx.send(SearchRequest::Query("needle".into(), SearchOpts::default()))
.unwrap();
let (_, hits, done) = collect_until_done(&e_rx, std::time::Duration::from_secs(2));
assert!(done);
assert_eq!(hits.len(), 1, "filter must restrict the scan to *.rs");
assert!(hits[0].path.ends_with("keep.rs"));
drop(q_tx);
join.join().unwrap();
}
#[test]
fn replace_in_text_never_matches_across_a_line_break() {
let re = SearchOpts {
use_regex: true,
..SearchOpts::default()
};
assert_eq!(
replace_in_text("let a = 1\nlet b = 2;\n", "a[^;]*", "Z", re),
Some((String::from("let Z\nlet b = 2;\n"), 1))
);
assert_eq!(
replace_in_text("foo \r\n bar\n", "foo\\s+", "X", re).map(|r| r.0),
Some(String::from("X\r\n bar\n"))
);
assert_eq!(
replace_in_text(" a\n\n b\n", "^\\s+", "", re).map(|r| r.0),
Some(String::from("a\n\nb\n"))
);
}
#[test]
fn replace_in_file_keeps_the_mode_and_reports_a_non_utf8_file() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("a.sh");
std::fs::write(&f, "echo foo\n").unwrap();
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(
replace_in_file(&f, "foo", "bar", SearchOpts::default()),
Some(1)
);
assert_eq!(std::fs::read_to_string(&f).unwrap(), "echo bar\n");
assert_eq!(
std::fs::metadata(&f).unwrap().permissions().mode() & 0o777,
0o755
);
let latin = dir.path().join("l.txt");
std::fs::write(&latin, b"foo \xe9\n").unwrap();
assert_eq!(
replace_in_file(&latin, "foo", "bar", SearchOpts::default()),
None
);
assert_eq!(
std::fs::read_dir(dir.path()).unwrap().count(),
2,
"no temp file left"
);
}
#[test]
fn a_symlink_planted_at_the_temp_name_is_not_written_through() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("a.txt");
std::fs::write(&f, "foo\n").unwrap();
let victim = dir.path().join("victim");
std::fs::write(&victim, "keep").unwrap();
let tmp = dir
.path()
.join(format!(".a.txt.croft-replace-{}", std::process::id()));
std::os::unix::fs::symlink(&victim, &tmp).unwrap();
assert_eq!(
replace_in_file(&f, "foo", "bar", SearchOpts::default()),
Some(1)
);
assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep");
assert_eq!(std::fs::read_to_string(&f).unwrap(), "bar\n");
}
#[test]
fn zero_width_patterns_and_longer_alternatives_replace_what_the_search_lists() {
let re = SearchOpts {
use_regex: true,
..SearchOpts::default()
};
assert_eq!(
replace_in_text("a\nb\n", "^", "// ", re),
Some((String::from("// a\n// b\n"), 2))
);
assert_eq!(
replace_in_text("a\r\nb\n", "$", ";", re),
Some((String::from("a;\r\nb;\n"), 2))
);
let ww = SearchOpts {
whole_word: true,
..re
};
assert_eq!(
replace_in_text("x foobar y", "foo|foobar", "Z", ww),
Some((String::from("x Z y"), 1))
);
assert_eq!(
replace_in_text("let a1 = b2;", "([a-z])(\\d)", "$2$1", re).map(|r| r.0),
Some(String::from("let 1a = 2b;"))
);
}
#[test]
fn captures_keep_the_context_around_the_match() {
let re = SearchOpts {
use_regex: true,
..SearchOpts::default()
};
assert_eq!(
replace_in_text("foo.rs", r"\b(\.rs)", "${1}x", re).map(|r| r.0),
Some(String::from("foo.rsx"))
);
}
#[test]
fn replace_in_file_keeps_hard_links_linked() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("a.txt");
std::fs::write(&f, "foo\n").unwrap();
let link = dir.path().join("b.txt");
std::fs::hard_link(&f, &link).unwrap();
assert_eq!(
replace_in_file(&f, "foo", "bar", SearchOpts::default()),
Some(1)
);
assert_eq!(std::fs::read_to_string(&link).unwrap(), "bar\n");
}
#[test]
fn whole_word_replace_takes_matches_edged_with_punctuation() {
let ww = SearchOpts {
whole_word: true,
..SearchOpts::default()
};
assert_eq!(
replace_in_text("echo $var here $variable", "$var", "$x", ww),
Some((String::from("echo $x here $variable"), 1))
);
}
#[test]
fn replace_in_text_literal_replaces_all_occurrences() {
let (out, n) =
replace_in_text("foo bar foo baz foo", "foo", "X", SearchOpts::default()).unwrap();
assert_eq!(n, 3);
assert_eq!(out, "X bar X baz X");
}
#[test]
fn replace_in_text_no_match_returns_zero_and_unchanged() {
let (out, n) = replace_in_text("hello world", "zzz", "X", SearchOpts::default()).unwrap();
assert_eq!(n, 0);
assert_eq!(out, "hello world");
}
#[test]
fn replace_in_text_literal_dollar_is_inserted_verbatim() {
let (out, n) = replace_in_text("price=AMT", "AMT", "$5", SearchOpts::default()).unwrap();
assert_eq!(n, 1);
assert_eq!(out, "price=$5");
}
#[test]
fn replace_in_text_case_insensitive_by_default() {
let (out, n) = replace_in_text("Foo foo FOO", "foo", "x", SearchOpts::default()).unwrap();
assert_eq!(n, 3);
assert_eq!(out, "x x x");
}
#[test]
fn replace_in_text_case_sensitive_only_exact_case() {
let opts = SearchOpts {
case_sensitive: true,
..Default::default()
};
let (out, n) = replace_in_text("Foo foo FOO", "foo", "x", opts).unwrap();
assert_eq!(n, 1);
assert_eq!(out, "Foo x FOO");
}
#[test]
fn replace_in_text_whole_word_skips_substrings() {
let opts = SearchOpts {
whole_word: true,
..Default::default()
};
let (out, n) = replace_in_text("cat category cat", "cat", "dog", opts).unwrap();
assert_eq!(n, 2);
assert_eq!(out, "dog category dog");
}
#[test]
fn replace_in_text_regex_with_capture_reference() {
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
let (out, n) = replace_in_text("a1 b2 c3", r"([a-z])(\d)", "$2$1", opts).unwrap();
assert_eq!(n, 3);
assert_eq!(out, "1a 2b 3c");
}
#[test]
fn replace_in_text_invalid_regex_returns_none() {
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
assert!(replace_in_text("anything", "[unclosed", "x", opts).is_none());
}
#[test]
fn replace_in_file_writes_only_when_a_match_is_replaced() {
let tmp = TempDir::new().unwrap();
let p = tmp.path().join("a.txt");
write(&p, "old value old\n");
let n = replace_in_file(&p, "old", "new", SearchOpts::default()).unwrap();
assert_eq!(n, 2);
assert_eq!(fs::read_to_string(&p).unwrap(), "new value new\n");
}
#[test]
fn replace_all_on_disk_replaces_across_distinct_hit_files() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "foo foo\n");
write(&tmp.path().join("b.txt"), "foo\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "foo".into();
panel.replace = "bar".into();
panel.run_query();
let total = panel.replace_all_on_disk();
assert_eq!(total, 3, "all three matches across both files replaced");
assert_eq!(
fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
"bar bar\n"
);
assert_eq!(
fs::read_to_string(tmp.path().join("b.txt")).unwrap(),
"bar\n"
);
}
#[test]
fn toggle_replace_expands_and_collapses_the_replace_row() {
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
assert!(!panel.replace_open);
panel.toggle_replace();
assert!(panel.replace_open);
panel.focus_field(SearchField::Replace);
panel.toggle_replace();
assert!(!panel.replace_open);
assert_eq!(panel.field, SearchField::Query);
}
#[test]
fn tab_cycles_only_through_visible_fields() {
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focus_next_field();
assert_eq!(panel.field, SearchField::Query);
panel.replace_open = true;
panel.details_open = true;
panel.focus_next_field();
assert_eq!(panel.field, SearchField::Replace);
panel.focus_next_field();
assert_eq!(panel.field, SearchField::Include);
panel.focus_next_field();
assert_eq!(panel.field, SearchField::Exclude);
panel.focus_next_field();
assert_eq!(panel.field, SearchField::Query);
}
#[test]
fn type_char_lands_in_the_focused_field() {
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.replace_open = true;
panel.type_char('a');
assert_eq!(panel.query, "a");
assert_eq!(panel.replace, "");
panel.focus_field(SearchField::Replace);
panel.type_char('b');
assert_eq!(panel.query, "a");
assert_eq!(panel.replace, "b");
}
#[test]
fn focused_query_field_exposes_a_caret_and_paints_no_static_block() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
panel.type_char('a');
panel.type_char('b');
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 20,
};
let mut buf = Buffer::empty(area);
Widget::render(&mut panel, area, &mut buf);
let (cx, cy) = panel
.cursor_screen_pos()
.expect("a focused query field must expose a caret position");
let r = panel.query_input_rect;
assert_eq!(cy, r.y, "caret rides the query row");
assert!(cx > r.x, "caret sits past the magnifier-led text start");
let row: String = (r.x..r.right())
.map(|x| buf[(x, r.y)].symbol().to_string())
.collect();
assert!(
!row.contains('\u{2588}'),
"the static full-block cursor must be gone now that the hardware caret blinks; row was {row:?}"
);
}
#[test]
fn an_unfocused_search_panel_exposes_no_caret() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = false;
panel.type_char('x');
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 20,
};
let mut buf = Buffer::empty(area);
Widget::render(&mut panel, area, &mut buf);
assert!(
panel.cursor_screen_pos().is_none(),
"an unfocused panel must not claim the hardware caret"
);
}
#[test]
fn backspace_removes_from_the_focused_field() {
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.details_open = true;
panel.focus_field(SearchField::Include);
panel.insert_str("*.rs");
assert_eq!(panel.include, "*.rs");
assert!(panel.backspace());
assert_eq!(panel.include, "*.r");
assert_eq!(panel.query, "");
}
#[test]
fn chevron_ellipsis_and_replace_all_hit_tests_after_render() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
panel.replace_open = true;
panel.details_open = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 24,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
assert!(panel.chevron_at(panel.chevron_x, panel.chevron_y));
assert!(panel.ellipsis_at(panel.ellipsis_x, panel.ellipsis_y));
assert!(panel.replace_all_at(panel.replace_all_x, panel.replace_all_y));
let q = panel.query_input_rect;
assert_eq!(panel.field_at(q.x, q.y), Some(SearchField::Query));
let r = panel.replace_input_rect;
assert_eq!(panel.field_at(r.x, r.y), Some(SearchField::Replace));
}
#[test]
fn expanded_rows_push_results_start_down() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let collapsed_offset = panel.results_start_offset;
panel.replace_open = true;
panel.details_open = true;
let mut buf2 = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf2);
assert!(
panel.results_start_offset > collapsed_offset,
"expanding replace + include/exclude must push results down (was {collapsed_offset}, now {})",
panel.results_start_offset
);
assert_eq!(panel.results_start_offset, collapsed_offset + 8);
}
#[test]
fn collapsed_panel_results_offset_is_five() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
assert_eq!(
panel.results_start_offset, 5,
"collapsed layout starts results at the 5-row offset"
);
}
#[test]
fn expand_replacement_honours_capture_references_in_regex_mode() {
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
assert_eq!(
expand_replacement("beta_42", r"beta_(\d+)", "id-$1", opts),
"id-42",
"regex mode expands $1 against the matched slice"
);
let literal = SearchOpts::default();
assert_eq!(
expand_replacement("beta", "beta", "x$1y", literal),
"x$1y",
"literal mode inserts the replacement verbatim"
);
}
#[test]
fn toggling_replace_open_focuses_the_replace_input() {
let mut panel = SearchPanel::new(PathBuf::from("/tmp"));
assert_eq!(panel.field, SearchField::Query);
panel.toggle_replace();
assert_eq!(
panel.field,
SearchField::Replace,
"revealing the row must focus it — typing used to extend the query"
);
panel.toggle_replace();
assert_eq!(panel.field, SearchField::Query, "collapsing returns focus");
}
#[test]
fn zero_width_regex_matches_advance_and_mark_positions() {
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
let segs = split_for_highlight("foo", r"\b", opts);
assert_eq!(
segs,
vec![
(String::new(), true),
(String::from("foo"), false),
(String::new(), true),
]
);
}
#[test]
fn the_scan_prefilter_never_hides_a_real_match() {
let lines = [
"ERROR disk full",
"error disk full",
"ErRoR",
"no match here",
"",
"prefix_error_suffix",
"\u{440}\u{443}\u{441}\u{441}\u{43a}\u{438}\u{439} error",
"\u{130}stanbul error",
"tab\terror",
];
let needles = ["error", "ERROR", "err", "\u{440}\u{443}", "zzz", ""];
let mut opt_sets = Vec::new();
for case_sensitive in [true, false] {
for whole_word in [true, false] {
for use_regex in [true, false] {
opt_sets.push(SearchOpts {
case_sensitive,
whole_word,
use_regex,
});
}
}
}
for line in lines {
for needle in needles {
for opts in &opt_sets {
let real =
!crate::widgets::editor_find::line_matches(line, *opts, needle).is_empty();
if real {
assert!(
line_may_match(line, needle, *opts),
"pre-filter hid a real match: line={line:?} needle={needle:?} \
case_sensitive={} whole_word={} regex={}",
opts.case_sensitive,
opts.whole_word,
opts.use_regex
);
}
}
}
}
}
#[test]
fn the_scan_prefilter_rejects_lines_that_cannot_match() {
let opts = SearchOpts::default();
assert!(!line_may_match("nothing to see", "error", opts));
assert!(!line_may_match(
"short",
"a longer needle than the line",
opts
));
let ci = SearchOpts {
case_sensitive: false,
..SearchOpts::default()
};
assert!(line_may_match("ERROR here", "error", ci), "case folds");
assert!(!line_may_match("ERROR here", "warning", ci));
}
}