buffer_search.rs

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