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