1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/// Search implementations: file/content search and in-document search.
///
/// All methods are part of `impl App`.
// Submodule of app — intentionally imports all parent symbols.
#[allow(clippy::wildcard_imports)]
use super::*;
use crate::action::Action;
use crate::fs::discovery::FileEntry;
use crate::ui::search_modal::{RESULT_CAP, SearchMode, SearchResult, build_preview, smartcase_is_sensitive};
use std::sync::{Arc, atomic::Ordering};
impl App {
// ── Content / filename search ─────────────────────────────────────────────
/// Start or refresh the current search.
///
/// Filename searches run synchronously on the main thread. Content
/// searches are dispatched to a background thread to avoid blocking the
/// event loop. A monotonically increasing generation counter ensures that
/// results from a superseded query are silently discarded.
#[allow(clippy::too_many_lines)]
pub(super) fn perform_search(&mut self) {
// Clear stale results immediately so the UI never shows results from a
// superseded query while the new background task is running.
self.search.results.clear();
self.search.selected_index = 0;
self.search.truncated_at_cap = false;
if self.search.query.is_empty() {
return;
}
let query = self.search.query.clone();
match self.search.mode {
SearchMode::FileName => {
// Filename search is O(n) over in-memory data — fast enough to
// run synchronously on the main thread with no perceptible delay.
// Uses smartcase: uppercase in query → case-sensitive match.
let sensitive = smartcase_is_sensitive(&query);
let query_cmp = if sensitive {
query.clone()
} else {
query.to_lowercase()
};
// Walk all entries (not just flat_items) so collapsed directories
// are still searched.
let all_paths = FileEntry::flat_paths(&self.tree.entries);
for path in all_paths {
let name = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let name_cmp = if sensitive {
name.clone()
} else {
name.to_lowercase()
};
if name_cmp.contains(query_cmp.as_str()) {
self.search.results.push(SearchResult {
path,
name,
match_count: 0,
preview: String::new(),
first_match_line: None,
});
if self.search.results.len() >= RESULT_CAP {
self.search.truncated_at_cap = true;
break;
}
}
}
}
SearchMode::Content => {
// Content search reads every file on disk — offload to a blocking
// thread so the event loop remains responsive during the scan.
let Some(tx) = self.action_tx.clone() else {
return;
};
// Advance the generation counter. The spawned task captures this
// generation; if it has been superseded by the time it finishes
// it will discard its results without sending to the channel.
let generation = self.search_generation.fetch_add(1, Ordering::Relaxed) + 1;
let gen_arc = Arc::clone(&self.search_generation);
let paths = FileEntry::flat_paths(&self.tree.entries);
let preview_mode = self.search_preview;
tokio::task::spawn_blocking(move || {
// Build the match predicate once — avoids re-lowercasing the
// query on every line comparison.
let sensitive = smartcase_is_sensitive(&query);
// Keep a separate clone for preview building (the predicate
// closure moves `query` or `query_lower` into itself).
let query_for_preview = query.clone();
let query_lower = query.to_lowercase();
let matches_line: Box<dyn Fn(&str) -> bool + Send> = if sensitive {
Box::new(move |line: &str| line.contains(query.as_str()))
} else {
Box::new(move |line: &str| {
line.to_lowercase().contains(query_lower.as_str())
})
};
let mut results: Vec<SearchResult> = Vec::new();
let mut truncated = false;
'files: for path in paths {
// Bail early if a newer search has already started.
if gen_arc.load(Ordering::Relaxed) != generation {
return;
}
let Ok(content) = std::fs::read_to_string(&path) else {
continue;
};
let mut match_count = 0usize;
let mut first_match: Option<(usize, String)> = None;
for (i, line) in content.lines().enumerate() {
if matches_line(line) {
match_count += 1;
if first_match.is_none() {
// Store i as 0-based; confirm_search passes it
// directly as a source-line coordinate.
first_match = Some((
i,
build_preview(line, &query_for_preview, preview_mode),
));
}
}
}
if match_count > 0 {
let name = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let (first_line, preview) = first_match.unwrap_or((0, String::new()));
results.push(SearchResult {
path,
name,
match_count,
preview,
first_match_line: Some(first_line),
});
if results.len() >= RESULT_CAP {
truncated = true;
break 'files;
}
}
}
// Final check before sending — another keystroke may have
// arrived while we were iterating the last file.
if gen_arc.load(Ordering::Relaxed) == generation {
let _ = tx.send(Action::SearchResults {
generation,
results,
truncated,
});
}
});
}
}
}
/// Open the file from the currently highlighted search result, jumping to
/// the first match line in content-search mode.
pub(super) fn confirm_search(&mut self) {
let Some(result) = self.search.results.get(self.search.selected_index).cloned() else {
return;
};
// Close the search overlay immediately so the UI is not frozen waiting
// for the read. The file content arrives via Action::FileLoaded.
self.search.active = false;
self.focus = Focus::Viewer;
// Expand ancestor directories and select the file row in the tree so the
// panel is aligned with the viewer even when the file was in a collapsed
// subtree.
self.tree.reveal_path(&result.path);
// `first_match_line` is 0-based; pass it directly as a source-line
// coordinate without adjustment.
let jump_to_source = result.first_match_line.map(crate::cast::u32_sat);
self.open_or_focus(result.path, true, jump_to_source);
}
// ── In-document search ────────────────────────────────────────────────────
/// Rebuild match-line list for the current in-document search query and
/// jump the cursor to the first match.
pub(super) fn perform_doc_search(&mut self) {
let query = match self.doc_search() {
Some(ds) => ds.query.clone(),
None => return,
};
if let Some(ds) = self.doc_search_mut() {
ds.match_lines.clear();
ds.current_match = 0;
}
if query.is_empty() {
return;
}
let query_lower = query.to_lowercase();
let Some(tab) = self.tabs.active_tab_mut() else {
return;
};
let match_lines = collect_match_lines(
&tab.view.rendered,
&tab.view.table_layouts,
&self.mermaid_cache,
&query_lower,
);
tab.doc_search.match_lines = match_lines;
// Copy the first match line before dropping the `tab` borrow so we can
// access `self.tabs.view_height` without a conflicting mutable borrow.
let first_match = tab.doc_search.match_lines.first().copied();
if let Some(line) = first_match {
// Mirror the j/k idiom: set cursor_line then let scroll_to_cursor
// decide whether the viewport needs to move. Setting scroll_offset
// directly would strand cursor_line at its old position and break
// subsequent j/k movement.
let vh = self.tabs.view_height;
if let Some(tab) = self.tabs.active_tab_mut() {
tab.view.cursor_line = line;
tab.view.scroll_to_cursor(vh);
}
}
}
/// Advance to the next in-document search match, wrapping around.
///
/// Sets `cursor_line` to the match line and calls `scroll_to_cursor` so
/// subsequent `j`/`k` presses move from the correct row.
pub(super) fn doc_search_next(&mut self) {
let vh = self.tabs.view_height;
let Some(tab) = self.tabs.active_tab_mut() else {
return;
};
let ds = &mut tab.doc_search;
if ds.match_lines.is_empty() {
return;
}
ds.current_match = (ds.current_match + 1) % ds.match_lines.len();
let line = ds.match_lines[ds.current_match];
tab.view.cursor_line = line;
tab.view.scroll_to_cursor(vh);
}
/// Retreat to the previous in-document search match, wrapping around.
///
/// Sets `cursor_line` to the match line and calls `scroll_to_cursor` so
/// subsequent `j`/`k` presses move from the correct row.
pub(super) fn doc_search_prev(&mut self) {
let vh = self.tabs.view_height;
let Some(tab) = self.tabs.active_tab_mut() else {
return;
};
let ds = &mut tab.doc_search;
if ds.match_lines.is_empty() {
return;
}
ds.current_match = if ds.current_match == 0 {
ds.match_lines.len() - 1
} else {
ds.current_match - 1
};
let line = ds.match_lines[ds.current_match];
tab.view.cursor_line = line;
tab.view.scroll_to_cursor(vh);
}
}