Skip to main content

gpui_base/input/editor/
search.rs

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/// Stateful, presentation-independent search engine used by text inputs.
12#[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/// One search over an input: the query, how the built-in panel shows it, and
22/// its matches. Read it through [`InputBaseState::search_session`]; it is
23/// written only through the input state's search methods, and it grows, so
24/// build it with `Default` and do not destructure it exhaustively.
25#[derive(Debug, Clone)]
26#[non_exhaustive]
27pub struct SearchSession {
28    /// The built-in search panel is showing.
29    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    /// A search is in progress and its matches are highlighted: the panel is
37    /// open, or a query was set without it and not closed since.
38    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    /// Start a search without the built-in panel. A custom search UI drives
64    /// the session through [`InputBaseState::set_search_query`], and the
65    /// editor highlights the matches the same way it does for the panel.
66    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    /// Whether a search is in progress: the built-in panel is open, or a
76    /// query was set without it and [`InputBaseState::close_search`] has not
77    /// run since. Matches are highlighted while this holds.
78    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    /// Open the search session, or re-invoke it if it is already open.
96    ///
97    /// This is not idempotent: every call advances
98    /// [`InputBaseState::search_activation_revision`], and the presentation
99    /// layer answers that by re-focusing the search field and selecting its
100    /// contents, the same as pressing the shortcut a second time. Call it from
101    /// an action or another user gesture, never from a render pass or an
102    /// observer that runs every frame — that would re-select the field under
103    /// the user on every frame and make it impossible to type.
104    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        // A retained query resumes its previous occurrence. Only a new query
119        // is anchored to the current viewport.
120        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    /// A counter that advances every time [`InputBaseState::open_search`] runs,
141    /// including while the session is already open.
142    ///
143    /// Re-invoking search leaves the session itself identical, so a presentation
144    /// layer that decides what to rebuild by comparing session state cannot see
145    /// the second request. Fold this into that comparison to notice it.
146    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    /// Returns true if the search panel can replace the matches.
157    ///
158    /// This is false when the input is not `replaceable`, or when it is
159    /// `disabled` or `readonly`.
160    pub fn is_replaceable(&self) -> bool {
161        self.replaceable && self.is_editable()
162    }
163
164    /// Set the search query and highlight its matches.
165    ///
166    /// This is the entry point for a custom search UI: it needs neither
167    /// `searchable` nor the built-in panel. Navigate the matches with
168    /// [`InputBaseState::next_search_match`] and
169    /// [`InputBaseState::previous_search_match`], read the count and the
170    /// current index from [`InputBaseState::search_session`], and end the
171    /// search with [`InputBaseState::close_search`].
172    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    /// End the search: hide the built-in panel and the match highlights. The
185    /// query is kept so the next [`InputBaseState::open_search`] resumes it.
186    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        self.sync_search_matcher();
193        let range = self.search_session.matcher.next()?;
194        // Match order does not describe viewport direction after a manual
195        // scroll. Always allow search navigation to reveal the active match.
196        self.scroll_to_with_padding(range.end, None, ScrollPadding::SurroundingLines, cx);
197        Some(range)
198    }
199
200    pub fn previous_search_match(&mut self, cx: &mut Context<Self>) -> Option<Range<usize>> {
201        self.sync_search_matcher();
202        let range = self.search_session.matcher.next_back()?;
203        // Match order does not describe viewport direction after a manual
204        // scroll. Always allow search navigation to reveal the active match.
205        self.scroll_to_with_padding(range.start, None, ScrollPadding::SurroundingLines, cx);
206        Some(range)
207    }
208
209    /// Replace the current match and move on to the next one. Returns whether
210    /// there was a match to replace.
211    pub fn replace_current_search_match(
212        &mut self,
213        replacement: &str,
214        window: &mut Window,
215        cx: &mut Context<Self>,
216    ) -> bool {
217        if !self.is_replaceable() {
218            return false;
219        }
220        self.sync_search_matcher();
221        let matcher = &mut self.search_session.matcher;
222        let Some(range) = matcher
223            .matched_ranges()
224            .get(matcher.current_match_index())
225            .cloned()
226        else {
227            return false;
228        };
229        let next = matcher.peek().unwrap_or_else(|| range.clone());
230        let direction = matcher
231            .has_next_without_wrap()
232            .then_some(MoveDirection::Down);
233        if direction.is_none() {
234            matcher.set_current_match_index(0);
235        }
236        matcher.begin_replacement();
237        let range_utf16 = self.range_to_utf16(&range);
238        self.scroll_to(next.end, direction, cx);
239        self.replace_text_in_range_silent(Some(range_utf16), replacement, window, cx);
240        true
241    }
242
243    /// Replace every match. Returns how many were replaced.
244    pub fn replace_all_search_matches(
245        &mut self,
246        replacement: &str,
247        window: &mut Window,
248        cx: &mut Context<Self>,
249    ) -> usize {
250        if !self.is_replaceable() {
251            return 0;
252        }
253        self.sync_search_matcher();
254        let ranges = self.search_session.matcher.matched_ranges();
255        if ranges.is_empty() {
256            return 0;
257        }
258        let mut text = self.text.clone();
259        for range in ranges.iter().rev() {
260            text.replace(range.clone(), replacement);
261        }
262        self.search_session.matcher.begin_replacement();
263        let count = ranges.len();
264        self.replace_text_in_range_silent(Some(0..self.text.len()), &text.to_string(), window, cx);
265        self.scroll_to(0, Some(MoveDirection::Down), cx);
266        count
267    }
268
269    /// Keep the matches in step with an edit. A closed search skips the scan:
270    /// it copies and searches the whole document, and nothing reads the
271    /// matches until the search is resumed or navigated, which sync first.
272    pub(super) fn update_search(&mut self, _cx: &mut gpui::App) {
273        if !self.search_session.is_active() {
274            return;
275        }
276        self.sync_search_matcher();
277    }
278
279    /// Recompute the matches if the text changed since the last scan.
280    fn sync_search_matcher(&mut self) {
281        self.search_session.matcher.update(&self.text);
282    }
283
284    /// An input that is not `searchable` leaves the shortcut to its
285    /// ancestors, so a custom search UI can take it.
286    pub(super) fn on_action_search(&mut self, _: &Search, _: &mut Window, cx: &mut Context<Self>) {
287        if !self.searchable {
288            cx.propagate();
289            return;
290        }
291        self.open_search(false, cx);
292    }
293
294    pub(super) fn on_action_replace(
295        &mut self,
296        _: &Replace,
297        _: &mut Window,
298        cx: &mut Context<Self>,
299    ) {
300        if !self.searchable {
301            cx.propagate();
302            return;
303        }
304        self.open_search(true, cx);
305    }
306}
307
308impl Default for SearchMatcher {
309    fn default() -> Self {
310        Self::new()
311    }
312}
313
314impl SearchMatcher {
315    pub fn new() -> Self {
316        Self {
317            text: "".into(),
318            query: None,
319            matched_ranges: Rc::new(Vec::new()),
320            current_match_ix: 0,
321            replacing: false,
322        }
323    }
324
325    /// Update the source text and recompute matches.
326    pub fn update(&mut self, text: &Rope) {
327        if self.text.eq(text) {
328            self.replacing = false;
329            return;
330        }
331        self.text = text.clone();
332        self.update_matches();
333    }
334
335    pub fn update_query(&mut self, query: &str, case_insensitive: bool) {
336        self.query = (!query.is_empty()).then(|| {
337            AhoCorasick::builder()
338                .ascii_case_insensitive(case_insensitive)
339                .build([query])
340                .expect("failed to build input search query")
341        });
342        self.update_matches();
343    }
344
345    pub fn matched_ranges(&self) -> Rc<Vec<Range<usize>>> {
346        self.matched_ranges.clone()
347    }
348
349    pub fn current_match_index(&self) -> usize {
350        self.current_match_ix
351    }
352
353    /// The index of the current match into [`SearchMatcher::matched_ranges`],
354    /// `None` while there is no match.
355    pub fn current(&self) -> Option<usize> {
356        (!self.is_empty()).then_some(self.current_match_ix)
357    }
358
359    pub fn len(&self) -> usize {
360        self.matched_ranges.len()
361    }
362
363    pub fn is_empty(&self) -> bool {
364        self.matched_ranges.is_empty()
365    }
366
367    /// `2/5`: the current match and the total, `0/0` without matches.
368    pub fn label(&self) -> String {
369        match self.current() {
370            Some(ix) => format!("{}/{}", ix + 1, self.len()),
371            None => "0/0".into(),
372        }
373    }
374
375    fn peek(&self) -> Option<Range<usize>> {
376        self.next_index()
377            .and_then(|ix| self.matched_ranges.get(ix).cloned())
378    }
379
380    fn has_next_without_wrap(&self) -> bool {
381        self.current_match_ix < self.matched_ranges.len().saturating_sub(1)
382    }
383
384    pub fn update_cursor_by_offset(&mut self, offset: usize) {
385        for (ix, range) in self.matched_ranges.iter().enumerate() {
386            self.current_match_ix = ix;
387            if range.contains(&offset) || range.end >= offset {
388                return;
389            }
390        }
391    }
392
393    /// Preserve the current logical match while a replacement mutates text.
394    fn begin_replacement(&mut self) {
395        self.replacing = true;
396    }
397
398    fn set_current_match_index(&mut self, index: usize) {
399        self.current_match_ix = index.min(self.matched_ranges.len().saturating_sub(1));
400    }
401
402    fn next_index(&self) -> Option<usize> {
403        if self.is_empty() {
404            None
405        } else if self.has_next_without_wrap() {
406            Some(self.current_match_ix + 1)
407        } else {
408            Some(0)
409        }
410    }
411
412    fn update_matches(&mut self) {
413        let mut ranges = Vec::new();
414        if let Some(query) = &self.query {
415            let text = self.text.to_string();
416            ranges.extend(
417                query
418                    .stream_find_iter(text.as_bytes())
419                    .map(|result| result.expect("input search match").range()),
420            );
421        }
422        self.matched_ranges = Rc::new(ranges);
423        if !self.replacing || self.is_empty() {
424            self.current_match_ix = 0;
425        } else {
426            self.current_match_ix = self.current_match_ix.min(self.len() - 1);
427        }
428        self.replacing = false;
429    }
430}
431
432impl Iterator for SearchMatcher {
433    type Item = Range<usize>;
434
435    fn next(&mut self) -> Option<Self::Item> {
436        let ix = self.next_index()?;
437        self.current_match_ix = ix;
438        self.matched_ranges.get(ix).cloned()
439    }
440}
441
442impl DoubleEndedIterator for SearchMatcher {
443    fn next_back(&mut self) -> Option<Self::Item> {
444        if self.is_empty() {
445            return None;
446        }
447        if self.current_match_ix == 0 {
448            self.current_match_ix = self.len();
449        }
450        self.current_match_ix -= 1;
451        self.matched_ranges.get(self.current_match_ix).cloned()
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458
459    #[test]
460    fn finds_navigates_and_preserves_replacement_position() {
461        let mut matcher = SearchMatcher::new();
462        matcher.update(&Rope::from("foo FOO foo"));
463        matcher.update_query("foo", true);
464        assert_eq!(&*matcher.matched_ranges(), &[0..3, 4..7, 8..11]);
465        assert_eq!(matcher.next(), Some(4..7));
466        assert_eq!(matcher.next_back(), Some(0..3));
467
468        matcher.set_current_match_index(2);
469        matcher.begin_replacement();
470        matcher.update(&Rope::from("foo FOO bar"));
471        assert_eq!(matcher.current_match_index(), 1);
472    }
473
474    #[test]
475    fn next_wraps_to_start() {
476        let mut matcher = SearchMatcher::new();
477        matcher.update(&Rope::from(".....aaaaa.....aaaaa.....aaaaa"));
478        matcher.update_query("aaaaa", false);
479        matcher.set_current_match_index(2);
480        assert_eq!(matcher.next(), Some(5..10));
481    }
482
483    #[test]
484    fn a_query_set_without_the_panel_keeps_the_session_active_until_closed() {
485        let mut session = SearchSession::default();
486        assert!(!session.is_active());
487
488        session.open(false, true);
489        assert!(session.is_active());
490        session.close();
491        assert!(!session.is_active());
492
493        // A custom search UI never opens the panel; setting a query is what
494        // turns the match highlights on, and closing turns them off again.
495        session.activate();
496        assert!(session.is_active());
497        assert!(!session.open);
498        session.close();
499        assert!(!session.is_active());
500    }
501
502    #[test]
503    fn identical_query_keeps_the_current_match() {
504        let mut session = SearchSession::default();
505        session.update_query("foo", true);
506        session.matcher.update(&Rope::from("foo bar foo baz foo"));
507        session.matcher.update_cursor_by_offset(12);
508        assert_eq!(session.matcher.current_match_index(), 2);
509
510        // Reopening Find and the styled search panel's initial query echo both
511        // update the session with the same query. Neither should reset the
512        // previously active occurrence.
513        session.update_query("foo", true);
514
515        assert_eq!(session.matcher.current_match_index(), 2);
516        assert_eq!(session.matcher.label(), "3/3");
517    }
518
519    #[test]
520    fn replacement_keeps_current_match_index_on_next_match() {
521        let mut matcher = SearchMatcher::new();
522        matcher.update(&Rope::from("foo foo foo"));
523        matcher.update_query("foo", true);
524        assert_eq!(matcher.label(), "1/3");
525
526        assert!(matcher.has_next_without_wrap());
527        matcher.begin_replacement();
528        matcher.update(&Rope::from("bar foo foo"));
529        assert_eq!(matcher.current_match_index(), 0);
530        assert_eq!(matcher.matched_ranges()[0], 4..7);
531        assert_eq!(matcher.label(), "1/2");
532
533        matcher.set_current_match_index(1);
534        assert!(!matcher.has_next_without_wrap());
535        matcher.set_current_match_index(0);
536        matcher.begin_replacement();
537        matcher.update(&Rope::from("bar foo bar"));
538        assert_eq!(matcher.current_match_index(), 0);
539        assert_eq!(matcher.matched_ranges()[0], 4..7);
540        assert_eq!(matcher.label(), "1/1");
541    }
542
543    #[test]
544    fn update_matches_clamps_current_match_index_while_replacing() {
545        let mut matcher = SearchMatcher::new();
546        matcher.update(&Rope::from("foo foo foo"));
547        matcher.update_query("foo", true);
548        matcher.set_current_match_index(2);
549        matcher.begin_replacement();
550
551        matcher.update(&Rope::from("foo xoo foo"));
552
553        assert_eq!(matcher.len(), 2);
554        assert_eq!(matcher.current_match_index(), 1);
555        assert_eq!(matcher.label(), "2/2");
556    }
557}