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.clone(),
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::new_with_defaults();
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
431impl BufferSearchBar {
432 pub fn register(registrar: &mut impl SearchActionsRegistrar) {
433 registrar.register_handler(ForDeployed(|this, _: &FocusSearch, cx| {
434 this.query_editor.focus_handle(cx).focus(cx);
435 this.select_query(cx);
436 }));
437 registrar.register_handler(ForDeployed(|this, action: &ToggleCaseSensitive, cx| {
438 if this.supported_options().case {
439 this.toggle_case_sensitive(action, cx);
440 }
441 }));
442 registrar.register_handler(ForDeployed(|this, action: &ToggleWholeWord, cx| {
443 if this.supported_options().word {
444 this.toggle_whole_word(action, cx);
445 }
446 }));
447 registrar.register_handler(ForDeployed(|this, action: &ToggleReplace, cx| {
448 if this.supported_options().replacement {
449 this.toggle_replace(action, cx);
450 }
451 }));
452 registrar.register_handler(WithResults(|this, action: &SelectNextMatch, cx| {
453 this.select_next_match(action, cx);
454 }));
455 registrar.register_handler(WithResults(|this, action: &SelectPrevMatch, cx| {
456 this.select_prev_match(action, cx);
457 }));
458 registrar.register_handler(WithResults(|this, action: &SelectAllMatches, cx| {
459 this.select_all_matches(action, cx);
460 }));
461 registrar.register_handler(ForDeployed(|this, _: &editor::actions::Cancel, cx| {
462 this.dismiss(&Dismiss, cx);
463 }));
464
465 // register deploy buffer search for both search bar states, since we want to focus into the search bar
466 // when the deploy action is triggered in the buffer.
467 registrar.register_handler(ForDeployed(|this, deploy, cx| {
468 this.deploy(deploy, cx);
469 }));
470 registrar.register_handler(ForDismissed(|this, deploy, cx| {
471 this.deploy(deploy, cx);
472 }))
473 }
474
475 pub fn new(cx: &mut ViewContext<Self>) -> Self {
476 let query_editor = cx.new_view(|cx| Editor::single_line(cx));
477 cx.subscribe(&query_editor, Self::on_query_editor_event)
478 .detach();
479 let replacement_editor = cx.new_view(|cx| Editor::single_line(cx));
480 cx.subscribe(&replacement_editor, Self::on_replacement_editor_event)
481 .detach();
482
483 Self {
484 query_editor,
485 query_editor_focused: false,
486 replacement_editor,
487 replacement_editor_focused: false,
488 active_searchable_item: None,
489 active_searchable_item_subscription: None,
490 active_match_index: None,
491 searchable_items_with_matches: Default::default(),
492 default_options: SearchOptions::NONE,
493 search_options: SearchOptions::NONE,
494 pending_search: None,
495 query_contains_error: false,
496 dismissed: true,
497 search_history: SearchHistory::new(
498 Some(MAX_BUFFER_SEARCH_HISTORY_SIZE),
499 project::search_history::QueryInsertionBehavior::ReplacePreviousIfContains,
500 ),
501 search_history_cursor: Default::default(),
502 active_search: None,
503 replace_enabled: false,
504 scroll_handle: ScrollHandle::new(),
505 editor_scroll_handle: ScrollHandle::new(),
506 editor_needed_width: px(0.),
507 }
508 }
509
510 pub fn is_dismissed(&self) -> bool {
511 self.dismissed
512 }
513
514 pub fn dismiss(&mut self, _: &Dismiss, cx: &mut ViewContext<Self>) {
515 self.dismissed = true;
516 for searchable_item in self.searchable_items_with_matches.keys() {
517 if let Some(searchable_item) =
518 WeakSearchableItemHandle::upgrade(searchable_item.as_ref(), cx)
519 {
520 searchable_item.clear_matches(cx);
521 }
522 }
523 if let Some(active_editor) = self.active_searchable_item.as_ref() {
524 active_editor.search_bar_visibility_changed(false, cx);
525 let handle = active_editor.focus_handle(cx);
526 cx.focus(&handle);
527 }
528 cx.emit(Event::UpdateLocation);
529 cx.emit(ToolbarItemEvent::ChangeLocation(
530 ToolbarItemLocation::Hidden,
531 ));
532 cx.notify();
533 }
534
535 pub fn deploy(&mut self, deploy: &Deploy, cx: &mut ViewContext<Self>) -> bool {
536 if self.show(cx) {
537 self.search_suggested(cx);
538 self.replace_enabled = deploy.replace_enabled;
539 if deploy.focus {
540 let mut handle = self.query_editor.focus_handle(cx).clone();
541 let mut select_query = true;
542 if deploy.replace_enabled && handle.is_focused(cx) {
543 handle = self.replacement_editor.focus_handle(cx).clone();
544 select_query = false;
545 };
546 if select_query {
547 self.select_query(cx);
548 }
549 cx.focus(&handle);
550 }
551 return true;
552 }
553
554 false
555 }
556
557 pub fn toggle(&mut self, action: &Deploy, cx: &mut ViewContext<Self>) {
558 if self.is_dismissed() {
559 self.deploy(action, cx);
560 } else {
561 self.dismiss(&Dismiss, cx);
562 }
563 }
564
565 pub fn show(&mut self, cx: &mut ViewContext<Self>) -> bool {
566 let Some(handle) = self.active_searchable_item.as_ref() else {
567 return false;
568 };
569
570 self.dismissed = false;
571 handle.search_bar_visibility_changed(true, cx);
572 cx.notify();
573 cx.emit(Event::UpdateLocation);
574 cx.emit(ToolbarItemEvent::ChangeLocation(
575 ToolbarItemLocation::Secondary,
576 ));
577 true
578 }
579
580 fn supported_options(&self) -> workspace::searchable::SearchOptions {
581 self.active_searchable_item
582 .as_deref()
583 .map(SearchableItemHandle::supported_options)
584 .unwrap_or_default()
585 }
586 pub fn search_suggested(&mut self, cx: &mut ViewContext<Self>) {
587 let search = self
588 .query_suggestion(cx)
589 .map(|suggestion| self.search(&suggestion, Some(self.default_options), cx));
590
591 if let Some(search) = search {
592 cx.spawn(|this, mut cx| async move {
593 search.await?;
594 this.update(&mut cx, |this, cx| this.activate_current_match(cx))
595 })
596 .detach_and_log_err(cx);
597 }
598 }
599
600 pub fn activate_current_match(&mut self, cx: &mut ViewContext<Self>) {
601 if let Some(match_ix) = self.active_match_index {
602 if let Some(active_searchable_item) = self.active_searchable_item.as_ref() {
603 if let Some(matches) = self
604 .searchable_items_with_matches
605 .get(&active_searchable_item.downgrade())
606 {
607 active_searchable_item.activate_match(match_ix, matches, cx)
608 }
609 }
610 }
611 }
612
613 pub fn select_query(&mut self, cx: &mut ViewContext<Self>) {
614 self.query_editor.update(cx, |query_editor, cx| {
615 query_editor.select_all(&Default::default(), cx);
616 });
617 }
618
619 pub fn query(&self, cx: &WindowContext) -> String {
620 self.query_editor.read(cx).text(cx)
621 }
622 pub fn replacement(&self, cx: &WindowContext) -> String {
623 self.replacement_editor.read(cx).text(cx)
624 }
625 pub fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<String> {
626 self.active_searchable_item
627 .as_ref()
628 .map(|searchable_item| searchable_item.query_suggestion(cx))
629 .filter(|suggestion| !suggestion.is_empty())
630 }
631
632 pub fn set_replacement(&mut self, replacement: Option<&str>, cx: &mut ViewContext<Self>) {
633 if replacement.is_none() {
634 self.replace_enabled = false;
635 return;
636 }
637 self.replace_enabled = true;
638 self.replacement_editor
639 .update(cx, |replacement_editor, cx| {
640 replacement_editor
641 .buffer()
642 .update(cx, |replacement_buffer, cx| {
643 let len = replacement_buffer.len(cx);
644 replacement_buffer.edit([(0..len, replacement.unwrap())], None, cx);
645 });
646 });
647 }
648
649 pub fn search(
650 &mut self,
651 query: &str,
652 options: Option<SearchOptions>,
653 cx: &mut ViewContext<Self>,
654 ) -> oneshot::Receiver<()> {
655 let options = options.unwrap_or(self.default_options);
656 if query != self.query(cx) || self.search_options != options {
657 self.query_editor.update(cx, |query_editor, cx| {
658 query_editor.buffer().update(cx, |query_buffer, cx| {
659 let len = query_buffer.len(cx);
660 query_buffer.edit([(0..len, query)], None, cx);
661 });
662 });
663 self.search_options = options;
664 self.clear_matches(cx);
665 cx.notify();
666 }
667 self.update_matches(cx)
668 }
669
670 fn render_search_option_button(
671 &self,
672 option: SearchOptions,
673 action: impl Fn(&ClickEvent, &mut WindowContext) + 'static,
674 ) -> impl IntoElement {
675 let is_active = self.search_options.contains(option);
676 option.as_button(is_active, action)
677 }
678
679 pub fn focus_editor(&mut self, _: &FocusEditor, cx: &mut ViewContext<Self>) {
680 if let Some(active_editor) = self.active_searchable_item.as_ref() {
681 let handle = active_editor.focus_handle(cx);
682 cx.focus(&handle);
683 }
684 }
685
686 fn toggle_search_option(&mut self, search_option: SearchOptions, cx: &mut ViewContext<Self>) {
687 self.search_options.toggle(search_option);
688 self.default_options = self.search_options;
689 let _ = self.update_matches(cx);
690 cx.notify();
691 }
692
693 pub fn enable_search_option(
694 &mut self,
695 search_option: SearchOptions,
696 cx: &mut ViewContext<Self>,
697 ) {
698 if !self.search_options.contains(search_option) {
699 self.toggle_search_option(search_option, cx)
700 }
701 }
702
703 pub fn set_search_options(
704 &mut self,
705 search_options: SearchOptions,
706 cx: &mut ViewContext<Self>,
707 ) {
708 self.search_options = search_options;
709 cx.notify();
710 }
711
712 fn select_next_match(&mut self, _: &SelectNextMatch, cx: &mut ViewContext<Self>) {
713 self.select_match(Direction::Next, 1, cx);
714 }
715
716 fn select_prev_match(&mut self, _: &SelectPrevMatch, cx: &mut ViewContext<Self>) {
717 self.select_match(Direction::Prev, 1, cx);
718 }
719
720 fn select_all_matches(&mut self, _: &SelectAllMatches, cx: &mut ViewContext<Self>) {
721 if !self.dismissed && self.active_match_index.is_some() {
722 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
723 if let Some(matches) = self
724 .searchable_items_with_matches
725 .get(&searchable_item.downgrade())
726 {
727 searchable_item.select_matches(matches, cx);
728 self.focus_editor(&FocusEditor, cx);
729 }
730 }
731 }
732 }
733
734 pub fn select_match(&mut self, direction: Direction, count: usize, cx: &mut ViewContext<Self>) {
735 if let Some(index) = self.active_match_index {
736 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
737 if let Some(matches) = self
738 .searchable_items_with_matches
739 .get(&searchable_item.downgrade())
740 {
741 let new_match_index = searchable_item
742 .match_index_for_direction(matches, index, direction, count, cx);
743
744 searchable_item.update_matches(matches, cx);
745 searchable_item.activate_match(new_match_index, matches, cx);
746 }
747 }
748 }
749 }
750
751 pub fn select_last_match(&mut self, cx: &mut ViewContext<Self>) {
752 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
753 if let Some(matches) = self
754 .searchable_items_with_matches
755 .get(&searchable_item.downgrade())
756 {
757 if matches.len() == 0 {
758 return;
759 }
760 let new_match_index = matches.len() - 1;
761 searchable_item.update_matches(matches, cx);
762 searchable_item.activate_match(new_match_index, matches, cx);
763 }
764 }
765 }
766
767 fn on_query_editor_event(
768 &mut self,
769 editor: View<Editor>,
770 event: &editor::EditorEvent,
771 cx: &mut ViewContext<Self>,
772 ) {
773 match event {
774 editor::EditorEvent::Focused => self.query_editor_focused = true,
775 editor::EditorEvent::Blurred => self.query_editor_focused = false,
776 editor::EditorEvent::Edited => {
777 self.clear_matches(cx);
778 let search = self.update_matches(cx);
779
780 let width = editor.update(cx, |editor, cx| {
781 let text_layout_details = editor.text_layout_details(cx);
782 let snapshot = editor.snapshot(cx).display_snapshot;
783
784 snapshot.x_for_display_point(snapshot.max_point(), &text_layout_details)
785 - snapshot.x_for_display_point(DisplayPoint::zero(), &text_layout_details)
786 });
787 self.editor_needed_width = width;
788 cx.notify();
789
790 cx.spawn(|this, mut cx| async move {
791 search.await?;
792 this.update(&mut cx, |this, cx| this.activate_current_match(cx))
793 })
794 .detach_and_log_err(cx);
795 }
796 _ => {}
797 }
798 }
799
800 fn on_replacement_editor_event(
801 &mut self,
802 _: View<Editor>,
803 event: &editor::EditorEvent,
804 _: &mut ViewContext<Self>,
805 ) {
806 match event {
807 editor::EditorEvent::Focused => self.replacement_editor_focused = true,
808 editor::EditorEvent::Blurred => self.replacement_editor_focused = false,
809 _ => {}
810 }
811 }
812
813 fn on_active_searchable_item_event(&mut self, event: &SearchEvent, cx: &mut ViewContext<Self>) {
814 match event {
815 SearchEvent::MatchesInvalidated => {
816 let _ = self.update_matches(cx);
817 }
818 SearchEvent::ActiveMatchChanged => self.update_match_index(cx),
819 }
820 }
821
822 fn toggle_case_sensitive(&mut self, _: &ToggleCaseSensitive, cx: &mut ViewContext<Self>) {
823 self.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx)
824 }
825
826 fn toggle_whole_word(&mut self, _: &ToggleWholeWord, cx: &mut ViewContext<Self>) {
827 self.toggle_search_option(SearchOptions::WHOLE_WORD, cx)
828 }
829
830 fn toggle_regex(&mut self, _: &ToggleRegex, cx: &mut ViewContext<Self>) {
831 self.toggle_search_option(SearchOptions::REGEX, cx)
832 }
833
834 fn clear_active_searchable_item_matches(&mut self, cx: &mut WindowContext) {
835 if let Some(active_searchable_item) = self.active_searchable_item.as_ref() {
836 self.active_match_index = None;
837 self.searchable_items_with_matches
838 .remove(&active_searchable_item.downgrade());
839 active_searchable_item.clear_matches(cx);
840 }
841 }
842
843 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
844 let mut active_item_matches = None;
845 for (searchable_item, matches) in self.searchable_items_with_matches.drain() {
846 if let Some(searchable_item) =
847 WeakSearchableItemHandle::upgrade(searchable_item.as_ref(), cx)
848 {
849 if Some(&searchable_item) == self.active_searchable_item.as_ref() {
850 active_item_matches = Some((searchable_item.downgrade(), matches));
851 } else {
852 searchable_item.clear_matches(cx);
853 }
854 }
855 }
856
857 self.searchable_items_with_matches
858 .extend(active_item_matches);
859 }
860
861 fn update_matches(&mut self, cx: &mut ViewContext<Self>) -> oneshot::Receiver<()> {
862 let (done_tx, done_rx) = oneshot::channel();
863 let query = self.query(cx);
864 self.pending_search.take();
865
866 if let Some(active_searchable_item) = self.active_searchable_item.as_ref() {
867 self.query_contains_error = false;
868 if query.is_empty() {
869 self.clear_active_searchable_item_matches(cx);
870 let _ = done_tx.send(());
871 cx.notify();
872 } else {
873 let query: Arc<_> = if self.search_options.contains(SearchOptions::REGEX) {
874 match SearchQuery::regex(
875 query,
876 self.search_options.contains(SearchOptions::WHOLE_WORD),
877 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
878 false,
879 Vec::new(),
880 Vec::new(),
881 ) {
882 Ok(query) => query.with_replacement(self.replacement(cx)),
883 Err(_) => {
884 self.query_contains_error = true;
885 self.clear_active_searchable_item_matches(cx);
886 cx.notify();
887 return done_rx;
888 }
889 }
890 } else {
891 match SearchQuery::text(
892 query,
893 self.search_options.contains(SearchOptions::WHOLE_WORD),
894 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
895 false,
896 Vec::new(),
897 Vec::new(),
898 ) {
899 Ok(query) => query.with_replacement(self.replacement(cx)),
900 Err(_) => {
901 self.query_contains_error = true;
902 self.clear_active_searchable_item_matches(cx);
903 cx.notify();
904 return done_rx;
905 }
906 }
907 }
908 .into();
909 self.active_search = Some(query.clone());
910 let query_text = query.as_str().to_string();
911
912 let matches = active_searchable_item.find_matches(query, cx);
913
914 let active_searchable_item = active_searchable_item.downgrade();
915 self.pending_search = Some(cx.spawn(|this, mut cx| async move {
916 let matches = matches.await;
917
918 this.update(&mut cx, |this, cx| {
919 if let Some(active_searchable_item) =
920 WeakSearchableItemHandle::upgrade(active_searchable_item.as_ref(), cx)
921 {
922 this.searchable_items_with_matches
923 .insert(active_searchable_item.downgrade(), matches);
924
925 this.update_match_index(cx);
926 this.search_history
927 .add(&mut this.search_history_cursor, query_text);
928 if !this.dismissed {
929 let matches = this
930 .searchable_items_with_matches
931 .get(&active_searchable_item.downgrade())
932 .unwrap();
933 active_searchable_item.update_matches(matches, cx);
934 let _ = done_tx.send(());
935 }
936 cx.notify();
937 }
938 })
939 .log_err();
940 }));
941 }
942 }
943 done_rx
944 }
945
946 pub fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
947 let new_index = self
948 .active_searchable_item
949 .as_ref()
950 .and_then(|searchable_item| {
951 let matches = self
952 .searchable_items_with_matches
953 .get(&searchable_item.downgrade())?;
954 searchable_item.active_match_index(matches, cx)
955 });
956 if new_index != self.active_match_index {
957 self.active_match_index = new_index;
958 cx.notify();
959 }
960 }
961
962 fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
963 // Search -> Replace -> Editor
964 let focus_handle = if self.replace_enabled && self.query_editor_focused {
965 self.replacement_editor.focus_handle(cx)
966 } else if let Some(item) = self.active_searchable_item.as_ref() {
967 item.focus_handle(cx)
968 } else {
969 return;
970 };
971 cx.focus(&focus_handle);
972 cx.stop_propagation();
973 }
974
975 fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
976 // Search -> Replace -> Search
977 let focus_handle = if self.replace_enabled && self.query_editor_focused {
978 self.replacement_editor.focus_handle(cx)
979 } else if self.replacement_editor_focused {
980 self.query_editor.focus_handle(cx)
981 } else {
982 return;
983 };
984 cx.focus(&focus_handle);
985 cx.stop_propagation();
986 }
987
988 fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
989 if let Some(new_query) = self
990 .search_history
991 .next(&mut self.search_history_cursor)
992 .map(str::to_string)
993 {
994 let _ = self.search(&new_query, Some(self.search_options), cx);
995 } else {
996 self.search_history_cursor.reset();
997 let _ = self.search("", Some(self.search_options), cx);
998 }
999 }
1000
1001 fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
1002 if self.query(cx).is_empty() {
1003 if let Some(new_query) = self
1004 .search_history
1005 .current(&mut self.search_history_cursor)
1006 .map(str::to_string)
1007 {
1008 let _ = self.search(&new_query, Some(self.search_options), cx);
1009 return;
1010 }
1011 }
1012
1013 if let Some(new_query) = self
1014 .search_history
1015 .previous(&mut self.search_history_cursor)
1016 .map(str::to_string)
1017 {
1018 let _ = self.search(&new_query, Some(self.search_options), cx);
1019 }
1020 }
1021
1022 fn toggle_replace(&mut self, _: &ToggleReplace, cx: &mut ViewContext<Self>) {
1023 if let Some(_) = &self.active_searchable_item {
1024 self.replace_enabled = !self.replace_enabled;
1025 let handle = if self.replace_enabled {
1026 self.replacement_editor.focus_handle(cx)
1027 } else {
1028 self.query_editor.focus_handle(cx)
1029 };
1030 cx.focus(&handle);
1031 cx.notify();
1032 }
1033 }
1034 fn replace_next(&mut self, _: &ReplaceNext, cx: &mut ViewContext<Self>) {
1035 let mut should_propagate = true;
1036 if !self.dismissed && self.active_search.is_some() {
1037 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
1038 if let Some(query) = self.active_search.as_ref() {
1039 if let Some(matches) = self
1040 .searchable_items_with_matches
1041 .get(&searchable_item.downgrade())
1042 {
1043 if let Some(active_index) = self.active_match_index {
1044 let query = query
1045 .as_ref()
1046 .clone()
1047 .with_replacement(self.replacement(cx));
1048 searchable_item.replace(matches.at(active_index), &query, cx);
1049 self.select_next_match(&SelectNextMatch, cx);
1050 }
1051 should_propagate = false;
1052 self.focus_editor(&FocusEditor, cx);
1053 }
1054 }
1055 }
1056 }
1057 if !should_propagate {
1058 cx.stop_propagation();
1059 }
1060 }
1061 pub fn replace_all(&mut self, _: &ReplaceAll, cx: &mut ViewContext<Self>) {
1062 if !self.dismissed && self.active_search.is_some() {
1063 if let Some(searchable_item) = self.active_searchable_item.as_ref() {
1064 if let Some(query) = self.active_search.as_ref() {
1065 if let Some(matches) = self
1066 .searchable_items_with_matches
1067 .get(&searchable_item.downgrade())
1068 {
1069 let query = query
1070 .as_ref()
1071 .clone()
1072 .with_replacement(self.replacement(cx));
1073 for m in matches {
1074 searchable_item.replace(m, &query, cx);
1075 }
1076 }
1077 }
1078 }
1079 }
1080 }
1081
1082 pub fn match_exists(&mut self, cx: &mut ViewContext<Self>) -> bool {
1083 self.update_match_index(cx);
1084 self.active_match_index.is_some()
1085 }
1086}
1087
1088#[cfg(test)]
1089mod tests {
1090 use std::ops::Range;
1091
1092 use super::*;
1093 use editor::{DisplayPoint, Editor};
1094 use gpui::{Context, Hsla, TestAppContext, VisualTestContext};
1095 use language::Buffer;
1096 use project::Project;
1097 use smol::stream::StreamExt as _;
1098 use unindent::Unindent as _;
1099
1100 fn init_globals(cx: &mut TestAppContext) {
1101 cx.update(|cx| {
1102 let store = settings::SettingsStore::test(cx);
1103 cx.set_global(store);
1104 editor::init(cx);
1105
1106 language::init(cx);
1107 Project::init_settings(cx);
1108 theme::init(theme::LoadThemes::JustBase, cx);
1109 });
1110 }
1111
1112 fn init_test(
1113 cx: &mut TestAppContext,
1114 ) -> (View<Editor>, View<BufferSearchBar>, &mut VisualTestContext) {
1115 init_globals(cx);
1116 let buffer = cx.new_model(|cx| {
1117 Buffer::local(
1118 r#"
1119 A regular expression (shortened as regex or regexp;[1] also referred to as
1120 rational expression[2][3]) is a sequence of characters that specifies a search
1121 pattern in text. Usually such patterns are used by string-searching algorithms
1122 for "find" or "find and replace" operations on strings, or for input validation.
1123 "#
1124 .unindent(),
1125 cx,
1126 )
1127 });
1128 let cx = cx.add_empty_window();
1129 let editor = cx.new_view(|cx| Editor::for_buffer(buffer.clone(), None, cx));
1130
1131 let search_bar = cx.new_view(|cx| {
1132 let mut search_bar = BufferSearchBar::new(cx);
1133 search_bar.set_active_pane_item(Some(&editor), cx);
1134 search_bar.show(cx);
1135 search_bar
1136 });
1137
1138 (editor, search_bar, cx)
1139 }
1140
1141 #[gpui::test]
1142 async fn test_search_simple(cx: &mut TestAppContext) {
1143 let (editor, search_bar, cx) = init_test(cx);
1144 let display_points_of = |background_highlights: Vec<(Range<DisplayPoint>, Hsla)>| {
1145 background_highlights
1146 .into_iter()
1147 .map(|(range, _)| range)
1148 .collect::<Vec<_>>()
1149 };
1150 // Search for a string that appears with different casing.
1151 // By default, search is case-insensitive.
1152 search_bar
1153 .update(cx, |search_bar, cx| search_bar.search("us", None, cx))
1154 .await
1155 .unwrap();
1156 editor.update(cx, |editor, cx| {
1157 assert_eq!(
1158 display_points_of(editor.all_text_background_highlights(cx)),
1159 &[
1160 DisplayPoint::new(2, 17)..DisplayPoint::new(2, 19),
1161 DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
1162 ]
1163 );
1164 });
1165
1166 // Switch to a case sensitive search.
1167 search_bar.update(cx, |search_bar, cx| {
1168 search_bar.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
1169 });
1170 let mut editor_notifications = cx.notifications(&editor);
1171 editor_notifications.next().await;
1172 editor.update(cx, |editor, cx| {
1173 assert_eq!(
1174 display_points_of(editor.all_text_background_highlights(cx)),
1175 &[DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),]
1176 );
1177 });
1178
1179 // Search for a string that appears both as a whole word and
1180 // within other words. By default, all results are found.
1181 search_bar
1182 .update(cx, |search_bar, cx| search_bar.search("or", None, cx))
1183 .await
1184 .unwrap();
1185 editor.update(cx, |editor, cx| {
1186 assert_eq!(
1187 display_points_of(editor.all_text_background_highlights(cx)),
1188 &[
1189 DisplayPoint::new(0, 24)..DisplayPoint::new(0, 26),
1190 DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
1191 DisplayPoint::new(2, 71)..DisplayPoint::new(2, 73),
1192 DisplayPoint::new(3, 1)..DisplayPoint::new(3, 3),
1193 DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
1194 DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
1195 DisplayPoint::new(3, 60)..DisplayPoint::new(3, 62),
1196 ]
1197 );
1198 });
1199
1200 // Switch to a whole word search.
1201 search_bar.update(cx, |search_bar, cx| {
1202 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1203 });
1204 let mut editor_notifications = cx.notifications(&editor);
1205 editor_notifications.next().await;
1206 editor.update(cx, |editor, cx| {
1207 assert_eq!(
1208 display_points_of(editor.all_text_background_highlights(cx)),
1209 &[
1210 DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
1211 DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
1212 DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
1213 ]
1214 );
1215 });
1216
1217 editor.update(cx, |editor, cx| {
1218 editor.change_selections(None, cx, |s| {
1219 s.select_display_ranges([DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)])
1220 });
1221 });
1222 search_bar.update(cx, |search_bar, cx| {
1223 assert_eq!(search_bar.active_match_index, Some(0));
1224 search_bar.select_next_match(&SelectNextMatch, cx);
1225 assert_eq!(
1226 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1227 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1228 );
1229 });
1230 search_bar.update(cx, |search_bar, _| {
1231 assert_eq!(search_bar.active_match_index, Some(0));
1232 });
1233
1234 search_bar.update(cx, |search_bar, cx| {
1235 search_bar.select_next_match(&SelectNextMatch, cx);
1236 assert_eq!(
1237 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1238 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1239 );
1240 });
1241 search_bar.update(cx, |search_bar, _| {
1242 assert_eq!(search_bar.active_match_index, Some(1));
1243 });
1244
1245 search_bar.update(cx, |search_bar, cx| {
1246 search_bar.select_next_match(&SelectNextMatch, cx);
1247 assert_eq!(
1248 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1249 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1250 );
1251 });
1252 search_bar.update(cx, |search_bar, _| {
1253 assert_eq!(search_bar.active_match_index, Some(2));
1254 });
1255
1256 search_bar.update(cx, |search_bar, cx| {
1257 search_bar.select_next_match(&SelectNextMatch, cx);
1258 assert_eq!(
1259 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1260 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1261 );
1262 });
1263 search_bar.update(cx, |search_bar, _| {
1264 assert_eq!(search_bar.active_match_index, Some(0));
1265 });
1266
1267 search_bar.update(cx, |search_bar, cx| {
1268 search_bar.select_prev_match(&SelectPrevMatch, cx);
1269 assert_eq!(
1270 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1271 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1272 );
1273 });
1274 search_bar.update(cx, |search_bar, _| {
1275 assert_eq!(search_bar.active_match_index, Some(2));
1276 });
1277
1278 search_bar.update(cx, |search_bar, cx| {
1279 search_bar.select_prev_match(&SelectPrevMatch, cx);
1280 assert_eq!(
1281 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1282 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1283 );
1284 });
1285 search_bar.update(cx, |search_bar, _| {
1286 assert_eq!(search_bar.active_match_index, Some(1));
1287 });
1288
1289 search_bar.update(cx, |search_bar, cx| {
1290 search_bar.select_prev_match(&SelectPrevMatch, cx);
1291 assert_eq!(
1292 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1293 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1294 );
1295 });
1296 search_bar.update(cx, |search_bar, _| {
1297 assert_eq!(search_bar.active_match_index, Some(0));
1298 });
1299
1300 // Park the cursor in between matches and ensure that going to the previous match selects
1301 // the closest match to the left.
1302 editor.update(cx, |editor, cx| {
1303 editor.change_selections(None, cx, |s| {
1304 s.select_display_ranges([DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)])
1305 });
1306 });
1307 search_bar.update(cx, |search_bar, cx| {
1308 assert_eq!(search_bar.active_match_index, Some(1));
1309 search_bar.select_prev_match(&SelectPrevMatch, cx);
1310 assert_eq!(
1311 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1312 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1313 );
1314 });
1315 search_bar.update(cx, |search_bar, _| {
1316 assert_eq!(search_bar.active_match_index, Some(0));
1317 });
1318
1319 // Park the cursor in between matches and ensure that going to the next match selects the
1320 // closest match to the right.
1321 editor.update(cx, |editor, cx| {
1322 editor.change_selections(None, cx, |s| {
1323 s.select_display_ranges([DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)])
1324 });
1325 });
1326 search_bar.update(cx, |search_bar, cx| {
1327 assert_eq!(search_bar.active_match_index, Some(1));
1328 search_bar.select_next_match(&SelectNextMatch, cx);
1329 assert_eq!(
1330 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1331 [DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
1332 );
1333 });
1334 search_bar.update(cx, |search_bar, _| {
1335 assert_eq!(search_bar.active_match_index, Some(1));
1336 });
1337
1338 // Park the cursor after the last match and ensure that going to the previous match selects
1339 // the last match.
1340 editor.update(cx, |editor, cx| {
1341 editor.change_selections(None, cx, |s| {
1342 s.select_display_ranges([DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)])
1343 });
1344 });
1345 search_bar.update(cx, |search_bar, cx| {
1346 assert_eq!(search_bar.active_match_index, Some(2));
1347 search_bar.select_prev_match(&SelectPrevMatch, cx);
1348 assert_eq!(
1349 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1350 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1351 );
1352 });
1353 search_bar.update(cx, |search_bar, _| {
1354 assert_eq!(search_bar.active_match_index, Some(2));
1355 });
1356
1357 // Park the cursor after the last match and ensure that going to the next match selects the
1358 // first match.
1359 editor.update(cx, |editor, cx| {
1360 editor.change_selections(None, cx, |s| {
1361 s.select_display_ranges([DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)])
1362 });
1363 });
1364 search_bar.update(cx, |search_bar, cx| {
1365 assert_eq!(search_bar.active_match_index, Some(2));
1366 search_bar.select_next_match(&SelectNextMatch, cx);
1367 assert_eq!(
1368 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1369 [DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
1370 );
1371 });
1372 search_bar.update(cx, |search_bar, _| {
1373 assert_eq!(search_bar.active_match_index, Some(0));
1374 });
1375
1376 // Park the cursor before the first match and ensure that going to the previous match
1377 // selects the last match.
1378 editor.update(cx, |editor, cx| {
1379 editor.change_selections(None, cx, |s| {
1380 s.select_display_ranges([DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)])
1381 });
1382 });
1383 search_bar.update(cx, |search_bar, cx| {
1384 assert_eq!(search_bar.active_match_index, Some(0));
1385 search_bar.select_prev_match(&SelectPrevMatch, cx);
1386 assert_eq!(
1387 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1388 [DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
1389 );
1390 });
1391 search_bar.update(cx, |search_bar, _| {
1392 assert_eq!(search_bar.active_match_index, Some(2));
1393 });
1394 }
1395
1396 #[gpui::test]
1397 async fn test_search_option_handling(cx: &mut TestAppContext) {
1398 let (editor, search_bar, cx) = init_test(cx);
1399
1400 // show with options should make current search case sensitive
1401 search_bar
1402 .update(cx, |search_bar, cx| {
1403 search_bar.show(cx);
1404 search_bar.search("us", Some(SearchOptions::CASE_SENSITIVE), cx)
1405 })
1406 .await
1407 .unwrap();
1408 let display_points_of = |background_highlights: Vec<(Range<DisplayPoint>, Hsla)>| {
1409 background_highlights
1410 .into_iter()
1411 .map(|(range, _)| range)
1412 .collect::<Vec<_>>()
1413 };
1414 editor.update(cx, |editor, cx| {
1415 assert_eq!(
1416 display_points_of(editor.all_text_background_highlights(cx)),
1417 &[DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),]
1418 );
1419 });
1420
1421 // search_suggested should restore default options
1422 search_bar.update(cx, |search_bar, cx| {
1423 search_bar.search_suggested(cx);
1424 assert_eq!(search_bar.search_options, SearchOptions::NONE)
1425 });
1426
1427 // toggling a search option should update the defaults
1428 search_bar
1429 .update(cx, |search_bar, cx| {
1430 search_bar.search("regex", Some(SearchOptions::CASE_SENSITIVE), cx)
1431 })
1432 .await
1433 .unwrap();
1434 search_bar.update(cx, |search_bar, cx| {
1435 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, cx)
1436 });
1437 let mut editor_notifications = cx.notifications(&editor);
1438 editor_notifications.next().await;
1439 editor.update(cx, |editor, cx| {
1440 assert_eq!(
1441 display_points_of(editor.all_text_background_highlights(cx)),
1442 &[DisplayPoint::new(0, 35)..DisplayPoint::new(0, 40),]
1443 );
1444 });
1445
1446 // defaults should still include whole word
1447 search_bar.update(cx, |search_bar, cx| {
1448 search_bar.search_suggested(cx);
1449 assert_eq!(
1450 search_bar.search_options,
1451 SearchOptions::CASE_SENSITIVE | SearchOptions::WHOLE_WORD
1452 )
1453 });
1454 }
1455
1456 #[gpui::test]
1457 async fn test_search_select_all_matches(cx: &mut TestAppContext) {
1458 init_globals(cx);
1459 let buffer_text = r#"
1460 A regular expression (shortened as regex or regexp;[1] also referred to as
1461 rational expression[2][3]) is a sequence of characters that specifies a search
1462 pattern in text. Usually such patterns are used by string-searching algorithms
1463 for "find" or "find and replace" operations on strings, or for input validation.
1464 "#
1465 .unindent();
1466 let expected_query_matches_count = buffer_text
1467 .chars()
1468 .filter(|c| c.to_ascii_lowercase() == 'a')
1469 .count();
1470 assert!(
1471 expected_query_matches_count > 1,
1472 "Should pick a query with multiple results"
1473 );
1474 let buffer = cx.new_model(|cx| Buffer::local(buffer_text, cx));
1475 let window = cx.add_window(|_| gpui::Empty);
1476
1477 let editor = window.build_view(cx, |cx| Editor::for_buffer(buffer.clone(), None, cx));
1478
1479 let search_bar = window.build_view(cx, |cx| {
1480 let mut search_bar = BufferSearchBar::new(cx);
1481 search_bar.set_active_pane_item(Some(&editor), cx);
1482 search_bar.show(cx);
1483 search_bar
1484 });
1485
1486 window
1487 .update(cx, |_, cx| {
1488 search_bar.update(cx, |search_bar, cx| search_bar.search("a", None, cx))
1489 })
1490 .unwrap()
1491 .await
1492 .unwrap();
1493 let initial_selections = window
1494 .update(cx, |_, cx| {
1495 search_bar.update(cx, |search_bar, cx| {
1496 let handle = search_bar.query_editor.focus_handle(cx);
1497 cx.focus(&handle);
1498 search_bar.activate_current_match(cx);
1499 });
1500 assert!(
1501 !editor.read(cx).is_focused(cx),
1502 "Initially, the editor should not be focused"
1503 );
1504 let initial_selections = editor.update(cx, |editor, cx| {
1505 let initial_selections = editor.selections.display_ranges(cx);
1506 assert_eq!(
1507 initial_selections.len(), 1,
1508 "Expected to have only one selection before adding carets to all matches, but got: {initial_selections:?}",
1509 );
1510 initial_selections
1511 });
1512 search_bar.update(cx, |search_bar, cx| {
1513 assert_eq!(search_bar.active_match_index, Some(0));
1514 let handle = search_bar.query_editor.focus_handle(cx);
1515 cx.focus(&handle);
1516 search_bar.select_all_matches(&SelectAllMatches, cx);
1517 });
1518 assert!(
1519 editor.read(cx).is_focused(cx),
1520 "Should focus editor after successful SelectAllMatches"
1521 );
1522 search_bar.update(cx, |search_bar, cx| {
1523 let all_selections =
1524 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1525 assert_eq!(
1526 all_selections.len(),
1527 expected_query_matches_count,
1528 "Should select all `a` characters in the buffer, but got: {all_selections:?}"
1529 );
1530 assert_eq!(
1531 search_bar.active_match_index,
1532 Some(0),
1533 "Match index should not change after selecting all matches"
1534 );
1535 });
1536
1537 search_bar.update(cx, |this, cx| this.select_next_match(&SelectNextMatch, cx));
1538 initial_selections
1539 }).unwrap();
1540
1541 window
1542 .update(cx, |_, cx| {
1543 assert!(
1544 editor.read(cx).is_focused(cx),
1545 "Should still have editor focused after SelectNextMatch"
1546 );
1547 search_bar.update(cx, |search_bar, cx| {
1548 let all_selections =
1549 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1550 assert_eq!(
1551 all_selections.len(),
1552 1,
1553 "On next match, should deselect items and select the next match"
1554 );
1555 assert_ne!(
1556 all_selections, initial_selections,
1557 "Next match should be different from the first selection"
1558 );
1559 assert_eq!(
1560 search_bar.active_match_index,
1561 Some(1),
1562 "Match index should be updated to the next one"
1563 );
1564 let handle = search_bar.query_editor.focus_handle(cx);
1565 cx.focus(&handle);
1566 search_bar.select_all_matches(&SelectAllMatches, cx);
1567 });
1568 })
1569 .unwrap();
1570 window
1571 .update(cx, |_, cx| {
1572 assert!(
1573 editor.read(cx).is_focused(cx),
1574 "Should focus editor after successful SelectAllMatches"
1575 );
1576 search_bar.update(cx, |search_bar, cx| {
1577 let all_selections =
1578 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1579 assert_eq!(
1580 all_selections.len(),
1581 expected_query_matches_count,
1582 "Should select all `a` characters in the buffer, but got: {all_selections:?}"
1583 );
1584 assert_eq!(
1585 search_bar.active_match_index,
1586 Some(1),
1587 "Match index should not change after selecting all matches"
1588 );
1589 });
1590 search_bar.update(cx, |search_bar, cx| {
1591 search_bar.select_prev_match(&SelectPrevMatch, cx);
1592 });
1593 })
1594 .unwrap();
1595 let last_match_selections = window
1596 .update(cx, |_, cx| {
1597 assert!(
1598 editor.read(cx).is_focused(&cx),
1599 "Should still have editor focused after SelectPrevMatch"
1600 );
1601
1602 search_bar.update(cx, |search_bar, cx| {
1603 let all_selections =
1604 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1605 assert_eq!(
1606 all_selections.len(),
1607 1,
1608 "On previous match, should deselect items and select the previous item"
1609 );
1610 assert_eq!(
1611 all_selections, initial_selections,
1612 "Previous match should be the same as the first selection"
1613 );
1614 assert_eq!(
1615 search_bar.active_match_index,
1616 Some(0),
1617 "Match index should be updated to the previous one"
1618 );
1619 all_selections
1620 })
1621 })
1622 .unwrap();
1623
1624 window
1625 .update(cx, |_, cx| {
1626 search_bar.update(cx, |search_bar, cx| {
1627 let handle = search_bar.query_editor.focus_handle(cx);
1628 cx.focus(&handle);
1629 search_bar.search("abas_nonexistent_match", None, cx)
1630 })
1631 })
1632 .unwrap()
1633 .await
1634 .unwrap();
1635 window
1636 .update(cx, |_, cx| {
1637 search_bar.update(cx, |search_bar, cx| {
1638 search_bar.select_all_matches(&SelectAllMatches, cx);
1639 });
1640 assert!(
1641 editor.update(cx, |this, cx| !this.is_focused(cx.window_context())),
1642 "Should not switch focus to editor if SelectAllMatches does not find any matches"
1643 );
1644 search_bar.update(cx, |search_bar, cx| {
1645 let all_selections =
1646 editor.update(cx, |editor, cx| editor.selections.display_ranges(cx));
1647 assert_eq!(
1648 all_selections, last_match_selections,
1649 "Should not select anything new if there are no matches"
1650 );
1651 assert!(
1652 search_bar.active_match_index.is_none(),
1653 "For no matches, there should be no active match index"
1654 );
1655 });
1656 })
1657 .unwrap();
1658 }
1659
1660 #[gpui::test]
1661 async fn test_search_query_history(cx: &mut TestAppContext) {
1662 init_globals(cx);
1663 let buffer_text = r#"
1664 A regular expression (shortened as regex or regexp;[1] also referred to as
1665 rational expression[2][3]) is a sequence of characters that specifies a search
1666 pattern in text. Usually such patterns are used by string-searching algorithms
1667 for "find" or "find and replace" operations on strings, or for input validation.
1668 "#
1669 .unindent();
1670 let buffer = cx.new_model(|cx| Buffer::local(buffer_text, cx));
1671 let cx = cx.add_empty_window();
1672
1673 let editor = cx.new_view(|cx| Editor::for_buffer(buffer.clone(), None, cx));
1674
1675 let search_bar = cx.new_view(|cx| {
1676 let mut search_bar = BufferSearchBar::new(cx);
1677 search_bar.set_active_pane_item(Some(&editor), cx);
1678 search_bar.show(cx);
1679 search_bar
1680 });
1681
1682 // Add 3 search items into the history.
1683 search_bar
1684 .update(cx, |search_bar, cx| search_bar.search("a", None, cx))
1685 .await
1686 .unwrap();
1687 search_bar
1688 .update(cx, |search_bar, cx| search_bar.search("b", None, cx))
1689 .await
1690 .unwrap();
1691 search_bar
1692 .update(cx, |search_bar, cx| {
1693 search_bar.search("c", Some(SearchOptions::CASE_SENSITIVE), cx)
1694 })
1695 .await
1696 .unwrap();
1697 // Ensure that the latest search is active.
1698 search_bar.update(cx, |search_bar, cx| {
1699 assert_eq!(search_bar.query(cx), "c");
1700 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1701 });
1702
1703 // Next history query after the latest should set the query to the empty string.
1704 search_bar.update(cx, |search_bar, cx| {
1705 search_bar.next_history_query(&NextHistoryQuery, cx);
1706 });
1707 search_bar.update(cx, |search_bar, cx| {
1708 assert_eq!(search_bar.query(cx), "");
1709 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1710 });
1711 search_bar.update(cx, |search_bar, cx| {
1712 search_bar.next_history_query(&NextHistoryQuery, cx);
1713 });
1714 search_bar.update(cx, |search_bar, cx| {
1715 assert_eq!(search_bar.query(cx), "");
1716 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1717 });
1718
1719 // First previous query for empty current query should set the query to the latest.
1720 search_bar.update(cx, |search_bar, cx| {
1721 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1722 });
1723 search_bar.update(cx, |search_bar, cx| {
1724 assert_eq!(search_bar.query(cx), "c");
1725 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1726 });
1727
1728 // Further previous items should go over the history in reverse order.
1729 search_bar.update(cx, |search_bar, cx| {
1730 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1731 });
1732 search_bar.update(cx, |search_bar, cx| {
1733 assert_eq!(search_bar.query(cx), "b");
1734 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1735 });
1736
1737 // Previous items should never go behind the first history item.
1738 search_bar.update(cx, |search_bar, cx| {
1739 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1740 });
1741 search_bar.update(cx, |search_bar, cx| {
1742 assert_eq!(search_bar.query(cx), "a");
1743 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1744 });
1745 search_bar.update(cx, |search_bar, cx| {
1746 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1747 });
1748 search_bar.update(cx, |search_bar, cx| {
1749 assert_eq!(search_bar.query(cx), "a");
1750 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1751 });
1752
1753 // Next items should go over the history in the original order.
1754 search_bar.update(cx, |search_bar, cx| {
1755 search_bar.next_history_query(&NextHistoryQuery, cx);
1756 });
1757 search_bar.update(cx, |search_bar, cx| {
1758 assert_eq!(search_bar.query(cx), "b");
1759 assert_eq!(search_bar.search_options, SearchOptions::CASE_SENSITIVE);
1760 });
1761
1762 search_bar
1763 .update(cx, |search_bar, cx| search_bar.search("ba", None, cx))
1764 .await
1765 .unwrap();
1766 search_bar.update(cx, |search_bar, cx| {
1767 assert_eq!(search_bar.query(cx), "ba");
1768 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1769 });
1770
1771 // New search input should add another entry to history and move the selection to the end of the history.
1772 search_bar.update(cx, |search_bar, cx| {
1773 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1774 });
1775 search_bar.update(cx, |search_bar, cx| {
1776 assert_eq!(search_bar.query(cx), "c");
1777 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1778 });
1779 search_bar.update(cx, |search_bar, cx| {
1780 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
1781 });
1782 search_bar.update(cx, |search_bar, cx| {
1783 assert_eq!(search_bar.query(cx), "b");
1784 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1785 });
1786 search_bar.update(cx, |search_bar, cx| {
1787 search_bar.next_history_query(&NextHistoryQuery, cx);
1788 });
1789 search_bar.update(cx, |search_bar, cx| {
1790 assert_eq!(search_bar.query(cx), "c");
1791 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1792 });
1793 search_bar.update(cx, |search_bar, cx| {
1794 search_bar.next_history_query(&NextHistoryQuery, cx);
1795 });
1796 search_bar.update(cx, |search_bar, cx| {
1797 assert_eq!(search_bar.query(cx), "ba");
1798 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1799 });
1800 search_bar.update(cx, |search_bar, cx| {
1801 search_bar.next_history_query(&NextHistoryQuery, cx);
1802 });
1803 search_bar.update(cx, |search_bar, cx| {
1804 assert_eq!(search_bar.query(cx), "");
1805 assert_eq!(search_bar.search_options, SearchOptions::NONE);
1806 });
1807 }
1808
1809 #[gpui::test]
1810 async fn test_replace_simple(cx: &mut TestAppContext) {
1811 let (editor, search_bar, cx) = init_test(cx);
1812
1813 search_bar
1814 .update(cx, |search_bar, cx| {
1815 search_bar.search("expression", None, cx)
1816 })
1817 .await
1818 .unwrap();
1819
1820 search_bar.update(cx, |search_bar, cx| {
1821 search_bar.replacement_editor.update(cx, |editor, cx| {
1822 // We use $1 here as initially we should be in Text mode, where `$1` should be treated literally.
1823 editor.set_text("expr$1", cx);
1824 });
1825 search_bar.replace_all(&ReplaceAll, cx)
1826 });
1827 assert_eq!(
1828 editor.update(cx, |this, cx| { this.text(cx) }),
1829 r#"
1830 A regular expr$1 (shortened as regex or regexp;[1] also referred to as
1831 rational expr$1[2][3]) is a sequence of characters that specifies a search
1832 pattern in text. Usually such patterns are used by string-searching algorithms
1833 for "find" or "find and replace" operations on strings, or for input validation.
1834 "#
1835 .unindent()
1836 );
1837
1838 // Search for word boundaries and replace just a single one.
1839 search_bar
1840 .update(cx, |search_bar, cx| {
1841 search_bar.search("or", Some(SearchOptions::WHOLE_WORD), cx)
1842 })
1843 .await
1844 .unwrap();
1845
1846 search_bar.update(cx, |search_bar, cx| {
1847 search_bar.replacement_editor.update(cx, |editor, cx| {
1848 editor.set_text("banana", cx);
1849 });
1850 search_bar.replace_next(&ReplaceNext, cx)
1851 });
1852 // Notice how the first or in the text (shORtened) is not replaced. Neither are the remaining hits of `or` in the text.
1853 assert_eq!(
1854 editor.update(cx, |this, cx| { this.text(cx) }),
1855 r#"
1856 A regular expr$1 (shortened as regex banana regexp;[1] also referred to as
1857 rational expr$1[2][3]) is a sequence of characters that specifies a search
1858 pattern in text. Usually such patterns are used by string-searching algorithms
1859 for "find" or "find and replace" operations on strings, or for input validation.
1860 "#
1861 .unindent()
1862 );
1863 // Let's turn on regex mode.
1864 search_bar
1865 .update(cx, |search_bar, cx| {
1866 search_bar.search("\\[([^\\]]+)\\]", Some(SearchOptions::REGEX), cx)
1867 })
1868 .await
1869 .unwrap();
1870 search_bar.update(cx, |search_bar, cx| {
1871 search_bar.replacement_editor.update(cx, |editor, cx| {
1872 editor.set_text("${1}number", cx);
1873 });
1874 search_bar.replace_all(&ReplaceAll, cx)
1875 });
1876 assert_eq!(
1877 editor.update(cx, |this, cx| { this.text(cx) }),
1878 r#"
1879 A regular expr$1 (shortened as regex banana regexp;1number also referred to as
1880 rational expr$12number3number) is a sequence of characters that specifies a search
1881 pattern in text. Usually such patterns are used by string-searching algorithms
1882 for "find" or "find and replace" operations on strings, or for input validation.
1883 "#
1884 .unindent()
1885 );
1886 // Now with a whole-word twist.
1887 search_bar
1888 .update(cx, |search_bar, cx| {
1889 search_bar.search(
1890 "a\\w+s",
1891 Some(SearchOptions::REGEX | SearchOptions::WHOLE_WORD),
1892 cx,
1893 )
1894 })
1895 .await
1896 .unwrap();
1897 search_bar.update(cx, |search_bar, cx| {
1898 search_bar.replacement_editor.update(cx, |editor, cx| {
1899 editor.set_text("things", cx);
1900 });
1901 search_bar.replace_all(&ReplaceAll, cx)
1902 });
1903 // The only word affected by this edit should be `algorithms`, even though there's a bunch
1904 // of words in this text that would match this regex if not for WHOLE_WORD.
1905 assert_eq!(
1906 editor.update(cx, |this, cx| { this.text(cx) }),
1907 r#"
1908 A regular expr$1 (shortened as regex banana regexp;1number also referred to as
1909 rational expr$12number3number) is a sequence of characters that specifies a search
1910 pattern in text. Usually such patterns are used by string-searching things
1911 for "find" or "find and replace" operations on strings, or for input validation.
1912 "#
1913 .unindent()
1914 );
1915 }
1916
1917 struct ReplacementTestParams<'a> {
1918 editor: &'a View<Editor>,
1919 search_bar: &'a View<BufferSearchBar>,
1920 cx: &'a mut VisualTestContext,
1921 search_text: &'static str,
1922 search_options: Option<SearchOptions>,
1923 replacement_text: &'static str,
1924 replace_all: bool,
1925 expected_text: String,
1926 }
1927
1928 async fn run_replacement_test(options: ReplacementTestParams<'_>) {
1929 options
1930 .search_bar
1931 .update(options.cx, |search_bar, cx| {
1932 if let Some(options) = options.search_options {
1933 search_bar.set_search_options(options, cx);
1934 }
1935 search_bar.search(options.search_text, options.search_options, cx)
1936 })
1937 .await
1938 .unwrap();
1939
1940 options.search_bar.update(options.cx, |search_bar, cx| {
1941 search_bar.replacement_editor.update(cx, |editor, cx| {
1942 editor.set_text(options.replacement_text, cx);
1943 });
1944
1945 if options.replace_all {
1946 search_bar.replace_all(&ReplaceAll, cx)
1947 } else {
1948 search_bar.replace_next(&ReplaceNext, cx)
1949 }
1950 });
1951
1952 assert_eq!(
1953 options
1954 .editor
1955 .update(options.cx, |this, cx| { this.text(cx) }),
1956 options.expected_text
1957 );
1958 }
1959
1960 #[gpui::test]
1961 async fn test_replace_special_characters(cx: &mut TestAppContext) {
1962 let (editor, search_bar, cx) = init_test(cx);
1963
1964 run_replacement_test(ReplacementTestParams {
1965 editor: &editor,
1966 search_bar: &search_bar,
1967 cx,
1968 search_text: "expression",
1969 search_options: None,
1970 replacement_text: r"\n",
1971 replace_all: true,
1972 expected_text: r#"
1973 A regular \n (shortened as regex or regexp;[1] also referred to as
1974 rational \n[2][3]) is a sequence of characters that specifies a search
1975 pattern in text. Usually such patterns are used by string-searching algorithms
1976 for "find" or "find and replace" operations on strings, or for input validation.
1977 "#
1978 .unindent(),
1979 })
1980 .await;
1981
1982 run_replacement_test(ReplacementTestParams {
1983 editor: &editor,
1984 search_bar: &search_bar,
1985 cx,
1986 search_text: "or",
1987 search_options: Some(SearchOptions::WHOLE_WORD | SearchOptions::REGEX),
1988 replacement_text: r"\\\n\\\\",
1989 replace_all: false,
1990 expected_text: r#"
1991 A regular \n (shortened as regex \
1992 \\ regexp;[1] also referred to as
1993 rational \n[2][3]) is a sequence of characters that specifies a search
1994 pattern in text. Usually such patterns are used by string-searching algorithms
1995 for "find" or "find and replace" operations on strings, or for input validation.
1996 "#
1997 .unindent(),
1998 })
1999 .await;
2000
2001 run_replacement_test(ReplacementTestParams {
2002 editor: &editor,
2003 search_bar: &search_bar,
2004 cx,
2005 search_text: r"(that|used) ",
2006 search_options: Some(SearchOptions::REGEX),
2007 replacement_text: r"$1\n",
2008 replace_all: true,
2009 expected_text: r#"
2010 A regular \n (shortened as regex \
2011 \\ regexp;[1] also referred to as
2012 rational \n[2][3]) is a sequence of characters that
2013 specifies a search
2014 pattern in text. Usually such patterns are used
2015 by string-searching algorithms
2016 for "find" or "find and replace" operations on strings, or for input validation.
2017 "#
2018 .unindent(),
2019 })
2020 .await;
2021 }
2022
2023 #[gpui::test]
2024 async fn test_invalid_regexp_search_after_valid(cx: &mut TestAppContext) {
2025 let (editor, search_bar, cx) = init_test(cx);
2026 let display_points_of = |background_highlights: Vec<(Range<DisplayPoint>, Hsla)>| {
2027 background_highlights
2028 .into_iter()
2029 .map(|(range, _)| range)
2030 .collect::<Vec<_>>()
2031 };
2032 // Search using valid regexp
2033 search_bar
2034 .update(cx, |search_bar, cx| {
2035 search_bar.enable_search_option(SearchOptions::REGEX, cx);
2036 search_bar.search("expression", None, cx)
2037 })
2038 .await
2039 .unwrap();
2040 editor.update(cx, |editor, cx| {
2041 assert_eq!(
2042 display_points_of(editor.all_text_background_highlights(cx)),
2043 &[
2044 DisplayPoint::new(0, 10)..DisplayPoint::new(0, 20),
2045 DisplayPoint::new(1, 9)..DisplayPoint::new(1, 19),
2046 ],
2047 );
2048 });
2049
2050 // Now, the expression is invalid
2051 search_bar
2052 .update(cx, |search_bar, cx| {
2053 search_bar.search("expression (", None, cx)
2054 })
2055 .await
2056 .unwrap_err();
2057 editor.update(cx, |editor, cx| {
2058 assert!(display_points_of(editor.all_text_background_highlights(cx)).is_empty(),);
2059 });
2060 }
2061}