1use crate::input::InputModeKind;
2use aho_corasick::AhoCorasick;
3use gpui::{Context, Window};
4use ropey::Rope;
5use std::{ops::Range, rc::Rc};
6
7use super::{
8 InputBaseState, Replace, RopeExt as _, Search, movement::MoveDirection, state::ScrollPadding,
9};
10
11#[derive(Debug, Clone)]
13pub struct SearchMatcher {
14 text: Rope,
15 pub query: Option<AhoCorasick>,
16 matched_ranges: Rc<Vec<Range<usize>>>,
17 current_match_ix: usize,
18 replacing: bool,
19}
20
21#[derive(Debug, Clone)]
26#[non_exhaustive]
27pub struct SearchSession {
28 pub open: bool,
30 pub replace_mode: bool,
31 pub case_insensitive: bool,
32 pub query: String,
33 pub replacement: String,
34 pub anchor_offset: Option<usize>,
35 pub matcher: SearchMatcher,
36 active: bool,
39}
40
41impl Default for SearchSession {
42 fn default() -> Self {
43 Self {
44 open: false,
45 active: false,
46 replace_mode: false,
47 case_insensitive: true,
48 query: String::new(),
49 replacement: String::new(),
50 anchor_offset: None,
51 matcher: SearchMatcher::new(),
52 }
53 }
54}
55
56impl SearchSession {
57 pub(crate) fn open(&mut self, replace_mode: bool, replaceable: bool) {
58 self.open = true;
59 self.active = true;
60 self.replace_mode = replace_mode && replaceable;
61 }
62
63 pub(crate) fn activate(&mut self) {
67 self.active = true;
68 }
69
70 pub(crate) fn close(&mut self) {
71 self.open = false;
72 self.active = false;
73 }
74
75 pub fn is_active(&self) -> bool {
79 self.active
80 }
81
82 pub(crate) fn update_query(&mut self, query: impl Into<String>, case_insensitive: bool) {
83 let query = query.into();
84 if self.query == query && self.case_insensitive == case_insensitive {
85 return;
86 }
87
88 self.query = query;
89 self.case_insensitive = case_insensitive;
90 self.matcher.update_query(&self.query, case_insensitive);
91 }
92}
93
94impl<M: InputModeKind> InputBaseState<M> {
95 pub fn open_search(&mut self, replace_mode: bool, cx: &mut Context<Self>) {
105 if !self.searchable {
106 return;
107 }
108 self.search_activation_revision = self.search_activation_revision.wrapping_add(1);
109 self.search_session
110 .open(replace_mode, self.is_replaceable());
111 let selected = self.selected_text().to_string();
112 let query = if selected.is_empty() {
113 self.search_session.query.clone()
114 } else {
115 selected
116 };
117 let query_changed = query != self.search_session.query;
118 self.search_session.anchor_offset = if query_changed {
121 self.last_layout
122 .as_ref()
123 .map(|layout| layout.visible_range_offset.start)
124 } else {
125 None
126 };
127 let case_insensitive = self.search_session.case_insensitive;
128 self.search_session.update_query(query, case_insensitive);
129 self.search_session.matcher.update(&self.text);
130 if query_changed && let Some(anchor) = self.search_session.anchor_offset {
131 self.search_session.matcher.update_cursor_by_offset(anchor);
132 }
133 cx.notify();
134 }
135
136 pub fn search_session(&self) -> &SearchSession {
137 &self.search_session
138 }
139
140 pub fn search_activation_revision(&self) -> u64 {
147 self.search_activation_revision
148 }
149
150 #[doc(hidden)]
151 pub fn set_search_replace_mode(&mut self, replace_mode: bool, cx: &mut Context<Self>) {
152 self.search_session.replace_mode = replace_mode && self.is_replaceable();
153 cx.notify();
154 }
155
156 pub fn is_replaceable(&self) -> bool {
161 self.replaceable && self.is_editable()
162 }
163
164 pub fn set_search_query(
173 &mut self,
174 query: impl Into<String>,
175 case_insensitive: bool,
176 cx: &mut Context<Self>,
177 ) {
178 self.search_session.activate();
179 self.search_session.update_query(query, case_insensitive);
180 self.search_session.matcher.update(&self.text);
181 cx.notify();
182 }
183
184 pub fn close_search(&mut self, cx: &mut Context<Self>) {
187 self.search_session.close();
188 cx.notify();
189 }
190
191 pub fn next_search_match(&mut self, cx: &mut Context<Self>) -> Option<Range<usize>> {
192 let range = self.search_session.matcher.next()?;
193 self.scroll_to_with_padding(range.end, None, ScrollPadding::SurroundingLines, cx);
196 Some(range)
197 }
198
199 pub fn previous_search_match(&mut self, cx: &mut Context<Self>) -> Option<Range<usize>> {
200 let range = self.search_session.matcher.next_back()?;
201 self.scroll_to_with_padding(range.start, None, ScrollPadding::SurroundingLines, cx);
204 Some(range)
205 }
206
207 pub fn replace_current_search_match(
210 &mut self,
211 replacement: &str,
212 window: &mut Window,
213 cx: &mut Context<Self>,
214 ) -> bool {
215 if !self.is_replaceable() {
216 return false;
217 }
218 let matcher = &mut self.search_session.matcher;
219 let Some(range) = matcher
220 .matched_ranges()
221 .get(matcher.current_match_index())
222 .cloned()
223 else {
224 return false;
225 };
226 let next = matcher.peek().unwrap_or_else(|| range.clone());
227 let direction = matcher
228 .has_next_without_wrap()
229 .then_some(MoveDirection::Down);
230 if direction.is_none() {
231 matcher.set_current_match_index(0);
232 }
233 matcher.begin_replacement();
234 let range_utf16 = self.range_to_utf16(&range);
235 self.scroll_to(next.end, direction, cx);
236 self.replace_text_in_range_silent(Some(range_utf16), replacement, window, cx);
237 true
238 }
239
240 pub fn replace_all_search_matches(
242 &mut self,
243 replacement: &str,
244 window: &mut Window,
245 cx: &mut Context<Self>,
246 ) -> usize {
247 if !self.is_replaceable() {
248 return 0;
249 }
250 let ranges = self.search_session.matcher.matched_ranges();
251 if ranges.is_empty() {
252 return 0;
253 }
254 let mut text = self.text.clone();
255 for range in ranges.iter().rev() {
256 text.replace(range.clone(), replacement);
257 }
258 self.search_session.matcher.begin_replacement();
259 let count = ranges.len();
260 self.replace_text_in_range_silent(Some(0..self.text.len()), &text.to_string(), window, cx);
261 self.scroll_to(0, Some(MoveDirection::Down), cx);
262 count
263 }
264
265 pub(super) fn update_search(&mut self, _cx: &mut gpui::App) {
266 self.search_session.matcher.update(&self.text);
267 }
268
269 pub(super) fn on_action_search(&mut self, _: &Search, _: &mut Window, cx: &mut Context<Self>) {
272 if !self.searchable {
273 cx.propagate();
274 return;
275 }
276 self.open_search(false, cx);
277 }
278
279 pub(super) fn on_action_replace(
280 &mut self,
281 _: &Replace,
282 _: &mut Window,
283 cx: &mut Context<Self>,
284 ) {
285 if !self.searchable {
286 cx.propagate();
287 return;
288 }
289 self.open_search(true, cx);
290 }
291}
292
293impl Default for SearchMatcher {
294 fn default() -> Self {
295 Self::new()
296 }
297}
298
299impl SearchMatcher {
300 pub fn new() -> Self {
301 Self {
302 text: "".into(),
303 query: None,
304 matched_ranges: Rc::new(Vec::new()),
305 current_match_ix: 0,
306 replacing: false,
307 }
308 }
309
310 pub fn update(&mut self, text: &Rope) {
312 if self.text.eq(text) {
313 self.replacing = false;
314 return;
315 }
316 self.text = text.clone();
317 self.update_matches();
318 }
319
320 pub fn update_query(&mut self, query: &str, case_insensitive: bool) {
321 self.query = (!query.is_empty()).then(|| {
322 AhoCorasick::builder()
323 .ascii_case_insensitive(case_insensitive)
324 .build([query])
325 .expect("failed to build input search query")
326 });
327 self.update_matches();
328 }
329
330 pub fn matched_ranges(&self) -> Rc<Vec<Range<usize>>> {
331 self.matched_ranges.clone()
332 }
333
334 pub fn current_match_index(&self) -> usize {
335 self.current_match_ix
336 }
337
338 pub fn current(&self) -> Option<usize> {
341 (!self.is_empty()).then_some(self.current_match_ix)
342 }
343
344 pub fn len(&self) -> usize {
345 self.matched_ranges.len()
346 }
347
348 pub fn is_empty(&self) -> bool {
349 self.matched_ranges.is_empty()
350 }
351
352 pub fn label(&self) -> String {
354 match self.current() {
355 Some(ix) => format!("{}/{}", ix + 1, self.len()),
356 None => "0/0".into(),
357 }
358 }
359
360 fn peek(&self) -> Option<Range<usize>> {
361 self.next_index()
362 .and_then(|ix| self.matched_ranges.get(ix).cloned())
363 }
364
365 fn has_next_without_wrap(&self) -> bool {
366 self.current_match_ix < self.matched_ranges.len().saturating_sub(1)
367 }
368
369 pub fn update_cursor_by_offset(&mut self, offset: usize) {
370 for (ix, range) in self.matched_ranges.iter().enumerate() {
371 self.current_match_ix = ix;
372 if range.contains(&offset) || range.end >= offset {
373 return;
374 }
375 }
376 }
377
378 fn begin_replacement(&mut self) {
380 self.replacing = true;
381 }
382
383 fn set_current_match_index(&mut self, index: usize) {
384 self.current_match_ix = index.min(self.matched_ranges.len().saturating_sub(1));
385 }
386
387 fn next_index(&self) -> Option<usize> {
388 if self.is_empty() {
389 None
390 } else if self.has_next_without_wrap() {
391 Some(self.current_match_ix + 1)
392 } else {
393 Some(0)
394 }
395 }
396
397 fn update_matches(&mut self) {
398 let mut ranges = Vec::new();
399 if let Some(query) = &self.query {
400 let text = self.text.to_string();
401 ranges.extend(
402 query
403 .stream_find_iter(text.as_bytes())
404 .map(|result| result.expect("input search match").range()),
405 );
406 }
407 self.matched_ranges = Rc::new(ranges);
408 if !self.replacing || self.is_empty() {
409 self.current_match_ix = 0;
410 } else {
411 self.current_match_ix = self.current_match_ix.min(self.len() - 1);
412 }
413 self.replacing = false;
414 }
415}
416
417impl Iterator for SearchMatcher {
418 type Item = Range<usize>;
419
420 fn next(&mut self) -> Option<Self::Item> {
421 let ix = self.next_index()?;
422 self.current_match_ix = ix;
423 self.matched_ranges.get(ix).cloned()
424 }
425}
426
427impl DoubleEndedIterator for SearchMatcher {
428 fn next_back(&mut self) -> Option<Self::Item> {
429 if self.is_empty() {
430 return None;
431 }
432 if self.current_match_ix == 0 {
433 self.current_match_ix = self.len();
434 }
435 self.current_match_ix -= 1;
436 self.matched_ranges.get(self.current_match_ix).cloned()
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443
444 #[test]
445 fn finds_navigates_and_preserves_replacement_position() {
446 let mut matcher = SearchMatcher::new();
447 matcher.update(&Rope::from("foo FOO foo"));
448 matcher.update_query("foo", true);
449 assert_eq!(&*matcher.matched_ranges(), &[0..3, 4..7, 8..11]);
450 assert_eq!(matcher.next(), Some(4..7));
451 assert_eq!(matcher.next_back(), Some(0..3));
452
453 matcher.set_current_match_index(2);
454 matcher.begin_replacement();
455 matcher.update(&Rope::from("foo FOO bar"));
456 assert_eq!(matcher.current_match_index(), 1);
457 }
458
459 #[test]
460 fn next_wraps_to_start() {
461 let mut matcher = SearchMatcher::new();
462 matcher.update(&Rope::from(".....aaaaa.....aaaaa.....aaaaa"));
463 matcher.update_query("aaaaa", false);
464 matcher.set_current_match_index(2);
465 assert_eq!(matcher.next(), Some(5..10));
466 }
467
468 #[test]
469 fn a_query_set_without_the_panel_keeps_the_session_active_until_closed() {
470 let mut session = SearchSession::default();
471 assert!(!session.is_active());
472
473 session.open(false, true);
474 assert!(session.is_active());
475 session.close();
476 assert!(!session.is_active());
477
478 session.activate();
481 assert!(session.is_active());
482 assert!(!session.open);
483 session.close();
484 assert!(!session.is_active());
485 }
486
487 #[test]
488 fn identical_query_keeps_the_current_match() {
489 let mut session = SearchSession::default();
490 session.update_query("foo", true);
491 session.matcher.update(&Rope::from("foo bar foo baz foo"));
492 session.matcher.update_cursor_by_offset(12);
493 assert_eq!(session.matcher.current_match_index(), 2);
494
495 session.update_query("foo", true);
499
500 assert_eq!(session.matcher.current_match_index(), 2);
501 assert_eq!(session.matcher.label(), "3/3");
502 }
503
504 #[test]
505 fn replacement_keeps_current_match_index_on_next_match() {
506 let mut matcher = SearchMatcher::new();
507 matcher.update(&Rope::from("foo foo foo"));
508 matcher.update_query("foo", true);
509 assert_eq!(matcher.label(), "1/3");
510
511 assert!(matcher.has_next_without_wrap());
512 matcher.begin_replacement();
513 matcher.update(&Rope::from("bar foo foo"));
514 assert_eq!(matcher.current_match_index(), 0);
515 assert_eq!(matcher.matched_ranges()[0], 4..7);
516 assert_eq!(matcher.label(), "1/2");
517
518 matcher.set_current_match_index(1);
519 assert!(!matcher.has_next_without_wrap());
520 matcher.set_current_match_index(0);
521 matcher.begin_replacement();
522 matcher.update(&Rope::from("bar foo bar"));
523 assert_eq!(matcher.current_match_index(), 0);
524 assert_eq!(matcher.matched_ranges()[0], 4..7);
525 assert_eq!(matcher.label(), "1/1");
526 }
527
528 #[test]
529 fn update_matches_clamps_current_match_index_while_replacing() {
530 let mut matcher = SearchMatcher::new();
531 matcher.update(&Rope::from("foo foo foo"));
532 matcher.update_query("foo", true);
533 matcher.set_current_match_index(2);
534 matcher.begin_replacement();
535
536 matcher.update(&Rope::from("foo xoo foo"));
537
538 assert_eq!(matcher.len(), 2);
539 assert_eq!(matcher.current_match_index(), 1);
540 assert_eq!(matcher.label(), "2/2");
541 }
542}