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