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