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