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