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 style = &cx
285 .global::<Settings>()
286 .theme
287 .search
288 .option_button
289 .style_for(state, is_active);
290 Label::new(icon.to_string(), style.text.clone())
291 .contained()
292 .with_style(style.container)
293 .boxed()
294 })
295 .on_click(move |_, cx| cx.dispatch_action(ToggleSearchOption(search_option)))
296 .with_cursor_style(CursorStyle::PointingHand)
297 .boxed()
298 }
299
300 fn render_nav_button(
301 &self,
302 icon: &str,
303 direction: Direction,
304 cx: &mut RenderContext<Self>,
305 ) -> ElementBox {
306 enum NavButton {}
307 MouseEventHandler::new::<NavButton, _, _>(direction as usize, cx, |state, cx| {
308 let style = &cx
309 .global::<Settings>()
310 .theme
311 .search
312 .option_button
313 .style_for(state, false);
314 Label::new(icon.to_string(), style.text.clone())
315 .contained()
316 .with_style(style.container)
317 .boxed()
318 })
319 .on_click(move |_, cx| match direction {
320 Direction::Prev => cx.dispatch_action(SelectPrevMatch),
321 Direction::Next => cx.dispatch_action(SelectNextMatch),
322 })
323 .with_cursor_style(CursorStyle::PointingHand)
324 .boxed()
325 }
326
327 fn deploy(pane: &mut Pane, action: &Deploy, cx: &mut ViewContext<Pane>) {
328 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
329 if search_bar.update(cx, |search_bar, cx| search_bar.show(action.focus, cx)) {
330 return;
331 }
332 }
333 cx.propagate_action();
334 }
335
336 fn handle_editor_cancel(pane: &mut Pane, _: &editor::Cancel, cx: &mut ViewContext<Pane>) {
337 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
338 if !search_bar.read(cx).dismissed {
339 search_bar.update(cx, |search_bar, cx| search_bar.dismiss(&Dismiss, cx));
340 return;
341 }
342 }
343 cx.propagate_action();
344 }
345
346 fn focus_editor(&mut self, _: &FocusEditor, cx: &mut ViewContext<Self>) {
347 if let Some(active_editor) = self.active_editor.as_ref() {
348 cx.focus(active_editor);
349 }
350 }
351
352 fn is_search_option_enabled(&self, search_option: SearchOption) -> bool {
353 match search_option {
354 SearchOption::WholeWord => self.whole_word,
355 SearchOption::CaseSensitive => self.case_sensitive,
356 SearchOption::Regex => self.regex,
357 }
358 }
359
360 fn toggle_search_option(
361 &mut self,
362 ToggleSearchOption(search_option): &ToggleSearchOption,
363 cx: &mut ViewContext<Self>,
364 ) {
365 let value = match search_option {
366 SearchOption::WholeWord => &mut self.whole_word,
367 SearchOption::CaseSensitive => &mut self.case_sensitive,
368 SearchOption::Regex => &mut self.regex,
369 };
370 *value = !*value;
371 self.update_matches(true, cx);
372 cx.notify();
373 }
374
375 fn select_next_match(&mut self, _: &SelectNextMatch, cx: &mut ViewContext<Self>) {
376 self.select_match(Direction::Next, cx);
377 }
378
379 fn select_prev_match(&mut self, _: &SelectPrevMatch, cx: &mut ViewContext<Self>) {
380 self.select_match(Direction::Prev, cx);
381 }
382
383 fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
384 if let Some(index) = self.active_match_index {
385 if let Some(editor) = self.active_editor.as_ref() {
386 editor.update(cx, |editor, cx| {
387 if let Some(ranges) = self.editors_with_matches.get(&cx.weak_handle()) {
388 let new_index = match_index_for_direction(
389 ranges,
390 &editor.newest_anchor_selection().head(),
391 index,
392 direction,
393 &editor.buffer().read(cx).read(cx),
394 );
395 let range_to_select = ranges[new_index].clone();
396 editor.unfold_ranges([range_to_select.clone()], false, cx);
397 editor.select_ranges([range_to_select], Some(Autoscroll::Fit), cx);
398 }
399 });
400 }
401 }
402 }
403
404 fn select_next_match_on_pane(
405 pane: &mut Pane,
406 action: &SelectNextMatch,
407 cx: &mut ViewContext<Pane>,
408 ) {
409 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
410 search_bar.update(cx, |bar, cx| bar.select_next_match(action, cx));
411 }
412 }
413
414 fn select_prev_match_on_pane(
415 pane: &mut Pane,
416 action: &SelectPrevMatch,
417 cx: &mut ViewContext<Pane>,
418 ) {
419 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
420 search_bar.update(cx, |bar, cx| bar.select_prev_match(action, cx));
421 }
422 }
423
424 fn on_query_editor_event(
425 &mut self,
426 _: ViewHandle<Editor>,
427 event: &editor::Event,
428 cx: &mut ViewContext<Self>,
429 ) {
430 match event {
431 editor::Event::BufferEdited { .. } => {
432 self.query_contains_error = false;
433 self.clear_matches(cx);
434 self.update_matches(true, cx);
435 cx.notify();
436 }
437 _ => {}
438 }
439 }
440
441 fn on_active_editor_event(
442 &mut self,
443 _: ViewHandle<Editor>,
444 event: &editor::Event,
445 cx: &mut ViewContext<Self>,
446 ) {
447 match event {
448 editor::Event::BufferEdited { .. } => self.update_matches(false, cx),
449 editor::Event::SelectionsChanged { .. } => self.update_match_index(cx),
450 _ => {}
451 }
452 }
453
454 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
455 let mut active_editor_matches = None;
456 for (editor, ranges) in self.editors_with_matches.drain() {
457 if let Some(editor) = editor.upgrade(cx) {
458 if Some(&editor) == self.active_editor.as_ref() {
459 active_editor_matches = Some((editor.downgrade(), ranges));
460 } else {
461 editor.update(cx, |editor, cx| {
462 editor.clear_background_highlights::<Self>(cx)
463 });
464 }
465 }
466 }
467 self.editors_with_matches.extend(active_editor_matches);
468 }
469
470 fn update_matches(&mut self, select_closest_match: bool, cx: &mut ViewContext<Self>) {
471 let query = self.query_editor.read(cx).text(cx);
472 self.pending_search.take();
473 if let Some(editor) = self.active_editor.as_ref() {
474 if query.is_empty() {
475 self.active_match_index.take();
476 editor.update(cx, |editor, cx| {
477 editor.clear_background_highlights::<Self>(cx)
478 });
479 } else {
480 let buffer = editor.read(cx).buffer().read(cx).snapshot(cx);
481 let query = if self.regex {
482 match SearchQuery::regex(query, self.whole_word, self.case_sensitive) {
483 Ok(query) => query,
484 Err(_) => {
485 self.query_contains_error = true;
486 cx.notify();
487 return;
488 }
489 }
490 } else {
491 SearchQuery::text(query, self.whole_word, self.case_sensitive)
492 };
493
494 let ranges = cx.background().spawn(async move {
495 let mut ranges = Vec::new();
496 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
497 ranges.extend(
498 query
499 .search(excerpt_buffer.as_rope())
500 .await
501 .into_iter()
502 .map(|range| {
503 buffer.anchor_after(range.start)
504 ..buffer.anchor_before(range.end)
505 }),
506 );
507 } else {
508 for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
509 let excerpt_range = excerpt.range.to_offset(&excerpt.buffer);
510 let rope = excerpt.buffer.as_rope().slice(excerpt_range.clone());
511 ranges.extend(query.search(&rope).await.into_iter().map(|range| {
512 let start = excerpt
513 .buffer
514 .anchor_after(excerpt_range.start + range.start);
515 let end = excerpt
516 .buffer
517 .anchor_before(excerpt_range.start + range.end);
518 buffer.anchor_in_excerpt(excerpt.id.clone(), start)
519 ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
520 }));
521 }
522 }
523 ranges
524 });
525
526 let editor = editor.downgrade();
527 self.pending_search = Some(cx.spawn_weak(|this, mut cx| async move {
528 let ranges = ranges.await;
529 if let Some((this, editor)) = this.upgrade(&cx).zip(editor.upgrade(&cx)) {
530 this.update(&mut cx, |this, cx| {
531 this.editors_with_matches
532 .insert(editor.downgrade(), ranges.clone());
533 this.update_match_index(cx);
534 if !this.dismissed {
535 editor.update(cx, |editor, cx| {
536 if select_closest_match {
537 if let Some(match_ix) = this.active_match_index {
538 editor.select_ranges(
539 [ranges[match_ix].clone()],
540 Some(Autoscroll::Fit),
541 cx,
542 );
543 }
544 }
545
546 editor.highlight_background::<Self>(
547 ranges,
548 |theme| theme.search.match_background,
549 cx,
550 );
551 });
552 }
553 cx.notify();
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}