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_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
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 let display_points_of = |background_highlights: Vec<(Range<DisplayPoint>, Hsla)>| {
1134 background_highlights
1135 .into_iter()
1136 .map(|(range, _)| range)
1137 .collect::<Vec<_>>()
1138 };
1139 // Search for a string that appears with different casing.
1140 // By default, search is case-insensitive.
1141 search_bar
1142 .update(cx, |search_bar, cx| search_bar.search("us", None, cx))
1143 .await
1144 .unwrap();
1145 editor.update(cx, |editor, cx| {
1146 assert_eq!(
1147 display_points_of(editor.all_text_background_highlights(cx)),
1148 &[
1149 DisplayPoint::new(2, 17)..DisplayPoint::new(2, 19),
1150 DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
1151 ]
1152 );
1153 });
1154
1155 // Switch to a case sensitive search.
1156 search_bar.update(cx, |search_bar, cx| {
1157 search_bar.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
1158 });
1159 let mut editor_notifications = cx.notifications(&editor);
1160 editor_notifications.next().await;
1161 editor.update(cx, |editor, cx| {
1162 assert_eq!(
1163 display_points_of(editor.all_text_background_highlights(cx)),
1164 &[DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),]
1165 );
1166 });
1167
1168 // Search for a string that appears both as a whole word and
1169 // within other words. By default, all results are found.
1170 search_bar
1171 .update(cx, |search_bar, cx| search_bar.search("or", None, cx))
1172 .await
1173 .unwrap();
1174 editor.update(cx, |editor, cx| {
1175 assert_eq!(
1176 display_points_of(editor.all_text_background_highlights(cx)),
1177 &[
1178 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 26),
1179 DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
1180 DisplayPoint::new(2, 71)..DisplayPoint::new(2, 73),
1181 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 3),
1182 DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
1183 DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
1184 DisplayPoint::new(3, 60)..DisplayPoint::new(3, 62),
1185 ]
1186 );
1187 });
1188
1189 // Switch to a whole word search.
1190 search_bar.update(cx, |search_bar, cx| {
1191 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1192 });
1193 let mut editor_notifications = cx.notifications(&editor);
1194 editor_notifications.next().await;
1195 editor.update(cx, |editor, cx| {
1196 assert_eq!(
1197 display_points_of(editor.all_text_background_highlights(cx)),
1198 &[
1199 DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
1200 DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
1201 DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
1202 ]
1203 );
1204 });
1205
1206 editor.update(cx, |editor, cx| {
1207 editor.change_selections(None, cx, |s| {
1208 s.select_display_ranges([DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)])
1209 });
1210 });
1211 search_bar.update(cx, |search_bar, cx| {
1212 assert_eq!(search_bar.active_match_index, Some(0));
1213 search_bar.select_next_match(&SelectNextMatch, cx);
1214 assert_eq!(
1215 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1216 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1217 );
1218 });
1219 search_bar.update(cx, |search_bar, _| {
1220 assert_eq!(search_bar.active_match_index, Some(0));
1221 });
1222
1223 search_bar.update(cx, |search_bar, cx| {
1224 search_bar.select_next_match(&SelectNextMatch, cx);
1225 assert_eq!(
1226 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1227 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1228 );
1229 });
1230 search_bar.update(cx, |search_bar, _| {
1231 assert_eq!(search_bar.active_match_index, Some(1));
1232 });
1233
1234 search_bar.update(cx, |search_bar, cx| {
1235 search_bar.select_next_match(&SelectNextMatch, cx);
1236 assert_eq!(
1237 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1238 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1239 );
1240 });
1241 search_bar.update(cx, |search_bar, _| {
1242 assert_eq!(search_bar.active_match_index, Some(2));
1243 });
1244
1245 search_bar.update(cx, |search_bar, cx| {
1246 search_bar.select_next_match(&SelectNextMatch, cx);
1247 assert_eq!(
1248 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1249 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1250 );
1251 });
1252 search_bar.update(cx, |search_bar, _| {
1253 assert_eq!(search_bar.active_match_index, Some(0));
1254 });
1255
1256 search_bar.update(cx, |search_bar, cx| {
1257 search_bar.select_prev_match(&SelectPrevMatch, cx);
1258 assert_eq!(
1259 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1260 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1261 );
1262 });
1263 search_bar.update(cx, |search_bar, _| {
1264 assert_eq!(search_bar.active_match_index, Some(2));
1265 });
1266
1267 search_bar.update(cx, |search_bar, cx| {
1268 search_bar.select_prev_match(&SelectPrevMatch, cx);
1269 assert_eq!(
1270 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1271 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1272 );
1273 });
1274 search_bar.update(cx, |search_bar, _| {
1275 assert_eq!(search_bar.active_match_index, Some(1));
1276 });
1277
1278 search_bar.update(cx, |search_bar, cx| {
1279 search_bar.select_prev_match(&SelectPrevMatch, cx);
1280 assert_eq!(
1281 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1282 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1283 );
1284 });
1285 search_bar.update(cx, |search_bar, _| {
1286 assert_eq!(search_bar.active_match_index, Some(0));
1287 });
1288
1289 // Park the cursor in between matches and ensure that going to the previous match selects
1290 // the closest match to the left.
1291 editor.update(cx, |editor, cx| {
1292 editor.change_selections(None, cx, |s| {
1293 s.select_display_ranges([DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)])
1294 });
1295 });
1296 search_bar.update(cx, |search_bar, cx| {
1297 assert_eq!(search_bar.active_match_index, Some(1));
1298 search_bar.select_prev_match(&SelectPrevMatch, cx);
1299 assert_eq!(
1300 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1301 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1302 );
1303 });
1304 search_bar.update(cx, |search_bar, _| {
1305 assert_eq!(search_bar.active_match_index, Some(0));
1306 });
1307
1308 // Park the cursor in between matches and ensure that going to the next match selects the
1309 // closest match to the right.
1310 editor.update(cx, |editor, cx| {
1311 editor.change_selections(None, cx, |s| {
1312 s.select_display_ranges([DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)])
1313 });
1314 });
1315 search_bar.update(cx, |search_bar, cx| {
1316 assert_eq!(search_bar.active_match_index, Some(1));
1317 search_bar.select_next_match(&SelectNextMatch, cx);
1318 assert_eq!(
1319 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1320 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1321 );
1322 });
1323 search_bar.update(cx, |search_bar, _| {
1324 assert_eq!(search_bar.active_match_index, Some(1));
1325 });
1326
1327 // Park the cursor after the last match and ensure that going to the previous match selects
1328 // the last match.
1329 editor.update(cx, |editor, cx| {
1330 editor.change_selections(None, cx, |s| {
1331 s.select_display_ranges([DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)])
1332 });
1333 });
1334 search_bar.update(cx, |search_bar, cx| {
1335 assert_eq!(search_bar.active_match_index, Some(2));
1336 search_bar.select_prev_match(&SelectPrevMatch, cx);
1337 assert_eq!(
1338 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1339 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1340 );
1341 });
1342 search_bar.update(cx, |search_bar, _| {
1343 assert_eq!(search_bar.active_match_index, Some(2));
1344 });
1345
1346 // Park the cursor after the last match and ensure that going to the next match selects the
1347 // first match.
1348 editor.update(cx, |editor, cx| {
1349 editor.change_selections(None, cx, |s| {
1350 s.select_display_ranges([DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)])
1351 });
1352 });
1353 search_bar.update(cx, |search_bar, cx| {
1354 assert_eq!(search_bar.active_match_index, Some(2));
1355 search_bar.select_next_match(&SelectNextMatch, cx);
1356 assert_eq!(
1357 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1358 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1359 );
1360 });
1361 search_bar.update(cx, |search_bar, _| {
1362 assert_eq!(search_bar.active_match_index, Some(0));
1363 });
1364
1365 // Park the cursor before the first match and ensure that going to the previous match
1366 // selects the last match.
1367 editor.update(cx, |editor, cx| {
1368 editor.change_selections(None, cx, |s| {
1369 s.select_display_ranges([DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)])
1370 });
1371 });
1372 search_bar.update(cx, |search_bar, cx| {
1373 assert_eq!(search_bar.active_match_index, Some(0));
1374 search_bar.select_prev_match(&SelectPrevMatch, cx);
1375 assert_eq!(
1376 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1377 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1378 );
1379 });
1380 search_bar.update(cx, |search_bar, _| {
1381 assert_eq!(search_bar.active_match_index, Some(2));
1382 });
1383 }
1384
1385 #[gpui::test]
1386 async fn test_search_option_handling(cx: &mut TestAppContext) {
1387 let (editor, search_bar, cx) = init_test(cx);
1388
1389 // show with options should make current search case sensitive
1390 search_bar
1391 .update(cx, |search_bar, cx| {
1392 search_bar.show(cx);
1393 search_bar.search("us", Some(SearchOptions::CASE_SENSITIVE), cx)
1394 })
1395 .await
1396 .unwrap();
1397 let display_points_of = |background_highlights: Vec<(Range<DisplayPoint>, Hsla)>| {
1398 background_highlights
1399 .into_iter()
1400 .map(|(range, _)| range)
1401 .collect::<Vec<_>>()
1402 };
1403 editor.update(cx, |editor, cx| {
1404 assert_eq!(
1405 display_points_of(editor.all_text_background_highlights(cx)),
1406 &[DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),]
1407 );
1408 });
1409
1410 // search_suggested should restore default options
1411 search_bar.update(cx, |search_bar, cx| {
1412 search_bar.search_suggested(cx);
1413 assert_eq!(search_bar.search_options, SearchOptions::NONE)
1414 });
1415
1416 // toggling a search option should update the defaults
1417 search_bar
1418 .update(cx, |search_bar, cx| {
1419 search_bar.search("regex", Some(SearchOptions::CASE_SENSITIVE), cx)
1420 })
1421 .await
1422 .unwrap();
1423 search_bar.update(cx, |search_bar, cx| {
1424 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, cx)
1425 });
1426 let mut editor_notifications = cx.notifications(&editor);
1427 editor_notifications.next().await;
1428 editor.update(cx, |editor, cx| {
1429 assert_eq!(
1430 display_points_of(editor.all_text_background_highlights(cx)),
1431 &[DisplayPoint::new(0, 35)..DisplayPoint::new(0, 40),]
1432 );
1433 });
1434
1435 // defaults should still include whole word
1436 search_bar.update(cx, |search_bar, cx| {
1437 search_bar.search_suggested(cx);
1438 assert_eq!(
1439 search_bar.search_options,
1440 SearchOptions::CASE_SENSITIVE | SearchOptions::WHOLE_WORD
1441 )
1442 });
1443 }
1444
1445 #[gpui::test]
1446 async fn test_search_select_all_matches(cx: &mut TestAppContext) {
1447 init_globals(cx);
1448 let buffer_text = r#"
1449 A regular expression (shortened as regex or regexp;[1] also referred to as
1450 rational expression[2][3]) is a sequence of characters that specifies a search
1451 pattern in text. Usually such patterns are used by string-searching algorithms
1452 for "find" or "find and replace" operations on strings, or for input validation.
1453 "#
1454 .unindent();
1455 let expected_query_matches_count = buffer_text
1456 .chars()
1457 .filter(|c| c.to_ascii_lowercase() == 'a')
1458 .count();
1459 assert!(
1460 expected_query_matches_count > 1,
1461 "Should pick a query with multiple results"
1462 );
1463 let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), buffer_text));
1464 let window = cx.add_window(|_| EmptyView {});
1465
1466 let editor = window.build_view(cx, |cx| Editor::for_buffer(buffer.clone(), None, cx));
1467
1468 let search_bar = window.build_view(cx, |cx| {
1469 let mut search_bar = BufferSearchBar::new(cx);
1470 search_bar.set_active_pane_item(Some(&editor), cx);
1471 search_bar.show(cx);
1472 search_bar
1473 });
1474
1475 window
1476 .update(cx, |_, cx| {
1477 search_bar.update(cx, |search_bar, cx| search_bar.search("a", None, cx))
1478 })
1479 .unwrap()
1480 .await
1481 .unwrap();
1482 let initial_selections = window
1483 .update(cx, |_, cx| {
1484 search_bar.update(cx, |search_bar, cx| {
1485 let handle = search_bar.query_editor.focus_handle(cx);
1486 cx.focus(&handle);
1487 search_bar.activate_current_match(cx);
1488 });
1489 assert!(
1490 !editor.read(cx).is_focused(cx),
1491 "Initially, the editor should not be focused"
1492 );
1493 let initial_selections = editor.update(cx, |editor, cx| {
1494 let initial_selections = editor.selections.display_ranges(cx);
1495 assert_eq!(
1496 initial_selections.len(), 1,
1497 "Expected to have only one selection before adding carets to all matches, but got: {initial_selections:?}",
1498 );
1499 initial_selections
1500 });
1501 search_bar.update(cx, |search_bar, cx| {
1502 assert_eq!(search_bar.active_match_index, Some(0));
1503 let handle = search_bar.query_editor.focus_handle(cx);
1504 cx.focus(&handle);
1505 search_bar.select_all_matches(&SelectAllMatches, cx);
1506 });
1507 assert!(
1508 editor.read(cx).is_focused(cx),
1509 "Should focus editor after successful SelectAllMatches"
1510 );
1511 search_bar.update(cx, |search_bar, cx| {
1512 let all_selections =
1513 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1514 assert_eq!(
1515 all_selections.len(),
1516 expected_query_matches_count,
1517 "Should select all `a` characters in the buffer, but got: {all_selections:?}"
1518 );
1519 assert_eq!(
1520 search_bar.active_match_index,
1521 Some(0),
1522 "Match index should not change after selecting all matches"
1523 );
1524 });
1525
1526 search_bar.update(cx, |this, cx| this.select_next_match(&SelectNextMatch, cx));
1527 initial_selections
1528 }).unwrap();
1529
1530 window
1531 .update(cx, |_, cx| {
1532 assert!(
1533 editor.read(cx).is_focused(cx),
1534 "Should still have editor focused after SelectNextMatch"
1535 );
1536 search_bar.update(cx, |search_bar, cx| {
1537 let all_selections =
1538 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1539 assert_eq!(
1540 all_selections.len(),
1541 1,
1542 "On next match, should deselect items and select the next match"
1543 );
1544 assert_ne!(
1545 all_selections, initial_selections,
1546 "Next match should be different from the first selection"
1547 );
1548 assert_eq!(
1549 search_bar.active_match_index,
1550 Some(1),
1551 "Match index should be updated to the next one"
1552 );
1553 let handle = search_bar.query_editor.focus_handle(cx);
1554 cx.focus(&handle);
1555 search_bar.select_all_matches(&SelectAllMatches, cx);
1556 });
1557 })
1558 .unwrap();
1559 window
1560 .update(cx, |_, cx| {
1561 assert!(
1562 editor.read(cx).is_focused(cx),
1563 "Should focus editor after successful SelectAllMatches"
1564 );
1565 search_bar.update(cx, |search_bar, cx| {
1566 let all_selections =
1567 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1568 assert_eq!(
1569 all_selections.len(),
1570 expected_query_matches_count,
1571 "Should select all `a` characters in the buffer, but got: {all_selections:?}"
1572 );
1573 assert_eq!(
1574 search_bar.active_match_index,
1575 Some(1),
1576 "Match index should not change after selecting all matches"
1577 );
1578 });
1579 search_bar.update(cx, |search_bar, cx| {
1580 search_bar.select_prev_match(&SelectPrevMatch, cx);
1581 });
1582 })
1583 .unwrap();
1584 let last_match_selections = window
1585 .update(cx, |_, cx| {
1586 assert!(
1587 editor.read(cx).is_focused(&cx),
1588 "Should still have editor focused after SelectPrevMatch"
1589 );
1590
1591 search_bar.update(cx, |search_bar, cx| {
1592 let all_selections =
1593 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1594 assert_eq!(
1595 all_selections.len(),
1596 1,
1597 "On previous match, should deselect items and select the previous item"
1598 );
1599 assert_eq!(
1600 all_selections, initial_selections,
1601 "Previous match should be the same as the first selection"
1602 );
1603 assert_eq!(
1604 search_bar.active_match_index,
1605 Some(0),
1606 "Match index should be updated to the previous one"
1607 );
1608 all_selections
1609 })
1610 })
1611 .unwrap();
1612
1613 window
1614 .update(cx, |_, cx| {
1615 search_bar.update(cx, |search_bar, cx| {
1616 let handle = search_bar.query_editor.focus_handle(cx);
1617 cx.focus(&handle);
1618 search_bar.search("abas_nonexistent_match", None, cx)
1619 })
1620 })
1621 .unwrap()
1622 .await
1623 .unwrap();
1624 window
1625 .update(cx, |_, cx| {
1626 search_bar.update(cx, |search_bar, cx| {
1627 search_bar.select_all_matches(&SelectAllMatches, cx);
1628 });
1629 assert!(
1630 editor.update(cx, |this, cx| !this.is_focused(cx.window_context())),
1631 "Should not switch focus to editor if SelectAllMatches does not find any matches"
1632 );
1633 search_bar.update(cx, |search_bar, cx| {
1634 let all_selections =
1635 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1636 assert_eq!(
1637 all_selections, last_match_selections,
1638 "Should not select anything new if there are no matches"
1639 );
1640 assert!(
1641 search_bar.active_match_index.is_none(),
1642 "For no matches, there should be no active match index"
1643 );
1644 });
1645 })
1646 .unwrap();
1647 }
1648
1649 #[gpui::test]
1650 async fn test_search_query_history(cx: &mut TestAppContext) {
1651 init_globals(cx);
1652 let buffer_text = r#"
1653 A regular expression (shortened as regex or regexp;[1] also referred to as
1654 rational expression[2][3]) is a sequence of characters that specifies a search
1655 pattern in text. Usually such patterns are used by string-searching algorithms
1656 for "find" or "find and replace" operations on strings, or for input validation.
1657 "#
1658 .unindent();
1659 let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), buffer_text));
1660 let (_, cx) = cx.add_window_view(|_| EmptyView {});
1661
1662 let editor = cx.new_view(|cx| Editor::for_buffer(buffer.clone(), None, cx));
1663
1664 let search_bar = cx.new_view(|cx| {
1665 let mut search_bar = BufferSearchBar::new(cx);
1666 search_bar.set_active_pane_item(Some(&editor), cx);
1667 search_bar.show(cx);
1668 search_bar
1669 });
1670
1671 // Add 3 search items into the history.
1672 search_bar
1673 .update(cx, |search_bar, cx| search_bar.search("a", None, cx))
1674 .await
1675 .unwrap();
1676 search_bar
1677 .update(cx, |search_bar, cx| search_bar.search("b", None, cx))
1678 .await
1679 .unwrap();
1680 search_bar
1681 .update(cx, |search_bar, cx| {
1682 search_bar.search("c", Some(SearchOptions::CASE_SENSITIVE), cx)
1683 })
1684 .await
1685 .unwrap();
1686 // Ensure that the latest search is active.
1687 search_bar.update(cx, |search_bar, cx| {
1688 assert_eq!(search_bar.query(cx), "c");
1689 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1690 });
1691
1692 // Next history query after the latest should set the query to the empty string.
1693 search_bar.update(cx, |search_bar, cx| {
1694 search_bar.next_history_query(&NextHistoryQuery, cx);
1695 });
1696 search_bar.update(cx, |search_bar, cx| {
1697 assert_eq!(search_bar.query(cx), "");
1698 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1699 });
1700 search_bar.update(cx, |search_bar, cx| {
1701 search_bar.next_history_query(&NextHistoryQuery, cx);
1702 });
1703 search_bar.update(cx, |search_bar, cx| {
1704 assert_eq!(search_bar.query(cx), "");
1705 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1706 });
1707
1708 // First previous query for empty current query should set the query to the latest.
1709 search_bar.update(cx, |search_bar, cx| {
1710 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1711 });
1712 search_bar.update(cx, |search_bar, cx| {
1713 assert_eq!(search_bar.query(cx), "c");
1714 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1715 });
1716
1717 // Further previous items should go over the history in reverse order.
1718 search_bar.update(cx, |search_bar, cx| {
1719 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1720 });
1721 search_bar.update(cx, |search_bar, cx| {
1722 assert_eq!(search_bar.query(cx), "b");
1723 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1724 });
1725
1726 // Previous items should never go behind the first history item.
1727 search_bar.update(cx, |search_bar, cx| {
1728 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1729 });
1730 search_bar.update(cx, |search_bar, cx| {
1731 assert_eq!(search_bar.query(cx), "a");
1732 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1733 });
1734 search_bar.update(cx, |search_bar, cx| {
1735 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1736 });
1737 search_bar.update(cx, |search_bar, cx| {
1738 assert_eq!(search_bar.query(cx), "a");
1739 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1740 });
1741
1742 // Next items should go over the history in the original order.
1743 search_bar.update(cx, |search_bar, cx| {
1744 search_bar.next_history_query(&NextHistoryQuery, cx);
1745 });
1746 search_bar.update(cx, |search_bar, cx| {
1747 assert_eq!(search_bar.query(cx), "b");
1748 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1749 });
1750
1751 search_bar
1752 .update(cx, |search_bar, cx| search_bar.search("ba", None, cx))
1753 .await
1754 .unwrap();
1755 search_bar.update(cx, |search_bar, cx| {
1756 assert_eq!(search_bar.query(cx), "ba");
1757 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1758 });
1759
1760 // New search input should add another entry to history and move the selection to the end of the history.
1761 search_bar.update(cx, |search_bar, cx| {
1762 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1763 });
1764 search_bar.update(cx, |search_bar, cx| {
1765 assert_eq!(search_bar.query(cx), "c");
1766 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1767 });
1768 search_bar.update(cx, |search_bar, cx| {
1769 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1770 });
1771 search_bar.update(cx, |search_bar, cx| {
1772 assert_eq!(search_bar.query(cx), "b");
1773 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1774 });
1775 search_bar.update(cx, |search_bar, cx| {
1776 search_bar.next_history_query(&NextHistoryQuery, cx);
1777 });
1778 search_bar.update(cx, |search_bar, cx| {
1779 assert_eq!(search_bar.query(cx), "c");
1780 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1781 });
1782 search_bar.update(cx, |search_bar, cx| {
1783 search_bar.next_history_query(&NextHistoryQuery, cx);
1784 });
1785 search_bar.update(cx, |search_bar, cx| {
1786 assert_eq!(search_bar.query(cx), "ba");
1787 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1788 });
1789 search_bar.update(cx, |search_bar, cx| {
1790 search_bar.next_history_query(&NextHistoryQuery, cx);
1791 });
1792 search_bar.update(cx, |search_bar, cx| {
1793 assert_eq!(search_bar.query(cx), "");
1794 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1795 });
1796 }
1797
1798 #[gpui::test]
1799 async fn test_replace_simple(cx: &mut TestAppContext) {
1800 let (editor, search_bar, cx) = init_test(cx);
1801
1802 search_bar
1803 .update(cx, |search_bar, cx| {
1804 search_bar.search("expression", None, cx)
1805 })
1806 .await
1807 .unwrap();
1808
1809 search_bar.update(cx, |search_bar, cx| {
1810 search_bar.replacement_editor.update(cx, |editor, cx| {
1811 // We use $1 here as initially we should be in Text mode, where `$1` should be treated literally.
1812 editor.set_text("expr$1", cx);
1813 });
1814 search_bar.replace_all(&ReplaceAll, cx)
1815 });
1816 assert_eq!(
1817 editor.update(cx, |this, cx| { this.text(cx) }),
1818 r#"
1819 A regular expr$1 (shortened as regex or regexp;[1] also referred to as
1820 rational expr$1[2][3]) is a sequence of characters that specifies a search
1821 pattern in text. Usually such patterns are used by string-searching algorithms
1822 for "find" or "find and replace" operations on strings, or for input validation.
1823 "#
1824 .unindent()
1825 );
1826
1827 // Search for word boundaries and replace just a single one.
1828 search_bar
1829 .update(cx, |search_bar, cx| {
1830 search_bar.search("or", Some(SearchOptions::WHOLE_WORD), cx)
1831 })
1832 .await
1833 .unwrap();
1834
1835 search_bar.update(cx, |search_bar, cx| {
1836 search_bar.replacement_editor.update(cx, |editor, cx| {
1837 editor.set_text("banana", cx);
1838 });
1839 search_bar.replace_next(&ReplaceNext, cx)
1840 });
1841 // Notice how the first or in the text (shORtened) is not replaced. Neither are the remaining hits of `or` in the text.
1842 assert_eq!(
1843 editor.update(cx, |this, cx| { this.text(cx) }),
1844 r#"
1845 A regular expr$1 (shortened as regex banana regexp;[1] also referred to as
1846 rational expr$1[2][3]) is a sequence of characters that specifies a search
1847 pattern in text. Usually such patterns are used by string-searching algorithms
1848 for "find" or "find and replace" operations on strings, or for input validation.
1849 "#
1850 .unindent()
1851 );
1852 // Let's turn on regex mode.
1853 search_bar
1854 .update(cx, |search_bar, cx| {
1855 search_bar.activate_search_mode(SearchMode::Regex, cx);
1856 search_bar.search("\\[([^\\]]+)\\]", None, cx)
1857 })
1858 .await
1859 .unwrap();
1860 search_bar.update(cx, |search_bar, cx| {
1861 search_bar.replacement_editor.update(cx, |editor, cx| {
1862 editor.set_text("${1}number", cx);
1863 });
1864 search_bar.replace_all(&ReplaceAll, cx)
1865 });
1866 assert_eq!(
1867 editor.update(cx, |this, cx| { this.text(cx) }),
1868 r#"
1869 A regular expr$1 (shortened as regex banana regexp;1number also referred to as
1870 rational expr$12number3number) is a sequence of characters that specifies a search
1871 pattern in text. Usually such patterns are used by string-searching algorithms
1872 for "find" or "find and replace" operations on strings, or for input validation.
1873 "#
1874 .unindent()
1875 );
1876 // Now with a whole-word twist.
1877 search_bar
1878 .update(cx, |search_bar, cx| {
1879 search_bar.activate_search_mode(SearchMode::Regex, cx);
1880 search_bar.search("a\\w+s", Some(SearchOptions::WHOLE_WORD), cx)
1881 })
1882 .await
1883 .unwrap();
1884 search_bar.update(cx, |search_bar, cx| {
1885 search_bar.replacement_editor.update(cx, |editor, cx| {
1886 editor.set_text("things", cx);
1887 });
1888 search_bar.replace_all(&ReplaceAll, cx)
1889 });
1890 // The only word affected by this edit should be `algorithms`, even though there's a bunch
1891 // of words in this text that would match this regex if not for WHOLE_WORD.
1892 assert_eq!(
1893 editor.update(cx, |this, cx| { this.text(cx) }),
1894 r#"
1895 A regular expr$1 (shortened as regex banana regexp;1number also referred to as
1896 rational expr$12number3number) is a sequence of characters that specifies a search
1897 pattern in text. Usually such patterns are used by string-searching things
1898 for "find" or "find and replace" operations on strings, or for input validation.
1899 "#
1900 .unindent()
1901 );
1902 }
1903}