find.rs

  1use aho_corasick::AhoCorasickBuilder;
  2use anyhow::Result;
  3use collections::HashMap;
  4use editor::{
  5    char_kind, display_map::ToDisplayPoint, Anchor, Autoscroll, Bias, Editor, EditorSettings,
  6    MultiBufferSnapshot,
  7};
  8use gpui::{
  9    action, elements::*, keymap::Binding, platform::CursorStyle, Entity, MutableAppContext,
 10    RenderContext, Subscription, Task, View, ViewContext, ViewHandle, WeakViewHandle,
 11};
 12use postage::watch;
 13use regex::RegexBuilder;
 14use smol::future::yield_now;
 15use std::{
 16    cmp::{self, Ordering},
 17    ops::Range,
 18    sync::Arc,
 19};
 20use workspace::{ItemViewHandle, Pane, Settings, Toolbar, Workspace};
 21
 22action!(Deploy, bool);
 23action!(Dismiss);
 24action!(FocusEditor);
 25action!(ToggleMode, SearchMode);
 26action!(GoToMatch, Direction);
 27
 28#[derive(Clone, Copy, PartialEq, Eq)]
 29pub enum Direction {
 30    Prev,
 31    Next,
 32}
 33
 34#[derive(Clone, Copy)]
 35pub enum SearchMode {
 36    WholeWord,
 37    CaseSensitive,
 38    Regex,
 39}
 40
 41pub fn init(cx: &mut MutableAppContext) {
 42    cx.add_bindings([
 43        Binding::new("cmd-f", Deploy(true), Some("Editor && mode == full")),
 44        Binding::new("cmd-e", Deploy(false), Some("Editor && mode == full")),
 45        Binding::new("escape", Dismiss, Some("FindBar")),
 46        Binding::new("cmd-f", FocusEditor, Some("FindBar")),
 47        Binding::new("enter", GoToMatch(Direction::Next), Some("FindBar")),
 48        Binding::new("shift-enter", GoToMatch(Direction::Prev), Some("FindBar")),
 49        Binding::new("cmd-g", GoToMatch(Direction::Next), Some("Pane")),
 50        Binding::new("cmd-shift-G", GoToMatch(Direction::Prev), Some("Pane")),
 51    ]);
 52    cx.add_action(FindBar::deploy);
 53    cx.add_action(FindBar::dismiss);
 54    cx.add_action(FindBar::focus_editor);
 55    cx.add_action(FindBar::toggle_mode);
 56    cx.add_action(FindBar::go_to_match);
 57    cx.add_action(FindBar::go_to_match_on_pane);
 58}
 59
 60struct FindBar {
 61    settings: watch::Receiver<Settings>,
 62    query_editor: ViewHandle<Editor>,
 63    active_editor: Option<ViewHandle<Editor>>,
 64    active_match_index: Option<usize>,
 65    active_editor_subscription: Option<Subscription>,
 66    editors_with_matches: HashMap<WeakViewHandle<Editor>, Vec<Range<Anchor>>>,
 67    pending_search: Option<Task<()>>,
 68    case_sensitive_mode: bool,
 69    whole_word_mode: bool,
 70    regex_mode: bool,
 71    query_contains_error: bool,
 72    dismissed: bool,
 73}
 74
 75impl Entity for FindBar {
 76    type Event = ();
 77}
 78
 79impl View for FindBar {
 80    fn ui_name() -> &'static str {
 81        "FindBar"
 82    }
 83
 84    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
 85        cx.focus(&self.query_editor);
 86    }
 87
 88    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
 89        let theme = &self.settings.borrow().theme;
 90        let editor_container = if self.query_contains_error {
 91            theme.find.invalid_editor
 92        } else {
 93            theme.find.editor.input.container
 94        };
 95        Flex::row()
 96            .with_child(
 97                ChildView::new(&self.query_editor)
 98                    .contained()
 99                    .with_style(editor_container)
100                    .aligned()
101                    .constrained()
102                    .with_max_width(theme.find.editor.max_width)
103                    .boxed(),
104            )
105            .with_child(
106                Flex::row()
107                    .with_child(self.render_mode_button("Case", SearchMode::CaseSensitive, cx))
108                    .with_child(self.render_mode_button("Word", SearchMode::WholeWord, cx))
109                    .with_child(self.render_mode_button("Regex", SearchMode::Regex, cx))
110                    .contained()
111                    .with_style(theme.find.mode_button_group)
112                    .aligned()
113                    .boxed(),
114            )
115            .with_child(
116                Flex::row()
117                    .with_child(self.render_nav_button("<", Direction::Prev, cx))
118                    .with_child(self.render_nav_button(">", Direction::Next, cx))
119                    .aligned()
120                    .boxed(),
121            )
122            .with_children(self.active_editor.as_ref().and_then(|editor| {
123                let matches = self.editors_with_matches.get(&editor.downgrade())?;
124                let message = if let Some(match_ix) = self.active_match_index {
125                    format!("{}/{}", match_ix + 1, matches.len())
126                } else {
127                    "No matches".to_string()
128                };
129
130                Some(
131                    Label::new(message, theme.find.match_index.text.clone())
132                        .contained()
133                        .with_style(theme.find.match_index.container)
134                        .aligned()
135                        .boxed(),
136                )
137            }))
138            .contained()
139            .with_style(theme.find.container)
140            .constrained()
141            .with_height(theme.workspace.toolbar.height)
142            .named("find bar")
143    }
144}
145
146impl Toolbar for FindBar {
147    fn active_item_changed(
148        &mut self,
149        item: Option<Box<dyn ItemViewHandle>>,
150        cx: &mut ViewContext<Self>,
151    ) -> bool {
152        self.active_editor_subscription.take();
153        self.active_editor.take();
154        self.pending_search.take();
155
156        if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
157            self.active_editor_subscription =
158                Some(cx.subscribe(&editor, Self::on_active_editor_event));
159            self.active_editor = Some(editor);
160            self.update_matches(false, cx);
161            true
162        } else {
163            false
164        }
165    }
166
167    fn on_dismiss(&mut self, cx: &mut ViewContext<Self>) {
168        self.dismissed = true;
169        for (editor, _) in &self.editors_with_matches {
170            if let Some(editor) = editor.upgrade(cx) {
171                editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
172            }
173        }
174    }
175}
176
177impl FindBar {
178    fn new(settings: watch::Receiver<Settings>, cx: &mut ViewContext<Self>) -> Self {
179        let query_editor = cx.add_view(|cx| {
180            Editor::auto_height(
181                2,
182                {
183                    let settings = settings.clone();
184                    Arc::new(move |_| {
185                        let settings = settings.borrow();
186                        EditorSettings {
187                            style: settings.theme.find.editor.input.as_editor(),
188                            tab_size: settings.tab_size,
189                            soft_wrap: editor::SoftWrap::None,
190                        }
191                    })
192                },
193                cx,
194            )
195        });
196        cx.subscribe(&query_editor, Self::on_query_editor_event)
197            .detach();
198
199        Self {
200            query_editor,
201            active_editor: None,
202            active_editor_subscription: None,
203            active_match_index: None,
204            editors_with_matches: Default::default(),
205            case_sensitive_mode: false,
206            whole_word_mode: false,
207            regex_mode: false,
208            settings,
209            pending_search: None,
210            query_contains_error: false,
211            dismissed: false,
212        }
213    }
214
215    fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
216        self.query_editor.update(cx, |query_editor, cx| {
217            query_editor.buffer().update(cx, |query_buffer, cx| {
218                let len = query_buffer.read(cx).len();
219                query_buffer.edit([0..len], query, cx);
220            });
221        });
222    }
223
224    fn render_mode_button(
225        &self,
226        icon: &str,
227        mode: SearchMode,
228        cx: &mut RenderContext<Self>,
229    ) -> ElementBox {
230        let theme = &self.settings.borrow().theme.find;
231        let is_active = self.is_mode_enabled(mode);
232        MouseEventHandler::new::<Self, _, _>(mode as usize, cx, |state, _| {
233            let style = match (is_active, state.hovered) {
234                (false, false) => &theme.mode_button,
235                (false, true) => &theme.hovered_mode_button,
236                (true, false) => &theme.active_mode_button,
237                (true, true) => &theme.active_hovered_mode_button,
238            };
239            Label::new(icon.to_string(), style.text.clone())
240                .contained()
241                .with_style(style.container)
242                .boxed()
243        })
244        .on_click(move |cx| cx.dispatch_action(ToggleMode(mode)))
245        .with_cursor_style(CursorStyle::PointingHand)
246        .boxed()
247    }
248
249    fn render_nav_button(
250        &self,
251        icon: &str,
252        direction: Direction,
253        cx: &mut RenderContext<Self>,
254    ) -> ElementBox {
255        let theme = &self.settings.borrow().theme.find;
256        enum NavButton {}
257        MouseEventHandler::new::<NavButton, _, _>(direction as usize, cx, |state, _| {
258            let style = if state.hovered {
259                &theme.hovered_mode_button
260            } else {
261                &theme.mode_button
262            };
263            Label::new(icon.to_string(), style.text.clone())
264                .contained()
265                .with_style(style.container)
266                .boxed()
267        })
268        .on_click(move |cx| cx.dispatch_action(GoToMatch(direction)))
269        .with_cursor_style(CursorStyle::PointingHand)
270        .boxed()
271    }
272
273    fn deploy(workspace: &mut Workspace, Deploy(focus): &Deploy, cx: &mut ViewContext<Workspace>) {
274        let settings = workspace.settings();
275        workspace.active_pane().update(cx, |pane, cx| {
276            pane.show_toolbar(cx, |cx| FindBar::new(settings, cx));
277
278            if let Some(find_bar) = pane
279                .active_toolbar()
280                .and_then(|toolbar| toolbar.downcast::<Self>())
281            {
282                find_bar.update(cx, |find_bar, _| find_bar.dismissed = false);
283                let editor = pane.active_item().unwrap().act_as::<Editor>(cx).unwrap();
284                let display_map = editor
285                    .update(cx, |editor, cx| editor.snapshot(cx))
286                    .display_snapshot;
287                let selection = editor
288                    .read(cx)
289                    .newest_selection::<usize>(&display_map.buffer_snapshot);
290
291                let mut text: String;
292                if selection.start == selection.end {
293                    let point = selection.start.to_display_point(&display_map);
294                    let range = editor::movement::surrounding_word(&display_map, point);
295                    let range = range.start.to_offset(&display_map, Bias::Left)
296                        ..range.end.to_offset(&display_map, Bias::Right);
297                    text = display_map.buffer_snapshot.text_for_range(range).collect();
298                    if text.trim().is_empty() {
299                        text = String::new();
300                    }
301                } else {
302                    text = display_map
303                        .buffer_snapshot
304                        .text_for_range(selection.start..selection.end)
305                        .collect();
306                }
307
308                if !text.is_empty() {
309                    find_bar.update(cx, |find_bar, cx| find_bar.set_query(&text, cx));
310                }
311
312                if *focus {
313                    let query_editor = find_bar.read(cx).query_editor.clone();
314                    query_editor.update(cx, |query_editor, cx| {
315                        query_editor.select_all(&editor::SelectAll, cx);
316                    });
317                    cx.focus(&find_bar);
318                }
319            }
320        });
321    }
322
323    fn dismiss(pane: &mut Pane, _: &Dismiss, cx: &mut ViewContext<Pane>) {
324        if pane.toolbar::<FindBar>().is_some() {
325            pane.dismiss_toolbar(cx);
326        }
327    }
328
329    fn focus_editor(&mut self, _: &FocusEditor, cx: &mut ViewContext<Self>) {
330        if let Some(active_editor) = self.active_editor.as_ref() {
331            cx.focus(active_editor);
332        }
333    }
334
335    fn is_mode_enabled(&self, mode: SearchMode) -> bool {
336        match mode {
337            SearchMode::WholeWord => self.whole_word_mode,
338            SearchMode::CaseSensitive => self.case_sensitive_mode,
339            SearchMode::Regex => self.regex_mode,
340        }
341    }
342
343    fn toggle_mode(&mut self, ToggleMode(mode): &ToggleMode, cx: &mut ViewContext<Self>) {
344        let value = match mode {
345            SearchMode::WholeWord => &mut self.whole_word_mode,
346            SearchMode::CaseSensitive => &mut self.case_sensitive_mode,
347            SearchMode::Regex => &mut self.regex_mode,
348        };
349        *value = !*value;
350        self.update_matches(true, cx);
351        cx.notify();
352    }
353
354    fn go_to_match(&mut self, GoToMatch(direction): &GoToMatch, cx: &mut ViewContext<Self>) {
355        if let Some(mut index) = self.active_match_index {
356            if let Some(editor) = self.active_editor.as_ref() {
357                editor.update(cx, |editor, cx| {
358                    let newest_selection = editor.newest_anchor_selection().clone();
359                    if let Some(ranges) = self.editors_with_matches.get(&cx.weak_handle()) {
360                        let position = newest_selection.head();
361                        let buffer = editor.buffer().read(cx).read(cx);
362                        if ranges[index].start.cmp(&position, &buffer).unwrap().is_gt() {
363                            if *direction == Direction::Prev {
364                                if index == 0 {
365                                    index = ranges.len() - 1;
366                                } else {
367                                    index -= 1;
368                                }
369                            }
370                        } else if ranges[index].end.cmp(&position, &buffer).unwrap().is_lt() {
371                            if *direction == Direction::Next {
372                                index = 0;
373                            }
374                        } else if *direction == Direction::Prev {
375                            if index == 0 {
376                                index = ranges.len() - 1;
377                            } else {
378                                index -= 1;
379                            }
380                        } else if *direction == Direction::Next {
381                            if index == ranges.len() - 1 {
382                                index = 0
383                            } else {
384                                index += 1;
385                            }
386                        }
387
388                        let range_to_select = ranges[index].clone();
389                        drop(buffer);
390                        editor.select_ranges([range_to_select], Some(Autoscroll::Fit), cx);
391                    }
392                });
393            }
394        }
395    }
396
397    fn go_to_match_on_pane(pane: &mut Pane, action: &GoToMatch, cx: &mut ViewContext<Pane>) {
398        if let Some(find_bar) = pane.toolbar::<FindBar>() {
399            find_bar.update(cx, |find_bar, cx| find_bar.go_to_match(action, cx));
400        }
401    }
402
403    fn on_query_editor_event(
404        &mut self,
405        _: ViewHandle<Editor>,
406        event: &editor::Event,
407        cx: &mut ViewContext<Self>,
408    ) {
409        match event {
410            editor::Event::Edited => {
411                self.query_contains_error = false;
412                self.clear_matches(cx);
413                self.update_matches(true, cx);
414                cx.notify();
415            }
416            _ => {}
417        }
418    }
419
420    fn on_active_editor_event(
421        &mut self,
422        _: ViewHandle<Editor>,
423        event: &editor::Event,
424        cx: &mut ViewContext<Self>,
425    ) {
426        match event {
427            editor::Event::Edited => self.update_matches(false, cx),
428            editor::Event::SelectionsChanged => self.update_match_index(cx),
429            _ => {}
430        }
431    }
432
433    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
434        for (editor, _) in self.editors_with_matches.drain() {
435            if let Some(editor) = editor.upgrade(cx) {
436                if Some(&editor) != self.active_editor.as_ref() {
437                    editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
438                }
439            }
440        }
441    }
442
443    fn update_matches(&mut self, select_closest_match: bool, cx: &mut ViewContext<Self>) {
444        let query = self.query_editor.read(cx).text(cx);
445        self.pending_search.take();
446        if let Some(editor) = self.active_editor.as_ref() {
447            if query.is_empty() {
448                self.active_match_index.take();
449                editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
450            } else {
451                let buffer = editor.read(cx).buffer().read(cx).snapshot(cx);
452                let case_sensitive = self.case_sensitive_mode;
453                let whole_word = self.whole_word_mode;
454                let ranges = if self.regex_mode {
455                    cx.background()
456                        .spawn(regex_search(buffer, query, case_sensitive, whole_word))
457                } else {
458                    cx.background().spawn(async move {
459                        Ok(search(buffer, query, case_sensitive, whole_word).await)
460                    })
461                };
462
463                let editor = editor.downgrade();
464                self.pending_search = Some(cx.spawn(|this, mut cx| async move {
465                    match ranges.await {
466                        Ok(ranges) => {
467                            if let Some(editor) = editor.upgrade(&cx) {
468                                this.update(&mut cx, |this, cx| {
469                                    this.editors_with_matches
470                                        .insert(editor.downgrade(), ranges.clone());
471                                    this.update_match_index(cx);
472                                    if !this.dismissed {
473                                        editor.update(cx, |editor, cx| {
474                                            let theme = &this.settings.borrow().theme.find;
475
476                                            if select_closest_match {
477                                                if let Some(match_ix) = this.active_match_index {
478                                                    editor.select_ranges(
479                                                        [ranges[match_ix].clone()],
480                                                        Some(Autoscroll::Fit),
481                                                        cx,
482                                                    );
483                                                }
484                                            }
485
486                                            editor.highlight_ranges::<Self>(
487                                                ranges,
488                                                theme.match_background,
489                                                cx,
490                                            );
491                                        });
492                                    }
493                                });
494                            }
495                        }
496                        Err(_) => {
497                            this.update(&mut cx, |this, cx| {
498                                this.query_contains_error = true;
499                                cx.notify();
500                            });
501                        }
502                    }
503                }));
504            }
505        }
506    }
507
508    fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
509        self.active_match_index = self.active_match_index(cx);
510        cx.notify();
511    }
512
513    fn active_match_index(&mut self, cx: &mut ViewContext<Self>) -> Option<usize> {
514        let editor = self.active_editor.as_ref()?;
515        let ranges = self.editors_with_matches.get(&editor.downgrade())?;
516        let editor = editor.read(cx);
517        let position = editor.newest_anchor_selection().head();
518        if ranges.is_empty() {
519            None
520        } else {
521            let buffer = editor.buffer().read(cx).read(cx);
522            match ranges.binary_search_by(|probe| {
523                if probe.end.cmp(&position, &*buffer).unwrap().is_lt() {
524                    Ordering::Less
525                } else if probe.start.cmp(&position, &*buffer).unwrap().is_gt() {
526                    Ordering::Greater
527                } else {
528                    Ordering::Equal
529                }
530            }) {
531                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
532            }
533        }
534    }
535}
536
537const YIELD_INTERVAL: usize = 20000;
538
539async fn search(
540    buffer: MultiBufferSnapshot,
541    query: String,
542    case_sensitive: bool,
543    whole_word: bool,
544) -> Vec<Range<Anchor>> {
545    let mut ranges = Vec::new();
546
547    let search = AhoCorasickBuilder::new()
548        .auto_configure(&[&query])
549        .ascii_case_insensitive(!case_sensitive)
550        .build(&[&query]);
551    for (ix, mat) in search
552        .stream_find_iter(buffer.bytes_in_range(0..buffer.len()))
553        .enumerate()
554    {
555        if (ix + 1) % YIELD_INTERVAL == 0 {
556            yield_now().await;
557        }
558
559        let mat = mat.unwrap();
560
561        if whole_word {
562            let prev_kind = buffer.reversed_chars_at(mat.start()).next().map(char_kind);
563            let start_kind = char_kind(buffer.chars_at(mat.start()).next().unwrap());
564            let end_kind = char_kind(buffer.reversed_chars_at(mat.end()).next().unwrap());
565            let next_kind = buffer.chars_at(mat.end()).next().map(char_kind);
566            if Some(start_kind) == prev_kind || Some(end_kind) == next_kind {
567                continue;
568            }
569        }
570
571        ranges.push(buffer.anchor_after(mat.start())..buffer.anchor_before(mat.end()));
572    }
573
574    ranges
575}
576
577async fn regex_search(
578    buffer: MultiBufferSnapshot,
579    mut query: String,
580    case_sensitive: bool,
581    whole_word: bool,
582) -> Result<Vec<Range<Anchor>>> {
583    if whole_word {
584        let mut word_query = String::new();
585        word_query.push_str("\\b");
586        word_query.push_str(&query);
587        word_query.push_str("\\b");
588        query = word_query;
589    }
590
591    let mut ranges = Vec::new();
592
593    if query.contains("\n") || query.contains("\\n") {
594        let regex = RegexBuilder::new(&query)
595            .case_insensitive(!case_sensitive)
596            .multi_line(true)
597            .build()?;
598        for (ix, mat) in regex.find_iter(&buffer.text()).enumerate() {
599            if (ix + 1) % YIELD_INTERVAL == 0 {
600                yield_now().await;
601            }
602
603            ranges.push(buffer.anchor_after(mat.start())..buffer.anchor_before(mat.end()));
604        }
605    } else {
606        let regex = RegexBuilder::new(&query)
607            .case_insensitive(!case_sensitive)
608            .build()?;
609
610        let mut line = String::new();
611        let mut line_offset = 0;
612        for (chunk_ix, chunk) in buffer
613            .chunks(0..buffer.len(), false)
614            .map(|c| c.text)
615            .chain(["\n"])
616            .enumerate()
617        {
618            if (chunk_ix + 1) % YIELD_INTERVAL == 0 {
619                yield_now().await;
620            }
621
622            for (newline_ix, text) in chunk.split('\n').enumerate() {
623                if newline_ix > 0 {
624                    for mat in regex.find_iter(&line) {
625                        let start = line_offset + mat.start();
626                        let end = line_offset + mat.end();
627                        ranges.push(buffer.anchor_after(start)..buffer.anchor_before(end));
628                    }
629
630                    line_offset += line.len() + 1;
631                    line.clear();
632                }
633                line.push_str(text);
634            }
635        }
636    }
637
638    Ok(ranges)
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644    use editor::{DisplayPoint, Editor, EditorSettings, MultiBuffer};
645    use gpui::{color::Color, TestAppContext};
646    use std::sync::Arc;
647    use unindent::Unindent as _;
648
649    #[gpui::test]
650    async fn test_find_simple(mut cx: TestAppContext) {
651        let fonts = cx.font_cache();
652        let mut theme = gpui::fonts::with_font_cache(fonts.clone(), || theme::Theme::default());
653        theme.find.match_background = Color::red();
654        let settings = Settings::new("Courier", &fonts, Arc::new(theme)).unwrap();
655
656        let buffer = cx.update(|cx| {
657            MultiBuffer::build_simple(
658                &r#"
659                A regular expression (shortened as regex or regexp;[1] also referred to as
660                rational expression[2][3]) is a sequence of characters that specifies a search
661                pattern in text. Usually such patterns are used by string-searching algorithms
662                for "find" or "find and replace" operations on strings, or for input validation.
663                "#
664                .unindent(),
665                cx,
666            )
667        });
668        let editor = cx.add_view(Default::default(), |cx| {
669            Editor::new(buffer.clone(), Arc::new(EditorSettings::test), None, cx)
670        });
671
672        let find_bar = cx.add_view(Default::default(), |cx| {
673            let mut find_bar = FindBar::new(watch::channel_with(settings).1, cx);
674            find_bar.active_item_changed(Some(Box::new(editor.clone())), cx);
675            find_bar
676        });
677
678        // Search for a string that appears with different casing.
679        // By default, search is case-insensitive.
680        find_bar.update(&mut cx, |find_bar, cx| {
681            find_bar.set_query("us", cx);
682        });
683        editor.next_notification(&cx).await;
684        editor.update(&mut cx, |editor, cx| {
685            assert_eq!(
686                editor.all_highlighted_ranges(cx),
687                &[
688                    (
689                        DisplayPoint::new(2, 17)..DisplayPoint::new(2, 19),
690                        Color::red(),
691                    ),
692                    (
693                        DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
694                        Color::red(),
695                    ),
696                ]
697            );
698        });
699
700        // Switch to a case sensitive search.
701        find_bar.update(&mut cx, |find_bar, cx| {
702            find_bar.toggle_mode(&ToggleMode(SearchMode::CaseSensitive), cx);
703        });
704        editor.next_notification(&cx).await;
705        editor.update(&mut cx, |editor, cx| {
706            assert_eq!(
707                editor.all_highlighted_ranges(cx),
708                &[(
709                    DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
710                    Color::red(),
711                )]
712            );
713        });
714
715        // Search for a string that appears both as a whole word and
716        // within other words. By default, all results are found.
717        find_bar.update(&mut cx, |find_bar, cx| {
718            find_bar.set_query("or", cx);
719        });
720        editor.next_notification(&cx).await;
721        editor.update(&mut cx, |editor, cx| {
722            assert_eq!(
723                editor.all_highlighted_ranges(cx),
724                &[
725                    (
726                        DisplayPoint::new(0, 24)..DisplayPoint::new(0, 26),
727                        Color::red(),
728                    ),
729                    (
730                        DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
731                        Color::red(),
732                    ),
733                    (
734                        DisplayPoint::new(2, 71)..DisplayPoint::new(2, 73),
735                        Color::red(),
736                    ),
737                    (
738                        DisplayPoint::new(3, 1)..DisplayPoint::new(3, 3),
739                        Color::red(),
740                    ),
741                    (
742                        DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
743                        Color::red(),
744                    ),
745                    (
746                        DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
747                        Color::red(),
748                    ),
749                    (
750                        DisplayPoint::new(3, 60)..DisplayPoint::new(3, 62),
751                        Color::red(),
752                    ),
753                ]
754            );
755        });
756
757        // Switch to a whole word search.
758        find_bar.update(&mut cx, |find_bar, cx| {
759            find_bar.toggle_mode(&ToggleMode(SearchMode::WholeWord), cx);
760        });
761        editor.next_notification(&cx).await;
762        editor.update(&mut cx, |editor, cx| {
763            assert_eq!(
764                editor.all_highlighted_ranges(cx),
765                &[
766                    (
767                        DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
768                        Color::red(),
769                    ),
770                    (
771                        DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
772                        Color::red(),
773                    ),
774                    (
775                        DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
776                        Color::red(),
777                    ),
778                ]
779            );
780        });
781
782        editor.update(&mut cx, |editor, cx| {
783            editor.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
784        });
785        find_bar.update(&mut cx, |find_bar, cx| {
786            assert_eq!(find_bar.active_match_index, Some(0));
787            find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
788            assert_eq!(
789                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
790                [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
791            );
792        });
793        find_bar.read_with(&cx, |find_bar, _| {
794            assert_eq!(find_bar.active_match_index, Some(0));
795        });
796
797        find_bar.update(&mut cx, |find_bar, cx| {
798            find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
799            assert_eq!(
800                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
801                [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
802            );
803        });
804        find_bar.read_with(&cx, |find_bar, _| {
805            assert_eq!(find_bar.active_match_index, Some(1));
806        });
807
808        find_bar.update(&mut cx, |find_bar, cx| {
809            find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
810            assert_eq!(
811                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
812                [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
813            );
814        });
815        find_bar.read_with(&cx, |find_bar, _| {
816            assert_eq!(find_bar.active_match_index, Some(2));
817        });
818
819        find_bar.update(&mut cx, |find_bar, cx| {
820            find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
821            assert_eq!(
822                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
823                [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
824            );
825        });
826        find_bar.read_with(&cx, |find_bar, _| {
827            assert_eq!(find_bar.active_match_index, Some(0));
828        });
829
830        find_bar.update(&mut cx, |find_bar, cx| {
831            find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
832            assert_eq!(
833                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
834                [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
835            );
836        });
837        find_bar.read_with(&cx, |find_bar, _| {
838            assert_eq!(find_bar.active_match_index, Some(2));
839        });
840
841        find_bar.update(&mut cx, |find_bar, cx| {
842            find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
843            assert_eq!(
844                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
845                [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
846            );
847        });
848        find_bar.read_with(&cx, |find_bar, _| {
849            assert_eq!(find_bar.active_match_index, Some(1));
850        });
851
852        find_bar.update(&mut cx, |find_bar, cx| {
853            find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
854            assert_eq!(
855                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
856                [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
857            );
858        });
859        find_bar.read_with(&cx, |find_bar, _| {
860            assert_eq!(find_bar.active_match_index, Some(0));
861        });
862
863        // Park the cursor in between matches and ensure that going to the previous match selects
864        // the closest match to the left.
865        editor.update(&mut cx, |editor, cx| {
866            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
867        });
868        find_bar.update(&mut cx, |find_bar, cx| {
869            assert_eq!(find_bar.active_match_index, Some(1));
870            find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
871            assert_eq!(
872                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
873                [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
874            );
875        });
876        find_bar.read_with(&cx, |find_bar, _| {
877            assert_eq!(find_bar.active_match_index, Some(0));
878        });
879
880        // Park the cursor in between matches and ensure that going to the next match selects the
881        // closest match to the right.
882        editor.update(&mut cx, |editor, cx| {
883            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
884        });
885        find_bar.update(&mut cx, |find_bar, cx| {
886            assert_eq!(find_bar.active_match_index, Some(1));
887            find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
888            assert_eq!(
889                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
890                [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
891            );
892        });
893        find_bar.read_with(&cx, |find_bar, _| {
894            assert_eq!(find_bar.active_match_index, Some(1));
895        });
896
897        // Park the cursor after the last match and ensure that going to the previous match selects
898        // the last match.
899        editor.update(&mut cx, |editor, cx| {
900            editor.select_display_ranges(&[DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)], cx);
901        });
902        find_bar.update(&mut cx, |find_bar, cx| {
903            assert_eq!(find_bar.active_match_index, Some(2));
904            find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
905            assert_eq!(
906                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
907                [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
908            );
909        });
910        find_bar.read_with(&cx, |find_bar, _| {
911            assert_eq!(find_bar.active_match_index, Some(2));
912        });
913
914        // Park the cursor after the last match and ensure that going to the next match selects the
915        // first match.
916        editor.update(&mut cx, |editor, cx| {
917            editor.select_display_ranges(&[DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)], cx);
918        });
919        find_bar.update(&mut cx, |find_bar, cx| {
920            assert_eq!(find_bar.active_match_index, Some(2));
921            find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
922            assert_eq!(
923                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
924                [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
925            );
926        });
927        find_bar.read_with(&cx, |find_bar, _| {
928            assert_eq!(find_bar.active_match_index, Some(0));
929        });
930
931        // Park the cursor before the first match and ensure that going to the previous match
932        // selects the last match.
933        editor.update(&mut cx, |editor, cx| {
934            editor.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
935        });
936        find_bar.update(&mut cx, |find_bar, cx| {
937            assert_eq!(find_bar.active_match_index, Some(0));
938            find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
939            assert_eq!(
940                editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
941                [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
942            );
943        });
944        find_bar.read_with(&cx, |find_bar, _| {
945            assert_eq!(find_bar.active_match_index, Some(2));
946        });
947    }
948}