Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
text_finder: Highlight the query as a regex when the regex filter is on (#61128)
Apoorva Verma803467f37f8f
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex 3689f1903d0..5329fdb7287 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -392,9 +392,8 @@ pub fn init(cx: &mut App) {.detach_and_log_err(cx);});_ = ui_input::ERASED_EDITOR_FACTORY.set(|window, cx| {- Arc::new(ErasedEditorImpl(- cx.new(|cx| Editor::single_line(window, cx)),- )) as Arc<dyn ErasedEditor>+ cx.new(|cx| Editor::single_line(window, cx))+ .update(cx, |editor, cx| editor.erased(cx))});_ = multi_buffer::EXCERPT_CONTEXT_LINES.set(multibuffer_context_lines);}@@ -1730,6 +1729,10 @@ impl Editor {Self::new(EditorMode::SingleLine, buffer, None, window, cx)}+ pub fn erased(&self, cx: &Context<Self>) -> Arc<dyn ErasedEditor> {+ Arc::new(ErasedEditorImpl(cx.entity()))+ }+pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {let buffer = cx.new(|cx| Buffer::local("", cx));let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));diff --git a/crates/picker/src/head.rs b/crates/picker/src/head.rsindex d0315e5064e..74f99bdaad7 100644--- a/crates/picker/src/head.rs+++ b/crates/picker/src/head.rs@@ -16,12 +16,21 @@ pub(crate) enum Head {impl Head {pub fn editor<V: 'static>(placeholder_text: Arc<str>,- mut edit_handler: impl FnMut(&mut V, &ErasedEditorEvent, &mut Window, &mut Context<V>) + 'static,+ edit_handler: impl FnMut(&mut V, &ErasedEditorEvent, &mut Window, &mut Context<V>) + 'static,window: &mut Window,cx: &mut Context<V>,) -> Self {let editor = (ui_input::ERASED_EDITOR_FACTORY.get().unwrap())(window, cx);+ Self::with_editor(editor, placeholder_text, edit_handler, window, cx)+ }+ pub fn with_editor<V: 'static>(+ editor: Arc<dyn ErasedEditor>,+ placeholder_text: Arc<str>,+ mut edit_handler: impl FnMut(&mut V, &ErasedEditorEvent, &mut Window, &mut Context<V>) + 'static,+ window: &mut Window,+ cx: &mut Context<V>,+ ) -> Self {editor.set_placeholder_text(placeholder_text.as_ref(), window, cx);let this = cx.weak_entity();editordiff --git a/crates/picker/src/picker.rs b/crates/picker/src/picker.rsindex ad20dfc28ce..c1c95fba6dc 100644--- a/crates/picker/src/picker.rs+++ b/crates/picker/src/picker.rs@@ -514,6 +514,32 @@ impl<D: PickerDelegate> Picker<D> {)}+ pub fn list_with_preview_and_query_editor(+ delegate: D,+ preview: Arc<dyn PreviewBackend>,+ query_editor: Arc<dyn ErasedEditor>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> Self {+ let head = Head::with_editor(+ query_editor,+ delegate.placeholder_text(window, cx),+ Self::on_input_editor_event,+ window,+ cx,+ );++ let preview = Preview::new(preview);+ Self::new(+ delegate,+ ContainerKind::List,+ head,+ Some(preview),+ window,+ cx,+ )+ }+/// A picker, which displays its matches using `gpui::uniform_list`, all matches should have the same height./// If `PickerDelegate::render_match` can return items with different heights, use `Picker::list`.pub fn nonsearchable_uniform_list(diff --git a/crates/search/src/text_finder.rs b/crates/search/src/text_finder.rsindex fcea325c68f..c2b15fa2522 100644--- a/crates/search/src/text_finder.rs+++ b/crates/search/src/text_finder.rs@@ -5,9 +5,10 @@ use db::{sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},sqlez_macros::sql,};+use editor::Editor;use gpui::{App, AppContext, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,- Modifiers, Subscription, Task, WeakEntity, actions,+ Modifiers, Subscription, Task, TaskExt as _, WeakEntity, actions,};use language::Buffer;use picker::Picker;@@ -420,12 +421,24 @@ impl TextFinder {cx: &mut Context<Self>,) -> Self {let project = delegate.project(cx).clone();+ let languages = project.read(cx).languages().clone();let preview = picker_preview::editor_preview(project, window, cx);- let picker = cx.new(|cx| Picker::list_with_preview(delegate, preview, window, cx));+ let query_editor = cx.new(|cx| Editor::single_line(window, cx));+ let erased_query_editor = query_editor.update(cx, |editor, cx| editor.erased(cx));+ let picker = cx.new(|cx| {+ Picker::list_with_preview_and_query_editor(+ delegate,+ preview,+ erased_query_editor,+ window,+ cx,+ )+ });let picker_weak = picker.downgrade();let picker_focus_handle = picker.focus_handle(cx);picker.update(cx, |picker, cx| {picker.delegate.focus_handle = picker_focus_handle.clone();+ picker.delegate.query_editor = Some(query_editor);picker.delegate.hook_up_any_ongoing_search(picker_weak, cx);if let Some(seed_query) = seed_query {// Restore filters before seeding the query so the initial search runs with them.@@ -436,6 +449,25 @@ impl TextFinder {picker.select_query(window, cx);}});+ cx.spawn({+ let picker = picker.downgrade();+ async move |_, cx| {+ use anyhow::Context as _;++ let regex_language = languages+ .language_for_name("regex")+ .await+ .context("loading regex language")?;+ picker+ .update(cx, |picker, cx| {+ picker.delegate.regex_language = Some(regex_language);+ picker.delegate.adjust_query_regex_language(cx);+ })+ .ok();+ anyhow::Ok(())+ }+ })+ .detach_and_log_err(cx);let subscription = cx.subscribe(&picker, |_, _, _: &DismissEvent, cx| {cx.emit(DismissEvent);});@@ -500,6 +532,8 @@ pub struct SearchMatch {#[cfg(test)]mod tests {+ use std::sync::Arc;+use gpui::{TestAppContext, VisualTestContext};use project::{FakeFs, Project};use serde_json::json;@@ -507,6 +541,7 @@ mod tests {use util::path;use workspace::MultiWorkspace;+ use super::delegate::toggle_search_option;use super::*;fn init_test(cx: &mut TestAppContext) {@@ -634,4 +669,79 @@ mod tests {});assert!(seed_query.is_none());}++ #[gpui::test]+ async fn test_query_highlighted_as_regex_while_regex_filter_is_on(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.background_executor.clone());+ fs.insert_tree(path!("/dir"), json!({"one.rs": "const ONE: usize = 1;"}))+ .await;+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());+ language_registry.add(Arc::new(language::Language::new(+ language::LanguageConfig {+ name: "regex".into(),+ ..Default::default()+ },+ None,+ )));++ let window = cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));+ let workspace = window+ .read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone())+ .unwrap();+ let cx = &mut VisualTestContext::from_window(window.into(), cx);++ let seed_query = SearchSeed {+ query: "O.E".to_string(),+ options: Some(SearchOptions::REGEX),+ };+ workspace+ .update_in(cx, |_, window, cx| {+ TextFinder::open(Some(seed_query), window, cx)+ })+ .await;+ cx.run_until_parked();++ let picker = workspace.update(cx, |workspace, cx| {+ workspace+ .active_modal::<TextFinder>(cx)+ .expect("text finder should be open")+ .read(cx)+ .picker+ .clone()+ });++ picker.read_with(cx, |picker, cx| {+ assert_eq!(+ query_language_name(&picker.delegate, cx).as_deref(),+ Some("regex"),+ "query should be highlighted as a regex while the regex filter is on"+ );+ });++ picker.update_in(cx, |picker, window, cx| {+ toggle_search_option(picker, SearchOptions::REGEX, window, cx);+ });++ picker.read_with(cx, |picker, cx| {+ assert_eq!(+ query_language_name(&picker.delegate, cx),+ None,+ "highlighting should be dropped once the regex filter is off"+ );+ });+ }++ fn query_language_name(delegate: &Delegate, cx: &App) -> Option<String> {+ let query_buffer = delegate+ .query_editor+ .as_ref()?+ .read(cx)+ .buffer()+ .read(cx)+ .as_singleton()?;+ Some(query_buffer.read(cx).language()?.name().to_string())+ }}diff --git a/crates/search/src/text_finder/delegate.rs b/crates/search/src/text_finder/delegate.rsindex 8acc4338d44..292ba1c3ee9 100644--- a/crates/search/src/text_finder/delegate.rs+++ b/crates/search/src/text_finder/delegate.rs@@ -28,15 +28,15 @@ use std::sync::atomic::{AtomicBool, Ordering};use std::{ops::Range, time::Duration};use collections::{HashMap, HashSet};-use editor::{MultiBufferSnapshot, PathKey, multibuffer_context_lines};+use editor::{Editor, MultiBufferSnapshot, PathKey, multibuffer_context_lines};use file_icons::FileIcons;use futures::StreamExt;use gpui::{- AnyElement, AppContext, AsyncApp, ClickEvent, DismissEvent, EntityId, HighlightStyle,+ AnyElement, App, AppContext, AsyncApp, ClickEvent, DismissEvent, EntityId, HighlightStyle,Modifiers, StyledText, Task, TextStyle, prelude::*,};use gpui::{Entity, FocusHandle, WeakEntity};-use language::{Buffer, LanguageAwareStyling};+use language::{Buffer, Language, LanguageAwareStyling};use picker::{Picker, PickerDelegate};use project::{Project, ProjectPath, Search};use project::{SearchResults, search::SearchQuery, search::SearchResult};@@ -88,6 +88,8 @@ pub struct Delegate {pub(crate) max_line_number: u32,pub(crate) selected_matches: Vec<SelectedMatch>,pub(crate) collapsed_paths: HashSet<ProjectPath>,+ pub(crate) query_editor: Option<Entity<Editor>>,+ pub(crate) regex_language: Option<Arc<Language>>,}/// Wrapper with Eq is path + range equality@@ -327,6 +329,8 @@ impl Delegate {max_line_number: 0,selected_matches: Vec::new(),collapsed_paths: HashSet::default(),+ query_editor: None,+ regex_language: None,});this@@ -593,6 +597,35 @@ impl Delegate {.detach();cx.emit(DismissEvent);}++ pub(crate) fn adjust_query_regex_language(&self, cx: &mut App) {+ let Some(query_buffer) = self+ .query_editor+ .as_ref()+ .and_then(|query_editor| query_editor.read(cx).buffer().read(cx).as_singleton())+ else {+ return;+ };+ let language = if self.search_options.contains(SearchOptions::REGEX) {+ self.regex_language.clone()+ } else {+ None+ };+ query_buffer.update(cx, |query_buffer, cx| {+ query_buffer.set_language(language, cx);+ });+ }+}++pub(crate) fn toggle_search_option(+ picker: &mut Picker<Delegate>,+ options: SearchOptions,+ window: &mut Window,+ cx: &mut Context<Picker<Delegate>>,+) {+ picker.delegate.search_options.toggle(options);+ picker.delegate.adjust_query_regex_language(cx);+ picker.refresh(window, cx);}pub(crate) enum PopulateProjectSearch {@@ -729,8 +762,7 @@ impl PickerDelegate for Delegate {.tooltip(move |_window, cx| Tooltip::for_action_in(label, action, &focus_handle, cx)).on_click(move |_, window, cx| {picker.update(cx, |picker, cx| {- picker.delegate.search_options.toggle(options);- picker.refresh(window, cx);+ toggle_search_option(picker, options, window, cx);});})});