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