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