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