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