buffer_search.rs

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