1use aho_corasick::AhoCorasickBuilder;
2use anyhow::Result;
3use collections::HashMap;
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 editors_with_matches: HashMap<WeakViewHandle<Editor>, Vec<Range<Anchor>>>,
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 dismissed: bool,
73}
74
75impl Entity for FindBar {
76 type Event = ();
77}
78
79impl View for FindBar {
80 fn ui_name() -> &'static str {
81 "FindBar"
82 }
83
84 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
85 cx.focus(&self.query_editor);
86 }
87
88 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
89 let theme = &self.settings.borrow().theme;
90 let editor_container = if self.query_contains_error {
91 theme.find.invalid_editor
92 } else {
93 theme.find.editor.input.container
94 };
95 Flex::row()
96 .with_child(
97 ChildView::new(&self.query_editor)
98 .contained()
99 .with_style(editor_container)
100 .aligned()
101 .constrained()
102 .with_max_width(theme.find.editor.max_width)
103 .boxed(),
104 )
105 .with_child(
106 Flex::row()
107 .with_child(self.render_mode_button("Case", SearchMode::CaseSensitive, cx))
108 .with_child(self.render_mode_button("Word", SearchMode::WholeWord, cx))
109 .with_child(self.render_mode_button("Regex", SearchMode::Regex, cx))
110 .contained()
111 .with_style(theme.find.mode_button_group)
112 .aligned()
113 .boxed(),
114 )
115 .with_child(
116 Flex::row()
117 .with_child(self.render_nav_button("<", Direction::Prev, cx))
118 .with_child(self.render_nav_button(">", Direction::Next, cx))
119 .aligned()
120 .boxed(),
121 )
122 .with_children(self.active_editor.as_ref().and_then(|editor| {
123 let matches = self.editors_with_matches.get(&editor.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.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.dismissed = true;
169 for (editor, _) in &self.editors_with_matches {
170 if let Some(editor) = editor.upgrade(cx) {
171 editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
172 }
173 }
174 }
175}
176
177impl FindBar {
178 fn new(settings: watch::Receiver<Settings>, cx: &mut ViewContext<Self>) -> Self {
179 let query_editor = cx.add_view(|cx| {
180 Editor::auto_height(
181 2,
182 {
183 let settings = settings.clone();
184 Arc::new(move |_| {
185 let settings = settings.borrow();
186 EditorSettings {
187 style: settings.theme.find.editor.input.as_editor(),
188 tab_size: settings.tab_size,
189 soft_wrap: editor::SoftWrap::None,
190 }
191 })
192 },
193 cx,
194 )
195 });
196 cx.subscribe(&query_editor, Self::on_query_editor_event)
197 .detach();
198
199 Self {
200 query_editor,
201 active_editor: None,
202 active_editor_subscription: None,
203 active_match_index: None,
204 editors_with_matches: Default::default(),
205 case_sensitive_mode: false,
206 whole_word_mode: false,
207 regex_mode: false,
208 settings,
209 pending_search: None,
210 query_contains_error: false,
211 dismissed: false,
212 }
213 }
214
215 fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
216 self.query_editor.update(cx, |query_editor, cx| {
217 query_editor.buffer().update(cx, |query_buffer, cx| {
218 let len = query_buffer.read(cx).len();
219 query_buffer.edit([0..len], query, cx);
220 });
221 });
222 }
223
224 fn render_mode_button(
225 &self,
226 icon: &str,
227 mode: SearchMode,
228 cx: &mut RenderContext<Self>,
229 ) -> ElementBox {
230 let theme = &self.settings.borrow().theme.find;
231 let is_active = self.is_mode_enabled(mode);
232 MouseEventHandler::new::<Self, _, _>(mode as usize, cx, |state, _| {
233 let style = match (is_active, state.hovered) {
234 (false, false) => &theme.mode_button,
235 (false, true) => &theme.hovered_mode_button,
236 (true, false) => &theme.active_mode_button,
237 (true, true) => &theme.active_hovered_mode_button,
238 };
239 Label::new(icon.to_string(), style.text.clone())
240 .contained()
241 .with_style(style.container)
242 .boxed()
243 })
244 .on_click(move |cx| cx.dispatch_action(ToggleMode(mode)))
245 .with_cursor_style(CursorStyle::PointingHand)
246 .boxed()
247 }
248
249 fn render_nav_button(
250 &self,
251 icon: &str,
252 direction: Direction,
253 cx: &mut RenderContext<Self>,
254 ) -> ElementBox {
255 let theme = &self.settings.borrow().theme.find;
256 enum NavButton {}
257 MouseEventHandler::new::<NavButton, _, _>(direction as usize, cx, |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 .on_click(move |cx| cx.dispatch_action(GoToMatch(direction)))
269 .with_cursor_style(CursorStyle::PointingHand)
270 .boxed()
271 }
272
273 fn deploy(workspace: &mut Workspace, Deploy(focus): &Deploy, cx: &mut ViewContext<Workspace>) {
274 let settings = workspace.settings();
275 workspace.active_pane().update(cx, |pane, cx| {
276 pane.show_toolbar(cx, |cx| FindBar::new(settings, cx));
277
278 if let Some(find_bar) = pane
279 .active_toolbar()
280 .and_then(|toolbar| toolbar.downcast::<Self>())
281 {
282 find_bar.update(cx, |find_bar, _| find_bar.dismissed = false);
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) = self.editors_with_matches.get(&cx.weak_handle()) {
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.editors_with_matches.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.editors_with_matches
470 .insert(editor.downgrade(), ranges.clone());
471 if !this.dismissed {
472 editor.update(cx, |editor, cx| {
473 let theme = &this.settings.borrow().theme.find;
474 editor.highlight_ranges::<Self>(
475 ranges,
476 theme.match_background,
477 cx,
478 )
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 ranges = self.editors_with_matches.get(&editor.downgrade())?;
505 let editor = editor.read(cx);
506 let position = editor.newest_anchor_selection().head();
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), None, 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}