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