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