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().clone();
359 if let Some((_, ranges)) = editor.highlighted_ranges_for_type::<Self>() {
360 let position = newest_selection.head();
361 let buffer = editor.buffer().read(cx).read(cx);
362 if ranges[index].start.cmp(&position, &buffer).unwrap().is_gt() {
363 if *direction == Direction::Prev {
364 if index == 0 {
365 index = ranges.len() - 1;
366 } else {
367 index -= 1;
368 }
369 }
370 } else if ranges[index].end.cmp(&position, &buffer).unwrap().is_lt() {
371 if *direction == Direction::Next {
372 index = 0;
373 }
374 } else if *direction == Direction::Prev {
375 if index == 0 {
376 index = ranges.len() - 1;
377 } else {
378 index -= 1;
379 }
380 } else if *direction == Direction::Next {
381 if index == ranges.len() - 1 {
382 index = 0
383 } else {
384 index += 1;
385 }
386 }
387
388 let range_to_select = ranges[index].clone();
389 drop(buffer);
390 editor.select_ranges([range_to_select], Some(Autoscroll::Fit), cx);
391 }
392 });
393 }
394 }
395 }
396
397 fn go_to_match_on_pane(pane: &mut Pane, action: &GoToMatch, cx: &mut ViewContext<Pane>) {
398 if let Some(find_bar) = pane.toolbar::<FindBar>() {
399 find_bar.update(cx, |find_bar, cx| find_bar.go_to_match(action, cx));
400 }
401 }
402
403 fn on_query_editor_event(
404 &mut self,
405 _: ViewHandle<Editor>,
406 event: &editor::Event,
407 cx: &mut ViewContext<Self>,
408 ) {
409 match event {
410 editor::Event::Edited => {
411 self.query_contains_error = false;
412 self.clear_matches(cx);
413 self.update_matches(cx);
414 cx.notify();
415 }
416 _ => {}
417 }
418 }
419
420 fn on_active_editor_event(
421 &mut self,
422 _: ViewHandle<Editor>,
423 event: &editor::Event,
424 cx: &mut ViewContext<Self>,
425 ) {
426 match event {
427 editor::Event::Edited => self.update_matches(cx),
428 editor::Event::SelectionsChanged => self.update_match_index(cx),
429 _ => {}
430 }
431 }
432
433 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
434 for editor in self.highlighted_editors.drain() {
435 if let Some(editor) = editor.upgrade(cx) {
436 if Some(&editor) != self.active_editor.as_ref() {
437 editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
438 }
439 }
440 }
441 }
442
443 fn update_matches(&mut self, cx: &mut ViewContext<Self>) {
444 let query = self.query_editor.read(cx).text(cx);
445 self.pending_search.take();
446 if let Some(editor) = self.active_editor.as_ref() {
447 if query.is_empty() {
448 self.active_match_index.take();
449 editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
450 } else {
451 let buffer = editor.read(cx).buffer().read(cx).snapshot(cx);
452 let case_sensitive = self.case_sensitive_mode;
453 let whole_word = self.whole_word_mode;
454 let ranges = if self.regex_mode {
455 cx.background()
456 .spawn(regex_search(buffer, query, case_sensitive, whole_word))
457 } else {
458 cx.background().spawn(async move {
459 Ok(search(buffer, query, case_sensitive, whole_word).await)
460 })
461 };
462
463 let editor = editor.downgrade();
464 self.pending_search = Some(cx.spawn(|this, mut cx| async move {
465 match ranges.await {
466 Ok(ranges) => {
467 if let Some(editor) = editor.upgrade(&cx) {
468 this.update(&mut cx, |this, cx| {
469 this.highlighted_editors.insert(editor.downgrade());
470 editor.update(cx, |editor, cx| {
471 let theme = &this.settings.borrow().theme.find;
472 editor.highlight_ranges::<Self>(
473 ranges,
474 theme.match_background,
475 cx,
476 )
477 });
478 this.update_match_index(cx);
479 });
480 }
481 }
482 Err(_) => {
483 this.update(&mut cx, |this, cx| {
484 this.query_contains_error = true;
485 cx.notify();
486 });
487 }
488 }
489 }));
490 }
491 }
492 }
493
494 fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
495 self.active_match_index = self.active_match_index(cx);
496 cx.notify();
497 }
498
499 fn active_match_index(&mut self, cx: &mut ViewContext<Self>) -> Option<usize> {
500 let editor = self.active_editor.as_ref()?;
501 let editor = editor.read(cx);
502 let position = editor.newest_anchor_selection().head();
503 let ranges = editor.highlighted_ranges_for_type::<Self>()?.1;
504 if ranges.is_empty() {
505 None
506 } else {
507 let buffer = editor.buffer().read(cx).read(cx);
508 match ranges.binary_search_by(|probe| {
509 if probe.end.cmp(&position, &*buffer).unwrap().is_lt() {
510 Ordering::Less
511 } else if probe.start.cmp(&position, &*buffer).unwrap().is_gt() {
512 Ordering::Greater
513 } else {
514 Ordering::Equal
515 }
516 }) {
517 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
518 }
519 }
520 }
521}
522
523const YIELD_INTERVAL: usize = 20000;
524
525async fn search(
526 buffer: MultiBufferSnapshot,
527 query: String,
528 case_sensitive: bool,
529 whole_word: bool,
530) -> Vec<Range<Anchor>> {
531 let mut ranges = Vec::new();
532
533 let search = AhoCorasickBuilder::new()
534 .auto_configure(&[&query])
535 .ascii_case_insensitive(!case_sensitive)
536 .build(&[&query]);
537 for (ix, mat) in search
538 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()))
539 .enumerate()
540 {
541 if (ix + 1) % YIELD_INTERVAL == 0 {
542 yield_now().await;
543 }
544
545 let mat = mat.unwrap();
546
547 if whole_word {
548 let prev_kind = buffer.reversed_chars_at(mat.start()).next().map(char_kind);
549 let start_kind = char_kind(buffer.chars_at(mat.start()).next().unwrap());
550 let end_kind = char_kind(buffer.reversed_chars_at(mat.end()).next().unwrap());
551 let next_kind = buffer.chars_at(mat.end()).next().map(char_kind);
552 if Some(start_kind) == prev_kind || Some(end_kind) == next_kind {
553 continue;
554 }
555 }
556
557 ranges.push(buffer.anchor_after(mat.start())..buffer.anchor_before(mat.end()));
558 }
559
560 ranges
561}
562
563async fn regex_search(
564 buffer: MultiBufferSnapshot,
565 mut query: String,
566 case_sensitive: bool,
567 whole_word: bool,
568) -> Result<Vec<Range<Anchor>>> {
569 if whole_word {
570 let mut word_query = String::new();
571 word_query.push_str("\\b");
572 word_query.push_str(&query);
573 word_query.push_str("\\b");
574 query = word_query;
575 }
576
577 let mut ranges = Vec::new();
578
579 if query.contains("\n") || query.contains("\\n") {
580 let regex = RegexBuilder::new(&query)
581 .case_insensitive(!case_sensitive)
582 .multi_line(true)
583 .build()?;
584 for (ix, mat) in regex.find_iter(&buffer.text()).enumerate() {
585 if (ix + 1) % YIELD_INTERVAL == 0 {
586 yield_now().await;
587 }
588
589 ranges.push(buffer.anchor_after(mat.start())..buffer.anchor_before(mat.end()));
590 }
591 } else {
592 let regex = RegexBuilder::new(&query)
593 .case_insensitive(!case_sensitive)
594 .build()?;
595
596 let mut line = String::new();
597 let mut line_offset = 0;
598 for (chunk_ix, chunk) in buffer
599 .chunks(0..buffer.len(), false)
600 .map(|c| c.text)
601 .chain(["\n"])
602 .enumerate()
603 {
604 if (chunk_ix + 1) % YIELD_INTERVAL == 0 {
605 yield_now().await;
606 }
607
608 for (newline_ix, text) in chunk.split('\n').enumerate() {
609 if newline_ix > 0 {
610 for mat in regex.find_iter(&line) {
611 let start = line_offset + mat.start();
612 let end = line_offset + mat.end();
613 ranges.push(buffer.anchor_after(start)..buffer.anchor_before(end));
614 }
615
616 line_offset += line.len() + 1;
617 line.clear();
618 }
619 line.push_str(text);
620 }
621 }
622 }
623
624 Ok(ranges)
625}
626
627#[cfg(test)]
628mod tests {
629 use super::*;
630 use editor::{DisplayPoint, Editor, EditorSettings, MultiBuffer};
631 use gpui::{color::Color, TestAppContext};
632 use std::sync::Arc;
633 use unindent::Unindent as _;
634
635 #[gpui::test]
636 async fn test_find_simple(mut cx: TestAppContext) {
637 let fonts = cx.font_cache();
638 let mut theme = gpui::fonts::with_font_cache(fonts.clone(), || theme::Theme::default());
639 theme.find.match_background = Color::red();
640 let settings = Settings::new("Courier", &fonts, Arc::new(theme)).unwrap();
641
642 let buffer = cx.update(|cx| {
643 MultiBuffer::build_simple(
644 &r#"
645 A regular expression (shortened as regex or regexp;[1] also referred to as
646 rational expression[2][3]) is a sequence of characters that specifies a search
647 pattern in text. Usually such patterns are used by string-searching algorithms
648 for "find" or "find and replace" operations on strings, or for input validation.
649 "#
650 .unindent(),
651 cx,
652 )
653 });
654 let editor = cx.add_view(Default::default(), |cx| {
655 Editor::new(buffer.clone(), Arc::new(EditorSettings::test), None, cx)
656 });
657
658 let find_bar = cx.add_view(Default::default(), |cx| {
659 let mut find_bar = FindBar::new(watch::channel_with(settings).1, cx);
660 find_bar.active_item_changed(Some(Box::new(editor.clone())), cx);
661 find_bar
662 });
663
664 // Search for a string that appears with different casing.
665 // By default, search is case-insensitive.
666 find_bar.update(&mut cx, |find_bar, cx| {
667 find_bar.set_query("us", cx);
668 });
669 editor.next_notification(&cx).await;
670 editor.update(&mut cx, |editor, cx| {
671 assert_eq!(
672 editor.all_highlighted_ranges(cx),
673 &[
674 (
675 DisplayPoint::new(2, 17)..DisplayPoint::new(2, 19),
676 Color::red(),
677 ),
678 (
679 DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
680 Color::red(),
681 ),
682 ]
683 );
684 });
685
686 // Switch to a case sensitive search.
687 find_bar.update(&mut cx, |find_bar, cx| {
688 find_bar.toggle_mode(&ToggleMode(SearchMode::CaseSensitive), cx);
689 });
690 editor.next_notification(&cx).await;
691 editor.update(&mut cx, |editor, cx| {
692 assert_eq!(
693 editor.all_highlighted_ranges(cx),
694 &[(
695 DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
696 Color::red(),
697 )]
698 );
699 });
700
701 // Search for a string that appears both as a whole word and
702 // within other words. By default, all results are found.
703 find_bar.update(&mut cx, |find_bar, cx| {
704 find_bar.set_query("or", cx);
705 });
706 editor.next_notification(&cx).await;
707 editor.update(&mut cx, |editor, cx| {
708 assert_eq!(
709 editor.all_highlighted_ranges(cx),
710 &[
711 (
712 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 26),
713 Color::red(),
714 ),
715 (
716 DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
717 Color::red(),
718 ),
719 (
720 DisplayPoint::new(2, 71)..DisplayPoint::new(2, 73),
721 Color::red(),
722 ),
723 (
724 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 3),
725 Color::red(),
726 ),
727 (
728 DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
729 Color::red(),
730 ),
731 (
732 DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
733 Color::red(),
734 ),
735 (
736 DisplayPoint::new(3, 60)..DisplayPoint::new(3, 62),
737 Color::red(),
738 ),
739 ]
740 );
741 });
742
743 // Switch to a whole word search.
744 find_bar.update(&mut cx, |find_bar, cx| {
745 find_bar.toggle_mode(&ToggleMode(SearchMode::WholeWord), cx);
746 });
747 editor.next_notification(&cx).await;
748 editor.update(&mut cx, |editor, cx| {
749 assert_eq!(
750 editor.all_highlighted_ranges(cx),
751 &[
752 (
753 DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
754 Color::red(),
755 ),
756 (
757 DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
758 Color::red(),
759 ),
760 (
761 DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
762 Color::red(),
763 ),
764 ]
765 );
766 });
767
768 editor.update(&mut cx, |editor, cx| {
769 editor.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
770 });
771 find_bar.update(&mut cx, |find_bar, cx| {
772 assert_eq!(find_bar.active_match_index, Some(0));
773 find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
774 assert_eq!(
775 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
776 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
777 );
778 });
779 find_bar.read_with(&cx, |find_bar, _| {
780 assert_eq!(find_bar.active_match_index, Some(0));
781 });
782
783 find_bar.update(&mut cx, |find_bar, cx| {
784 find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
785 assert_eq!(
786 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
787 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
788 );
789 });
790 find_bar.read_with(&cx, |find_bar, _| {
791 assert_eq!(find_bar.active_match_index, Some(1));
792 });
793
794 find_bar.update(&mut cx, |find_bar, cx| {
795 find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
796 assert_eq!(
797 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
798 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
799 );
800 });
801 find_bar.read_with(&cx, |find_bar, _| {
802 assert_eq!(find_bar.active_match_index, Some(2));
803 });
804
805 find_bar.update(&mut cx, |find_bar, cx| {
806 find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
807 assert_eq!(
808 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
809 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
810 );
811 });
812 find_bar.read_with(&cx, |find_bar, _| {
813 assert_eq!(find_bar.active_match_index, Some(0));
814 });
815
816 find_bar.update(&mut cx, |find_bar, cx| {
817 find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
818 assert_eq!(
819 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
820 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
821 );
822 });
823 find_bar.read_with(&cx, |find_bar, _| {
824 assert_eq!(find_bar.active_match_index, Some(2));
825 });
826
827 find_bar.update(&mut cx, |find_bar, cx| {
828 find_bar.go_to_match(&GoToMatch(Direction::Prev), 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 find_bar.read_with(&cx, |find_bar, _| {
835 assert_eq!(find_bar.active_match_index, Some(1));
836 });
837
838 find_bar.update(&mut cx, |find_bar, cx| {
839 find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
840 assert_eq!(
841 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
842 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
843 );
844 });
845 find_bar.read_with(&cx, |find_bar, _| {
846 assert_eq!(find_bar.active_match_index, Some(0));
847 });
848
849 // Park the cursor in between matches and ensure that going to the previous match selects
850 // the closest match to the left.
851 editor.update(&mut cx, |editor, cx| {
852 editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
853 });
854 find_bar.update(&mut cx, |find_bar, cx| {
855 assert_eq!(find_bar.active_match_index, Some(1));
856 find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
857 assert_eq!(
858 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
859 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
860 );
861 });
862 find_bar.read_with(&cx, |find_bar, _| {
863 assert_eq!(find_bar.active_match_index, Some(0));
864 });
865
866 // Park the cursor in between matches and ensure that going to the next match selects the
867 // closest match to the right.
868 editor.update(&mut cx, |editor, cx| {
869 editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
870 });
871 find_bar.update(&mut cx, |find_bar, cx| {
872 assert_eq!(find_bar.active_match_index, Some(1));
873 find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
874 assert_eq!(
875 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
876 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
877 );
878 });
879 find_bar.read_with(&cx, |find_bar, _| {
880 assert_eq!(find_bar.active_match_index, Some(1));
881 });
882
883 // Park the cursor after the last match and ensure that going to the previous match selects
884 // the last match.
885 editor.update(&mut cx, |editor, cx| {
886 editor.select_display_ranges(&[DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)], cx);
887 });
888 find_bar.update(&mut cx, |find_bar, cx| {
889 assert_eq!(find_bar.active_match_index, Some(2));
890 find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
891 assert_eq!(
892 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
893 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
894 );
895 });
896 find_bar.read_with(&cx, |find_bar, _| {
897 assert_eq!(find_bar.active_match_index, Some(2));
898 });
899
900 // Park the cursor after the last match and ensure that going to the next match selects the
901 // first match.
902 editor.update(&mut cx, |editor, cx| {
903 editor.select_display_ranges(&[DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)], cx);
904 });
905 find_bar.update(&mut cx, |find_bar, cx| {
906 assert_eq!(find_bar.active_match_index, Some(2));
907 find_bar.go_to_match(&GoToMatch(Direction::Next), cx);
908 assert_eq!(
909 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
910 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
911 );
912 });
913 find_bar.read_with(&cx, |find_bar, _| {
914 assert_eq!(find_bar.active_match_index, Some(0));
915 });
916
917 // Park the cursor before the first match and ensure that going to the previous match
918 // selects the last match.
919 editor.update(&mut cx, |editor, cx| {
920 editor.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
921 });
922 find_bar.update(&mut cx, |find_bar, cx| {
923 assert_eq!(find_bar.active_match_index, Some(0));
924 find_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
925 assert_eq!(
926 editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
927 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
928 );
929 });
930 find_bar.read_with(&cx, |find_bar, _| {
931 assert_eq!(find_bar.active_match_index, Some(2));
932 });
933 }
934}