use globset::{Glob, GlobSet, GlobSetBuilder};
use grep_matcher::{LineMatchKind, LineTerminator, Match, Matcher, NoCaptures, NoError};
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::Widget,
};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use unicode_width::UnicodeWidthStr;
use crate::glob_list::split_globs;
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,
pub matches: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct SearchOpts {
pub case_sensitive: bool,
pub whole_word: bool,
pub use_regex: bool,
pub preserve_case: bool,
}
impl SearchOpts {
pub fn same_matching(&self, other: &SearchOpts) -> bool {
self.case_sensitive == other.case_sensitive
&& self.whole_word == other.whole_word
&& self.use_regex == other.use_regex
}
}
fn build_matcher(query: &str, opts: SearchOpts) -> Option<SearchMatcher> {
if query.is_empty() {
return None;
}
compile_matcher(query, opts).ok()
}
fn compile_matcher(query: &str, opts: SearchOpts) -> Result<SearchMatcher, grep_regex::Error> {
let mut b = RegexMatcherBuilder::new();
b.case_insensitive(!opts.case_sensitive);
b.word(opts.whole_word);
b.fixed_strings(!opts.use_regex);
match b.build(query) {
Ok(m) => Ok(SearchMatcher::Fast(m)),
Err(err) => {
if !opts.use_regex {
return Err(err);
}
let case = if opts.case_sensitive { "" } else { "(?i)" };
let pattern = if opts.whole_word {
format!(r"{case}(?<!\w)(?:{query})(?!\w)")
} else {
format!("{case}{query}")
};
fancy_regex::Regex::new(&pattern)
.map(|re| SearchMatcher::Fancy(Arc::new(re)))
.map_err(|_| err)
}
}
}
#[derive(Clone, Debug)]
enum SearchMatcher {
Fast(RegexMatcher),
Fancy(Arc<fancy_regex::Regex>),
}
impl Matcher for SearchMatcher {
type Captures = NoCaptures;
type Error = NoError;
fn find_at(&self, haystack: &[u8], at: usize) -> Result<Option<Match>, NoError> {
match self {
Self::Fast(m) => m.find_at(haystack, at),
Self::Fancy(re) => Ok(std::str::from_utf8(haystack)
.ok()
.filter(|text| text.is_char_boundary(at))
.and_then(|text| re.find_from_pos(text, at).ok().flatten())
.map(|m| Match::new(m.start(), m.end()))),
}
}
fn new_captures(&self) -> Result<NoCaptures, NoError> {
Ok(NoCaptures::new())
}
fn shortest_match_at(&self, haystack: &[u8], at: usize) -> Result<Option<usize>, NoError> {
match self {
Self::Fast(m) => m.shortest_match_at(haystack, at),
Self::Fancy(_) => Ok(self.find_at(haystack, at)?.map(|m| m.end())),
}
}
fn is_match_at(&self, haystack: &[u8], at: usize) -> Result<bool, NoError> {
match self {
Self::Fast(m) => m.is_match_at(haystack, at),
Self::Fancy(_) => Ok(self.find_at(haystack, at)?.is_some()),
}
}
fn non_matching_bytes(&self) -> Option<&grep_matcher::ByteSet> {
match self {
Self::Fast(m) => m.non_matching_bytes(),
Self::Fancy(_) => None,
}
}
fn line_terminator(&self) -> Option<LineTerminator> {
match self {
Self::Fast(m) => m.line_terminator(),
Self::Fancy(_) => None,
}
}
fn find_candidate_line(&self, haystack: &[u8]) -> Result<Option<LineMatchKind>, NoError> {
match self {
Self::Fast(m) => m.find_candidate_line(haystack),
Self::Fancy(_) => Ok(self.shortest_match(haystack)?.map(LineMatchKind::Confirmed)),
}
}
}
pub(crate) enum Pattern {
Plain(regex::Regex),
Fancy(fancy_regex::Regex),
}
impl Pattern {
fn new(pattern: &str) -> Option<Self> {
match regex::Regex::new(pattern) {
Ok(re) => Some(Self::Plain(re)),
Err(_) => fancy_regex::Regex::new(pattern).ok().map(Self::Fancy),
}
}
pub(crate) fn for_find(body: &str, opts: SearchOpts) -> Option<Self> {
let case = if opts.case_sensitive { "" } else { "(?i)" };
if !opts.whole_word {
return Self::new(&format!("{case}{body}"));
}
match regex::Regex::new(&format!(r"{case}\b(?:{body})\b")) {
Ok(re) => Some(Self::Plain(re)),
Err(_) => fancy_regex::Regex::new(&format!(r"{case}(?<!\w)(?:{body})(?!\w)"))
.ok()
.map(Self::Fancy),
}
}
fn has_group(&self, name: &str) -> bool {
match self {
Self::Plain(re) => re.capture_names().flatten().any(|n| n == name),
Self::Fancy(re) => re.capture_names().flatten().any(|n| n == name),
}
}
fn captures_len(&self) -> usize {
match self {
Self::Plain(re) => re.captures_len(),
Self::Fancy(re) => re.captures_len(),
}
}
pub(crate) fn spans(&self, line: &str) -> Vec<(usize, usize)> {
match self {
Self::Plain(re) => re.find_iter(line).map(|m| (m.start(), m.end())).collect(),
Self::Fancy(re) => re
.find_iter(line)
.map_while(Result::ok)
.map(|m| (m.start(), m.end()))
.collect(),
}
}
pub(crate) fn expand_at(
&self,
line: &str,
start: usize,
end: usize,
replacement: &str,
) -> Option<String> {
let template = brace_refs(replacement, self.captures_len(), |name| {
self.has_group(name)
});
let mut out = String::new();
match self {
Self::Plain(re) => {
let caps = 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)))
})?;
caps.expand(&template, &mut out);
}
Self::Fancy(re) => {
let caps = re
.captures_from_pos(line, start)
.ok()
.flatten()
.filter(|c| {
c.get(0)
.is_some_and(|m| (m.start(), m.end()) == (start, end))
})
.or_else(|| {
re.captures(&line[start..end])
.ok()
.flatten()
.filter(|c| c.get(0).is_some_and(|m| m.range() == (0..end - start)))
})?;
caps.expand(&template, &mut out);
}
}
Some(out)
}
}
pub fn query_error(query: &str, opts: SearchOpts) -> Option<String> {
let q = as_typed(query);
if q.is_empty() {
return None;
}
let err = compile_matcher(q, opts).err()?.to_string();
let reason = err
.lines()
.rev()
.find_map(|l| l.trim().strip_prefix("error: "))
.unwrap_or_else(|| err.lines().next().unwrap_or("").trim());
Some(format!("Invalid regex: {reason}"))
}
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>,
include_dirs: Option<GlobSet>,
exclude: Option<GlobSet>,
}
fn compile_glob(pat: &str) -> Option<Glob> {
if let Some(anchored) = pat.strip_prefix('/') {
return globset::GlobBuilder::new(anchored)
.literal_separator(true)
.build()
.ok();
}
let expanded = if let Some(anchored) = pat.strip_prefix("./") {
anchored.to_string()
} else if pat.contains('/') {
pat.to_string()
} else {
format!("**/{pat}")
};
Glob::new(&expanded).ok()
}
pub fn invalid_globs(raw: &str) -> Vec<&str> {
split_globs(raw)
.filter(|p| compile_glob(p).is_none())
.collect()
}
fn build_glob_set(raw: &str, fail_closed: bool) -> Option<GlobSet> {
build_glob_set_of(raw, fail_closed, |_| true)
}
fn build_glob_set_of(raw: &str, fail_closed: bool, keep: impl Fn(&str) -> bool) -> Option<GlobSet> {
let mut builder = GlobSetBuilder::new();
let mut any = false;
let mut typed = false;
for pat in split_globs(raw).filter(|p| keep(p)) {
typed = true;
if let Some(g) = compile_glob(pat) {
builder.add(g);
any = true;
}
}
if !any && !(typed && fail_closed) {
return None;
}
builder.build().ok()
}
fn names_a_folder(pat: &str) -> bool {
let last = pat.trim_end_matches('/').rsplit('/').next().unwrap_or(pat);
!last.is_empty() && !last.contains(['*', '?', '[', '{'])
}
fn matches_self_or_parent(set: &GlobSet, rel: &Path) -> bool {
rel.ancestors()
.any(|p| !p.as_os_str().is_empty() && set.is_match(p))
}
impl PathFilter {
pub fn new(include: &str, exclude: &str) -> Self {
Self {
include: build_glob_set(include, true),
include_dirs: build_glob_set_of(include, false, names_a_folder),
exclude: build_glob_set(exclude, false),
}
}
pub fn is_empty(&self) -> bool {
self.include.is_none() && self.exclude.is_none()
}
pub fn allows(&self, root: &Path, path: &Path) -> bool {
let inside = path.strip_prefix(root).ok();
let rel = inside.unwrap_or(path);
if let Some(inc) = &self.include
&& !inc.is_match(rel)
&& !inside.is_some_and(|rel| {
self.include_dirs
.as_ref()
.is_some_and(|dirs| matches_self_or_parent(dirs, rel))
})
{
return false;
}
if let Some(exc) = &self.exclude
&& matches_self_or_parent(exc, rel)
{
return false;
}
true
}
pub fn excludes(&self, root: &Path, path: &Path) -> bool {
let rel = path.strip_prefix(root).unwrap_or(path);
self.exclude
.as_ref()
.is_some_and(|exc| matches_self_or_parent(exc, rel))
}
pub fn excluding(globs: &[String]) -> Self {
Self::new("", &globs.join(", "))
}
}
struct HitSink<'a> {
path: PathBuf,
matcher: &'a SearchMatcher,
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 indent = stripped.len() - stripped.trim_start().len();
let start = grep_matcher::Matcher::find(self.matcher, stripped.as_bytes())
.ok()
.flatten()
.map_or(indent, |m| m.start().min(indent));
let trimmed = stripped.get(start..).unwrap_or(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,
matches: count_in_line(stripped, self.matcher).max(1),
});
Ok(true)
}
}
pub(crate) fn as_typed(query: &str) -> &str {
query.trim_matches(|c| c == '\r' || c == '\n')
}
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 = as_typed(query);
if q.is_empty() {
return;
}
let Some(matcher) = build_matcher(q, opts) else {
return;
};
let walker = WalkBuilder::new(root)
.git_ignore(true)
.hidden(false)
.filter_entry(|entry| entry.depth() == 0 || !is_vcs_store(entry.file_name()))
.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(),
matcher: &matcher,
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
})
});
}
fn is_vcs_store(name: &std::ffi::OsStr) -> bool {
matches!(
name.to_str(),
Some(".git" | ".hg" | ".svn" | ".bzr" | "CVS")
)
}
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 Some(re) = Pattern::for_find(needle, opts) else {
return vec![(line.to_string(), false)];
};
let mut out: Vec<(String, bool)> = Vec::new();
let mut last = 0usize;
for (start, end) in re.spans(line) {
if start > last {
out.push((line[last..start].to_string(), false));
}
if end == start {
out.push((String::new(), true));
last = end;
continue;
}
out.push((line[start..end].to_string(), true));
last = 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 as_typed(&query).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 = as_typed(query);
if q.is_empty() {
return;
}
let Some(matcher) = build_matcher(q, opts) else {
return;
};
let mut sink = HitSink {
path: path.to_path_buf(),
matcher: &matcher,
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<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)
}
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)
}
fn count_in_line(line: &str, matcher: &SearchMatcher) -> usize {
replace_in_line(line, matcher, None, "", SearchOpts::default()).1
}
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())
}
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
}
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)
}
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,
query_error_memo: Option<(String, SearchOpts, Option<String>)>,
pub toggle_case_x: u16,
pub toggle_word_x: u16,
pub toggle_regex_x: u16,
pub toggle_preserve_x: u16,
pub toggle_preserve_y: 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)>,
carets: [Option<usize>; 4],
field_origin: [(u16, usize); 4],
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 project_exclude_rect: Rect,
pub project_exclude: Vec<String>,
pub use_exclude_settings: bool,
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 SearchField {
fn index(self) -> usize {
match self {
SearchField::Query => 0,
SearchField::Replace => 1,
SearchField::Include => 2,
SearchField::Exclude => 3,
}
}
}
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(),
query_error_memo: None,
toggle_case_x: 0,
toggle_word_x: 0,
toggle_regex_x: 0,
toggle_preserve_x: 0,
toggle_preserve_y: 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,
carets: [None; 4],
field_origin: [(0, 0); 4],
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(),
project_exclude_rect: Rect::default(),
project_exclude: Vec::new(),
use_exclude_settings: true,
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;
for f in [
SearchField::Query,
SearchField::Include,
SearchField::Exclude,
] {
self.carets[f.index()] = None;
}
}
pub fn caret(&self) -> usize {
self.field_caret(self.field)
}
fn field_text(&self, field: SearchField) -> &str {
match field {
SearchField::Query => &self.query,
SearchField::Replace => &self.replace,
SearchField::Include => &self.include,
SearchField::Exclude => &self.exclude,
}
}
fn field_caret(&self, field: SearchField) -> usize {
let text = self.field_text(field);
crate::widgets::line_edit::clamp(text, self.carets[field.index()].unwrap_or(usize::MAX))
}
fn store_caret(&mut self, field: SearchField, at: usize) {
let len = crate::widgets::line_edit::char_len(self.field_text(field));
self.carets[field.index()] = (at < len).then_some(at);
}
fn set_caret(&mut self, at: usize) {
self.store_caret(self.field, at);
}
pub fn move_caret(&mut self, step: impl FnOnce(&str, usize) -> usize) {
let at = step(self.active_text(), self.caret());
self.set_active_selection(None);
self.set_caret(at);
}
pub fn click_caret(&mut self, col: u16) {
let (text_x, start) = self.field_origin[self.field.index()];
let at = crate::widgets::line_edit::char_at_cell(
self.active_text(),
start,
usize::from(col.saturating_sub(text_x)),
);
self.set_active_selection(None);
self.set_caret(at);
}
fn edit_active(&mut self, edit: impl FnOnce(&str, usize) -> (String, usize)) -> bool {
let (text, caret) = edit(self.active_text(), self.caret());
let changed = text != self.active_text();
*self.active_text_mut() = text;
self.set_caret(caret);
changed
}
pub fn select_all_query(&mut self) {
if self.query.is_empty() {
self.selection = None;
} else {
self.selection = Some((0, self.query.len()));
}
self.carets[SearchField::Query.index()] = None;
}
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;
let at = crate::widgets::line_edit::char_of(&self.query, a);
self.store_caret(SearchField::Query, at);
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(),
}
}
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();
self.set_caret(0);
}
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();
let typed = c.to_string();
self.edit_active(|t, at| crate::widgets::line_edit::insert_at(t, at, &typed));
}
pub fn backspace(&mut self) -> bool {
if self.delete_active_selection() {
return true;
}
self.edit_active(|t, at| crate::widgets::line_edit::delete_before(t, at, false))
}
pub fn backspace_by(&mut self, word: bool) -> bool {
if self.delete_active_selection() {
return true;
}
self.edit_active(|t, at| crate::widgets::line_edit::delete_before(t, at, word))
}
pub fn delete_forward(&mut self, word: bool) -> bool {
if self.delete_active_selection() {
return true;
}
self.edit_active(|t, at| crate::widgets::line_edit::delete_at(t, at, word))
}
pub fn insert_str(&mut self, s: &str) {
self.delete_active_selection();
self.edit_active(|t, at| crate::widgets::line_edit::insert_at(t, at, s));
}
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)));
}
let end = crate::widgets::line_edit::char_len(self.active_text());
self.set_caret(end);
}
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);
let at = crate::widgets::line_edit::char_of(self.active_text(), a);
self.set_caret(at);
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 open_replace(&mut self) {
self.replace_open = true;
self.focus_field(SearchField::Replace);
}
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.effective_exclude())
}
pub fn effective_exclude(&self) -> String {
if !self.use_exclude_settings || self.project_exclude.is_empty() {
return self.exclude.clone();
}
let mut parts: Vec<&str> = Vec::new();
if !self.exclude.trim().is_empty() {
parts.push(&self.exclude);
}
parts.extend(self.project_exclude.iter().map(String::as_str));
parts.join(", ")
}
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 (Alt+D)");
}
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 (Alt+C)",
SearchToggle::WholeWord => "Match Whole Word (Alt+W)",
SearchToggle::UseRegex => "Use Regular Expression (Alt+R)",
SearchToggle::PreserveCase => "Preserve Case (Alt+P)",
});
}
None
}
pub fn result_path_at(&self, col: u16, row: u16) -> Option<&Path> {
let inner = self.last_inner;
let overflows = self.hits.len() > self.results_viewport_height();
let right = inner.x + inner.width - u16::from(overflows && inner.width > 0);
if col < inner.x || col >= right {
return None;
}
self.hit_at_y(row).map(|i| self.hits[i].path.as_path())
}
pub fn clear_all(&mut self) {
self.query.clear();
self.replace.clear();
self.carets[SearchField::Query.index()] = None;
self.carets[SearchField::Replace.index()] = None;
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 project_exclude_toggle_at(&self, col: u16, row: u16) -> bool {
let r = self.project_exclude_rect;
r.width != 0 && row == r.y && col >= r.x && col < r.x + r.width
}
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)
}
fn hit_order<'a>(&self, hit: &'a SearchHit) -> (usize, &'a Path, usize) {
let roots = if self.roots.is_empty() {
std::slice::from_ref(&self.root)
} else {
self.roots.as_slice()
};
let owner = roots
.iter()
.enumerate()
.filter(|(_, r)| hit.path.starts_with(r))
.max_by_key(|(_, r)| r.components().count());
match owner {
Some((i, r)) => (
i,
hit.path.strip_prefix(r).unwrap_or(&hit.path),
hit.line_no,
),
None => (usize::MAX, hit.path.as_path(), hit.line_no),
}
}
pub fn add_hits(&mut self, mut batch: Vec<SearchHit>) {
if batch.is_empty() {
return;
}
batch.sort_by_cached_key(|h| {
let (root, rel, line) = self.hit_order(h);
(root, rel.to_path_buf(), line)
});
let old = std::mem::take(&mut self.hits);
let selected = (self.selected < old.len()).then_some(self.selected);
let mut merged = Vec::with_capacity(old.len() + batch.len());
let mut rest = old.into_iter();
let mut moved = 0usize;
let mut prev_path: Option<PathBuf> = None;
for hit in batch {
let pending = rest.as_slice();
let same_file = prev_path.as_deref() == Some(hit.path.as_path());
let n = if same_file && pending.first().is_none_or(|o| o.path != hit.path) {
0
} else {
let key = self.hit_order(&hit);
pending.partition_point(|o| self.hit_order(o) <= key)
};
if let Some(s) = selected
&& (moved..moved + n).contains(&s)
{
self.selected = merged.len() + (s - moved);
}
merged.extend(rest.by_ref().take(n));
moved += n;
if !same_file {
prev_path = Some(hit.path.clone());
}
merged.push(hit);
}
if let Some(s) = selected
&& s >= moved
{
self.selected = merged.len() + (s - moved);
}
merged.extend(rest);
self.hits = merged;
}
pub fn query_error(&mut self) -> Option<String> {
let fresh = matches!(&self.query_error_memo,
Some((q, o, _)) if *q == self.query && *o == self.opts);
if !fresh {
let error = query_error(&self.query, self.opts);
self.query_error_memo = Some((self.query.clone(), self.opts, error));
}
self.query_error_memo
.as_ref()
.and_then(|(_, _, e)| e.clone())
}
pub fn run_query(&mut self) {
self.hits.clear();
self.add_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> {
let preserve = self.toggle_preserve_x;
if preserve != 0 && row == self.toggle_preserve_y && col >= preserve && col < preserve + 2 {
return Some(SearchToggle::PreserveCase);
}
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 toggle_opt(&mut self, toggle: SearchToggle) -> bool {
let flag = match toggle {
SearchToggle::CaseSensitive => &mut self.opts.case_sensitive,
SearchToggle::WholeWord => &mut self.opts.whole_word,
SearchToggle::UseRegex => &mut self.opts.use_regex,
SearchToggle::PreserveCase => &mut self.opts.preserve_case,
};
*flag = !*flag;
*flag
}
pub fn result_counts(&self) -> (usize, usize) {
let results = self.hits.iter().map(|h| h.matches).sum();
let files = self
.hits
.first()
.into_iter()
.chain(
self.hits
.windows(2)
.filter(|w| w[0].path != w[1].path)
.map(|w| &w[1]),
)
.map(|h| &h.path)
.collect::<HashSet<_>>()
.len();
(results, files)
}
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,
PreserveCase,
}
struct FieldArgs<'a> {
bar_x: u16,
y: u16,
fill_right: u16,
lead_glyph: Option<&'a str>,
text: &'a str,
caret: usize,
placeholder: &'a str,
selection: Option<(usize, usize)>,
field_focused: bool,
accent: Color,
bg: (u8, u8, u8),
reserve_right: u16,
}
fn draw_glob_caption(
buf: &mut Buffer,
(x, y, right): (u16, u16, u16),
label: &str,
raw: &str,
style: Style,
theme: crate::theme::Theme,
) {
let bad = invalid_globs(raw);
if bad.is_empty() {
buf.set_string(x, y, label, style);
return;
}
buf.set_stringn(
x,
y,
format!("invalid glob: {}", bad.join(", ")),
right.saturating_sub(x) as usize + 1,
Style::default().fg(theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c))),
);
}
fn render_field(
buf: &mut Buffer,
args: FieldArgs,
theme: crate::theme::Theme,
caret_out: &mut Option<(u16, u16)>,
origin_out: &mut (u16, usize),
) -> 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);
let win = crate::widgets::line_edit::window(args.text, args.caret, usize::from(text_w));
*origin_out = (text_x, win.start);
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)));
let (sb, eb) = (
crate::widgets::line_edit::byte_of(args.text, win.start),
crate::widgets::line_edit::byte_of(args.text, win.end),
);
let shown = &args.text[sb..eb];
let sel = args
.selection
.map(|(a, b)| (a.max(sb) - sb.min(a.max(sb)), b.min(eb).saturating_sub(sb)))
.filter(|&(a, b)| a < b && b <= shown.len());
match sel {
Some((a, b)) => {
if a > 0 {
spans.push(Span::styled(shown[..a].to_string(), plain));
}
spans.push(Span::styled(shown[a..b].to_string(), selected));
if b < shown.len() {
spans.push(Span::styled(shown[b..].to_string(), plain));
}
}
None => spans.push(Span::styled(shown.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 = (win.caret_cell 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 = crate::widgets::surface::view_block(self.theme, true, outer_style);
let inner = outer.inner(area);
outer.render(area, buf);
crate::widgets::surface::paint_view_focus(
buf,
area,
self.theme,
self.focused,
self.focus_gradient,
);
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 mut origins = self.field_origin;
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,
caret: self.field_caret(SearchField::Query),
placeholder: "Search",
selection: self.selection_range(),
field_focused: query_focused,
accent,
bg,
reserve_right: query_reserve,
},
self.theme,
&mut caret,
&mut origins[SearchField::Query.index()],
);
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.toggle_preserve_x = 0;
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,
caret: self.field_caret(SearchField::Replace),
placeholder: "Replace (Tab switches)",
selection: if self.field == SearchField::Replace {
self.active_selection()
} else {
None
},
field_focused: replace_focused,
accent,
bg,
reserve_right: 3,
},
self.theme,
&mut caret,
&mut origins[SearchField::Replace.index()],
);
let preserve_x = replace_fill_right.saturating_sub(2);
if preserve_x > bar_x + 1 {
let fill = lift_bg(
bg,
if replace_focused {
FIELD_FILL_LIFT_FOCUS
} else {
FIELD_FILL_LIFT_IDLE
},
);
let style = if self.opts.preserve_case {
active_style
} else {
inactive_style.bg(fill)
};
buf.set_string(preserve_x, next_y, "AB", style);
self.toggle_preserve_x = preserve_x;
self.toggle_preserve_y = next_y;
}
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();
self.project_exclude_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;
draw_glob_caption(
buf,
(bar_x, next_y, detail_fill_right),
"files to include",
&self.include,
caption_style,
self.theme,
);
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,
caret: self.field_caret(SearchField::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,
&mut origins[SearchField::Include.index()],
);
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;
draw_glob_caption(
buf,
(bar_x, next_y, detail_fill_right),
"files to exclude",
&self.exclude,
caption_style,
self.theme,
);
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,
caret: self.field_caret(SearchField::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,
&mut origins[SearchField::Exclude.index()],
);
next_y += 1;
if !self.project_exclude.is_empty() && next_y + 1 < inner.y + inner.height {
let text = format!(
"[{}] project excludes: {}",
if self.use_exclude_settings { "x" } else { " " },
self.project_exclude.join(", ")
);
let width = detail_fill_right.saturating_sub(bar_x) + 1;
let style = if self.use_exclude_settings {
caption_style
} else {
caption_style.add_modifier(Modifier::CROSSED_OUT)
};
buf.set_stringn(bar_x, next_y, &text, width as usize, style);
self.project_exclude_rect = Rect {
x: bar_x,
y: next_y,
width: (text.chars().count() as u16).min(width),
height: 1,
};
next_y += 1;
}
}
}
self.caret_cell = caret;
self.field_origin = origins;
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 mut results_start_y = caption_y + 1;
if caption_y < inner.y + inner.height && !as_typed(&self.query).is_empty() {
if let Some(error) = self.query_error() {
let style = Style::default().fg(self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c)));
let rows = crate::sarif::render::wrap(&error, inner.width.max(1) as usize);
let mut y = caption_y;
for row in rows {
if y >= inner.y + inner.height {
break;
}
buf.set_stringn(inner.x, y, &row, inner.width as usize, style);
y += 1;
}
results_start_y = y.max(caption_y + 1);
} else {
let (results, files) = self.result_counts();
let header = format!(
"{results} result{} in {files} file{}",
if results == 1 { "" } else { "s" },
if files == 1 { "" } else { "s" }
);
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.results_start_offset = results_start_y.saturating_sub(inner.y);
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 = as_typed(&self.query);
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();
let mut chunks = split_for_highlight(&hit.line_text, needle, self.opts);
if let Some(first) = chunks.iter().position(|(_, is_match)| *is_match) {
let prefix_w: usize = spans.iter().map(Span::width).sum();
let avail = usize::from(row_width).saturating_sub(prefix_w);
let matched = &chunks[first].0;
let mut need = matched.width();
if preview {
need += expand_replacement(matched, needle, &self.replace, self.opts).width();
}
let lead: String = chunks[..first].iter().map(|(t, _)| t.as_str()).collect();
if let Some(kept) = trim_leading_context(&lead, avail, need) {
chunks.splice(..first, std::iter::once((kept, false)));
}
}
for (chunk, is_match) in chunks {
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");
}
fn highlighted(hit: &SearchHit, query: &str, opts: SearchOpts) -> Vec<String> {
split_for_highlight(&hit.line_text, as_typed(query), opts)
.into_iter()
.filter(|(_, m)| *m)
.map(|(t, _)| t)
.collect()
}
#[test]
fn a_match_starting_in_the_indent_keeps_its_highlight() {
for (content, query) in [
("\tleading word\n", "\tleading"),
(" spaced out\n", " spaced"),
("x\n \n", " "),
] {
let mut out = Vec::new();
collect_matches_in_text(
Path::new("a.txt"),
content,
query,
SearchOpts::default(),
&mut out,
);
assert_eq!(out.len(), 1, "{query:?}");
assert_eq!(
highlighted(&out[0], query, SearchOpts::default()).first(),
Some(&as_typed(query).to_string()),
"{query:?} in {:?}",
out[0].line_text
);
}
}
#[test]
fn a_regex_match_starting_in_the_indent_keeps_its_highlight() {
let opts = SearchOpts {
use_regex: true,
..SearchOpts::default()
};
let mut out = Vec::new();
collect_matches_in_text(
Path::new("a.txt"),
" foo()\n",
r"^\s+foo",
opts,
&mut out,
);
assert_eq!(highlighted(&out[0], r"^\s+foo", opts), [" foo"]);
}
#[test]
fn the_indent_is_still_trimmed_when_the_match_starts_after_it() {
let mut out = Vec::new();
collect_matches_in_text(
Path::new("a.txt"),
" let x = 1;\n\t\tx y\n",
"x",
SearchOpts::default(),
&mut out,
);
assert_eq!(out[0].line_text, "let x = 1;");
assert_eq!(out[1].line_text, "x y");
let mut out = Vec::new();
collect_matches_in_text(
Path::new("a.txt"),
"\tif a b {\n",
" b",
SearchOpts::default(),
&mut out,
);
assert_eq!(out[0].line_text, "if a b {");
}
#[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()));
}
fn dotfile_repo() -> TempDir {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let ok = std::process::Command::new("git")
.args(["init", "-q"])
.current_dir(root)
.status()
.unwrap()
.success();
assert!(ok);
fs::create_dir_all(root.join("src")).unwrap();
fs::create_dir_all(root.join(".github/workflows")).unwrap();
fs::create_dir_all(root.join("node_modules/x")).unwrap();
write(&root.join(".gitignore"), "node_modules/\n*.log\n");
write(&root.join("src/app.js"), "const SECRET_TOKEN = 1;\n");
write(&root.join(".env"), "SECRET_TOKEN=abc\n");
write(&root.join(".github/workflows/ci.yml"), "SECRET_TOKEN\n");
write(&root.join("node_modules/x/index.js"), "SECRET_TOKEN\n");
write(&root.join("debug.log"), "SECRET_TOKEN\n");
write(&root.join(".git/SECRET_TOKEN_NOTE"), "SECRET_TOKEN\n");
tmp
}
fn hit_paths(root: &Path, query: &str) -> Vec<String> {
let mut paths: Vec<String> = search_workspace(root, query, SearchOpts::default())
.into_iter()
.map(|h| {
h.path
.strip_prefix(root)
.unwrap()
.to_string_lossy()
.into_owned()
})
.collect();
paths.sort();
paths
}
#[test]
fn search_finds_matches_in_dotfiles_and_dot_directories() {
let tmp = dotfile_repo();
assert_eq!(
hit_paths(tmp.path(), "SECRET_TOKEN"),
[".env", ".github/workflows/ci.yml", "src/app.js"]
);
}
#[test]
fn search_still_skips_gitignored_files_and_vcs_internals() {
let tmp = dotfile_repo();
for vcs in [".hg", ".svn"] {
fs::create_dir_all(tmp.path().join(vcs)).unwrap();
write(&tmp.path().join(vcs).join("store"), "SECRET_TOKEN\n");
}
let paths = hit_paths(tmp.path(), "SECRET_TOKEN");
for skipped in ["node_modules", "debug.log", ".git/", ".hg/", ".svn/"] {
assert!(
paths.iter().all(|p| !p.starts_with(skipped)),
"{skipped} must not be searched: {paths:?}"
);
}
assert!(hit_paths(tmp.path(), "core.bare").is_empty());
}
#[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.theme = crate::theme::Theme::BLACK;
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());
panel.theme = crate::theme::Theme::BLACK;
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 a_regex_that_will_not_compile_names_the_problem() {
let re = SearchOpts {
use_regex: true,
..SearchOpts::default()
};
assert_eq!(
query_error("foo(", re).as_deref(),
Some("Invalid regex: unclosed group")
);
let typo = query_error(r"(?<=@)\w+(", re).unwrap();
assert!(typo.starts_with("Invalid regex: "), "{typo}");
}
fn regex_opts() -> SearchOpts {
SearchOpts {
use_regex: true,
..SearchOpts::default()
}
}
fn hit_lines(content: &str, query: &str, opts: SearchOpts) -> Vec<(usize, String)> {
let mut hits = Vec::new();
collect_matches_in_text(Path::new("a.py"), content, query, opts, &mut hits);
hits.into_iter().map(|h| (h.line_no, h.line_text)).collect()
}
#[test]
fn look_around_and_backreferences_search() {
let re = regex_opts();
let prices = "price: 10 USD\nprice: 20 EUR\n";
assert_eq!(query_error(r"\d+ (?!USD)", re), None);
assert_eq!(
hit_lines(prices, r"\d+ (?!USD)", re),
[(2, String::from("price: 20 EUR"))]
);
assert_eq!(
hit_lines("to: ada@host\nno at here\n", r"(?<=@)\w+", re),
[(1, String::from("to: ada@host"))]
);
assert_eq!(query_error(r"(\w+) \1", re), None);
assert_eq!(
hit_lines("one two\nsaw the the cat\n", r"(\w+) \1", re),
[(2, String::from("saw the the cat"))]
);
}
#[test]
fn look_around_keeps_case_and_whole_word() {
let text = "a@Host\nb@hostname\n";
let insensitive = regex_opts();
assert_eq!(hit_lines(text, r"(?<=@)host", insensitive).len(), 2);
let sensitive = SearchOpts {
case_sensitive: true,
..insensitive
};
assert_eq!(
hit_lines(text, r"(?<=@)host", sensitive),
[(2, String::from("b@hostname"))]
);
let word = SearchOpts {
whole_word: true,
..insensitive
};
assert_eq!(
hit_lines(text, r"(?<=@)host", word),
[(1, String::from("a@Host"))]
);
}
#[test]
fn look_ahead_matches_are_highlighted_and_counted() {
let re = regex_opts();
assert_eq!(
split_for_highlight("10 USD 20 EUR 30 GBP", r"\d+ (?!USD)", re),
[
(String::from("10 USD "), false),
(String::from("20 "), true),
(String::from("EUR "), false),
(String::from("30 "), true),
(String::from("GBP"), false),
]
);
let mut hits = Vec::new();
collect_matches_in_text(
Path::new("a"),
"10 USD 20 EUR 30 GBP\n",
r"\d+ (?!USD)",
re,
&mut hits,
);
assert_eq!(hits[0].matches, 2);
}
#[test]
fn whole_word_look_ahead_highlights_by_the_search_rule() {
let word = SearchOpts {
whole_word: true,
..regex_opts()
};
let mut hits = Vec::new();
collect_matches_in_text(Path::new("a"), "- \n", "-(?= )", word, &mut hits);
assert_eq!(hits.len(), 1);
assert_eq!(
split_for_highlight("- ", "-(?= )", word),
[(String::from("-"), true), (String::from(" "), false)]
);
assert_eq!(
split_for_highlight("a- ", "-(?= )", word),
[(String::from("a- "), false)]
);
}
#[test]
fn replace_with_a_backreference_pattern() {
let re = regex_opts();
assert_eq!(
replace_in_text("saw the the cat\nok ok\none\n", r"\b(\w+) \1\b", "$1", re),
Some((String::from("saw the cat\nok\none\n"), 2))
);
assert_eq!(
replace_in_text("price: 10 USD 20 EUR\n", r"(\d+) (?!USD)", "${1}€ ", re),
Some((String::from("price: 10 USD 20€ EUR\n"), 1))
);
assert_eq!(
expand_replacement("the the", r"(\w+) \1", "[$1]", re),
"[the]"
);
}
#[test]
fn the_fallback_is_only_for_patterns_that_need_it() {
let re = regex_opts();
assert!(matches!(
compile_matcher(r"\d+ USD", re),
Ok(SearchMatcher::Fast(_))
));
assert!(matches!(
compile_matcher(r"\d+ (?!USD)", re),
Ok(SearchMatcher::Fancy(_))
));
let literal = SearchOpts::default();
assert!(hit_lines("price: 10 USD\n", "(?!USD)", literal).is_empty());
assert_eq!(
hit_lines("odd (?!USD) text\n", "(?!USD)", literal),
[(1, String::from("odd (?!USD) text"))]
);
}
#[test]
fn valid_and_literal_queries_have_no_regex_error() {
let re = SearchOpts {
use_regex: true,
..SearchOpts::default()
};
assert_eq!(query_error(r"foo\(", re), None);
assert_eq!(query_error(r"get_(user_\w+)", re), None);
assert_eq!(query_error("", re), None);
assert_eq!(query_error("foo(", SearchOpts::default()), None);
let whole_word = SearchOpts {
whole_word: true,
..re
};
assert_eq!(query_error("foo", whole_word), None);
}
#[test]
fn the_sidebar_shows_the_regex_error_in_place_of_the_count() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.py"), "def foo(x):\n return foo(1)\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.opts.use_regex = true;
panel.query = "foo(".into();
panel.run_query();
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 text = buffer_to_string(&buf);
assert!(text.contains("Invalid regex: unclosed group"), "{text}");
assert!(!text.contains("0 results"), "{text}");
panel.query = r"foo\(".into();
panel.run_query();
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let text = buffer_to_string(&buf);
assert!(text.contains("2 results in 1 file"), "{text}");
assert!(!text.contains("Invalid regex"), "{text}");
}
#[test]
fn a_long_regex_error_wraps_in_a_narrow_sidebar() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.py"), "foo(1)\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.opts.use_regex = true;
panel.query = r"foo(?=\()(".into();
panel.run_query();
let area = Rect {
x: 0,
y: 0,
width: 32,
height: 14,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let text = buffer_to_string(&buf);
let flat: String = text
.lines()
.map(|l| l.trim_matches(|c: char| c == '│' || c.is_whitespace()))
.collect::<Vec<_>>()
.join(" ");
assert!(flat.contains("is not supported"), "{text}");
let error_rows = text
.lines()
.filter(|l| l.contains("look-") || l.contains("supported"))
.count();
assert!(error_rows >= 2, "{text}");
let header = panel.last_inner.y + panel.results_start_offset;
let last_error_row = text.lines().position(|l| l.contains("supported")).unwrap() as u16;
assert!(
header > last_error_row,
"results start under the error\n{text}"
);
}
#[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 (Alt+C)")
);
assert_eq!(
panel.tooltip_at(panel.toggle_word_x, y),
Some("Match Whole Word (Alt+W)")
);
assert_eq!(
panel.tooltip_at(panel.toggle_regex_x, y),
Some("Use Regular Expression (Alt+R)")
);
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 hit(path: &Path, line_no: usize) -> SearchHit {
SearchHit {
path: path.to_path_buf(),
line_no,
line_text: format!("line {line_no}"),
matches: 1,
}
}
fn listed(panel: &SearchPanel) -> Vec<(String, usize)> {
panel
.hits
.iter()
.map(|h| {
let root = panel
.roots
.iter()
.find(|r| h.path.starts_with(r))
.unwrap_or(&panel.root);
let rel = h.path.strip_prefix(root).unwrap_or(&h.path);
(rel.display().to_string(), h.line_no)
})
.collect()
}
#[test]
fn streamed_batches_are_listed_by_path_whatever_order_they_arrive_in() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let mut panel = SearchPanel::new(root.to_path_buf());
panel.add_hits(vec![hit(&root.join("b.rs"), 2), hit(&root.join("b.rs"), 9)]);
panel.add_hits(vec![hit(&root.join("src/z.rs"), 1)]);
panel.add_hits(vec![hit(&root.join("a.rs"), 7)]);
panel.add_hits(vec![hit(&root.join("c.rs"), 4)]);
panel.add_hits(vec![hit(&root.join("src/m.rs"), 3)]);
assert_eq!(
listed(&panel),
[
("a.rs".into(), 7),
("b.rs".into(), 2),
("b.rs".into(), 9),
("c.rs".into(), 4),
("src/m.rs".into(), 3),
("src/z.rs".into(), 1),
]
);
}
#[test]
fn every_hit_of_the_first_root_is_listed_before_the_second_roots() {
let tmp = TempDir::new().unwrap();
let first = tmp.path().join("zeta");
let second = tmp.path().join("alpha");
let mut panel = SearchPanel::new(first.clone());
panel.roots = vec![first.clone(), second.clone()];
panel.add_hits(vec![hit(&second.join("a.rs"), 1)]);
panel.add_hits(vec![hit(&first.join("y.rs"), 1)]);
panel.add_hits(vec![hit(&second.join("b.rs"), 1)]);
panel.add_hits(vec![hit(&first.join("x.rs"), 1)]);
let paths: Vec<PathBuf> = panel.hits.iter().map(|h| h.path.clone()).collect();
assert_eq!(
paths,
[
first.join("x.rs"),
first.join("y.rs"),
second.join("a.rs"),
second.join("b.rs"),
]
);
}
#[test]
fn the_selection_stays_on_its_hit_as_earlier_files_arrive() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let mut panel = SearchPanel::new(root.to_path_buf());
panel.add_hits(vec![hit(&root.join("m.rs"), 1), hit(&root.join("m.rs"), 5)]);
panel.move_down();
assert_eq!(panel.selected_hit().map(|h| h.line_no), Some(5));
panel.add_hits(vec![hit(&root.join("a.rs"), 3)]);
panel.add_hits(vec![hit(&root.join("z.rs"), 3)]);
let sel = panel.selected_hit().unwrap();
assert_eq!((sel.path.clone(), sel.line_no), (root.join("m.rs"), 5));
}
#[test]
fn hits_arriving_in_any_order_and_drain_size_list_as_one_sort_would() {
let tmp = TempDir::new().unwrap();
let outer = tmp.path().to_path_buf();
let inner = outer.join("pkg");
let mut all: Vec<SearchHit> = Vec::new();
for f in 0..60 {
let dir = if f % 3 == 0 { &inner } else { &outer };
let path = dir.join(format!("d{}/f{f}.rs", f % 7));
all.extend((0..f % 5 + 1).map(|l| hit(&path, l * 4 + 1)));
}
let mut want = SearchPanel::new(outer.clone());
want.roots = vec![outer.clone(), inner.clone()];
want.add_hits(all.clone());
let mut x = 0x9e37_79b9u64;
let mut next = move |n: usize| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
(x as usize) % n.max(1)
};
for _round in 0..20 {
let mut shuffled = all.clone();
for i in (1..shuffled.len()).rev() {
shuffled.swap(i, next(i + 1));
}
let mut panel = SearchPanel::new(outer.clone());
panel.roots = vec![outer.clone(), inner.clone()];
let mut picked: Option<SearchHit> = None;
let mut rest = shuffled.as_slice();
while !rest.is_empty() {
let (drain, after) = rest.split_at(next(8).min(rest.len() - 1) + 1);
let mut drain = drain.to_vec();
drain.sort_by_key(|h| (h.path.clone(), h.line_no));
panel.add_hits(drain);
rest = after;
if let Some(p) = &picked {
assert_eq!(panel.selected_hit(), Some(p), "the selection moved");
} else if panel.hits.len() > 3 {
panel.selected = panel.hits.len() / 2;
picked = panel.selected_hit().cloned();
}
}
assert_eq!(panel.hits, want.hits);
}
}
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}"),
matches: 1,
})
.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}"),
matches: 1,
})
.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_dot_slash_anchors_a_glob_to_the_root() {
let root = Path::new("/ws");
let f = PathFilter::new("./main.rs,./src/**", "");
assert!(f.allows(root, Path::new("/ws/main.rs")));
assert!(f.allows(root, Path::new("/ws/src/deep/x.rs")));
assert!(!f.allows(root, Path::new("/ws/lib/main.rs")));
assert!(!f.allows(root, Path::new("/ws/vendor/src/x.rs")));
assert!(PathFilter::new("main.rs", "").allows(root, Path::new("/ws/lib/main.rs")));
}
#[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_include_keeps_commas_inside_braces() {
let f = PathFilter::new("*.{ts,tsx}", "");
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/src/a.ts")));
assert!(f.allows(root, Path::new("/proj/src/b.tsx")));
assert!(!f.allows(root, Path::new("/proj/other/d.js")));
assert!(!f.allows(root, Path::new("/proj/README.md")));
}
#[test]
fn path_filter_include_brace_glob_mixes_with_plain_ones() {
let f = PathFilter::new("*.md, src/**/*.{js,jsx}", "");
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/README.md")));
assert!(f.allows(root, Path::new("/proj/src/ui/app.jsx")));
assert!(!f.allows(root, Path::new("/proj/lib/app.jsx")));
assert!(!f.allows(root, Path::new("/proj/src/app.ts")));
}
#[test]
fn path_filter_include_with_no_valid_glob_allows_nothing() {
let f = PathFilter::new("*.{ts", "");
let root = Path::new("/proj");
assert!(!f.allows(root, Path::new("/proj/src/a.ts")));
assert!(!f.allows(root, Path::new("/proj/README.md")));
}
#[test]
fn path_filter_exclude_keeps_commas_inside_braces() {
let f = PathFilter::new("", "*.{md,js}, target/**");
let root = Path::new("/proj");
assert!(!f.allows(root, Path::new("/proj/README.md")));
assert!(!f.allows(root, Path::new("/proj/other/d.js")));
assert!(!f.allows(root, Path::new("/proj/target/x.rs")));
assert!(f.allows(root, Path::new("/proj/src/a.ts")));
}
#[test]
fn an_excluded_folder_hides_the_files_inside_it() {
let f = PathFilter::new("", "**/generated, target");
let root = Path::new("/proj");
assert!(!f.allows(root, Path::new("/proj/generated/api_pb2.py")));
assert!(!f.allows(root, Path::new("/proj/a/generated/deep/x.py")));
assert!(!f.allows(root, Path::new("/proj/target/debug/x.rs")));
assert!(f.allows(root, Path::new("/proj/generated_stub.py")));
assert!(f.allows(root, Path::new("/proj/src/targets/x.rs")));
}
#[test]
fn an_included_folder_searches_the_files_inside_it() {
let root = Path::new("/proj");
let f = PathFilter::new("tests", "");
assert!(f.allows(root, Path::new("/proj/tests/cli.rs")));
assert!(f.allows(root, Path::new("/proj/crate/tests/deep/x.rs")));
assert!(!f.allows(root, Path::new("/proj/src/main.rs")));
assert!(!f.allows(root, Path::new("/proj/tests_old/x.rs")));
let f = PathFilter::new("src/widgets", "");
assert!(f.allows(root, Path::new("/proj/src/widgets/search.rs")));
assert!(!f.allows(root, Path::new("/proj/src/app/mod.rs")));
let f = PathFilter::new("./src", "");
assert!(f.allows(root, Path::new("/proj/src/app/mod.rs")));
assert!(!f.allows(root, Path::new("/proj/vendor/src/x.rs")));
let f = PathFilter::new("*.rs, src", "");
assert!(f.allows(root, Path::new("/proj/a/main.rs")));
assert!(!f.allows(root, Path::new("/proj/generated.rs/notes.txt")));
assert!(!f.allows(root, Path::new("/home/me/src/elsewhere.txt")));
let f = PathFilter::new("", "src/widgets, dist");
assert!(!f.allows(root, Path::new("/proj/src/widgets/search.rs")));
assert!(!f.allows(root, Path::new("/proj/dist/bundle.js")));
assert!(f.allows(root, Path::new("/proj/src/app/mod.rs")));
}
#[test]
fn path_filter_invalid_exclude_hides_nothing() {
let f = PathFilter::new("", "*.{md");
let root = Path::new("/proj");
assert!(f.allows(root, Path::new("/proj/README.md")));
assert!(f.allows(root, Path::new("/proj/src/a.ts")));
}
#[test]
fn an_invalid_include_glob_is_named_above_the_box() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.details_open = true;
panel.include = String::from("*.md, *.{ts");
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 16,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let text: String = (0..area.height)
.map(|y| {
(0..area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n");
assert!(text.contains("invalid glob: *.{ts"), "{text}");
assert!(text.contains("files to exclude\u{20}"), "{text}");
}
#[test]
fn a_leading_slash_anchors_an_exclude_glob_to_the_root() {
let root = Path::new("/r");
let f = PathFilter::excluding(&[String::from("/build")]);
assert!(f.excludes(root, Path::new("/r/build/out.js")));
assert!(f.excludes(root, Path::new("/r/build")));
assert!(!f.excludes(root, Path::new("/r/scripts/build/release.py")));
assert!(!f.excludes(root, Path::new("/r/rebuild/x")));
let f = PathFilter::excluding(&[String::from("/*.log")]);
assert!(f.excludes(root, Path::new("/r/app.log")));
assert!(!f.excludes(root, Path::new("/r/logs/app.log")));
}
#[test]
fn a_bare_or_starred_exclude_glob_still_matches_at_any_depth() {
let root = Path::new("/r");
for glob in ["build", "**/build"] {
let f = PathFilter::excluding(&[String::from(glob)]);
assert!(f.excludes(root, Path::new("/r/build/out.js")), "{glob}");
assert!(
f.excludes(root, Path::new("/r/scripts/build/release.py")),
"{glob}"
);
}
}
#[test]
fn project_excludes_are_listed_under_the_exclude_box() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.details_open = true;
let area = Rect {
x: 0,
y: 0,
width: 70,
height: 16,
};
let render = |panel: &mut SearchPanel| {
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(panel, area, &mut buf);
(0..area.height)
.map(|y| {
(0..area.width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
};
assert!(!render(&mut panel).contains("project excludes"));
assert_eq!(panel.project_exclude_rect, Rect::default());
panel.project_exclude = vec![
String::from("**/generated"),
String::from("**/tests/fixtures"),
];
let text = render(&mut panel);
assert!(
text.contains("[x] project excludes: **/generated, **/tests/fixtures"),
"{text}"
);
let r = panel.project_exclude_rect;
assert!(panel.project_exclude_toggle_at(r.x + 1, r.y));
assert!(!panel.project_exclude_toggle_at(r.x + 1, r.y + 1));
assert_eq!(panel.exclude, "", "the box keeps only what was typed");
assert_eq!(panel.effective_exclude(), "**/generated, **/tests/fixtures");
panel.use_exclude_settings = false;
assert!(render(&mut panel).contains("[ ] project excludes"));
assert_eq!(panel.effective_exclude(), "");
}
#[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 a_dollar_name_that_is_no_group_stays_literal() {
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
let replace =
|text: &str, find: &str, with: &str| replace_in_text(text, find, with, opts).unwrap().0;
assert_eq!(
replace("cp a /opt/app\n", r"/opt/(\S+)", "$PREFIX/$1"),
"cp a $PREFIX/app\n"
);
assert_eq!(replace("x", "x", "${HOME}/x"), "${HOME}/x");
assert_eq!(replace("x", "x", "cost $"), "cost $");
assert_eq!(replace("x", "x", "$_ and $@"), "$_ and $@");
assert_eq!(replace("abc", "b", "[$&]"), "a[b]c");
assert_eq!(
expand_replacement("/opt/app", r"/opt/(\S+)", "$PREFIX/$1", opts),
"$PREFIX/app"
);
}
#[test]
fn real_capture_references_still_expand() {
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
let replace =
|text: &str, find: &str, with: &str| replace_in_text(text, find, with, opts).unwrap().0;
assert_eq!(replace("ab", "(a)(b)", "$2$1 $0 ${1} $$"), "ba ab a $");
assert_eq!(replace("foo", "(foo)", "$1_old"), "foo_old");
assert_eq!(replace("cat", r"(?P<HOME>\w+)", "${HOME}/$HOME"), "cat/cat");
}
#[test]
fn a_numbered_reference_with_no_group_stays_literal() {
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
let replace =
|text: &str, find: &str, with: &str| replace_in_text(text, find, with, opts).unwrap().0;
assert_eq!(replace("apple", "(apple)", "$1 costs $5"), "apple costs $5");
assert_eq!(replace("x", "x", "echo $2 $9"), "echo $2 $9");
assert_eq!(replace("x", "x", "${3}"), "${3}");
assert_eq!(
replace("apple\nitem 7\n", "(apple)", "v$10 costs $5"),
"vapple0 costs $5\nitem 7\n"
);
assert_eq!(
expand_replacement("apple", "(apple)", "v$10 costs $5", opts),
"vapple0 costs $5"
);
}
#[test]
fn numbered_references_to_existing_groups_still_expand() {
let opts = SearchOpts {
use_regex: true,
..Default::default()
};
let replace =
|text: &str, find: &str, with: &str| replace_in_text(text, find, with, opts).unwrap().0;
let ten = "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)";
assert_eq!(replace("abcdefghij", ten, "$10$1"), "ja");
assert_eq!(replace("abcdefghij", ten, "${10}"), "j");
assert_eq!(replace("ab", "(a)(b)", "$1 ${1} $2 $0"), "a a b ab");
assert_eq!(replace("ab", "(a)(b)", "$2_x"), "b_x");
}
#[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");
}
fn srch_workspace() -> TempDir {
let tmp = TempDir::new().unwrap();
write(
&tmp.path().join("app.py"),
"def run(value):\n returned = value\n return value\n",
);
write(&tmp.path().join("calc.py"), "total = price * qty\n");
tmp
}
#[test]
fn a_trailing_space_in_the_query_is_searched_for() {
let tmp = srch_workspace();
let hits = search_workspace(tmp.path(), "return ", SearchOpts::default());
let lines: Vec<usize> = hits.iter().map(|h| h.line_no).collect();
assert_eq!(lines, vec![3]);
}
#[test]
fn replace_all_keeps_the_spaces_typed_in_the_query() {
let tmp = srch_workspace();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "return ".into();
panel.replace = "yield ".into();
panel.run_query();
assert_eq!(panel.count_replacements(&HashSet::new()), (1, 1));
assert_eq!(panel.replace_all_on_disk(), 1);
assert_eq!(
fs::read_to_string(tmp.path().join("app.py")).unwrap(),
"def run(value):\n returned = value\n yield value\n"
);
assert_eq!(
replace_in_text(
"returned\nreturn x\n",
"return ",
"yield ",
SearchOpts::default()
),
Some((String::from("returned\nyield x\n"), 1))
);
}
#[test]
fn a_query_of_spaces_finds_runs_of_spaces() {
let tmp = srch_workspace();
let hits = search_workspace(tmp.path(), " ", SearchOpts::default());
let mut files: Vec<String> = hits
.iter()
.map(|h| h.path.file_name().unwrap().to_string_lossy().into_owned())
.collect();
files.sort();
files.dedup();
assert_eq!(files, vec!["app.py", "calc.py"]);
}
#[test]
fn an_empty_query_finds_nothing_and_a_pasted_newline_is_dropped() {
let tmp = srch_workspace();
assert!(search_workspace(tmp.path(), "", SearchOpts::default()).is_empty());
let hits = search_workspace(tmp.path(), "returned\n", SearchOpts::default());
assert_eq!(hits.len(), 1);
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.replace = "x".into();
assert_eq!(panel.replace_all_on_disk(), 0);
}
#[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 the_caret_follows_its_char_and_a_long_query_scrolls() {
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: 30,
height: 20,
};
let draw = |panel: &mut SearchPanel| {
let mut buf = Buffer::empty(area);
Widget::render(panel, area, &mut buf);
buf
};
for c in "abcdef".chars() {
panel.type_char(c);
}
draw(&mut panel);
let (end_x, _) = panel.cursor_screen_pos().unwrap();
panel.move_caret(|_, _| 3);
draw(&mut panel);
let (mid_x, y) = panel.cursor_screen_pos().unwrap();
assert_eq!(end_x - mid_x, 3, "three chars left of the end");
assert_eq!(y, panel.query_input_rect.y);
panel.seed("0123456789".repeat(6), String::new(), String::new());
let buf = draw(&mut panel);
let r = panel.query_input_rect;
let (cx, cy) = panel.cursor_screen_pos().unwrap();
assert!(cx >= r.x && cx < r.right(), "caret {cx} inside {r:?}");
let row: String = (r.x..r.right())
.map(|x| buf[(x, cy)].symbol().to_string())
.collect();
assert!(row.contains("789"), "the tail is the part in view: {row:?}");
panel.move_caret(|_, _| 0);
let buf = draw(&mut panel);
let row: String = (r.x..r.right())
.map(|x| buf[(x, cy)].symbol().to_string())
.collect();
assert!(row.contains("0123"), "Home brings the head back: {row:?}");
}
#[test]
fn a_click_in_the_query_places_the_caret_under_it() {
use ratatui::buffer::Buffer;
let tmp = TempDir::new().unwrap();
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.focused = true;
for c in "abcdef".chars() {
panel.type_char(c);
}
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 20,
};
let mut buf = Buffer::empty(area);
Widget::render(&mut panel, area, &mut buf);
let (end_x, _) = panel.cursor_screen_pos().unwrap();
panel.click_caret(end_x - 4);
assert_eq!(panel.caret(), 2);
panel.click_caret(end_x + 5);
assert_eq!(panel.caret(), 6, "past the text is the end");
}
#[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 preserve_case_renames_user_to_account_in_each_case() {
let file = "class UserService:\n \"\"\"Load a user by id.\"\"\"\n\n USER_TABLE = \"users\"\n\n def get_user(self, user_id):\n return self.db.find(USER_TABLE, user_id)\n";
let opts = SearchOpts {
preserve_case: true,
..SearchOpts::default()
};
let (out, n) = replace_in_text(file, "user", "account", opts).unwrap();
assert_eq!(n, 8);
assert_eq!(
out,
"class AccountService:\n \"\"\"Load a account by id.\"\"\"\n\n ACCOUNT_TABLE = \"accounts\"\n\n def get_account(self, account_id):\n return self.db.find(ACCOUNT_TABLE, account_id)\n"
);
}
#[test]
fn without_preserve_case_the_replacement_goes_in_as_typed() {
let (out, _) = replace_in_text(
"UserService USER_TABLE",
"user",
"account",
SearchOpts::default(),
)
.unwrap();
assert_eq!(out, "accountService account_TABLE");
}
#[test]
fn preserve_case_follows_each_dash_or_underscore_part() {
assert_eq!(preserve_case("User", "account"), "Account");
assert_eq!(preserve_case("USER", "account"), "ACCOUNT");
assert_eq!(preserve_case("user", "Account"), "account");
assert_eq!(preserve_case("User-name", "account-id"), "Account-id");
assert_eq!(preserve_case("USER_name", "account_id"), "ACCOUNT_id");
assert_eq!(preserve_case("Élan", "été"), "Été");
}
#[test]
fn preserve_case_leaves_what_it_cannot_read() {
assert_eq!(preserve_case("User-Name", "account"), "Account");
assert_eq!(preserve_case("a-b_C", "x-y_z"), "x-y_z");
assert_eq!(preserve_case("", "Account"), "Account");
assert_eq!(preserve_case("1-2", "a-B"), "A-B");
assert_eq!(preserve_case("_x", "Ab"), "ab");
}
#[test]
fn preserve_case_shapes_regex_replacements_and_the_preview() {
let opts = SearchOpts {
use_regex: true,
preserve_case: true,
..SearchOpts::default()
};
let (out, n) =
replace_in_text("USER_TABLE user_id", r"user_(\w+)", "account_$1", opts).unwrap();
assert_eq!((out.as_str(), n), ("ACCOUNT_TABLE account_id", 2));
let literal = SearchOpts {
preserve_case: true,
..SearchOpts::default()
};
assert_eq!(
expand_replacement("User", "user", "account", literal),
"Account"
);
assert_eq!(
expand_replacement("User", "user", "account", SearchOpts::default()),
"account"
);
}
#[test]
fn the_replace_row_has_a_preserve_case_toggle() {
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);
assert_eq!(panel.toggle_preserve_x, 0, "no replace row, no chip");
panel.open_replace();
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut panel, area, &mut buf);
let (x, y) = (panel.toggle_preserve_x, panel.toggle_preserve_y);
assert_ne!(x, 0);
assert_eq!(buf[(x, y)].symbol(), "A");
assert_eq!(buf[(x + 1, y)].symbol(), "B");
assert_eq!(panel.toggle_at(x + 1, y), Some(SearchToggle::PreserveCase));
assert_eq!(panel.tooltip_at(x, y), Some("Preserve Case (Alt+P)"));
assert!(panel.toggle_opt(SearchToggle::PreserveCase));
assert!(panel.opts.preserve_case);
assert_eq!(panel.toggle_at(x - 1, y), None);
}
#[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,
..SearchOpts::default()
});
}
}
}
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));
}
#[test]
fn the_header_counts_occurrences_as_replace_all_does() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "foo foo\nfoo\n");
write(&tmp.path().join("b.txt"), "foo\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "foo".into();
panel.run_query();
assert_eq!(panel.hits.len(), 3, "one hit per matching line");
assert_eq!(panel.result_counts(), (4, 2));
assert_eq!(panel.count_replacements(&HashSet::new()), (4, 2));
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 text = buffer_to_string(&buf);
assert!(text.contains("4 results in 2 files"), "{text}");
let mut out = Vec::new();
let whole_word = SearchOpts {
whole_word: true,
..SearchOpts::default()
};
collect_matches_in_text(
Path::new("c.txt"),
"foo foobar foo",
"foo",
whole_word,
&mut out,
);
assert_eq!(out.len(), 1);
assert_eq!(out[0].matches, 2);
}
#[test]
fn the_rendered_header_counts_two_matches_on_a_line_as_two() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "foo foo\nfoo\n");
write(&tmp.path().join("b.txt"), "foo\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "foo".into();
panel.run_query();
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 text = buffer_to_string(&buf);
assert!(text.contains("4 results in 2 files"), "{text}");
}
#[test]
fn a_file_whose_hits_are_apart_still_counts_once() {
let mut panel = SearchPanel::new(PathBuf::from("/w"));
let hit = |path: &str, line_no: usize, matches: usize| SearchHit {
path: PathBuf::from(path),
line_no,
line_text: String::from("foo"),
matches,
};
panel.hits = vec![
hit("/w/a.txt", 1, 2),
hit("/w/a.txt", 2, 1),
hit("/w/b.txt", 1, 1),
hit("/w/a.txt", 9, 1),
hit("/w/c.txt", 3, 3),
];
assert_eq!(panel.result_counts(), (8, 3));
panel.hits.clear();
assert_eq!(panel.result_counts(), (0, 0), "no hits, no files");
}
#[test]
fn the_header_is_singular_for_one_result_and_counts_files_once() {
let tmp = TempDir::new().unwrap();
write(&tmp.path().join("a.txt"), "foo\nbar\n");
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "foo".into();
panel.run_query();
assert_eq!(panel.result_counts(), (1, 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 text = buffer_to_string(&buf);
assert!(text.contains("1 result in 1 file"), "{text}");
assert!(!text.contains("1 results"), "{text}");
write(&tmp.path().join("a.txt"), "foo foo foo\n");
panel.run_query();
assert_eq!(panel.result_counts(), (3, 1), "three results, one file");
}
fn result_row(buf: &Buffer, path_line: &str) -> String {
buffer_to_string(buf)
.lines()
.find(|l| l.contains(path_line))
.unwrap_or_else(|| panic!("no row for {path_line}"))
.trim_matches(|c| c == '│' || c == ' ')
.to_string()
}
#[test]
fn the_column_the_scrollbar_takes_has_no_path_hint() {
let tmp = TempDir::new().unwrap();
let mut panel = make_panel_with_hits(&tmp, 1);
render_panel(&mut panel, 40);
let fits = panel.results_viewport_height();
panel.hits.clear();
panel.add_hits(
(0..fits)
.map(|i| hit(&tmp.path().join("a.txt"), i + 1))
.collect(),
);
render_panel(&mut panel, 40);
let inner = panel.last_inner;
let (row, right) = (
inner.y + panel.results_start_offset,
inner.x + inner.width - 1,
);
assert_eq!(
panel.last_scrollbar,
Rect::default(),
"precondition: no overflow yet"
);
assert!(panel.result_path_at(right, row).is_some());
panel.add_hits(vec![hit(&tmp.path().join("b.txt"), 1)]);
assert_eq!(panel.result_path_at(right, row), None);
assert!(panel.result_path_at(right - 1, row).is_some());
}
fn render_panel(panel: &mut SearchPanel, width: u16) -> Buffer {
let area = Rect {
x: 0,
y: 0,
width,
height: 14,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(panel, area, &mut buf);
buf
}
#[test]
fn a_match_past_the_panel_width_drops_leading_context_to_show() {
let tmp = TempDir::new().unwrap();
write(
&tmp.path().join("a.txt"),
"date,category,amount,description,payee,note\n",
);
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "note".into();
panel.run_query();
let row = result_row(&render_panel(&mut panel, 40), "a.txt:1:");
assert!(row.contains("note"), "the match is visible: {row:?}");
assert!(row.starts_with("a.txt:1: "), "{row:?}");
assert!(!row.contains('…'), "no ellipsis: {row:?}");
panel.replace_open = true;
panel.replace = "memo".into();
let row = result_row(&render_panel(&mut panel, 40), "a.txt:1:");
assert!(
row.contains("notememo"),
"the match and its replacement both show: {row:?}"
);
}
#[test]
fn a_match_that_already_shows_renders_as_before() {
let tmp = TempDir::new().unwrap();
let near = "note,date,category,amount,description,payee";
let edge = "date,category,amount,xxxnote,payee,description";
assert_eq!(
edge.find("note").unwrap() + 4,
28,
"fixture: ends on the edge"
);
write(&tmp.path().join("a.txt"), &format!("{near}\n"));
write(&tmp.path().join("b.txt"), &format!("{edge}\n"));
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "note".into();
panel.run_query();
let buf = render_panel(&mut panel, 40);
assert_eq!(
result_row(&buf, "a.txt:1:"),
format!("a.txt:1: {}", &near[..28])
);
assert_eq!(
result_row(&buf, "b.txt:1:"),
format!("a.txt:1: {}", &edge[..28]).replacen("a.txt", "b.txt", 1)
);
}
#[test]
fn leading_context_of_wide_characters_is_dropped_whole() {
let tmp = TempDir::new().unwrap();
write(
&tmp.path().join("a.txt"),
"日本語のテキストが長く続いた後にnoteがある\n",
);
let mut panel = SearchPanel::new(tmp.path().to_path_buf());
panel.query = "note".into();
panel.run_query();
let row = result_row(&render_panel(&mut panel, 40), "a.txt:1:");
assert!(row.contains("note"), "{row:?}");
assert!(row.starts_with("a.txt:1: "), "{row:?}");
assert!(!row.contains('…'), "{row:?}");
}
}