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