diff --git a/Cargo.lock b/Cargo.lock index ff1041695e1f1e..edb0acdce20484 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14453,6 +14453,28 @@ dependencies = [ "zed_actions", ] +[[package]] +name = "search_everywhere" +version = "0.1.0" +dependencies = [ + "anyhow", + "collections", + "command_palette_hooks", + "ctor", + "editor", + "futures 0.3.31", + "fuzzy", + "gpui", + "language", + "log", + "parking_lot", + "picker", + "project", + "ui", + "util", + "workspace", +] + [[package]] name = "sec1" version = "0.3.0" @@ -20563,6 +20585,7 @@ dependencies = [ "reqwest_client", "rope", "search", + "search_everywhere", "semver", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 523dce229e6b58..f68728f9a6a4e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -147,6 +147,7 @@ members = [ "crates/rules_library", "crates/schema_generator", "crates/search", + "crates/search_everywhere", "crates/session", "crates/settings", "crates/settings_json", @@ -373,6 +374,7 @@ rope = { path = "crates/rope" } rpc = { path = "crates/rpc" } rules_library = { path = "crates/rules_library" } search = { path = "crates/search" } +search_everywhere = { path = "crates/search_everywhere" } session = { path = "crates/session" } settings = { path = "crates/settings" } settings_json = { path = "crates/settings_json" } diff --git a/assets/keymaps/default-linux.json b/assets/keymaps/default-linux.json index 1fb02e6c1f1bf4..432f44cca430b5 100644 --- a/assets/keymaps/default-linux.json +++ b/assets/keymaps/default-linux.json @@ -617,6 +617,7 @@ "ctrl-alt-super-p": "settings_profile_selector::Toggle", "ctrl-t": "project_symbols::Toggle", "ctrl-p": "file_finder::Toggle", + "shift shift": "search_everywhere::Toggle", "ctrl-shift-tab": ["tab_switcher::Toggle", { "select_last": true }], "ctrl-tab": "tab_switcher::Toggle", "ctrl-e": "file_finder::Toggle", diff --git a/assets/keymaps/default-macos.json b/assets/keymaps/default-macos.json index 9edfaa03f8d7c9..fdfe3107d0fd1e 100644 --- a/assets/keymaps/default-macos.json +++ b/assets/keymaps/default-macos.json @@ -684,6 +684,7 @@ "ctrl-alt-cmd-p": "settings_profile_selector::Toggle", "cmd-t": "project_symbols::Toggle", "cmd-p": "file_finder::Toggle", + "shift shift": "search_everywhere::Toggle", "ctrl-shift-tab": ["tab_switcher::Toggle", { "select_last": true }], "ctrl-tab": "tab_switcher::Toggle", "cmd-shift-p": "command_palette::Toggle", diff --git a/assets/keymaps/default-windows.json b/assets/keymaps/default-windows.json index a4211e3c25a58f..511955fdeda640 100644 --- a/assets/keymaps/default-windows.json +++ b/assets/keymaps/default-windows.json @@ -609,6 +609,7 @@ "ctrl-alt-super-p": "settings_profile_selector::Toggle", "ctrl-t": "project_symbols::Toggle", "ctrl-p": "file_finder::Toggle", + "shift shift": "search_everywhere::Toggle", "ctrl-shift-tab": ["tab_switcher::Toggle", { "select_last": true }], "ctrl-tab": "tab_switcher::Toggle", "ctrl-e": "file_finder::Toggle", diff --git a/crates/search_everywhere/Cargo.toml b/crates/search_everywhere/Cargo.toml new file mode 100644 index 00000000000000..a09d1d9e46c658 --- /dev/null +++ b/crates/search_everywhere/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "search_everywhere" +version = "0.1.0" +edition.workspace = true +publish.workspace = true +license = "GPL-3.0-or-later" + +[lints] +workspace = true + +[lib] +path = "src/search_everywhere.rs" +doctest = false + +[dependencies] +anyhow.workspace = true +collections.workspace = true +command_palette_hooks.workspace = true +editor.workspace = true +futures.workspace = true +fuzzy.workspace = true +gpui.workspace = true +language.workspace = true +log.workspace = true +parking_lot.workspace = true +picker.workspace = true +project.workspace = true +ui.workspace = true +util.workspace = true +workspace.workspace = true + +[dev-dependencies] +ctor.workspace = true +editor = { workspace = true, features = ["test-support"] } +gpui = { workspace = true, features = ["test-support"] } +language = { workspace = true, features = ["test-support"] } +picker = { workspace = true, features = ["test-support"] } +workspace = { workspace = true, features = ["test-support"] } diff --git a/crates/search_everywhere/LICENSE-GPL b/crates/search_everywhere/LICENSE-GPL new file mode 120000 index 00000000000000..89e542f750cd38 --- /dev/null +++ b/crates/search_everywhere/LICENSE-GPL @@ -0,0 +1 @@ +../../LICENSE-GPL \ No newline at end of file diff --git a/crates/search_everywhere/src/actions.rs b/crates/search_everywhere/src/actions.rs new file mode 100644 index 00000000000000..442401e2214f4d --- /dev/null +++ b/crates/search_everywhere/src/actions.rs @@ -0,0 +1,136 @@ +use command_palette_hooks::CommandPaletteFilter; +use fuzzy::{StringMatch, StringMatchCandidate}; +use gpui::{Action, SharedString, Task, Window}; + +use crate::SearchEverywhereDelegate; +use crate::providers::{SearchResult, SearchResultCategory}; + +pub struct ActionProvider { + commands: Vec, +} + +struct Command { + name: String, + action: Box, +} + +impl ActionProvider { + pub fn new(window: &mut Window, cx: &mut gpui::Context) -> Self { + let filter = CommandPaletteFilter::try_global(cx); + + let commands = window + .available_actions(cx) + .into_iter() + .filter_map(|action| { + if filter.is_some_and(|filter| filter.is_hidden(&*action)) { + return None; + } + + Some(Command { + name: humanize_action_name(action.name()), + action, + }) + }) + .collect(); + + Self { commands } + } + + pub fn search( + &self, + query: &str, + _window: &mut Window, + cx: &mut gpui::Context>, + ) -> Task> { + if query.is_empty() { + return Task::ready(Vec::new()); + } + + let candidates: Vec = self + .commands + .iter() + .enumerate() + .map(|(id, c)| StringMatchCandidate::new(id, &c.name)) + .collect(); + + let query = query.to_string(); + let commands: Vec<_> = self + .commands + .iter() + .map(|c| (c.name.clone(), c.action.boxed_clone())) + .collect(); + + cx.spawn(async move |_, cx| { + let matches = fuzzy::match_strings( + &candidates, + &query, + true, + true, + 100, + &Default::default(), + cx.background_executor().clone(), + ) + .await; + + matches + .into_iter() + .filter_map(|m| { + let (name, action) = commands.get(m.candidate_id)?; + + let result = SearchResult { + label: SharedString::from(name.clone()), + detail: None, + category: SearchResultCategory::Action, + path: None, + action: Some(action.boxed_clone()), + symbol: None, + document_symbol: None, + }; + + Some((result, m)) + }) + .collect() + }) + } +} + +fn humanize_action_name(name: &str) -> String { + let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count(); + let mut result = String::with_capacity(capacity); + + for char in name.chars() { + if char == ':' { + if result.ends_with(':') { + result.push(' '); + } else { + result.push(':'); + } + } else if char == '_' { + result.push(' '); + } else if char.is_uppercase() { + if !result.ends_with(' ') && !result.ends_with(':') { + result.push(' '); + } + result.extend(char.to_lowercase()); + } else { + result.push(char); + } + } + + let mut title_cased = String::with_capacity(result.len()); + let mut should_capitalize = true; + + for char in result.chars() { + if should_capitalize && char.is_alphabetic() { + title_cased.extend(char.to_uppercase()); + should_capitalize = false; + } else { + title_cased.push(char); + if char == ' ' || char == ':' { + should_capitalize = true; + } + } + } + + title_cased +} diff --git a/crates/search_everywhere/src/files.rs b/crates/search_everywhere/src/files.rs new file mode 100644 index 00000000000000..2967f03f019fcc --- /dev/null +++ b/crates/search_everywhere/src/files.rs @@ -0,0 +1,109 @@ +use fuzzy::{StringMatch, StringMatchCandidate}; +use gpui::{App, Entity, SharedString, Task}; +use project::{Project, ProjectPath, WorktreeId}; + +use crate::SearchEverywhereDelegate; +use crate::providers::{SearchResult, SearchResultCategory}; + +pub struct FileProvider { + project: Entity, +} + +impl FileProvider { + pub fn new(project: Entity, _cx: &App) -> Self { + Self { project } + } + + pub fn search( + &self, + query: &str, + cx: &mut gpui::Context>, + ) -> Task> { + if query.is_empty() { + return Task::ready(Vec::new()); + } + + let project = self.project.clone(); + let query = query.to_string(); + + cx.spawn(async move |_, cx| { + let Some(candidates) = cx + .update(|cx| { + let project = project.read(cx); + let worktrees = project.visible_worktrees(cx).collect::>(); + + let mut candidates = Vec::new(); + for worktree in worktrees { + let worktree = worktree.read(cx); + let worktree_id = worktree.id(); + + for entry in worktree.files(false, 0) { + let path = entry.path.as_unix_str().to_string(); + candidates.push(FileCandidate { + path: path.clone(), + worktree_id, + project_path: ProjectPath { + worktree_id, + path: entry.path.clone(), + }, + }); + } + } + candidates + }) + .ok() + else { + return Vec::new(); + }; + + let string_candidates: Vec = candidates + .iter() + .enumerate() + .map(|(id, c)| StringMatchCandidate::new(id, &c.path)) + .collect(); + + let matches = fuzzy::match_strings( + &string_candidates, + &query, + true, + true, + 100, + &Default::default(), + cx.background_executor().clone(), + ) + .await; + + matches + .into_iter() + .filter_map(|m| { + let candidate = candidates.get(m.candidate_id)?; + let file_name = candidate + .project_path + .path + .file_name() + .map(|n| n.to_string()) + .unwrap_or_else(|| candidate.path.clone()); + + let result = SearchResult { + label: SharedString::from(file_name), + detail: Some(SharedString::from(candidate.path.clone())), + category: SearchResultCategory::File, + path: Some(candidate.project_path.clone()), + action: None, + symbol: None, + document_symbol: None, + }; + + Some((result, m)) + }) + .collect() + }) + } +} + +struct FileCandidate { + path: String, + #[allow(dead_code)] + worktree_id: WorktreeId, + project_path: ProjectPath, +} diff --git a/crates/search_everywhere/src/providers.rs b/crates/search_everywhere/src/providers.rs new file mode 100644 index 00000000000000..92ee9fb28c9fdb --- /dev/null +++ b/crates/search_everywhere/src/providers.rs @@ -0,0 +1,26 @@ +use gpui::{Action, Entity, SharedString}; +use language::{Anchor, Buffer}; +use project::{ProjectPath, Symbol}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SearchResultCategory { + File, + Symbol, + Action, +} + +pub struct SearchResult { + pub label: SharedString, + pub detail: Option, + pub category: SearchResultCategory, + pub path: Option, + pub action: Option>, + pub symbol: Option, + pub document_symbol: Option, +} + +#[derive(Clone)] +pub struct DocumentSymbolResult { + pub buffer: Entity, + pub range: std::ops::Range, +} diff --git a/crates/search_everywhere/src/search_everywhere.rs b/crates/search_everywhere/src/search_everywhere.rs new file mode 100644 index 00000000000000..a65099b49c952e --- /dev/null +++ b/crates/search_everywhere/src/search_everywhere.rs @@ -0,0 +1,559 @@ +mod actions; +mod files; +mod providers; +mod symbols; + +use std::sync::Arc; + +use actions::ActionProvider; +use editor::{Bias, Editor, SelectionEffects, scroll::Autoscroll}; +use files::FileProvider; +use fuzzy::StringMatch; +use gpui::{ + App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, IntoElement, + ParentElement, Render, SharedString, Styled, Task, WeakEntity, Window, actions, rems, +}; +use language::ToPoint; +use picker::{Picker, PickerDelegate}; +use providers::{SearchResult, SearchResultCategory}; +use symbols::SymbolProvider; +use ui::{ + Divider, IconName, KeyBinding, ListItem, ListItemSpacing, ToggleButtonGroup, + ToggleButtonGroupStyle, ToggleButtonSimple, prelude::*, +}; +use util::ResultExt; +use workspace::{ModalView, Workspace}; + +actions!( + search_everywhere, + [ + /// Toggle the Search Everywhere modal. + Toggle, + ] +); + +pub fn init(cx: &mut App) { + cx.observe_new(SearchEverywhere::register).detach(); +} + +impl ModalView for SearchEverywhere {} + +pub struct SearchEverywhere { + picker: Entity>, + active_tab: SearchTab, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SearchTab { + #[default] + All, + Files, + Symbols, + Actions, +} + +impl SearchEverywhere { + fn register( + workspace: &mut Workspace, + _window: Option<&mut Window>, + _: &mut Context, + ) { + workspace.register_action(|workspace, _: &Toggle, window, cx| { + Self::toggle(workspace, window, cx); + }); + } + + pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context) { + let Some(previous_focus_handle) = window.focused(cx) else { + return; + }; + + let project = workspace.project().clone(); + let weak_workspace = cx.entity().downgrade(); + + workspace.toggle_modal(window, cx, move |window, cx| { + SearchEverywhere::new(weak_workspace, project, previous_focus_handle, window, cx) + }); + } + + fn new( + workspace: WeakEntity, + project: Entity, + previous_focus_handle: FocusHandle, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let weak_search_everywhere = cx.entity().downgrade(); + + let delegate = SearchEverywhereDelegate::new( + weak_search_everywhere, + workspace, + project, + previous_focus_handle, + window, + cx, + ); + + // Only start indexing if we don't have cached symbols already + if !delegate.symbol_provider.has_cached_symbols() { + delegate.symbol_provider.start_indexing(cx); + } + + let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx)); + + Self { + picker, + active_tab: SearchTab::All, + } + } + + fn set_active_tab(&mut self, tab: SearchTab, window: &mut Window, cx: &mut Context) { + self.active_tab = tab; + self.picker.update(cx, |picker, cx| { + picker.delegate.active_tab = tab; + picker.refresh(window, cx); + }); + cx.notify(); + } +} + +impl EventEmitter for SearchEverywhere {} + +impl Focusable for SearchEverywhere { + fn focus_handle(&self, cx: &App) -> FocusHandle { + self.picker.focus_handle(cx) + } +} + +impl Render for SearchEverywhere { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + v_flex() + .key_context("SearchEverywhere") + .w(rems(34.)) + .child(self.picker.clone()) + } +} + +pub struct SearchEverywhereDelegate { + search_everywhere: WeakEntity, + workspace: WeakEntity, + project: Entity, + previous_focus_handle: FocusHandle, + active_tab: SearchTab, + matches: Vec, + selected_ix: usize, + is_loading: bool, + file_provider: FileProvider, + action_provider: ActionProvider, + symbol_provider: SymbolProvider, +} + +struct SearchResultMatch { + result: SearchResult, + string_match: StringMatch, +} + +impl SearchEverywhereDelegate { + fn new( + search_everywhere: WeakEntity, + workspace: WeakEntity, + project: Entity, + previous_focus_handle: FocusHandle, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let file_provider = FileProvider::new(project.clone(), cx); + let action_provider = ActionProvider::new(window, cx); + let symbol_provider = SymbolProvider::new(project.clone()); + + Self { + search_everywhere, + workspace, + project, + previous_focus_handle, + active_tab: SearchTab::All, + matches: Vec::new(), + selected_ix: 0, + is_loading: false, + file_provider, + action_provider, + symbol_provider, + } + } + + fn filter_matches_by_tab(&self, matches: Vec) -> Vec { + match self.active_tab { + SearchTab::All => matches, + SearchTab::Files => matches + .into_iter() + .filter(|m| m.result.category == SearchResultCategory::File) + .collect(), + SearchTab::Symbols => matches + .into_iter() + .filter(|m| m.result.category == SearchResultCategory::Symbol) + .collect(), + SearchTab::Actions => matches + .into_iter() + .filter(|m| m.result.category == SearchResultCategory::Action) + .collect(), + } + } +} + +impl PickerDelegate for SearchEverywhereDelegate { + type ListItem = ListItem; + + fn match_count(&self) -> usize { + self.matches.len() + } + + fn selected_index(&self) -> usize { + self.selected_ix + } + + fn set_selected_index( + &mut self, + ix: usize, + _window: &mut Window, + _cx: &mut Context>, + ) { + self.selected_ix = ix; + } + + fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc { + "Search everywhere...".into() + } + + fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option { + if self.symbol_provider.is_indexing() { + let progress = self.symbol_provider.indexing_progress_percent(); + Some(SharedString::from(format!( + "Indexing project... {}%", + progress + ))) + } else if self.is_loading { + Some("Searching...".into()) + } else { + Some("No matches".into()) + } + } + + fn render_editor( + &self, + editor: &Entity, + _window: &mut Window, + _cx: &mut Context>, + ) -> Div { + let selected_index = match self.active_tab { + SearchTab::All => 0, + SearchTab::Files => 1, + SearchTab::Symbols => 2, + SearchTab::Actions => 3, + }; + + let search_everywhere = self.search_everywhere.clone(); + + v_flex() + .child( + h_flex().px_2().py_1p5().child( + ToggleButtonGroup::single_row( + "search-everywhere-tabs", + [ + ToggleButtonSimple::new("All", { + let search_everywhere = search_everywhere.clone(); + move |_event, window, cx| { + search_everywhere + .update(cx, |this, cx| { + this.set_active_tab(SearchTab::All, window, cx); + }) + .log_err(); + } + }), + ToggleButtonSimple::new("Files", { + let search_everywhere = search_everywhere.clone(); + move |_event, window, cx| { + search_everywhere + .update(cx, |this, cx| { + this.set_active_tab(SearchTab::Files, window, cx); + }) + .log_err(); + } + }), + ToggleButtonSimple::new("Symbols", { + let search_everywhere = search_everywhere.clone(); + move |_event, window, cx| { + search_everywhere + .update(cx, |this, cx| { + this.set_active_tab(SearchTab::Symbols, window, cx); + }) + .log_err(); + } + }), + ToggleButtonSimple::new("Actions", { + move |_event, window, cx| { + search_everywhere + .update(cx, |this, cx| { + this.set_active_tab(SearchTab::Actions, window, cx); + }) + .log_err(); + } + }), + ], + ) + .style(ToggleButtonGroupStyle::Outlined) + .selected_index(selected_index), + ), + ) + .child( + h_flex() + .overflow_hidden() + .flex_none() + .h_9() + .px_2p5() + .child(editor.clone()), + ) + .child(Divider::horizontal()) + } + + fn update_matches( + &mut self, + query: String, + window: &mut Window, + cx: &mut Context>, + ) -> Task<()> { + self.is_loading = true; + cx.notify(); + + let file_results = self.file_provider.search(&query, cx); + let action_results = self.action_provider.search(&query, window, cx); + let symbol_results = self.symbol_provider.search(&query, cx); + + cx.spawn_in(window, async move |picker, cx| { + let (file_matches, action_matches, symbol_matches) = + futures::join!(file_results, action_results, symbol_results); + + let mut all_matches: Vec = Vec::new(); + + for (result, string_match) in file_matches { + all_matches.push(SearchResultMatch { + result, + string_match, + }); + } + + for (result, string_match) in action_matches { + all_matches.push(SearchResultMatch { + result, + string_match, + }); + } + + for (result, string_match) in symbol_matches { + all_matches.push(SearchResultMatch { + result, + string_match, + }); + } + + all_matches.sort_by(|a, b| { + b.string_match + .score + .partial_cmp(&a.string_match.score) + .unwrap_or(std::cmp::Ordering::Equal) + }); + + picker + .update(cx, |picker, cx| { + let filtered = picker.delegate.filter_matches_by_tab(all_matches); + picker.delegate.matches = filtered; + picker.delegate.selected_ix = 0; + picker.delegate.is_loading = false; + cx.notify(); + }) + .log_err(); + }) + } + + fn confirm(&mut self, _secondary: bool, window: &mut Window, cx: &mut Context>) { + if self.matches.is_empty() { + self.dismissed(window, cx); + return; + } + + let selected_ix = self.selected_ix; + if selected_ix >= self.matches.len() { + self.dismissed(window, cx); + return; + } + + let selected_match = &self.matches[selected_ix]; + + match selected_match.result.category { + SearchResultCategory::File => { + if let Some(path) = &selected_match.result.path { + let path = path.clone(); + if let Some(workspace) = self.workspace.upgrade() { + workspace.update(cx, |workspace, cx| { + workspace + .open_path(path, None, true, window, cx) + .detach_and_log_err(cx); + }); + } + window.focus(&self.previous_focus_handle); + self.search_everywhere + .update(cx, |_, cx| cx.emit(DismissEvent)) + .log_err(); + } + } + SearchResultCategory::Action => { + if let Some(action) = &selected_match.result.action { + let action = action.boxed_clone(); + window.focus(&self.previous_focus_handle); + self.search_everywhere + .update(cx, |_, cx| cx.emit(DismissEvent)) + .log_err(); + window.dispatch_action(action, cx); + } + } + SearchResultCategory::Symbol => { + if let Some(symbol) = &selected_match.result.symbol { + let symbol = symbol.clone(); + let project = self.project.clone(); + let workspace = self.workspace.clone(); + let search_everywhere = self.search_everywhere.clone(); + + let buffer = project.update(cx, |project, cx| { + project.open_buffer_for_symbol(&symbol, cx) + }); + + cx.spawn_in(window, async move |_, cx| { + let buffer = buffer.await?; + workspace.update_in(cx, |workspace, window, cx| { + let position = buffer + .read(cx) + .clip_point_utf16(symbol.range.start, Bias::Left); + + let editor = workspace.open_project_item::( + workspace.active_pane().clone(), + buffer, + true, + true, + true, + true, + window, + cx, + ); + + editor.update(cx, |editor, cx| { + editor.change_selections( + SelectionEffects::scroll(Autoscroll::center()), + window, + cx, + |s| s.select_ranges([position..position]), + ); + }); + })?; + search_everywhere + .update(cx, |_, cx| cx.emit(DismissEvent)) + .log_err(); + anyhow::Ok(()) + }) + .detach_and_log_err(cx); + } else if let Some(doc_symbol) = &selected_match.result.document_symbol { + let buffer = doc_symbol.buffer.clone(); + let range = doc_symbol.range.clone(); + let workspace = self.workspace.clone(); + let search_everywhere = self.search_everywhere.clone(); + + if let Some(workspace) = workspace.upgrade() { + workspace.update(cx, |workspace, cx| { + // Convert anchor to point using buffer snapshot + let point = { + let buffer_snapshot = buffer.read(cx).snapshot(); + range.start.to_point(&buffer_snapshot) + }; + + let editor = workspace.open_project_item::( + workspace.active_pane().clone(), + buffer, + true, + true, + true, + true, + window, + cx, + ); + + editor.update(cx, |editor, cx| { + editor.change_selections( + SelectionEffects::scroll(Autoscroll::center()), + window, + cx, + |s| s.select_ranges([point..point]), + ); + }); + }); + } + + search_everywhere + .update(cx, |_, cx| cx.emit(DismissEvent)) + .log_err(); + } + } + } + } + + fn dismissed(&mut self, window: &mut Window, cx: &mut Context>) { + window.focus(&self.previous_focus_handle); + self.search_everywhere + .update(cx, |_, cx| cx.emit(DismissEvent)) + .log_err(); + } + + fn render_match( + &self, + ix: usize, + selected: bool, + _window: &mut Window, + cx: &mut Context>, + ) -> Option { + let search_match = self.matches.get(ix)?; + let result = &search_match.result; + + let icon = match result.category { + SearchResultCategory::File => IconName::File, + SearchResultCategory::Symbol => IconName::Code, + SearchResultCategory::Action => IconName::BoltOutlined, + }; + + let keybinding = result + .action + .as_ref() + .map(|action| KeyBinding::for_action_in(&**action, &self.previous_focus_handle, cx)); + + Some( + ListItem::new(ix) + .inset(true) + .spacing(ListItemSpacing::Sparse) + .toggle_state(selected) + .start_slot(Icon::new(icon).color(Color::Muted)) + .child( + h_flex() + .gap_2() + .child(Label::new(result.label.clone())) + .when_some(result.detail.clone(), |this, detail| { + this.child( + Label::new(detail) + .size(LabelSize::Small) + .color(Color::Muted), + ) + }), + ) + .end_slot( + h_flex() + .gap_2() + .when_some(keybinding, |this, kb| this.child(kb)), + ), + ) + } +} diff --git a/crates/search_everywhere/src/symbols.rs b/crates/search_everywhere/src/symbols.rs new file mode 100644 index 00000000000000..a14b9f62915654 --- /dev/null +++ b/crates/search_everywhere/src/symbols.rs @@ -0,0 +1,339 @@ +use std::sync::Arc; + +use collections::HashMap; +use fuzzy::{StringMatch, StringMatchCandidate}; +use gpui::{App, Entity, EntityId, SharedString, Task as GpuiTask}; +use language::{Anchor, Buffer, OutlineItem}; +use parking_lot::Mutex; +use project::{Project, Symbol}; +use util::ResultExt; + +use crate::SearchEverywhereDelegate; +use crate::providers::{DocumentSymbolResult, SearchResult, SearchResultCategory}; + +// Global cache for symbol providers, keyed by project entity ID +static SYMBOL_CACHES: Mutex>>> = Mutex::new(None); + +struct SymbolCache { + cached_symbols: Mutex>, + is_indexing: Mutex, + indexing_progress: Mutex<(usize, usize)>, +} + +pub struct SymbolProvider { + project: Entity, + cache: Arc, +} + +#[derive(Clone)] +pub enum SymbolEntry { + Workspace(Symbol), + Outline { + name: String, + path: String, + buffer: Entity, + range: std::ops::Range, + }, +} + +impl SymbolProvider { + pub fn new(project: Entity) -> Self { + let project_id = project.entity_id(); + + // Get or create the cache for this project + let cache = { + let mut caches = SYMBOL_CACHES.lock(); + let caches = caches.get_or_insert_with(HashMap::default); + caches + .entry(project_id) + .or_insert_with(|| { + Arc::new(SymbolCache { + cached_symbols: Mutex::new(Vec::new()), + is_indexing: Mutex::new(false), + indexing_progress: Mutex::new((0, 0)), + }) + }) + .clone() + }; + + Self { project, cache } + } + + /// Start indexing all symbols in the project. Call this when the modal opens. + pub fn start_indexing(&self, cx: &mut App) { + // Don't start if already indexing + { + let mut is_indexing = self.cache.is_indexing.lock(); + if *is_indexing { + return; + } + *is_indexing = true; + } + + let project = self.project.clone(); + let cache = self.cache.clone(); + + // Get all file paths from all worktrees (respects .gitignore) + let worktrees: Vec<_> = project.read(cx).visible_worktrees(cx).collect(); + + let mut paths_to_index: Vec = Vec::new(); + for worktree in &worktrees { + let snapshot = worktree.read(cx).snapshot(); + for entry in snapshot.files(false, 0) { + // Skip ignored files + if entry.is_ignored { + continue; + } + paths_to_index.push(project::ProjectPath { + worktree_id: snapshot.id(), + path: entry.path.clone(), + }); + } + } + + log::info!( + "Search everywhere: starting to index {} files for symbols", + paths_to_index.len() + ); + + // Also try workspace symbols with empty query to get all symbols (if LSP supports it) + let workspace_symbols_task = project.update(cx, |project, cx| project.symbols("", cx)); + + // Initialize progress + { + let mut progress = cache.indexing_progress.lock(); + *progress = (0, paths_to_index.len()); + } + + cx.spawn({ + let project = project.clone(); + async move |cx| { + let mut all_symbols: Vec = Vec::new(); + + // Collect workspace symbols first (fast, if LSP supports it) + if let Some(symbols) = workspace_symbols_task.await.log_err() { + log::info!( + "Search everywhere: indexed {} workspace symbols", + symbols.len() + ); + for symbol in symbols { + all_symbols.push(SymbolEntry::Workspace(symbol)); + } + } + + // Now open each file and get outline items (Tree-sitter based, no LSP needed) + // Process in batches to avoid overwhelming the system + let batch_size = 50; + let total_files = paths_to_index.len(); + + for (batch_idx, paths_batch) in paths_to_index.chunks(batch_size).enumerate() { + let mut batch_tasks: Vec<( + String, + GpuiTask, Vec>)>>, + )> = Vec::new(); + + for path in paths_batch { + let path_string = path.path.as_unix_str().to_string(); + let path = path.clone(); + let project = project.clone(); + + // Open buffer and get outline items + let task = cx.update(|cx| { + project.update(cx, |project, cx| { + let open_task = project.open_buffer(path.clone(), cx); + cx.spawn(async move |_weak_project, cx| { + let buffer = open_task.await?; + let outline_items = cx.update(|cx| { + let buffer_snapshot = buffer.read(cx).snapshot(); + let outline = buffer_snapshot.outline(None); + outline.items + })?; + anyhow::Ok((buffer, outline_items)) + }) + }) + }); + + if let Ok(task) = task { + batch_tasks.push((path_string, task)); + } + } + + // Wait for batch to complete + for (file_path, task) in batch_tasks { + match task.await { + Ok((buffer, outline_items)) => { + if !outline_items.is_empty() { + log::debug!( + "Search everywhere: got {} outline items from {}", + outline_items.len(), + file_path + ); + } + for item in outline_items { + all_symbols.push(SymbolEntry::Outline { + name: item.text.clone(), + path: file_path.clone(), + buffer: buffer.clone(), + range: item.range.clone(), + }); + } + } + Err(e) => { + log::debug!( + "Search everywhere: failed to get outline for {}: {}", + file_path, + e + ); + } + } + } + + // Update progress + let processed = ((batch_idx + 1) * batch_size).min(total_files); + { + let mut progress = cache.indexing_progress.lock(); + *progress = (processed, total_files); + } + + if processed % 100 == 0 || processed >= total_files { + log::info!( + "Search everywhere: indexed {}/{} files ({}%), {} symbols so far", + processed, + total_files, + (processed * 100) / total_files.max(1), + all_symbols.len() + ); + } + + // Update cache incrementally so results appear as we index + { + let mut symbols = cache.cached_symbols.lock(); + *symbols = all_symbols.clone(); + } + } + + log::info!( + "Search everywhere: indexing complete, {} total symbols", + all_symbols.len() + ); + + // Final cache update + { + let mut symbols = cache.cached_symbols.lock(); + *symbols = all_symbols; + } + + // Mark indexing as complete + { + let mut indexing = cache.is_indexing.lock(); + *indexing = false; + } + + // Notify to refresh UI + cx.update(|_cx| {}).ok(); + } + }) + .detach(); + } + + pub fn is_indexing(&self) -> bool { + *self.cache.is_indexing.lock() + } + + pub fn indexing_progress_percent(&self) -> usize { + let (processed, total) = *self.cache.indexing_progress.lock(); + if total == 0 { + 0 + } else { + (processed * 100) / total + } + } + + pub fn has_cached_symbols(&self) -> bool { + !self.cache.cached_symbols.lock().is_empty() + } + + pub fn search( + &self, + query: &str, + cx: &mut gpui::Context>, + ) -> GpuiTask> { + if query.is_empty() { + return GpuiTask::ready(Vec::new()); + } + + let cached_symbols = self.cache.cached_symbols.lock().clone(); + let query = query.to_string(); + + cx.spawn(async move |_, cx| { + if cached_symbols.is_empty() { + return Vec::new(); + } + + let candidates: Vec = cached_symbols + .iter() + .enumerate() + .map(|(id, entry)| { + let name = match entry { + SymbolEntry::Workspace(s) => s.label.filter_text().to_string(), + SymbolEntry::Outline { name, .. } => name.clone(), + }; + StringMatchCandidate::new(id, &name) + }) + .collect(); + + let matches = fuzzy::match_strings( + &candidates, + &query, + false, + true, + 100, + &Default::default(), + cx.background_executor().clone(), + ) + .await; + + matches + .into_iter() + .filter_map(|m| { + let entry = cached_symbols.get(m.candidate_id)?; + + let result = match entry { + SymbolEntry::Workspace(symbol) => { + let label = symbol.label.text.clone(); + let detail = symbol.label.filter_text().to_string(); + SearchResult { + label: SharedString::from(label), + detail: Some(SharedString::from(detail)), + category: SearchResultCategory::Symbol, + path: None, + action: None, + symbol: Some(symbol.clone()), + document_symbol: None, + } + } + SymbolEntry::Outline { + name, + path, + buffer, + range, + } => SearchResult { + label: SharedString::from(name.clone()), + detail: Some(SharedString::from(path.clone())), + category: SearchResultCategory::Symbol, + path: None, + action: None, + symbol: None, + document_symbol: Some(DocumentSymbolResult { + buffer: buffer.clone(), + range: range.clone(), + }), + }, + }; + + Some((result, m)) + }) + .collect() + }) + } +} diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.toml index 92a274da9640bb..66f9f33a2047c9 100644 --- a/crates/zed/Cargo.toml +++ b/crates/zed/Cargo.toml @@ -124,6 +124,7 @@ reqwest.workspace = true reqwest_client.workspace = true rope.workspace = true search.workspace = true +search_everywhere.workspace = true serde.workspace = true serde_json.workspace = true session.workspace = true diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rs index 2e85da2c062230..6d5a9edabf7966 100644 --- a/crates/zed/src/main.rs +++ b/crates/zed/src/main.rs @@ -613,6 +613,7 @@ pub fn main() { go_to_line::init(cx); file_finder::init(cx); + search_everywhere::init(cx); tab_switcher::init(cx); outline::init(cx); project_symbols::init(cx); diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rs index 71653124b1c4af..43e7425af10714 100644 --- a/crates/zed/src/zed.rs +++ b/crates/zed/src/zed.rs @@ -4769,6 +4769,7 @@ mod tests { "repl", "rules_library", "search", + "search_everywhere", "settings_editor", "settings_profile_selector", "snippets",