1use crate::{
2 history::SearchHistory,
3 mode::{next_mode, SearchMode},
4 search_bar::{render_nav_button, render_search_mode_button},
5 ActivateRegexMode, ActivateTextMode, CycleMode, NextHistoryQuery, PreviousHistoryQuery,
6 ReplaceAll, ReplaceNext, SearchOptions, SelectAllMatches, SelectNextMatch, SelectPrevMatch,
7 ToggleCaseSensitive, ToggleReplace, ToggleWholeWord,
8};
9use collections::HashMap;
10use editor::{Editor, EditorMode};
11use futures::channel::oneshot;
12use gpui::{
13 actions, div, red, Action, AppContext, Div, EventEmitter, FocusableView,
14 InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled, Subscription, Task,
15 View, ViewContext, VisualContext as _, WeakView, WindowContext,
16};
17use project::search::SearchQuery;
18use serde::Deserialize;
19use std::{any::Any, sync::Arc};
20
21use ui::{h_stack, Icon, IconButton, IconElement};
22use util::ResultExt;
23use workspace::{
24 item::ItemHandle,
25 searchable::{Direction, SearchEvent, SearchableItemHandle, WeakSearchableItemHandle},
26 ToolbarItemLocation, ToolbarItemView,
27};
28
29#[derive(PartialEq, Clone, Deserialize, Default, Action)]
30pub struct Deploy {
31 pub focus: bool,
32}
33
34actions!(Dismiss, FocusEditor);
35
36pub enum Event {
37 UpdateLocation,
38}
39
40pub fn init(cx: &mut AppContext) {
41 cx.observe_new_views(|editor: &mut Editor, cx| BufferSearchBar::register(editor, cx))
42 .detach();
43}
44
45pub struct BufferSearchBar {
46 query_editor: View<Editor>,
47 replacement_editor: View<Editor>,
48 active_searchable_item: Option<Box<dyn SearchableItemHandle>>,
49 active_match_index: Option<usize>,
50 active_searchable_item_subscription: Option<Subscription>,
51 active_search: Option<Arc<SearchQuery>>,
52 searchable_items_with_matches:
53 HashMap<Box<dyn WeakSearchableItemHandle>, Vec<Box<dyn Any + Send>>>,
54 pending_search: Option<Task<()>>,
55 search_options: SearchOptions,
56 default_options: SearchOptions,
57 query_contains_error: bool,
58 dismissed: bool,
59 search_history: SearchHistory,
60 current_mode: SearchMode,
61 replace_enabled: bool,
62}
63
64impl EventEmitter<Event> for BufferSearchBar {}
65impl EventEmitter<workspace::ToolbarItemEvent> for BufferSearchBar {}
66impl Render for BufferSearchBar {
67 type Element = Div;
68 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
69 // let query_container_style = if self.query_contains_error {
70 // theme.search.invalid_editor
71 // } else {
72 // theme.search.editor.input.container
73 // };
74 if self.dismissed {
75 return div();
76 }
77 let supported_options = self.supported_options();
78
79 let previous_query_keystrokes = cx
80 .bindings_for_action(&PreviousHistoryQuery {})
81 .into_iter()
82 .next()
83 .map(|binding| {
84 binding
85 .keystrokes()
86 .iter()
87 .map(|k| k.to_string())
88 .collect::<Vec<_>>()
89 });
90 let next_query_keystrokes = cx
91 .bindings_for_action(&NextHistoryQuery {})
92 .into_iter()
93 .next()
94 .map(|binding| {
95 binding
96 .keystrokes()
97 .iter()
98 .map(|k| k.to_string())
99 .collect::<Vec<_>>()
100 });
101 let new_placeholder_text = match (previous_query_keystrokes, next_query_keystrokes) {
102 (Some(previous_query_keystrokes), Some(next_query_keystrokes)) => {
103 format!(
104 "Search ({}/{} for previous/next query)",
105 previous_query_keystrokes.join(" "),
106 next_query_keystrokes.join(" ")
107 )
108 }
109 (None, Some(next_query_keystrokes)) => {
110 format!(
111 "Search ({} for next query)",
112 next_query_keystrokes.join(" ")
113 )
114 }
115 (Some(previous_query_keystrokes), None) => {
116 format!(
117 "Search ({} for previous query)",
118 previous_query_keystrokes.join(" ")
119 )
120 }
121 (None, None) => String::new(),
122 };
123 let new_placeholder_text = Arc::from(new_placeholder_text);
124 self.query_editor.update(cx, |editor, cx| {
125 editor.set_placeholder_text(new_placeholder_text, cx);
126 });
127 self.replacement_editor.update(cx, |editor, cx| {
128 editor.set_placeholder_text("Replace with...", cx);
129 });
130
131 let search_button_for_mode = |mode| {
132 let is_active = self.current_mode == mode;
133
134 render_search_mode_button(
135 mode,
136 is_active,
137 cx.listener(move |this, _, cx| {
138 this.activate_search_mode(mode, cx);
139 }),
140 )
141 };
142 let search_option_button = |option| {
143 let is_active = self.search_options.contains(option);
144 option.as_button(is_active)
145 };
146 let match_count = self
147 .active_searchable_item
148 .as_ref()
149 .and_then(|searchable_item| {
150 if self.query(cx).is_empty() {
151 return None;
152 }
153 let matches = self
154 .searchable_items_with_matches
155 .get(&searchable_item.downgrade())?;
156 let message = if let Some(match_ix) = self.active_match_index {
157 format!("{}/{}", match_ix + 1, matches.len())
158 } else {
159 "No matches".to_string()
160 };
161
162 Some(ui::Label::new(message))
163 });
164 let nav_button_for_direction = |icon, direction| {
165 render_nav_button(
166 icon,
167 self.active_match_index.is_some(),
168 cx.listener(move |this, _, cx| match direction {
169 Direction::Prev => this.select_prev_match(&Default::default(), cx),
170 Direction::Next => this.select_next_match(&Default::default(), cx),
171 }),
172 )
173 };
174 let should_show_replace_input = self.replace_enabled && supported_options.replacement;
175 let replace_all = should_show_replace_input
176 .then(|| super::render_replace_button(ReplaceAll, ui::Icon::ReplaceAll));
177 let replace_next = should_show_replace_input
178 .then(|| super::render_replace_button(ReplaceNext, ui::Icon::Replace));
179 let in_replace = self.replacement_editor.focus_handle(cx).is_focused(cx);
180
181 h_stack()
182 .key_context("BufferSearchBar")
183 .when(in_replace, |this| {
184 this.key_context("in_replace")
185 .on_action(cx.listener(Self::replace_next))
186 .on_action(cx.listener(Self::replace_all))
187 })
188 .on_action(cx.listener(Self::previous_history_query))
189 .on_action(cx.listener(Self::next_history_query))
190 .on_action(cx.listener(Self::dismiss))
191 .w_full()
192 .p_1()
193 .child(
194 div()
195 .flex()
196 .flex_1()
197 .border_1()
198 .border_color(red())
199 .rounded_md()
200 .items_center()
201 .child(IconElement::new(Icon::MagnifyingGlass))
202 .child(self.query_editor.clone())
203 .children(
204 supported_options
205 .case
206 .then(|| search_option_button(SearchOptions::CASE_SENSITIVE)),
207 )
208 .children(
209 supported_options
210 .word
211 .then(|| search_option_button(SearchOptions::WHOLE_WORD)),
212 ),
213 )
214 .child(
215 h_stack()
216 .flex_none()
217 .child(
218 h_stack()
219 .child(search_button_for_mode(SearchMode::Text))
220 .child(search_button_for_mode(SearchMode::Regex)),
221 )
222 .when(supported_options.replacement, |this| {
223 this.child(super::toggle_replace_button(self.replace_enabled))
224 }),
225 )
226 .child(
227 h_stack()
228 .gap_0p5()
229 .flex_1()
230 .when(self.replace_enabled, |this| {
231 this.child(self.replacement_editor.clone())
232 .children(replace_next)
233 .children(replace_all)
234 }),
235 )
236 .child(
237 h_stack()
238 .gap_0p5()
239 .flex_none()
240 .child(self.render_action_button())
241 .children(match_count)
242 .child(nav_button_for_direction(
243 ui::Icon::ChevronLeft,
244 Direction::Prev,
245 ))
246 .child(nav_button_for_direction(
247 ui::Icon::ChevronRight,
248 Direction::Next,
249 )),
250 )
251 }
252}
253
254impl FocusableView for BufferSearchBar {
255 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
256 self.query_editor.focus_handle(cx)
257 }
258}
259
260impl ToolbarItemView for BufferSearchBar {
261 fn set_active_pane_item(
262 &mut self,
263 item: Option<&dyn ItemHandle>,
264 cx: &mut ViewContext<Self>,
265 ) -> ToolbarItemLocation {
266 cx.notify();
267 self.active_searchable_item_subscription.take();
268 self.active_searchable_item.take();
269
270 self.pending_search.take();
271
272 if let Some(searchable_item_handle) =
273 item.and_then(|item| item.to_searchable_item_handle(cx))
274 {
275 let this = cx.view().downgrade();
276
277 searchable_item_handle
278 .subscribe_to_search_events(
279 cx,
280 Box::new(move |search_event, cx| {
281 if let Some(this) = this.upgrade() {
282 this.update(cx, |this, cx| {
283 this.on_active_searchable_item_event(search_event, cx)
284 });
285 }
286 }),
287 )
288 .detach();
289
290 self.active_searchable_item = Some(searchable_item_handle);
291 let _ = self.update_matches(cx);
292 if !self.dismissed {
293 return ToolbarItemLocation::Secondary;
294 }
295 }
296 ToolbarItemLocation::Hidden
297 }
298
299 fn row_count(&self, _: &WindowContext<'_>) -> usize {
300 1
301 }
302}
303
304impl BufferSearchBar {
305 pub fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
306 if editor.mode() != EditorMode::Full {
307 return;
308 };
309
310 let handle = cx.view().downgrade();
311
312 editor.register_action(move |a: &Deploy, cx| {
313 let Some(pane) = handle.upgrade().and_then(|editor| editor.read(cx).pane(cx)) else {
314 return;
315 };
316
317 pane.update(cx, |this, cx| {
318 this.toolbar().update(cx, |this, cx| {
319 if let Some(search_bar) = this.item_of_type::<BufferSearchBar>() {
320 search_bar.update(cx, |this, cx| {
321 if this.is_dismissed() {
322 this.show(cx);
323 } else {
324 this.dismiss(&Dismiss, cx);
325 }
326 });
327 return;
328 }
329 let view = cx.build_view(|cx| BufferSearchBar::new(cx));
330 this.add_item(view.clone(), cx);
331 view.update(cx, |this, cx| this.deploy(a, cx));
332 cx.notify();
333 })
334 });
335 });
336 fn register_action<A: Action>(
337 editor: &mut Editor,
338 handle: WeakView<Editor>,
339 update: fn(&mut BufferSearchBar, &A, &mut ViewContext<BufferSearchBar>),
340 ) {
341 editor.register_action(move |action: &A, cx| {
342 let Some(pane) = handle.upgrade().and_then(|editor| editor.read(cx).pane(cx))
343 else {
344 return;
345 };
346 pane.update(cx, move |this, cx| {
347 this.toolbar().update(cx, move |this, cx| {
348 if let Some(search_bar) = this.item_of_type::<BufferSearchBar>() {
349 search_bar.update(cx, move |this, cx| update(this, action, cx));
350 cx.notify();
351 }
352 })
353 });
354 });
355 }
356
357 let handle = cx.view().downgrade();
358 register_action(
359 editor,
360 handle.clone(),
361 |this, action: &ToggleCaseSensitive, cx| {
362 if this.supported_options().case {
363 this.toggle_case_sensitive(action, cx);
364 }
365 },
366 );
367 register_action(
368 editor,
369 handle.clone(),
370 |this, action: &ToggleWholeWord, cx| {
371 if this.supported_options().word {
372 this.toggle_whole_word(action, cx);
373 }
374 },
375 );
376 register_action(
377 editor,
378 handle.clone(),
379 |this, action: &ToggleReplace, cx| {
380 if this.supported_options().replacement {
381 this.toggle_replace(action, cx);
382 }
383 },
384 );
385 register_action(editor, handle.clone(), |this, _: &ActivateRegexMode, cx| {
386 if this.supported_options().regex {
387 this.activate_search_mode(SearchMode::Regex, cx);
388 }
389 });
390 register_action(editor, handle.clone(), |this, _: &ActivateTextMode, cx| {
391 this.activate_search_mode(SearchMode::Text, cx);
392 });
393 register_action(editor, handle.clone(), |this, action: &CycleMode, cx| {
394 if this.supported_options().regex {
395 // If regex is not supported then search has just one mode (text) - in that case there's no point in supporting
396 // cycling.
397 this.cycle_mode(action, cx)
398 }
399 });
400 register_action(
401 editor,
402 handle.clone(),
403 |this, action: &SelectNextMatch, cx| {
404 this.select_next_match(action, cx);
405 },
406 );
407 register_action(
408 editor,
409 handle.clone(),
410 |this, action: &SelectPrevMatch, cx| {
411 this.select_prev_match(action, cx);
412 },
413 );
414 register_action(
415 editor,
416 handle.clone(),
417 |this, action: &SelectAllMatches, cx| {
418 this.select_all_matches(action, cx);
419 },
420 );
421 register_action(editor, handle.clone(), |this, _: &editor::Cancel, cx| {
422 if !this.dismissed {
423 this.dismiss(&Dismiss, cx);
424 return;
425 }
426 cx.propagate();
427 });
428 }
429 pub fn new(cx: &mut ViewContext<Self>) -> Self {
430 let query_editor = cx.build_view(|cx| Editor::single_line(cx));
431 cx.subscribe(&query_editor, Self::on_query_editor_event)
432 .detach();
433 let replacement_editor = cx.build_view(|cx| Editor::single_line(cx));
434 cx.subscribe(&replacement_editor, Self::on_query_editor_event)
435 .detach();
436 Self {
437 query_editor,
438 replacement_editor,
439 active_searchable_item: None,
440 active_searchable_item_subscription: None,
441 active_match_index: None,
442 searchable_items_with_matches: Default::default(),
443 default_options: SearchOptions::NONE,
444 search_options: SearchOptions::NONE,
445 pending_search: None,
446 query_contains_error: false,
447 dismissed: true,
448 search_history: SearchHistory::default(),
449 current_mode: SearchMode::default(),
450 active_search: None,
451 replace_enabled: false,
452 }
453 }
454
455 pub fn is_dismissed(&self) -> bool {
456 self.dismissed
457 }
458
459 pub fn dismiss(&mut self, _: &Dismiss, cx: &mut ViewContext<Self>) {
460 self.dismissed = true;
461 for searchable_item in self.searchable_items_with_matches.keys() {
462 if let Some(searchable_item) =
463 WeakSearchableItemHandle::upgrade(searchable_item.as_ref(), cx)
464 {
465 searchable_item.clear_matches(cx);
466 }
467 }
468 if let Some(active_editor) = self.active_searchable_item.as_ref() {
469 let handle = active_editor.focus_handle(cx);
470 cx.focus(&handle);
471 }
472 cx.emit(Event::UpdateLocation);
473 cx.notify();
474 }
475
476 pub fn deploy(&mut self, deploy: &Deploy, cx: &mut ViewContext<Self>) -> bool {
477 if self.show(cx) {
478 self.search_suggested(cx);
479 if deploy.focus {
480 self.select_query(cx);
481 let handle = cx.focus_handle();
482 cx.focus(&handle);
483 }
484 return true;
485 }
486
487 false
488 }
489
490 pub fn show(&mut self, cx: &mut ViewContext<Self>) -> bool {
491 if self.active_searchable_item.is_none() {
492 return false;
493 }
494 self.dismissed = false;
495 cx.notify();
496 cx.emit(Event::UpdateLocation);
497 true
498 }
499
500 fn supported_options(&self) -> workspace::searchable::SearchOptions {
501 self.active_searchable_item
502 .as_deref()
503 .map(SearchableItemHandle::supported_options)
504 .unwrap_or_default()
505 }
506 pub fn search_suggested(&mut self, cx: &mut ViewContext<Self>) {
507 let search = self
508 .query_suggestion(cx)
509 .map(|suggestion| self.search(&suggestion, Some(self.default_options), cx));
510
511 if let Some(search) = search {
512 cx.spawn(|this, mut cx| async move {
513 search.await?;
514 this.update(&mut cx, |this, cx| this.activate_current_match(cx))
515 })
516 .detach_and_log_err(cx);
517 }
518 }
519
520 pub fn activate_current_match(&mut self, cx: &mut ViewContext<Self>) {
521 if let Some(match_ix) = self.active_match_index {
522 if let Some(active_searchable_item) = self.active_searchable_item.as_ref() {
523 if let Some(matches) = self
524 .searchable_items_with_matches
525 .get(&active_searchable_item.downgrade())
526 {
527 active_searchable_item.activate_match(match_ix, matches, cx)
528 }
529 }
530 }
531 }
532
533 pub fn select_query(&mut self, cx: &mut ViewContext<Self>) {
534 self.query_editor.update(cx, |query_editor, cx| {
535 query_editor.select_all(&Default::default(), cx);
536 });
537 }
538
539 pub fn query(&self, cx: &WindowContext) -> String {
540 self.query_editor.read(cx).text(cx)
541 }
542 pub fn replacement(&self, cx: &WindowContext) -> String {
543 self.replacement_editor.read(cx).text(cx)
544 }
545 pub fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<String> {
546 self.active_searchable_item
547 .as_ref()
548 .map(|searchable_item| searchable_item.query_suggestion(cx))
549 .filter(|suggestion| !suggestion.is_empty())
550 }
551
552 pub fn set_replacement(&mut self, replacement: Option<&str>, cx: &mut ViewContext<Self>) {
553 if replacement.is_none() {
554 self.replace_enabled = false;
555 return;
556 }
557 self.replace_enabled = true;
558 self.replacement_editor
559 .update(cx, |replacement_editor, cx| {
560 replacement_editor
561 .buffer()
562 .update(cx, |replacement_buffer, cx| {
563 let len = replacement_buffer.len(cx);
564 replacement_buffer.edit([(0..len, replacement.unwrap())], None, cx);
565 });
566 });
567 }
568
569 pub fn search(
570 &mut self,
571 query: &str,
572 options: Option<SearchOptions>,
573 cx: &mut ViewContext<Self>,
574 ) -> oneshot::Receiver<()> {
575 let options = options.unwrap_or(self.default_options);
576 if query != self.query(cx) || self.search_options != options {
577 self.query_editor.update(cx, |query_editor, cx| {
578 query_editor.buffer().update(cx, |query_buffer, cx| {
579 let len = query_buffer.len(cx);
580 query_buffer.edit([(0..len, query)], None, cx);
581 });
582 });
583 self.search_options = options;
584 self.query_contains_error = false;
585 self.clear_matches(cx);
586 cx.notify();
587 }
588 self.update_matches(cx)
589 }
590
591 fn render_action_button(&self) -> impl IntoElement {
592 // let tooltip_style = theme.tooltip.clone();
593
594 // let style = theme.search.action_button.clone();
595
596 IconButton::new(0, ui::Icon::SelectAll).action(Box::new(SelectAllMatches))
597 }
598
599 pub fn activate_search_mode(&mut self, mode: SearchMode, cx: &mut ViewContext<Self>) {
600 assert_ne!(
601 mode,
602 SearchMode::Semantic,
603 "Semantic search is not supported in buffer search"
604 );
605 if mode == self.current_mode {
606 return;
607 }
608 self.current_mode = mode;
609 let _ = self.update_matches(cx);
610 cx.notify();
611 }
612
613 pub fn focus_editor(&mut self, _: &FocusEditor, cx: &mut ViewContext<Self>) {
614 if let Some(active_editor) = self.active_searchable_item.as_ref() {
615 let handle = active_editor.focus_handle(cx);
616 cx.focus(&handle);
617 }
618 }
619
620 fn toggle_search_option(&mut self, search_option: SearchOptions, cx: &mut ViewContext<Self>) {
621 self.search_options.toggle(search_option);
622 self.default_options = self.search_options;
623 let _ = self.update_matches(cx);
624 cx.notify();
625 }
626
627 pub fn set_search_options(
628 &mut self,
629 search_options: SearchOptions,
630 cx: &mut ViewContext<Self>,
631 ) {
632 self.search_options = search_options;
633 cx.notify();
634 }
635
636 fn select_next_match(&mut self, _: &SelectNextMatch, cx: &mut ViewContext<Self>) {
637 self.select_match(Direction::Next, 1, cx);
638 }
639
640 fn select_prev_match(&mut self, _: &SelectPrevMatch, cx: &mut ViewContext<Self>) {
641 self.select_match(Direction::Prev, 1, cx);
642 }
643
644 fn select_all_matches(&mut self, _: &SelectAllMatches, cx: &mut ViewContext<Self>) {
645 if !self.dismissed && self.active_match_index.is_some() {
646 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
647 if let Some(matches) = self
648 .searchable_items_with_matches
649 .get(&searchable_item.downgrade())
650 {
651 searchable_item.select_matches(matches, cx);
652 self.focus_editor(&FocusEditor, cx);
653 }
654 }
655 }
656 }
657
658 pub fn select_match(&mut self, direction: Direction, count: usize, cx: &mut ViewContext<Self>) {
659 if let Some(index) = self.active_match_index {
660 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
661 if let Some(matches) = self
662 .searchable_items_with_matches
663 .get(&searchable_item.downgrade())
664 {
665 let new_match_index = searchable_item
666 .match_index_for_direction(matches, index, direction, count, cx);
667
668 searchable_item.update_matches(matches, cx);
669 searchable_item.activate_match(new_match_index, matches, cx);
670 }
671 }
672 }
673 }
674
675 pub fn select_last_match(&mut self, cx: &mut ViewContext<Self>) {
676 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
677 if let Some(matches) = self
678 .searchable_items_with_matches
679 .get(&searchable_item.downgrade())
680 {
681 if matches.len() == 0 {
682 return;
683 }
684 let new_match_index = matches.len() - 1;
685 searchable_item.update_matches(matches, cx);
686 searchable_item.activate_match(new_match_index, matches, cx);
687 }
688 }
689 }
690
691 fn on_query_editor_event(
692 &mut self,
693 _: View<Editor>,
694 event: &editor::EditorEvent,
695 cx: &mut ViewContext<Self>,
696 ) {
697 if let editor::EditorEvent::Edited { .. } = event {
698 self.query_contains_error = false;
699 self.clear_matches(cx);
700 let search = self.update_matches(cx);
701 cx.spawn(|this, mut cx| async move {
702 search.await?;
703 this.update(&mut cx, |this, cx| this.activate_current_match(cx))
704 })
705 .detach_and_log_err(cx);
706 }
707 }
708
709 fn on_active_searchable_item_event(&mut self, event: &SearchEvent, cx: &mut ViewContext<Self>) {
710 match event {
711 SearchEvent::MatchesInvalidated => {
712 let _ = self.update_matches(cx);
713 }
714 SearchEvent::ActiveMatchChanged => self.update_match_index(cx),
715 }
716 }
717
718 fn toggle_case_sensitive(&mut self, _: &ToggleCaseSensitive, cx: &mut ViewContext<Self>) {
719 self.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx)
720 }
721 fn toggle_whole_word(&mut self, _: &ToggleWholeWord, cx: &mut ViewContext<Self>) {
722 self.toggle_search_option(SearchOptions::WHOLE_WORD, cx)
723 }
724 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
725 let mut active_item_matches = None;
726 for (searchable_item, matches) in self.searchable_items_with_matches.drain() {
727 if let Some(searchable_item) =
728 WeakSearchableItemHandle::upgrade(searchable_item.as_ref(), cx)
729 {
730 if Some(&searchable_item) == self.active_searchable_item.as_ref() {
731 active_item_matches = Some((searchable_item.downgrade(), matches));
732 } else {
733 searchable_item.clear_matches(cx);
734 }
735 }
736 }
737
738 self.searchable_items_with_matches
739 .extend(active_item_matches);
740 }
741
742 fn update_matches(&mut self, cx: &mut ViewContext<Self>) -> oneshot::Receiver<()> {
743 let (done_tx, done_rx) = oneshot::channel();
744 let query = self.query(cx);
745 self.pending_search.take();
746
747 if let Some(active_searchable_item) = self.active_searchable_item.as_ref() {
748 if query.is_empty() {
749 self.active_match_index.take();
750 active_searchable_item.clear_matches(cx);
751 let _ = done_tx.send(());
752 cx.notify();
753 } else {
754 let query: Arc<_> = if self.current_mode == SearchMode::Regex {
755 match SearchQuery::regex(
756 query,
757 self.search_options.contains(SearchOptions::WHOLE_WORD),
758 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
759 false,
760 Vec::new(),
761 Vec::new(),
762 ) {
763 Ok(query) => query.with_replacement(self.replacement(cx)),
764 Err(_) => {
765 self.query_contains_error = true;
766 cx.notify();
767 return done_rx;
768 }
769 }
770 } else {
771 match SearchQuery::text(
772 query,
773 self.search_options.contains(SearchOptions::WHOLE_WORD),
774 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
775 false,
776 Vec::new(),
777 Vec::new(),
778 ) {
779 Ok(query) => query.with_replacement(self.replacement(cx)),
780 Err(_) => {
781 self.query_contains_error = true;
782 cx.notify();
783 return done_rx;
784 }
785 }
786 }
787 .into();
788 self.active_search = Some(query.clone());
789 let query_text = query.as_str().to_string();
790
791 let matches = active_searchable_item.find_matches(query, cx);
792
793 let active_searchable_item = active_searchable_item.downgrade();
794 self.pending_search = Some(cx.spawn(|this, mut cx| async move {
795 let matches = matches.await;
796
797 this.update(&mut cx, |this, cx| {
798 if let Some(active_searchable_item) =
799 WeakSearchableItemHandle::upgrade(active_searchable_item.as_ref(), cx)
800 {
801 this.searchable_items_with_matches
802 .insert(active_searchable_item.downgrade(), matches);
803
804 this.update_match_index(cx);
805 this.search_history.add(query_text);
806 if !this.dismissed {
807 let matches = this
808 .searchable_items_with_matches
809 .get(&active_searchable_item.downgrade())
810 .unwrap();
811 active_searchable_item.update_matches(matches, cx);
812 let _ = done_tx.send(());
813 }
814 cx.notify();
815 }
816 })
817 .log_err();
818 }));
819 }
820 }
821 done_rx
822 }
823
824 fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
825 let new_index = self
826 .active_searchable_item
827 .as_ref()
828 .and_then(|searchable_item| {
829 let matches = self
830 .searchable_items_with_matches
831 .get(&searchable_item.downgrade())?;
832 searchable_item.active_match_index(matches, cx)
833 });
834 if new_index != self.active_match_index {
835 self.active_match_index = new_index;
836 cx.notify();
837 }
838 }
839
840 fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
841 if let Some(new_query) = self.search_history.next().map(str::to_string) {
842 let _ = self.search(&new_query, Some(self.search_options), cx);
843 } else {
844 self.search_history.reset_selection();
845 let _ = self.search("", Some(self.search_options), cx);
846 }
847 }
848
849 fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
850 if self.query(cx).is_empty() {
851 if let Some(new_query) = self.search_history.current().map(str::to_string) {
852 let _ = self.search(&new_query, Some(self.search_options), cx);
853 return;
854 }
855 }
856
857 if let Some(new_query) = self.search_history.previous().map(str::to_string) {
858 let _ = self.search(&new_query, Some(self.search_options), cx);
859 }
860 }
861 fn cycle_mode(&mut self, _: &CycleMode, cx: &mut ViewContext<Self>) {
862 self.activate_search_mode(next_mode(&self.current_mode, false), cx);
863 }
864 fn toggle_replace(&mut self, _: &ToggleReplace, cx: &mut ViewContext<Self>) {
865 if let Some(_) = &self.active_searchable_item {
866 self.replace_enabled = !self.replace_enabled;
867 if !self.replace_enabled {
868 let handle = self.query_editor.focus_handle(cx);
869 cx.focus(&handle);
870 }
871 cx.notify();
872 }
873 }
874 fn replace_next(&mut self, _: &ReplaceNext, cx: &mut ViewContext<Self>) {
875 let mut should_propagate = true;
876 if !self.dismissed && self.active_search.is_some() {
877 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
878 if let Some(query) = self.active_search.as_ref() {
879 if let Some(matches) = self
880 .searchable_items_with_matches
881 .get(&searchable_item.downgrade())
882 {
883 if let Some(active_index) = self.active_match_index {
884 let query = query
885 .as_ref()
886 .clone()
887 .with_replacement(self.replacement(cx));
888 searchable_item.replace(&matches[active_index], &query, cx);
889 self.select_next_match(&SelectNextMatch, cx);
890 }
891 should_propagate = false;
892 self.focus_editor(&FocusEditor, cx);
893 }
894 }
895 }
896 }
897 if !should_propagate {
898 cx.stop_propagation();
899 }
900 }
901 pub fn replace_all(&mut self, _: &ReplaceAll, cx: &mut ViewContext<Self>) {
902 if !self.dismissed && self.active_search.is_some() {
903 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
904 if let Some(query) = self.active_search.as_ref() {
905 if let Some(matches) = self
906 .searchable_items_with_matches
907 .get(&searchable_item.downgrade())
908 {
909 let query = query
910 .as_ref()
911 .clone()
912 .with_replacement(self.replacement(cx));
913 for m in matches {
914 searchable_item.replace(m, &query, cx);
915 }
916 }
917 }
918 }
919 }
920 }
921}
922
923#[cfg(test)]
924mod tests {
925 use std::ops::Range;
926
927 use super::*;
928 use editor::{DisplayPoint, Editor};
929 use gpui::{Context, EmptyView, Hsla, TestAppContext, VisualTestContext};
930 use language::Buffer;
931 use smol::stream::StreamExt as _;
932 use unindent::Unindent as _;
933
934 fn init_globals(cx: &mut TestAppContext) {
935 cx.update(|cx| {
936 let store = settings::SettingsStore::test(cx);
937 cx.set_global(store);
938 editor::init(cx);
939
940 language::init(cx);
941 theme::init(theme::LoadThemes::JustBase, cx);
942 });
943 }
944 fn init_test(
945 cx: &mut TestAppContext,
946 ) -> (
947 View<Editor>,
948 View<BufferSearchBar>,
949 &mut VisualTestContext<'_>,
950 ) {
951 init_globals(cx);
952 let buffer = cx.build_model(|cx| {
953 Buffer::new(
954 0,
955 cx.entity_id().as_u64(),
956 r#"
957 A regular expression (shortened as regex or regexp;[1] also referred to as
958 rational expression[2][3]) is a sequence of characters that specifies a search
959 pattern in text. Usually such patterns are used by string-searching algorithms
960 for "find" or "find and replace" operations on strings, or for input validation.
961 "#
962 .unindent(),
963 )
964 });
965 let (_, cx) = cx.add_window_view(|_| EmptyView {});
966 let editor = cx.build_view(|cx| Editor::for_buffer(buffer.clone(), None, cx));
967
968 let search_bar = cx.build_view(|cx| {
969 let mut search_bar = BufferSearchBar::new(cx);
970 search_bar.set_active_pane_item(Some(&editor), cx);
971 search_bar.show(cx);
972 search_bar
973 });
974
975 (editor, search_bar, cx)
976 }
977
978 #[gpui::test]
979 async fn test_search_simple(cx: &mut TestAppContext) {
980 let (editor, search_bar, cx) = init_test(cx);
981 // todo! osiewicz: these tests asserted on background color as well, that should be brought back.
982 let display_points_of = |background_highlights: Vec<(Range<DisplayPoint>, Hsla)>| {
983 background_highlights
984 .into_iter()
985 .map(|(range, _)| range)
986 .collect::<Vec<_>>()
987 };
988 // Search for a string that appears with different casing.
989 // By default, search is case-insensitive.
990 search_bar
991 .update(cx, |search_bar, cx| search_bar.search("us", None, cx))
992 .await
993 .unwrap();
994 editor.update(cx, |editor, cx| {
995 assert_eq!(
996 display_points_of(editor.all_text_background_highlights(cx)),
997 &[
998 DisplayPoint::new(2, 17)..DisplayPoint::new(2, 19),
999 DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
1000 ]
1001 );
1002 });
1003
1004 // Switch to a case sensitive search.
1005 search_bar.update(cx, |search_bar, cx| {
1006 search_bar.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
1007 });
1008 let mut editor_notifications = cx.notifications(&editor);
1009 editor_notifications.next().await;
1010 editor.update(cx, |editor, cx| {
1011 assert_eq!(
1012 display_points_of(editor.all_text_background_highlights(cx)),
1013 &[DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),]
1014 );
1015 });
1016
1017 // Search for a string that appears both as a whole word and
1018 // within other words. By default, all results are found.
1019 search_bar
1020 .update(cx, |search_bar, cx| search_bar.search("or", None, cx))
1021 .await
1022 .unwrap();
1023 editor.update(cx, |editor, cx| {
1024 assert_eq!(
1025 display_points_of(editor.all_text_background_highlights(cx)),
1026 &[
1027 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 26),
1028 DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
1029 DisplayPoint::new(2, 71)..DisplayPoint::new(2, 73),
1030 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 3),
1031 DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
1032 DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
1033 DisplayPoint::new(3, 60)..DisplayPoint::new(3, 62),
1034 ]
1035 );
1036 });
1037
1038 // Switch to a whole word search.
1039 search_bar.update(cx, |search_bar, cx| {
1040 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1041 });
1042 let mut editor_notifications = cx.notifications(&editor);
1043 editor_notifications.next().await;
1044 editor.update(cx, |editor, cx| {
1045 assert_eq!(
1046 display_points_of(editor.all_text_background_highlights(cx)),
1047 &[
1048 DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
1049 DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
1050 DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
1051 ]
1052 );
1053 });
1054
1055 editor.update(cx, |editor, cx| {
1056 editor.change_selections(None, cx, |s| {
1057 s.select_display_ranges([DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)])
1058 });
1059 });
1060 search_bar.update(cx, |search_bar, cx| {
1061 assert_eq!(search_bar.active_match_index, Some(0));
1062 search_bar.select_next_match(&SelectNextMatch, cx);
1063 assert_eq!(
1064 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1065 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1066 );
1067 });
1068 search_bar.update(cx, |search_bar, _| {
1069 assert_eq!(search_bar.active_match_index, Some(0));
1070 });
1071
1072 search_bar.update(cx, |search_bar, cx| {
1073 search_bar.select_next_match(&SelectNextMatch, cx);
1074 assert_eq!(
1075 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1076 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1077 );
1078 });
1079 search_bar.update(cx, |search_bar, _| {
1080 assert_eq!(search_bar.active_match_index, Some(1));
1081 });
1082
1083 search_bar.update(cx, |search_bar, cx| {
1084 search_bar.select_next_match(&SelectNextMatch, cx);
1085 assert_eq!(
1086 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1087 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1088 );
1089 });
1090 search_bar.update(cx, |search_bar, _| {
1091 assert_eq!(search_bar.active_match_index, Some(2));
1092 });
1093
1094 search_bar.update(cx, |search_bar, cx| {
1095 search_bar.select_next_match(&SelectNextMatch, cx);
1096 assert_eq!(
1097 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1098 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1099 );
1100 });
1101 search_bar.update(cx, |search_bar, _| {
1102 assert_eq!(search_bar.active_match_index, Some(0));
1103 });
1104
1105 search_bar.update(cx, |search_bar, cx| {
1106 search_bar.select_prev_match(&SelectPrevMatch, cx);
1107 assert_eq!(
1108 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1109 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1110 );
1111 });
1112 search_bar.update(cx, |search_bar, _| {
1113 assert_eq!(search_bar.active_match_index, Some(2));
1114 });
1115
1116 search_bar.update(cx, |search_bar, cx| {
1117 search_bar.select_prev_match(&SelectPrevMatch, cx);
1118 assert_eq!(
1119 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1120 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1121 );
1122 });
1123 search_bar.update(cx, |search_bar, _| {
1124 assert_eq!(search_bar.active_match_index, Some(1));
1125 });
1126
1127 search_bar.update(cx, |search_bar, cx| {
1128 search_bar.select_prev_match(&SelectPrevMatch, cx);
1129 assert_eq!(
1130 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1131 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1132 );
1133 });
1134 search_bar.update(cx, |search_bar, _| {
1135 assert_eq!(search_bar.active_match_index, Some(0));
1136 });
1137
1138 // Park the cursor in between matches and ensure that going to the previous match selects
1139 // the closest match to the left.
1140 editor.update(cx, |editor, cx| {
1141 editor.change_selections(None, cx, |s| {
1142 s.select_display_ranges([DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)])
1143 });
1144 });
1145 search_bar.update(cx, |search_bar, cx| {
1146 assert_eq!(search_bar.active_match_index, Some(1));
1147 search_bar.select_prev_match(&SelectPrevMatch, cx);
1148 assert_eq!(
1149 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1150 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1151 );
1152 });
1153 search_bar.update(cx, |search_bar, _| {
1154 assert_eq!(search_bar.active_match_index, Some(0));
1155 });
1156
1157 // Park the cursor in between matches and ensure that going to the next match selects the
1158 // closest match to the right.
1159 editor.update(cx, |editor, cx| {
1160 editor.change_selections(None, cx, |s| {
1161 s.select_display_ranges([DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)])
1162 });
1163 });
1164 search_bar.update(cx, |search_bar, cx| {
1165 assert_eq!(search_bar.active_match_index, Some(1));
1166 search_bar.select_next_match(&SelectNextMatch, cx);
1167 assert_eq!(
1168 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1169 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1170 );
1171 });
1172 search_bar.update(cx, |search_bar, _| {
1173 assert_eq!(search_bar.active_match_index, Some(1));
1174 });
1175
1176 // Park the cursor after the last match and ensure that going to the previous match selects
1177 // the last match.
1178 editor.update(cx, |editor, cx| {
1179 editor.change_selections(None, cx, |s| {
1180 s.select_display_ranges([DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)])
1181 });
1182 });
1183 search_bar.update(cx, |search_bar, cx| {
1184 assert_eq!(search_bar.active_match_index, Some(2));
1185 search_bar.select_prev_match(&SelectPrevMatch, cx);
1186 assert_eq!(
1187 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1188 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1189 );
1190 });
1191 search_bar.update(cx, |search_bar, _| {
1192 assert_eq!(search_bar.active_match_index, Some(2));
1193 });
1194
1195 // Park the cursor after the last match and ensure that going to the next match selects the
1196 // first match.
1197 editor.update(cx, |editor, cx| {
1198 editor.change_selections(None, cx, |s| {
1199 s.select_display_ranges([DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)])
1200 });
1201 });
1202 search_bar.update(cx, |search_bar, cx| {
1203 assert_eq!(search_bar.active_match_index, Some(2));
1204 search_bar.select_next_match(&SelectNextMatch, cx);
1205 assert_eq!(
1206 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1207 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1208 );
1209 });
1210 search_bar.update(cx, |search_bar, _| {
1211 assert_eq!(search_bar.active_match_index, Some(0));
1212 });
1213
1214 // Park the cursor before the first match and ensure that going to the previous match
1215 // selects the last match.
1216 editor.update(cx, |editor, cx| {
1217 editor.change_selections(None, cx, |s| {
1218 s.select_display_ranges([DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)])
1219 });
1220 });
1221 search_bar.update(cx, |search_bar, cx| {
1222 assert_eq!(search_bar.active_match_index, Some(0));
1223 search_bar.select_prev_match(&SelectPrevMatch, cx);
1224 assert_eq!(
1225 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1226 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1227 );
1228 });
1229 search_bar.update(cx, |search_bar, _| {
1230 assert_eq!(search_bar.active_match_index, Some(2));
1231 });
1232 }
1233
1234 #[gpui::test]
1235 async fn test_search_option_handling(cx: &mut TestAppContext) {
1236 let (editor, search_bar, cx) = init_test(cx);
1237
1238 // show with options should make current search case sensitive
1239 search_bar
1240 .update(cx, |search_bar, cx| {
1241 search_bar.show(cx);
1242 search_bar.search("us", Some(SearchOptions::CASE_SENSITIVE), cx)
1243 })
1244 .await
1245 .unwrap();
1246 // todo! osiewicz: these tests previously asserted on background color highlights; that should be introduced back.
1247 let display_points_of = |background_highlights: Vec<(Range<DisplayPoint>, Hsla)>| {
1248 background_highlights
1249 .into_iter()
1250 .map(|(range, _)| range)
1251 .collect::<Vec<_>>()
1252 };
1253 editor.update(cx, |editor, cx| {
1254 assert_eq!(
1255 display_points_of(editor.all_text_background_highlights(cx)),
1256 &[DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),]
1257 );
1258 });
1259
1260 // search_suggested should restore default options
1261 search_bar.update(cx, |search_bar, cx| {
1262 search_bar.search_suggested(cx);
1263 assert_eq!(search_bar.search_options, SearchOptions::NONE)
1264 });
1265
1266 // toggling a search option should update the defaults
1267 search_bar
1268 .update(cx, |search_bar, cx| {
1269 search_bar.search("regex", Some(SearchOptions::CASE_SENSITIVE), cx)
1270 })
1271 .await
1272 .unwrap();
1273 search_bar.update(cx, |search_bar, cx| {
1274 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, cx)
1275 });
1276 let mut editor_notifications = cx.notifications(&editor);
1277 editor_notifications.next().await;
1278 editor.update(cx, |editor, cx| {
1279 assert_eq!(
1280 display_points_of(editor.all_text_background_highlights(cx)),
1281 &[DisplayPoint::new(0, 35)..DisplayPoint::new(0, 40),]
1282 );
1283 });
1284
1285 // defaults should still include whole word
1286 search_bar.update(cx, |search_bar, cx| {
1287 search_bar.search_suggested(cx);
1288 assert_eq!(
1289 search_bar.search_options,
1290 SearchOptions::CASE_SENSITIVE | SearchOptions::WHOLE_WORD
1291 )
1292 });
1293 }
1294
1295 #[gpui::test]
1296 async fn test_search_select_all_matches(cx: &mut TestAppContext) {
1297 init_globals(cx);
1298 let buffer_text = r#"
1299 A regular expression (shortened as regex or regexp;[1] also referred to as
1300 rational expression[2][3]) is a sequence of characters that specifies a search
1301 pattern in text. Usually such patterns are used by string-searching algorithms
1302 for "find" or "find and replace" operations on strings, or for input validation.
1303 "#
1304 .unindent();
1305 let expected_query_matches_count = buffer_text
1306 .chars()
1307 .filter(|c| c.to_ascii_lowercase() == 'a')
1308 .count();
1309 assert!(
1310 expected_query_matches_count > 1,
1311 "Should pick a query with multiple results"
1312 );
1313 let buffer = cx.build_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), buffer_text));
1314 let window = cx.add_window(|_| EmptyView {});
1315
1316 let editor = window.build_view(cx, |cx| Editor::for_buffer(buffer.clone(), None, cx));
1317
1318 let search_bar = window.build_view(cx, |cx| {
1319 let mut search_bar = BufferSearchBar::new(cx);
1320 search_bar.set_active_pane_item(Some(&editor), cx);
1321 search_bar.show(cx);
1322 search_bar
1323 });
1324
1325 window
1326 .update(cx, |_, cx| {
1327 search_bar.update(cx, |search_bar, cx| search_bar.search("a", None, cx))
1328 })
1329 .unwrap()
1330 .await
1331 .unwrap();
1332 let initial_selections = window
1333 .update(cx, |_, cx| {
1334 search_bar.update(cx, |search_bar, cx| {
1335 let handle = search_bar.query_editor.focus_handle(cx);
1336 cx.focus(&handle);
1337 search_bar.activate_current_match(cx);
1338 });
1339 assert!(
1340 !editor.read(cx).is_focused(cx),
1341 "Initially, the editor should not be focused"
1342 );
1343 let initial_selections = editor.update(cx, |editor, cx| {
1344 let initial_selections = editor.selections.display_ranges(cx);
1345 assert_eq!(
1346 initial_selections.len(), 1,
1347 "Expected to have only one selection before adding carets to all matches, but got: {initial_selections:?}",
1348 );
1349 initial_selections
1350 });
1351 search_bar.update(cx, |search_bar, cx| {
1352 assert_eq!(search_bar.active_match_index, Some(0));
1353 let handle = search_bar.query_editor.focus_handle(cx);
1354 cx.focus(&handle);
1355 search_bar.select_all_matches(&SelectAllMatches, cx);
1356 });
1357 assert!(
1358 editor.read(cx).is_focused(cx),
1359 "Should focus editor after successful SelectAllMatches"
1360 );
1361 search_bar.update(cx, |search_bar, cx| {
1362 let all_selections =
1363 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1364 assert_eq!(
1365 all_selections.len(),
1366 expected_query_matches_count,
1367 "Should select all `a` characters in the buffer, but got: {all_selections:?}"
1368 );
1369 assert_eq!(
1370 search_bar.active_match_index,
1371 Some(0),
1372 "Match index should not change after selecting all matches"
1373 );
1374 });
1375
1376 search_bar.update(cx, |this, cx| this.select_next_match(&SelectNextMatch, cx));
1377 initial_selections
1378 }).unwrap();
1379
1380 window
1381 .update(cx, |_, cx| {
1382 assert!(
1383 editor.read(cx).is_focused(cx),
1384 "Should still have editor focused after SelectNextMatch"
1385 );
1386 search_bar.update(cx, |search_bar, cx| {
1387 let all_selections =
1388 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1389 assert_eq!(
1390 all_selections.len(),
1391 1,
1392 "On next match, should deselect items and select the next match"
1393 );
1394 assert_ne!(
1395 all_selections, initial_selections,
1396 "Next match should be different from the first selection"
1397 );
1398 assert_eq!(
1399 search_bar.active_match_index,
1400 Some(1),
1401 "Match index should be updated to the next one"
1402 );
1403 let handle = search_bar.query_editor.focus_handle(cx);
1404 cx.focus(&handle);
1405 search_bar.select_all_matches(&SelectAllMatches, cx);
1406 });
1407 })
1408 .unwrap();
1409 window
1410 .update(cx, |_, cx| {
1411 assert!(
1412 editor.read(cx).is_focused(cx),
1413 "Should focus editor after successful SelectAllMatches"
1414 );
1415 search_bar.update(cx, |search_bar, cx| {
1416 let all_selections =
1417 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1418 assert_eq!(
1419 all_selections.len(),
1420 expected_query_matches_count,
1421 "Should select all `a` characters in the buffer, but got: {all_selections:?}"
1422 );
1423 assert_eq!(
1424 search_bar.active_match_index,
1425 Some(1),
1426 "Match index should not change after selecting all matches"
1427 );
1428 });
1429 search_bar.update(cx, |search_bar, cx| {
1430 search_bar.select_prev_match(&SelectPrevMatch, cx);
1431 });
1432 })
1433 .unwrap();
1434 let last_match_selections = window
1435 .update(cx, |_, cx| {
1436 assert!(
1437 editor.read(cx).is_focused(&cx),
1438 "Should still have editor focused after SelectPrevMatch"
1439 );
1440
1441 search_bar.update(cx, |search_bar, cx| {
1442 let all_selections =
1443 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1444 assert_eq!(
1445 all_selections.len(),
1446 1,
1447 "On previous match, should deselect items and select the previous item"
1448 );
1449 assert_eq!(
1450 all_selections, initial_selections,
1451 "Previous match should be the same as the first selection"
1452 );
1453 assert_eq!(
1454 search_bar.active_match_index,
1455 Some(0),
1456 "Match index should be updated to the previous one"
1457 );
1458 all_selections
1459 })
1460 })
1461 .unwrap();
1462
1463 window
1464 .update(cx, |_, cx| {
1465 search_bar.update(cx, |search_bar, cx| {
1466 let handle = search_bar.query_editor.focus_handle(cx);
1467 cx.focus(&handle);
1468 search_bar.search("abas_nonexistent_match", None, cx)
1469 })
1470 })
1471 .unwrap()
1472 .await
1473 .unwrap();
1474 window
1475 .update(cx, |_, cx| {
1476 search_bar.update(cx, |search_bar, cx| {
1477 search_bar.select_all_matches(&SelectAllMatches, cx);
1478 });
1479 assert!(
1480 editor.update(cx, |this, cx| !this.is_focused(cx.window_context())),
1481 "Should not switch focus to editor if SelectAllMatches does not find any matches"
1482 );
1483 search_bar.update(cx, |search_bar, cx| {
1484 let all_selections =
1485 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1486 assert_eq!(
1487 all_selections, last_match_selections,
1488 "Should not select anything new if there are no matches"
1489 );
1490 assert!(
1491 search_bar.active_match_index.is_none(),
1492 "For no matches, there should be no active match index"
1493 );
1494 });
1495 })
1496 .unwrap();
1497 }
1498
1499 #[gpui::test]
1500 async fn test_search_query_history(cx: &mut TestAppContext) {
1501 //crate::project_search::tests::init_test(cx);
1502 init_globals(cx);
1503 let buffer_text = r#"
1504 A regular expression (shortened as regex or regexp;[1] also referred to as
1505 rational expression[2][3]) is a sequence of characters that specifies a search
1506 pattern in text. Usually such patterns are used by string-searching algorithms
1507 for "find" or "find and replace" operations on strings, or for input validation.
1508 "#
1509 .unindent();
1510 let buffer = cx.build_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), buffer_text));
1511 let (_, cx) = cx.add_window_view(|_| EmptyView {});
1512
1513 let editor = cx.build_view(|cx| Editor::for_buffer(buffer.clone(), None, cx));
1514
1515 let search_bar = cx.build_view(|cx| {
1516 let mut search_bar = BufferSearchBar::new(cx);
1517 search_bar.set_active_pane_item(Some(&editor), cx);
1518 search_bar.show(cx);
1519 search_bar
1520 });
1521
1522 // Add 3 search items into the history.
1523 search_bar
1524 .update(cx, |search_bar, cx| search_bar.search("a", None, cx))
1525 .await
1526 .unwrap();
1527 search_bar
1528 .update(cx, |search_bar, cx| search_bar.search("b", None, cx))
1529 .await
1530 .unwrap();
1531 search_bar
1532 .update(cx, |search_bar, cx| {
1533 search_bar.search("c", Some(SearchOptions::CASE_SENSITIVE), cx)
1534 })
1535 .await
1536 .unwrap();
1537 // Ensure that the latest search is active.
1538 search_bar.update(cx, |search_bar, cx| {
1539 assert_eq!(search_bar.query(cx), "c");
1540 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1541 });
1542
1543 // Next history query after the latest should set the query to the empty string.
1544 search_bar.update(cx, |search_bar, cx| {
1545 search_bar.next_history_query(&NextHistoryQuery, cx);
1546 });
1547 search_bar.update(cx, |search_bar, cx| {
1548 assert_eq!(search_bar.query(cx), "");
1549 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1550 });
1551 search_bar.update(cx, |search_bar, cx| {
1552 search_bar.next_history_query(&NextHistoryQuery, cx);
1553 });
1554 search_bar.update(cx, |search_bar, cx| {
1555 assert_eq!(search_bar.query(cx), "");
1556 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1557 });
1558
1559 // First previous query for empty current query should set the query to the latest.
1560 search_bar.update(cx, |search_bar, cx| {
1561 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1562 });
1563 search_bar.update(cx, |search_bar, cx| {
1564 assert_eq!(search_bar.query(cx), "c");
1565 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1566 });
1567
1568 // Further previous items should go over the history in reverse order.
1569 search_bar.update(cx, |search_bar, cx| {
1570 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1571 });
1572 search_bar.update(cx, |search_bar, cx| {
1573 assert_eq!(search_bar.query(cx), "b");
1574 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1575 });
1576
1577 // Previous items should never go behind the first history item.
1578 search_bar.update(cx, |search_bar, cx| {
1579 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1580 });
1581 search_bar.update(cx, |search_bar, cx| {
1582 assert_eq!(search_bar.query(cx), "a");
1583 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1584 });
1585 search_bar.update(cx, |search_bar, cx| {
1586 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1587 });
1588 search_bar.update(cx, |search_bar, cx| {
1589 assert_eq!(search_bar.query(cx), "a");
1590 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1591 });
1592
1593 // Next items should go over the history in the original order.
1594 search_bar.update(cx, |search_bar, cx| {
1595 search_bar.next_history_query(&NextHistoryQuery, cx);
1596 });
1597 search_bar.update(cx, |search_bar, cx| {
1598 assert_eq!(search_bar.query(cx), "b");
1599 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1600 });
1601
1602 search_bar
1603 .update(cx, |search_bar, cx| search_bar.search("ba", None, cx))
1604 .await
1605 .unwrap();
1606 search_bar.update(cx, |search_bar, cx| {
1607 assert_eq!(search_bar.query(cx), "ba");
1608 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1609 });
1610
1611 // New search input should add another entry to history and move the selection to the end of the history.
1612 search_bar.update(cx, |search_bar, cx| {
1613 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1614 });
1615 search_bar.update(cx, |search_bar, cx| {
1616 assert_eq!(search_bar.query(cx), "c");
1617 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1618 });
1619 search_bar.update(cx, |search_bar, cx| {
1620 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1621 });
1622 search_bar.update(cx, |search_bar, cx| {
1623 assert_eq!(search_bar.query(cx), "b");
1624 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1625 });
1626 search_bar.update(cx, |search_bar, cx| {
1627 search_bar.next_history_query(&NextHistoryQuery, cx);
1628 });
1629 search_bar.update(cx, |search_bar, cx| {
1630 assert_eq!(search_bar.query(cx), "c");
1631 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1632 });
1633 search_bar.update(cx, |search_bar, cx| {
1634 search_bar.next_history_query(&NextHistoryQuery, cx);
1635 });
1636 search_bar.update(cx, |search_bar, cx| {
1637 assert_eq!(search_bar.query(cx), "ba");
1638 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1639 });
1640 search_bar.update(cx, |search_bar, cx| {
1641 search_bar.next_history_query(&NextHistoryQuery, cx);
1642 });
1643 search_bar.update(cx, |search_bar, cx| {
1644 assert_eq!(search_bar.query(cx), "");
1645 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1646 });
1647 }
1648 #[gpui::test]
1649 async fn test_replace_simple(cx: &mut TestAppContext) {
1650 let (editor, search_bar, cx) = init_test(cx);
1651
1652 search_bar
1653 .update(cx, |search_bar, cx| {
1654 search_bar.search("expression", None, cx)
1655 })
1656 .await
1657 .unwrap();
1658
1659 search_bar.update(cx, |search_bar, cx| {
1660 search_bar.replacement_editor.update(cx, |editor, cx| {
1661 // We use $1 here as initially we should be in Text mode, where `$1` should be treated literally.
1662 editor.set_text("expr$1", cx);
1663 });
1664 search_bar.replace_all(&ReplaceAll, cx)
1665 });
1666 assert_eq!(
1667 editor.update(cx, |this, cx| { this.text(cx) }),
1668 r#"
1669 A regular expr$1 (shortened as regex or regexp;[1] also referred to as
1670 rational expr$1[2][3]) is a sequence of characters that specifies a search
1671 pattern in text. Usually such patterns are used by string-searching algorithms
1672 for "find" or "find and replace" operations on strings, or for input validation.
1673 "#
1674 .unindent()
1675 );
1676
1677 // Search for word boundaries and replace just a single one.
1678 search_bar
1679 .update(cx, |search_bar, cx| {
1680 search_bar.search("or", Some(SearchOptions::WHOLE_WORD), cx)
1681 })
1682 .await
1683 .unwrap();
1684
1685 search_bar.update(cx, |search_bar, cx| {
1686 search_bar.replacement_editor.update(cx, |editor, cx| {
1687 editor.set_text("banana", cx);
1688 });
1689 search_bar.replace_next(&ReplaceNext, cx)
1690 });
1691 // Notice how the first or in the text (shORtened) is not replaced. Neither are the remaining hits of `or` in the text.
1692 assert_eq!(
1693 editor.update(cx, |this, cx| { this.text(cx) }),
1694 r#"
1695 A regular expr$1 (shortened as regex banana regexp;[1] also referred to as
1696 rational expr$1[2][3]) is a sequence of characters that specifies a search
1697 pattern in text. Usually such patterns are used by string-searching algorithms
1698 for "find" or "find and replace" operations on strings, or for input validation.
1699 "#
1700 .unindent()
1701 );
1702 // Let's turn on regex mode.
1703 search_bar
1704 .update(cx, |search_bar, cx| {
1705 search_bar.activate_search_mode(SearchMode::Regex, cx);
1706 search_bar.search("\\[([^\\]]+)\\]", None, cx)
1707 })
1708 .await
1709 .unwrap();
1710 search_bar.update(cx, |search_bar, cx| {
1711 search_bar.replacement_editor.update(cx, |editor, cx| {
1712 editor.set_text("${1}number", cx);
1713 });
1714 search_bar.replace_all(&ReplaceAll, cx)
1715 });
1716 assert_eq!(
1717 editor.update(cx, |this, cx| { this.text(cx) }),
1718 r#"
1719 A regular expr$1 (shortened as regex banana regexp;1number also referred to as
1720 rational expr$12number3number) is a sequence of characters that specifies a search
1721 pattern in text. Usually such patterns are used by string-searching algorithms
1722 for "find" or "find and replace" operations on strings, or for input validation.
1723 "#
1724 .unindent()
1725 );
1726 // Now with a whole-word twist.
1727 search_bar
1728 .update(cx, |search_bar, cx| {
1729 search_bar.activate_search_mode(SearchMode::Regex, cx);
1730 search_bar.search("a\\w+s", Some(SearchOptions::WHOLE_WORD), cx)
1731 })
1732 .await
1733 .unwrap();
1734 search_bar.update(cx, |search_bar, cx| {
1735 search_bar.replacement_editor.update(cx, |editor, cx| {
1736 editor.set_text("things", cx);
1737 });
1738 search_bar.replace_all(&ReplaceAll, cx)
1739 });
1740 // The only word affected by this edit should be `algorithms`, even though there's a bunch
1741 // of words in this text that would match this regex if not for WHOLE_WORD.
1742 assert_eq!(
1743 editor.update(cx, |this, cx| { this.text(cx) }),
1744 r#"
1745 A regular expr$1 (shortened as regex banana regexp;1number also referred to as
1746 rational expr$12number3number) is a sequence of characters that specifies a search
1747 pattern in text. Usually such patterns are used by string-searching things
1748 for "find" or "find and replace" operations on strings, or for input validation.
1749 "#
1750 .unindent()
1751 );
1752 }
1753}