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