Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
file_finder: Implement SeedQuerySetting::Selection seed_query (#64946)
Arti708c7eef558b
diff --git a/assets/settings/default.json b/assets/settings/default.jsonindex 4145a821991..40173f5840e 100644--- a/assets/settings/default.json+++ b/assets/settings/default.json@@ -1587,6 +1587,11 @@"include_ignored": "smart",// Whether to include text channels in file finder results."include_channels": false,+ // Whether to pre-fill the file finder's query with the text selected in the+ // focused item (e.g. an editor or a terminal) when it is opened.+ //+ // Default: true+ "prefill_query_from_selection": true,},// Whether or not to remove any trailing whitespace from lines of a buffer// before saving it.diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rsindex a1a25b94ac5..82085cb8c52 100644--- a/crates/file_finder/src/file_finder.rs+++ b/crates/file_finder/src/file_finder.rs@@ -25,7 +25,7 @@ use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId, worktree_store::WorktreeStore,};-use settings::{ModalWidthContent, Settings, SettingsStore};+use settings::{ModalWidthContent, SeedQuerySetting, Settings, SettingsStore};use std::{borrow::Cow,cmp, mem,@@ -84,10 +84,12 @@ impl FileFinder {workspace.register_action(|workspace, action: &workspace::ToggleFileFinder, window, cx| {let Some(file_finder) = workspace.active_modal::<Self>(cx) else {+ let seed_query = Self::seed_query(workspace, window, cx);Self::open(workspace,action.separate_history,action.include_ignored,+ seed_query,window,cx,)@@ -109,6 +111,7 @@ impl FileFinder {workspace: &mut Workspace,separate_history: bool,include_ignored: Option<bool>,+ seed_query: Option<String>,window: &mut Window,cx: &mut Context<Workspace>,) -> Task<()> {@@ -166,14 +169,53 @@ impl FileFinder {cx,);- FileFinder::new(delegate, window, cx)+ FileFinder::new(delegate, seed_query, window, cx)});}).ok();})}- fn new(delegate: FileFinderDelegate, window: &mut Window, cx: &mut Context<Self>) -> Self {+ /// The query to pre-fill the finder with from the user's latest selection,+ /// when `prefill_query_from_selection` is enabled. The focused pane's item+ /// (e.g. a terminal in a dock) is consulted before the active center pane's+ /// item, so the selection next to the focus wins.+ fn seed_query(+ workspace: &mut Workspace,+ window: &mut Window,+ cx: &mut Context<Workspace>,+ ) -> Option<String> {+ if !FileFinderSettings::get_global(cx).prefill_query_from_selection {+ return None;+ }++ let focused_item = workspace.focused_pane(window, cx).read(cx).active_item();+ let active_item = workspace+ .active_item(cx)+ .filter(|active| match &focused_item {+ Some(focused) => focused.item_id() != active.item_id(),+ None => true,+ });++ focused_item+ .into_iter()+ .chain(active_item)+ .find_map(|item| {+ let query = item.to_searchable_item_handle(cx)?.query_suggestion(+ Some(SeedQuerySetting::Selection),+ window,+ cx,+ );+ sanitize_file_query(&query)+ })+ }++ fn new(+ delegate: FileFinderDelegate,+ seed_query: Option<String>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> Self {let modal_max_width_setting = FileFinderSettings::get_global(cx).modal_max_width;let project = delegate.project.clone();@@ -184,8 +226,12 @@ impl FileFinder {.initial_width(Rems::from_pixels(modal_max_width, window))});let picker_focus_handle = picker.focus_handle(cx);- picker.update(cx, |picker, _| {+ picker.update(cx, |picker, cx| {picker.delegate.focus_handle = picker_focus_handle.clone();+ if let Some(seed_query) = seed_query {+ picker.set_query(&seed_query, window, cx);+ picker.select_query(window, cx);+ }});Self {picker,@@ -328,6 +374,15 @@ impl FileFinder {}}+const MAX_SEED_QUERY_LENGTH: usize = 100;++/// Flattens a selection into a single-line file query, capped to a sane length,+/// since the selection seeds a file-name lookup.+fn sanitize_file_query(selection: &str) -> Option<String> {+ let query = selection.split_whitespace().collect::<Vec<_>>().join(" ");+ (!query.is_empty()).then(|| query.chars().take(MAX_SEED_QUERY_LENGTH).collect())+}+impl EventEmitter<DismissEvent> for FileFinder {}impl Focusable for FileFinder {diff --git a/crates/file_finder/src/file_finder_tests.rs b/crates/file_finder/src/file_finder_tests.rsindex 18d0728d460..8c313818ae2 100644--- a/crates/file_finder/src/file_finder_tests.rs+++ b/crates/file_finder/src/file_finder_tests.rs@@ -1,7 +1,7 @@use std::{future::IntoFuture, path::Path, time::Duration};use super::*;-use editor::Editor;+use editor::{Editor, SelectionEffects};use gpui::{Entity, TestAppContext, VisualTestContext};use menu::{Cancel, Confirm, SelectNext, SelectPrevious};use pretty_assertions::{assert_eq, assert_matches};@@ -4717,6 +4717,195 @@ fn collect_search_matches(picker: &Picker<FileFinderDelegate>) -> SearchEntriessearch_entries}+#[cfg(test)]+fn select_range_in_active_editor(+ workspace: &Entity<Workspace>,+ cx: &mut VisualTestContext,+ range: Range<Point>,+) {+ let editor = cx.read(|cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());+ editor.update_in(cx, |editor, window, cx| {+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {+ s.select_ranges([range]);+ });+ });+}++#[gpui::test]+async fn test_seed_query_from_editor_selection(cx: &mut TestAppContext) {+ let app_state = init_test(cx);++ app_state+ .fs+ .as_fake()+ .insert_tree(+ path!("/src"),+ json!({+ "the_quick.rs": "quick brown",+ "unrelated.rs": "",+ }),+ )+ .await;++ let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));+ let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());++ open_queried_buffer("the_quick", 1, "the_quick.rs", &workspace, cx).await;+ select_range_in_active_editor(&workspace, cx, Point::new(0, 0)..Point::new(0, 5));++ // The finder opens pre-filled with the selection and searches for it.+ cx.dispatch_action(ToggleFileFinder {+ separate_history: true,+ include_ignored: None,+ });+ let picker = active_file_picker(&workspace, cx);+ assert_eq!(picker.read_with(cx, |picker, cx| picker.query(cx)), "quick");++ cx.executor().advance_clock(SEARCH_DEBOUNCE);+ cx.run_until_parked();+ picker.update(cx, |finder, _| {+ assert_match_at_position(finder, 0, "the_quick.rs");+ });+}++#[gpui::test]+async fn test_no_seed_query_without_selection(cx: &mut TestAppContext) {+ let app_state = init_test(cx);++ app_state+ .fs+ .as_fake()+ .insert_tree(+ path!("/src"),+ json!({+ "the_quick.rs": "quick brown",+ }),+ )+ .await;++ let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));+ let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());++ open_queried_buffer("the_quick", 1, "the_quick.rs", &workspace, cx).await;++ // Without a selection the finder opens in history mode.+ cx.dispatch_action(ToggleFileFinder {+ separate_history: true,+ include_ignored: None,+ });+ let picker = active_file_picker(&workspace, cx);+ assert_eq!(picker.read_with(cx, |picker, cx| picker.query(cx)), "");+ picker.update(cx, |finder, _| {+ assert_eq!(finder.delegate.matches.len(), 1);+ assert_match_at_position(finder, 0, "the_quick.rs");+ });+}++#[gpui::test]+async fn test_seed_query_flattens_multiline_selection(cx: &mut TestAppContext) {+ let app_state = init_test(cx);++ app_state+ .fs+ .as_fake()+ .insert_tree(+ path!("/src"),+ json!({+ "words.rs": "alpha beta\ngamma delta\n",+ }),+ )+ .await;++ let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));+ let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());++ open_queried_buffer("words", 1, "words.rs", &workspace, cx).await;+ select_range_in_active_editor(&workspace, cx, Point::new(0, 0)..Point::new(1, 11));++ cx.dispatch_action(ToggleFileFinder {+ separate_history: true,+ include_ignored: None,+ });+ let picker = active_file_picker(&workspace, cx);+ assert_eq!(+ picker.read_with(cx, |picker, cx| picker.query(cx)),+ "alpha beta gamma delta"+ );++ cx.executor().advance_clock(SEARCH_DEBOUNCE);+ cx.run_until_parked();+}++#[gpui::test]+async fn test_no_seed_query_when_setting_disabled(cx: &mut TestAppContext) {+ let app_state = init_test(cx);++ cx.update(|cx| {+ let settings = *FileFinderSettings::get_global(cx);+ FileFinderSettings::override_global(+ FileFinderSettings {+ prefill_query_from_selection: false,+ ..settings+ },+ cx,+ );+ });++ app_state+ .fs+ .as_fake()+ .insert_tree(+ path!("/src"),+ json!({+ "the_quick.rs": "quick brown",+ }),+ )+ .await;++ let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;+ let (multi_workspace, cx) =+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));+ let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());++ open_queried_buffer("the_quick", 1, "the_quick.rs", &workspace, cx).await;+ select_range_in_active_editor(&workspace, cx, Point::new(0, 0)..Point::new(0, 5));++ cx.dispatch_action(ToggleFileFinder {+ separate_history: true,+ include_ignored: None,+ });+ let picker = active_file_picker(&workspace, cx);+ assert_eq!(picker.read_with(cx, |picker, cx| picker.query(cx)), "");+ picker.update(cx, |finder, _| {+ assert_eq!(finder.delegate.matches.len(), 1);+ assert_match_at_position(finder, 0, "the_quick.rs");+ });+}++#[test]+fn test_sanitize_file_query() {+ assert_eq!(+ sanitize_file_query(" the quick\nbrown fox\ttabs ").as_deref(),+ Some("the quick brown fox tabs")+ );+ assert_eq!(sanitize_file_query("").as_deref(), None);+ assert_eq!(sanitize_file_query(" \n\t ").as_deref(), None);+ let long_selection = "a".repeat(MAX_SEED_QUERY_LENGTH + 1);+ assert_eq!(+ sanitize_file_query(&long_selection)+ .unwrap()+ .chars()+ .count(),+ MAX_SEED_QUERY_LENGTH+ );+}+#[track_caller]fn assert_match_selection(finder: &Picker<FileFinderDelegate>,diff --git a/crates/open_path_prompt/src/file_finder_settings.rs b/crates/open_path_prompt/src/file_finder_settings.rsindex 76be55a70e4..560d02da9da 100644--- a/crates/open_path_prompt/src/file_finder_settings.rs+++ b/crates/open_path_prompt/src/file_finder_settings.rs@@ -8,6 +8,7 @@ pub struct FileFinderSettings {pub skip_focus_for_active_in_search: bool,pub include_ignored: Option<bool>,pub include_channels: bool,+ pub prefill_query_from_selection: bool,}impl Settings for FileFinderSettings {@@ -24,6 +25,7 @@ impl Settings for FileFinderSettings {settings::IncludeIgnoredContent::Smart => None,},include_channels: file_finder.include_channels.unwrap(),+ prefill_query_from_selection: file_finder.prefill_query_from_selection.unwrap(),}}}diff --git a/crates/settings_content/src/settings_content.rs b/crates/settings_content/src/settings_content.rsindex 54e07da76a5..88083da0ba8 100644--- a/crates/settings_content/src/settings_content.rs+++ b/crates/settings_content/src/settings_content.rs@@ -990,6 +990,11 @@ pub struct FileFinderSettingsContent {////// Default: falsepub include_channels: Option<bool>,+ /// Whether to pre-fill the file finder's query with the text selected in the+ /// focused item (e.g. an editor or a terminal) when it is opened.+ ///+ /// Default: true+ pub prefill_query_from_selection: Option<bool>,}#[derive(diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rsindex 09b2643673f..525511fbf4f 100644--- a/crates/settings_ui/src/page_data.rs+++ b/crates/settings_ui/src/page_data.rs@@ -3884,7 +3884,7 @@ fn search_and_files_page() -> SettingsPage {]}- fn file_finder_section() -> [SettingsPageItem; 4] {+ fn file_finder_section() -> [SettingsPageItem; 5] {[SettingsPageItem::SectionHeader("File Finder"),// todo: null by default@@ -3953,6 +3953,29 @@ fn search_and_files_page() -> SettingsPage {metadata: None,files: USER,}),+ SettingsPageItem::SettingItem(SettingItem {+ title: "Prefill Query From Selection",+ description: "Whether to pre-fill the file finder's query with the text selected in the focused item (e.g. an editor or a terminal).",+ field: Box::new(SettingField {+ organization_override: None,+ json_path: Some("file_finder.prefill_query_from_selection"),+ pick: |settings_content| {+ settings_content+ .file_finder+ .as_ref()?+ .prefill_query_from_selection+ .as_ref()+ },+ write: |settings_content, value, _| {+ settings_content+ .file_finder+ .get_or_insert_default()+ .prefill_query_from_selection = value;+ },+ }),+ metadata: None,+ files: USER,+ }),]}