buffer_search.rs

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