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