Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

search: Add LSP location pickers for references, definitions, and diagnostics (#59838)

David63692b8b4724
diff --git a/Cargo.lock b/Cargo.lock
index 6293cb2a217..79664e0cfd3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -10583,6 +10583,32 @@ dependencies = [
"url",
]
+[[package]]
+name = "lsp_locations"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "collections",
+ "editor",
+ "file_icons",
+ "fuzzy",
+ "gpui",
+ "indoc",
+ "language",
+ "log",
+ "lsp",
+ "picker",
+ "picker_preview",
+ "project",
+ "settings",
+ "text",
+ "theme",
+ "theme_settings",
+ "ui",
+ "util",
+ "workspace",
+]
+
[[package]]
name = "lyon"
version = "1.0.16"
@@ -23126,6 +23152,7 @@ dependencies = [
"languages",
"line_ending_selector",
"log",
+ "lsp_locations",
"markdown",
"markdown_preview",
"menu",
diff --git a/Cargo.toml b/Cargo.toml
index 62c2381988b..3e126c2690a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -129,6 +129,7 @@ members = [
"crates/llama_cpp",
"crates/lmstudio",
"crates/lsp",
+ "crates/lsp_locations",
"crates/markdown",
"crates/markdown_preview",
"crates/mermaid_render",
@@ -390,6 +391,7 @@ livekit_client = { path = "crates/livekit_client" }
llama_cpp = { path = "crates/llama_cpp" }
lmstudio = { path = "crates/lmstudio" }
lsp = { path = "crates/lsp" }
+lsp_locations = { path = "crates/lsp_locations" }
markdown = { path = "crates/markdown" }
markdown_preview = { path = "crates/markdown_preview" }
mermaid_render = { path = "crates/mermaid_render" }
diff --git a/assets/settings/default.json b/assets/settings/default.json
index b2fdb36f7e1..563aeaf1a2a 100644
--- a/assets/settings/default.json
+++ b/assets/settings/default.json
@@ -410,6 +410,14 @@
// 4. Preserve the cursor's vertical position within the viewport, falling back to `center` when the cursor is
// offscreen: `preserve`
"go_to_definition_scroll_strategy": "center",
+ // Where to show LSP results that can contain multiple locations
+ // (Go to Definition, Go to Implementation, Find All References). A single
+ // result always opens directly. Individual actions can override this with
+ // their `open_results_in` argument.
+ //
+ // 1. Open the results in a multibuffer: `multi_buffer` (default)
+ // 2. Open the results in a filterable picker: `picker`
+ "lsp_results_location": "multi_buffer",
// Which level to use to filter out diagnostics displayed in the editor.
//
// Affects the editor rendering only, and does not interrupt
diff --git a/crates/editor/src/actions.rs b/crates/editor/src/actions.rs
index 2bd544736a5..d88ca2200ff 100644
--- a/crates/editor/src/actions.rs
+++ b/crates/editor/src/actions.rs
@@ -582,16 +582,12 @@ actions!(
GoToDeclaration,
/// Goes to declaration in a split pane.
GoToDeclarationSplit,
- /// Goes to the definition of the symbol at cursor.
- GoToDefinition,
/// Goes to definition in a split pane.
GoToDefinitionSplit,
/// Goes to the next diff hunk.
GoToHunk,
/// Goes to the previous diff hunk.
GoToPreviousHunk,
- /// Goes to the implementation of the symbol at cursor.
- GoToImplementation,
/// Goes to implementation in a split pane.
GoToImplementationSplit,
/// Goes to the next bookmark in the file.
@@ -951,6 +947,28 @@ actions!(
]
);
+/// Goes to the definition of the symbol at cursor.
+#[derive(PartialEq, Clone, Default, Deserialize, JsonSchema, Action)]
+#[action(namespace = editor)]
+#[serde(deny_unknown_fields)]
+pub struct GoToDefinition {
+ /// Where to show the definitions. Falls back to the `lsp_results_location`
+ /// setting when omitted. A single result is always opened directly.
+ #[serde(default)]
+ pub open_results_in: Option<OpenResultsIn>,
+}
+
+/// Goes to the implementation of the symbol at cursor.
+#[derive(PartialEq, Clone, Default, Deserialize, JsonSchema, Action)]
+#[action(namespace = editor)]
+#[serde(deny_unknown_fields)]
+pub struct GoToImplementation {
+ /// Where to show the implementations. Falls back to the `lsp_results_location`
+ /// setting when omitted. A single result is always opened directly.
+ #[serde(default)]
+ pub open_results_in: Option<OpenResultsIn>,
+}
+
/// Finds all references to the symbol at cursor.
#[derive(PartialEq, Clone, Deserialize, JsonSchema, Action)]
#[action(namespace = editor)]
@@ -958,12 +976,17 @@ actions!(
pub struct FindAllReferences {
#[serde(default = "default_true")]
pub always_open_multibuffer: bool,
+ /// Where to show the references. Falls back to the `lsp_results_location`
+ /// setting when omitted. A single result is always opened directly.
+ #[serde(default)]
+ pub open_results_in: Option<OpenResultsIn>,
}
impl Default for FindAllReferences {
fn default() -> Self {
Self {
always_open_multibuffer: true,
+ open_results_in: None,
}
}
}
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 0e2e4d635b4..06c2913c5dd 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -98,8 +98,9 @@ pub use edit_prediction_types::Direction;
pub use edit_prediction_types::EditPredictionRequestTrigger;
pub use editor_settings::{
CompletionDetailAlignment, CompletionMenuItemKind, CurrentLineHighlight, DiffViewStyle,
- DocumentColorsRenderMode, EditorSettings, EditorSettingsScrollbarProxy, ScrollBeyondLastLine,
- ScrollbarAxes, SearchSettings, ShowMinimap, ui_scrollbar_settings_from_raw,
+ DocumentColorsRenderMode, EditorSettings, EditorSettingsScrollbarProxy, OpenResultsIn,
+ ScrollBeyondLastLine, ScrollbarAxes, SearchSettings, ShowMinimap,
+ ui_scrollbar_settings_from_raw,
};
pub use element::{
CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
diff --git a/crates/editor/src/editor_settings.rs b/crates/editor/src/editor_settings.rs
index 05a89a5907c..ffda80c3581 100644
--- a/crates/editor/src/editor_settings.rs
+++ b/crates/editor/src/editor_settings.rs
@@ -7,8 +7,8 @@ pub use settings::{
CodeLens, CompletionDetailAlignment, CompletionMenuItemKind, CurrentLineHighlight, DelayMs,
DiffViewStyle, DisplayIn, DocumentColorsRenderMode, DoubleClickInMultibuffer,
GoToDefinitionFallback, GoToDefinitionScrollStrategy, MinimapThumb, MinimapThumbBorder,
- MultiCursorModifier, ScrollBeyondLastLine, ScrollbarDiagnostics, SeedQuerySetting, ShowMinimap,
- SnippetSortOrder,
+ MultiCursorModifier, OpenResultsIn, ScrollBeyondLastLine, ScrollbarDiagnostics,
+ SeedQuerySetting, ShowMinimap, SnippetSortOrder,
};
use settings::{RegisterSetting, RelativeLineNumbers, Settings};
use ui::scrollbars::ShowScrollbar;
@@ -54,6 +54,7 @@ pub struct EditorSettings {
pub show_signature_help_after_edits: bool,
pub go_to_definition_fallback: GoToDefinitionFallback,
pub go_to_definition_scroll_strategy: GoToDefinitionScrollStrategy,
+ pub lsp_results_location: OpenResultsIn,
pub jupyter: Jupyter,
pub snippet_sort_order: SnippetSortOrder,
pub diagnostics_max_severity: Option<DiagnosticSeverity>,
@@ -289,6 +290,7 @@ impl Settings for EditorSettings {
show_signature_help_after_edits: editor.show_signature_help_after_edits.unwrap(),
go_to_definition_fallback: editor.go_to_definition_fallback.unwrap(),
go_to_definition_scroll_strategy: editor.go_to_definition_scroll_strategy.unwrap(),
+ lsp_results_location: editor.lsp_results_location.unwrap(),
jupyter: Jupyter {
enabled: editor.jupyter.unwrap().enabled.unwrap(),
},
diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rs
index b90054064ae..3efc8a5b291 100644
--- a/crates/editor/src/editor_tests.rs
+++ b/crates/editor/src/editor_tests.rs
@@ -28884,7 +28884,9 @@ async fn test_goto_definition_with_find_all_references_fallback(cx: &mut TestApp
);
set_up_lsp_handlers(false, &mut cx);
let navigated = cx
- .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
+ .update_editor(|editor, window, cx| {
+ editor.go_to_definition(&GoToDefinition::default(), window, cx)
+ })
.await
.expect("Failed to navigate to definition");
assert_eq!(
@@ -28918,7 +28920,9 @@ async fn test_goto_definition_with_find_all_references_fallback(cx: &mut TestApp
set_up_lsp_handlers(true, &mut cx);
let navigated = cx
- .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
+ .update_editor(|editor, window, cx| {
+ editor.go_to_definition(&GoToDefinition::default(), window, cx)
+ })
.await
.expect("Failed to navigate to lookup references");
assert_eq!(
@@ -28995,7 +28999,9 @@ async fn test_goto_definition_no_fallback(cx: &mut TestAppContext) {
});
let navigated = cx
- .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
+ .update_editor(|editor, window, cx| {
+ editor.go_to_definition(&GoToDefinition::default(), window, cx)
+ })
.await
.expect("Failed to navigate to lookup references");
go_to_definition
@@ -29064,7 +29070,9 @@ async fn test_goto_definition_close_ranges_open_singleton(cx: &mut TestAppContex
});
let navigated = cx
- .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
+ .update_editor(|editor, window, cx| {
+ editor.go_to_definition(&GoToDefinition::default(), window, cx)
+ })
.await
.expect("Failed to navigate to definitions");
assert_eq!(navigated, Navigated::Yes);
@@ -29148,7 +29156,9 @@ async fn test_goto_definition_far_ranges_open_multibuffer(cx: &mut TestAppContex
});
let navigated = cx
- .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
+ .update_editor(|editor, window, cx| {
+ editor.go_to_definition(&GoToDefinition::default(), window, cx)
+ })
.await
.expect("Failed to navigate to definitions");
assert_eq!(navigated, Navigated::Yes);
@@ -29221,7 +29231,9 @@ async fn test_goto_definition_contained_ranges(cx: &mut TestAppContext) {
});
let navigated = cx
- .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
+ .update_editor(|editor, window, cx| {
+ editor.go_to_definition(&GoToDefinition::default(), window, cx)
+ })
.await
.expect("Failed to navigate to definitions");
assert_eq!(navigated, Navigated::Yes);
@@ -29318,9 +29330,11 @@ async fn test_goto_definition_preserve_scroll_strategy(cx: &mut TestAppContext)
cx.update_editor(|editor, window, cx| {
editor.set_scroll_position(gpui::Point::new(0.0, caller_row - offset), window, cx);
});
- cx.update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
- .await
- .expect("Failed to navigate to definition");
+ cx.update_editor(|editor, window, cx| {
+ editor.go_to_definition(&GoToDefinition::default(), window, cx)
+ })
+ .await
+ .expect("Failed to navigate to definition");
cx.run_until_parked();
cx.update_editor(|editor, window, cx| {
assert_eq!(
@@ -29351,9 +29365,11 @@ async fn test_goto_definition_preserve_scroll_strategy(cx: &mut TestAppContext)
assert!(cursor_row >= visible_lines, "Cursor should be offscreen");
});
- cx.update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
- .await
- .expect("Failed to navigate to definition");
+ cx.update_editor(|editor, window, cx| {
+ editor.go_to_definition(&GoToDefinition::default(), window, cx)
+ })
+ .await
+ .expect("Failed to navigate to definition");
cx.run_until_parked();
cx.update_editor(|editor, window, cx| {
assert_eq!(
@@ -37901,6 +37917,7 @@ async fn test_find_references_single_case(cx: &mut TestAppContext) {
let action = FindAllReferences {
always_open_multibuffer: false,
+ open_results_in: None,
};
let navigated = cx
@@ -37916,6 +37933,116 @@ async fn test_find_references_single_case(cx: &mut TestAppContext) {
cx.assert_editor_state(after);
}
+/// Maps each resolved [`Location`] to `(row, start_column, end_column)`.
+fn location_row_columns(
+ cx: &mut EditorLspTestContext,
+ locations: &[project::Location],
+) -> Vec<(u32, u32, u32)> {
+ let mut rows = cx.update_editor(|_editor, _window, cx| {
+ locations
+ .iter()
+ .map(|location| {
+ let snapshot = location.buffer.read(cx).snapshot();
+ let start: usize = snapshot.summary_for_anchor(&location.range.start);
+ let end: usize = snapshot.summary_for_anchor(&location.range.end);
+ let start = snapshot.offset_to_point(start);
+ let end = snapshot.offset_to_point(end);
+ (start.row, start.column, end.column)
+ })
+ .collect::<Vec<_>>()
+ });
+ rows.sort();
+ rows
+}
+
+#[gpui::test]
+async fn test_definition_locations_of_kind_excludes_self_link(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+ let mut cx = EditorLspTestContext::new_rust(
+ lsp::ServerCapabilities {
+ definition_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ cx,
+ )
+ .await;
+
+ // Cursor sits inside the `abc` use on row 2 (columns 14..17).
+ cx.set_state(indoc!(
+ r#"
+ fn main() {
+ let abc = 123;
+ let xyz = aˇbc;
+ }
+ "#
+ ));
+
+ // The server returns two targets: the location covering the cursor (which
+ // must be filtered out as a self-link) and the real definition on row 1.
+ cx.lsp
+ .set_request_handler::<lsp::request::GotoDefinition, _, _>(async move |params, _| {
+ let uri = params.text_document_position_params.text_document.uri;
+ Ok(Some(lsp::GotoDefinitionResponse::Array(vec![
+ lsp::Location {
+ uri: uri.clone(),
+ range: lsp::Range::new(lsp::Position::new(2, 14), lsp::Position::new(2, 17)),
+ },
+ lsp::Location {
+ uri,
+ range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 11)),
+ },
+ ])))
+ });
+
+ let locations = cx
+ .update_editor(|editor, _window, cx| {
+ editor.definition_locations_of_kind(GotoDefinitionKind::Symbol, cx)
+ })
+ .expect("definition query should spawn a task")
+ .await
+ .unwrap();
+
+ // Only the real definition remains; the target covering the cursor is dropped.
+ assert_eq!(location_row_columns(&mut cx, &locations), vec![(1, 8, 11)]);
+}
+
+#[test]
+fn test_open_results_in_action_argument_parsing() {
+ // A bare keybinding (no arguments) resolves to `None`, i.e. defer to the
+ // `lsp_results_location` setting. Keymap loading builds actions from `{}`
+ // when no arguments are given, so that is what we deserialize here.
+ assert_eq!(
+ serde_json::from_value::<GoToDefinition>(json!({}))
+ .unwrap()
+ .open_results_in,
+ None,
+ );
+
+ // The `OpenResultsIn` variants must keep the snake_case spelling that
+ // keymaps and the `lsp_results_location` setting rely on; a rename here
+ // would silently break those keybindings.
+ assert_eq!(
+ serde_json::from_value::<GoToDefinition>(json!({ "open_results_in": "picker" }))
+ .unwrap()
+ .open_results_in,
+ Some(OpenResultsIn::Picker),
+ );
+ assert_eq!(
+ serde_json::from_value::<GoToImplementation>(json!({ "open_results_in": "multi_buffer" }))
+ .unwrap()
+ .open_results_in,
+ Some(OpenResultsIn::MultiBuffer),
+ );
+
+ // The argument coexists with `FindAllReferences`'s existing field, which
+ // keeps its own default when only `open_results_in` is provided.
+ let references =
+ serde_json::from_value::<FindAllReferences>(json!({ "open_results_in": "picker" }))
+ .unwrap();
+ assert_eq!(references.open_results_in, Some(OpenResultsIn::Picker));
+ assert!(references.always_open_multibuffer);
+}
+
#[gpui::test]
async fn test_newline_task_list_continuation(cx: &mut TestAppContext) {
init_test(cx, |settings| {
diff --git a/crates/editor/src/hover_links.rs b/crates/editor/src/hover_links.rs
index 9e943d37daf..2f7fe2787df 100644
--- a/crates/editor/src/hover_links.rs
+++ b/crates/editor/src/hover_links.rs
@@ -335,7 +335,7 @@ impl Editor {
}
(true, false) => self.go_to_type_definition(&GoToTypeDefinition, window, cx),
(false, true) => self.go_to_definition_split(&GoToDefinitionSplit, window, cx),
- (false, false) => self.go_to_definition(&GoToDefinition, window, cx),
+ (false, false) => self.go_to_definition(&GoToDefinition::default(), window, cx),
}
} else {
Task::ready(Ok(Navigated::No))
diff --git a/crates/editor/src/mouse_context_menu.rs b/crates/editor/src/mouse_context_menu.rs
index 879384fb6e6..0c4cbb3667a 100644
--- a/crates/editor/src/mouse_context_menu.rs
+++ b/crates/editor/src/mouse_context_menu.rs
@@ -256,10 +256,13 @@ pub fn deploy_context_menu(
run_to_cursor || (evaluate_selection && has_selections),
|builder| builder.separator(),
)
- .action("Go to Definition", Box::new(GoToDefinition))
+ .action("Go to Definition", Box::new(GoToDefinition::default()))
.action("Go to Declaration", Box::new(GoToDeclaration))
.action("Go to Type Definition", Box::new(GoToTypeDefinition))
- .action("Go to Implementation", Box::new(GoToImplementation))
+ .action(
+ "Go to Implementation",
+ Box::new(GoToImplementation::default()),
+ )
.action(
"Find All References",
Box::new(FindAllReferences::default()),
diff --git a/crates/editor/src/navigation.rs b/crates/editor/src/navigation.rs
index 471f68b16b8..29447dd2f3e 100644
--- a/crates/editor/src/navigation.rs
+++ b/crates/editor/src/navigation.rs
@@ -1298,6 +1298,62 @@ impl Editor {
}))
}
+ /// Runs the LSP go-to query for `kind` (definition / declaration / type /
+ /// implementation) against the symbol under the cursor and returns the raw
+ /// target [`Location`]s. The go-to counterpart to
+ /// [`Self::find_all_references_locations`]; used by the LSP location pickers.
+ pub fn definition_locations_of_kind(
+ &mut self,
+ kind: GotoDefinitionKind,
+ cx: &mut Context<Self>,
+ ) -> Option<Task<Result<Vec<Location>>>> {
+ let provider = self.semantics_provider.clone()?;
+ let selection = self.selections.newest_anchor();
+ let multi_buffer = self.buffer.read(cx);
+ let multi_buffer_snapshot = multi_buffer.snapshot(cx);
+ let head = selection
+ .map(|anchor| anchor.to_offset(&multi_buffer_snapshot))
+ .head();
+
+ let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
+ let definitions = provider.definitions(&buffer, head, kind, cx)?;
+ Some(cx.spawn(async move |editor, cx| {
+ let definitions = definitions.await?.unwrap_or_default();
+ // Drop a result that points back at the cursor, matching
+ // `go_to_definition_of_kind` (otherwise the picker lists the symbol
+ // you invoked it on).
+ editor.update(cx, |_, cx| {
+ definitions
+ .into_iter()
+ .filter(|link| hover_links::exclude_link_to_position(&buffer, &head, link, cx))
+ .map(|link| link.target)
+ .collect()
+ })
+ }))
+ }
+
+ /// Runs an LSP "find all references" query for the symbol under the cursor
+ /// and returns the raw [`Location`]s. Unlike [`Self::find_all_references`],
+ /// this does not group the results or open any UI
+ pub fn find_all_references_locations(
+ &mut self,
+ project: &Entity<Project>,
+ cx: &mut Context<Self>,
+ ) -> Option<Task<Result<Vec<Location>>>> {
+ let selection = self.selections.newest_anchor();
+ let multi_buffer = self.buffer.read(cx);
+ let multi_buffer_snapshot = multi_buffer.snapshot(cx);
+ let head = selection
+ .map(|anchor| anchor.to_offset(&multi_buffer_snapshot))
+ .head();
+
+ let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
+ let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
+ // Keep every reference, including the one under the cursor, to match the
+ // default `find_all_references` multibuffer (`always_open_multibuffer`).
+ Some(cx.spawn(async move |_, _| Ok(references.await?.unwrap_or_default())))
+ }
+
pub fn find_all_references(
&mut self,
action: &FindAllReferences,
@@ -2101,6 +2157,25 @@ impl Editor {
self.go_to_symbol_by_offset(window, cx, -1).detach();
}
+ /// Opens `location` and jumps to it through the same path as
+ /// go-to-definition, so selection, autoscroll, and jumplist tagging all
+ /// match. `split` opens it in the adjacent pane. Called on the editor the
+ /// jump originates from.
+ pub fn open_location(
+ &mut self,
+ location: Location,
+ split: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Task<Result<Navigated>> {
+ let origin = self.navigation_entry(self.selections.newest_anchor().head(), cx);
+ let link = HoverLink::Text(LocationLink {
+ origin: None,
+ target: location,
+ });
+ self.navigate_to_hover_links(None, vec![link], origin, split, window, cx)
+ }
+
/// Opens a multibuffer with the given project locations in it.
pub(super) fn open_locations_in_multibuffer(
workspace: &mut Workspace,
diff --git a/crates/lsp_locations/Cargo.toml b/crates/lsp_locations/Cargo.toml
new file mode 100644
index 00000000000..2559e571e80
--- /dev/null
+++ b/crates/lsp_locations/Cargo.toml
@@ -0,0 +1,43 @@
+[package]
+name = "lsp_locations"
+version = "0.1.0"
+edition.workspace = true
+publish.workspace = true
+license = "GPL-3.0-or-later"
+
+[lints]
+workspace = true
+
+[lib]
+path = "src/lsp_locations.rs"
+doctest = false
+
+[dependencies]
+anyhow.workspace = true
+collections.workspace = true
+editor.workspace = true
+file_icons.workspace = true
+fuzzy.workspace = true
+gpui.workspace = true
+language.workspace = true
+log.workspace = true
+picker.workspace = true
+picker_preview.workspace = true
+project.workspace = true
+settings.workspace = true
+text.workspace = true
+theme_settings.workspace = true
+ui.workspace = true
+util.workspace = true
+workspace.workspace = true
+
+[dev-dependencies]
+editor = { workspace = true, features = ["test-support"] }
+gpui = { workspace = true, features = ["test-support"] }
+indoc.workspace = true
+language = { workspace = true, features = ["test-support"] }
+lsp = { workspace = true, features = ["test-support"] }
+project = { workspace = true, features = ["test-support"] }
+settings = { workspace = true, features = ["test-support"] }
+theme = { workspace = true, features = ["test-support"] }
+workspace = { workspace = true, features = ["test-support"] }
diff --git a/crates/lsp_locations/LICENSE-GPL b/crates/lsp_locations/LICENSE-GPL
new file mode 120000
index 00000000000..89e542f750c
--- /dev/null
+++ b/crates/lsp_locations/LICENSE-GPL
@@ -0,0 +1 @@
+../../LICENSE-GPL
\ No newline at end of file
diff --git a/crates/lsp_locations/src/lsp_locations.rs b/crates/lsp_locations/src/lsp_locations.rs
new file mode 100644
index 00000000000..90f29ae7bc0
--- /dev/null
+++ b/crates/lsp_locations/src/lsp_locations.rs
@@ -0,0 +1,972 @@
+use std::ops::Range;
+use std::sync::Arc;
+
+use collections::HashMap;
+use editor::actions::{FindAllReferences, GoToDefinition, GoToImplementation};
+use editor::{Editor, EditorSettings, GotoDefinitionKind, OpenResultsIn};
+use file_icons::FileIcons;
+use fuzzy::StringMatchCandidate;
+use gpui::{
+ AnyElement, App, AppContext, AsyncWindowContext, Context, DismissEvent, Entity, EventEmitter,
+ FocusHandle, Focusable, HighlightStyle, StyledText, Subscription, Task, TextStyle, WeakEntity,
+ prelude::*,
+};
+use language::{Buffer, HighlightId, LanguageAwareStyling};
+use picker::{Picker, PickerDelegate};
+use project::{Location, Project, ProjectPath};
+use settings::{GoToDefinitionFallback, Settings as _};
+use text::{Anchor, Point};
+use theme_settings::ThemeSettings;
+use ui::{Divider, FluentBuilder};
+use ui::{ListItem, ListItemSpacing, prelude::*};
+use util::ResultExt as _;
+use workspace::item::ItemSettings;
+use workspace::notifications::NotificationId;
+use workspace::{ModalView, Toast, Workspace};
+
+pub fn init(cx: &mut App) {
+ cx.observe_new(register).detach();
+}
+
+/// Registers handlers for the navigation actions on each full editor. When the
+/// action resolves to [`OpenResultsIn::Picker`], we open the filterable picker;
+/// otherwise we `cx.propagate()` so the editor's own handler runs and builds a
+/// multibuffer.
+fn register(editor: &mut Editor, _window: Option<&mut Window>, cx: &mut Context<Editor>) {
+ if !editor.mode().is_full() {
+ return;
+ }
+ let handle = cx.entity().downgrade();
+ editor
+ .register_action({
+ let handle = handle.clone();
+ move |action: &GoToDefinition, window, cx| {
+ handle_nav_action(
+ action.open_results_in,
+ LspPickerKind::Definition,
+ &handle,
+ window,
+ cx,
+ );
+ }
+ })
+ .detach();
+ editor
+ .register_action({
+ let handle = handle.clone();
+ move |action: &GoToImplementation, window, cx| {
+ handle_nav_action(
+ action.open_results_in,
+ LspPickerKind::Implementation,
+ &handle,
+ window,
+ cx,
+ );
+ }
+ })
+ .detach();
+ editor
+ .register_action(move |action: &FindAllReferences, window, cx| {
+ handle_nav_action(
+ action.open_results_in,
+ LspPickerKind::References,
+ &handle,
+ window,
+ cx,
+ );
+ })
+ .detach();
+}
+
+/// Either opens the picker for the editor, or propagates the action so the
+/// editor's built-in (multibuffer) handler runs. A `None` argument falls back to
+/// the `lsp_results_location` setting.
+fn handle_nav_action(
+ open_results_in: Option<OpenResultsIn>,
+ kind: LspPickerKind,
+ editor: &WeakEntity<Editor>,
+ window: &mut Window,
+ cx: &mut App,
+) {
+ let open_results_in =
+ open_results_in.unwrap_or_else(|| EditorSettings::get_global(cx).lsp_results_location);
+ if open_results_in != OpenResultsIn::Picker {
+ cx.propagate();
+ return;
+ }
+ LspLocationsPicker::open_for_editor(kind, editor.clone(), window, cx);
+}
+
+/// Runs the LSP query for `kind` and returns the raw locations. Returns `None`
+/// (and reports any error) when there is nothing to query, so the caller stops
+/// without an empty-results toast. Deduplication and dropping fileless results
+/// happen later in [`build_location_matches`].
+async fn run_picker_query(
+ kind: LspPickerKind,
+ editor: &WeakEntity<Editor>,
+ workspace: &WeakEntity<Workspace>,
+ project: &Entity<Project>,
+ cx: &mut AsyncWindowContext,
+) -> Option<Vec<Location>> {
+ let query = editor
+ .update(cx, |editor, cx| kind.run_query(editor, project, cx))
+ .ok()
+ .flatten()?;
+ match query.await {
+ Ok(locations) => Some(locations),
+ Err(error) => {
+ log::error!("LSP {kind:?} query failed: {error:#}");
+ workspace
+ .update(cx, |workspace, cx| workspace.show_error(error, cx))
+ .log_err();
+ None
+ }
+ }
+}
+
+/// Runs the query for `kind` and builds the displayable, deduped matches.
+async fn run_picker_matches(
+ kind: LspPickerKind,
+ editor: &WeakEntity<Editor>,
+ workspace: &WeakEntity<Workspace>,
+ project: &Entity<Project>,
+ cx: &mut AsyncWindowContext,
+) -> Option<Vec<LocationMatch>> {
+ let locations = run_picker_query(kind, editor, workspace, project, cx).await?;
+ editor
+ .update(cx, |_, cx| build_location_matches(&locations, cx))
+ .ok()
+}
+
+fn show_no_results_toast(
+ workspace: &WeakEntity<Workspace>,
+ kind: LspPickerKind,
+ cx: &mut AsyncWindowContext,
+) {
+ workspace
+ .update(cx, |workspace, cx| {
+ struct NoLspResults;
+ workspace.show_toast(
+ Toast::new(
+ NotificationId::unique::<NoLspResults>(),
+ kind.empty_message(),
+ )
+ .autohide(),
+ cx,
+ );
+ })
+ .log_err();
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum LspPickerKind {
+ References,
+ Definition,
+ Implementation,
+}
+
+impl LspPickerKind {
+ fn placeholder(self) -> &'static str {
+ match self {
+ LspPickerKind::References => "Filter references…",
+ LspPickerKind::Definition => "Filter definitions…",
+ LspPickerKind::Implementation => "Filter implementations…",
+ }
+ }
+
+ /// Message shown when the query produces no results, so the command does not
+ /// appear to silently do nothing.
+ fn empty_message(self) -> &'static str {
+ match self {
+ LspPickerKind::References => "No references found",
+ LspPickerKind::Definition => "No definitions found",
+ LspPickerKind::Implementation => "No implementations found",
+ }
+ }
+
+ /// Runs the query for this kind against the active editor, returning the raw
+ /// locations to populate the picker.
+ fn run_query(
+ self,
+ editor: &mut Editor,
+ project: &Entity<Project>,
+ cx: &mut Context<Editor>,
+ ) -> Option<Task<anyhow::Result<Vec<Location>>>> {
+ match self {
+ LspPickerKind::References => editor.find_all_references_locations(project, cx),
+ LspPickerKind::Definition => {
+ editor.definition_locations_of_kind(GotoDefinitionKind::Symbol, cx)
+ }
+ LspPickerKind::Implementation => {
+ editor.definition_locations_of_kind(GotoDefinitionKind::Implementation, cx)
+ }
+ }
+ }
+}
+
+pub struct LspLocationsPicker {
+ picker: Entity<Picker<LspLocationsDelegate>>,
+ _subscription: Subscription,
+}
+
+impl LspLocationsPicker {
+ fn open_for_editor(
+ kind: LspPickerKind,
+ editor: WeakEntity<Editor>,
+ window: &mut Window,
+ cx: &mut App,
+ ) {
+ let Some(editor) = editor.upgrade() else {
+ return;
+ };
+ let Some(workspace) = editor.read(cx).workspace() else {
+ return;
+ };
+ workspace.update(cx, |workspace, cx| {
+ Self::open(kind, editor, workspace, window, cx);
+ });
+ }
+
+ /// Opens the picker for `kind`: runs a fresh LSP query and shows the
+ /// results. An empty definitions query falls back to references when the
+ /// `go_to_definition_fallback` setting calls for it, matching
+ /// [`Editor::go_to_definition`].
+ fn open(
+ kind: LspPickerKind,
+ editor: Entity<Editor>,
+ workspace: &mut Workspace,
+ window: &mut Window,
+ cx: &mut Context<Workspace>,
+ ) {
+ let project = workspace.project().clone();
+ let fallback = EditorSettings::get_global(cx).go_to_definition_fallback;
+ let editor = editor.downgrade();
+ cx.spawn_in(window, async move |workspace, cx| {
+ // The kind the user invoked, kept for user-facing messages even if
+ // the query below falls back to references.
+ let invoked_kind = kind;
+ let mut kind = kind;
+
+ // Count on the built matches (not raw locations): they are deduped by
+ // range and exclude fileless results, so a single distinct result
+ // jumps directly and a fileless-only result reports "no results"
+ // instead of opening a blank picker.
+ let Some(mut matches) =
+ run_picker_matches(kind, &editor, &workspace, &project, cx).await
+ else {
+ return;
+ };
+
+ if matches.is_empty()
+ && kind == LspPickerKind::Definition
+ && fallback == GoToDefinitionFallback::FindAllReferences
+ {
+ kind = LspPickerKind::References;
+ let Some(references) =
+ run_picker_matches(kind, &editor, &workspace, &project, cx).await
+ else {
+ return;
+ };
+ matches = references;
+ }
+
+ if matches.is_empty() {
+ show_no_results_toast(&workspace, invoked_kind, cx);
+ return;
+ }
+
+ if matches.len() == 1 {
+ if let Some(location_match) = matches.into_iter().next() {
+ let location = Location {
+ buffer: location_match.buffer,
+ range: location_match.anchor_range,
+ };
+ if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
+ editor.open_location(location, false, window, cx)
+ }) {
+ task.await.log_err();
+ }
+ }
+ return;
+ }
+
+ workspace
+ .update_in(cx, |workspace, window, cx| {
+ workspace.toggle_modal(window, cx, |window, cx| {
+ Self::new(kind, matches, project, editor, window, cx)
+ });
+ })
+ .log_err();
+ })
+ .detach();
+ }
+
+ fn new(
+ kind: LspPickerKind,
+ matches: Vec<LocationMatch>,
+ project: Entity<Project>,
+ editor: WeakEntity<Editor>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Self {
+ let preview = picker_preview::editor_preview(project.clone(), window, cx);
+ let delegate = LspLocationsDelegate::new(kind, matches, project, editor);
+ let picker = cx.new(|cx| Picker::list_with_preview(delegate, preview, window, cx));
+ let subscription = cx.subscribe(&picker, |_, _, _: &DismissEvent, cx| {
+ cx.emit(DismissEvent);
+ });
+ Self {
+ picker,
+ _subscription: subscription,
+ }
+ }
+}
+
+impl ModalView for LspLocationsPicker {}
+
+impl EventEmitter<DismissEvent> for LspLocationsPicker {}
+
+impl Focusable for LspLocationsPicker {
+ fn focus_handle(&self, cx: &App) -> FocusHandle {
+ self.picker.focus_handle(cx)
+ }
+}
+
+impl Render for LspLocationsPicker {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ v_flex().child(self.picker.clone())
+ }
+}
+
+struct LocationMatch {
+ path: ProjectPath,
+ buffer: Entity<Buffer>,
+ anchor_range: Range<Anchor>,
+ range: Range<usize>,
+ display_text: String,
+ syntax_highlights: Vec<(Range<usize>, HighlightId)>,
+ match_range: Range<usize>,
+ line_number: u32,
+}
+
+/// A row in the grouped display list: a non-selectable file header, a match, or
+/// a separator between file groups. `selected_index` indexes into this list.
+enum Entry {
+ Header(ProjectPath),
+ Match(usize),
+ Separator,
+}
+
+struct LspLocationsDelegate {
+ kind: LspPickerKind,
+ project: Entity<Project>,
+ editor: WeakEntity<Editor>,
+ all_matches: Vec<LocationMatch>,
+ candidates: Arc<[StringMatchCandidate]>,
+ matches: Vec<usize>,
+ entries: Vec<Entry>,
+ selected_index: usize,
+ max_line_number: u32,
+}
+
+impl LspLocationsDelegate {
+ fn new(
+ kind: LspPickerKind,
+ all_matches: Vec<LocationMatch>,
+ project: Entity<Project>,
+ editor: WeakEntity<Editor>,
+ ) -> Self {
+ // Match against the line text and the file path, mirroring the fuzzy
+ // matching every other Zed picker uses.
+ let candidates = all_matches
+ .iter()
+ .enumerate()
+ .map(|(index, location_match)| {
+ StringMatchCandidate::new(
+ index,
+ &format!(
+ "{} {}",
+ location_match.display_text,
+ location_match.path.path.as_unix_str()
+ ),
+ )
+ })
+ .collect();
+ let matches = (0..all_matches.len()).collect();
+ let mut this = Self {
+ kind,
+ project,
+ editor,
+ all_matches,
+ candidates,
+ matches,
+ entries: Vec::new(),
+ selected_index: 0,
+ max_line_number: 0,
+ };
+ this.rebuild_entries();
+ this
+ }
+
+ /// Rebuilds the grouped [`Self::entries`] from the filtered [`Self::matches`]:
+ /// one header per file, its matches, and a separator before every group
+ /// after the first. Selection snaps to the first selectable row.
+ fn rebuild_entries(&mut self) {
+ let mut entries = Vec::with_capacity(self.matches.len());
+ let mut last_path: Option<&ProjectPath> = None;
+ let mut max_line_number = 0;
+ for &match_index in &self.matches {
+ let location_match = &self.all_matches[match_index];
+ if last_path != Some(&location_match.path) {
+ if last_path.is_some() {
+ entries.push(Entry::Separator);
+ }
+ entries.push(Entry::Header(location_match.path.clone()));
+ last_path = Some(&location_match.path);
+ }
+ max_line_number = max_line_number.max(location_match.line_number);
+ entries.push(Entry::Match(match_index));
+ }
+ self.entries = entries;
+ self.max_line_number = max_line_number;
+ self.selected_index = self.first_selectable_index().unwrap_or(0);
+ }
+
+ fn first_selectable_index(&self) -> Option<usize> {
+ self.entries
+ .iter()
+ .position(|entry| matches!(entry, Entry::Match(_)))
+ }
+
+ fn selected_location_match(&self) -> Option<&LocationMatch> {
+ match self.entries.get(self.selected_index)? {
+ Entry::Match(match_index) => self.all_matches.get(*match_index),
+ Entry::Header(_) | Entry::Separator => None,
+ }
+ }
+
+ fn open_selected(&mut self, split: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
+ let Some(location_match) = self.selected_location_match() else {
+ return;
+ };
+ let location = Location {
+ buffer: location_match.buffer.clone(),
+ range: location_match.anchor_range.clone(),
+ };
+ let Some(editor) = self.editor.upgrade() else {
+ return;
+ };
+ editor
+ .update(cx, |editor, cx| {
+ editor.open_location(location, split, window, cx)
+ })
+ .detach_and_log_err(cx);
+ cx.emit(DismissEvent);
+ }
+}
+
+fn build_location_matches(locations: &[Location], cx: &App) -> Vec<LocationMatch> {
+ use gpui::EntityId;
+ let mut snapshots: HashMap<EntityId, language::BufferSnapshot> = HashMap::default();
+ let mut matches = Vec::with_capacity(locations.len());
+
+ for location in locations {
+ let snapshot = snapshots
+ .entry(location.buffer.entity_id())
+ .or_insert_with(|| location.buffer.read(cx).snapshot());
+
+ let Some(file) = snapshot.file() else {
+ continue;
+ };
+ let path = ProjectPath {
+ worktree_id: file.worktree_id(cx),
+ path: file.path().clone(),
+ };
+
+ let start_offset: usize = snapshot.summary_for_anchor(&location.range.start);
+ let end_offset: usize = snapshot.summary_for_anchor(&location.range.end);
+ let row = snapshot.offset_to_point(start_offset).row;
+ let line_start = snapshot.point_to_offset(Point::new(row, 0));
+ let line_end = snapshot.point_to_offset(Point::new(row, snapshot.line_len(row)));
+ let full_line: String = snapshot.text_for_range(line_start..line_end).collect();
+
+ // The row shows the line with leading indentation trimmed. Offsets below
+ // are relative to that displayed text.
+ let display_text = full_line.trim_start().to_string();
+ let visible_start = line_end.saturating_sub(display_text.len());
+ let visible_end = line_end;
+
+ // Precompute syntax highlights for the displayed text so rendering a row
+ // never re-snapshots the buffer or re-runs highlighting.
+ let mut syntax_highlights = Vec::new();
+ let mut offset = 0;
+ for chunk in snapshot.chunks(
+ visible_start..visible_end,
+ LanguageAwareStyling {
+ tree_sitter: true,
+ diagnostics: false,
+ },
+ ) {
+ let chunk_len = chunk.text.len();
+ if let Some(id) = chunk.syntax_highlight_id {
+ syntax_highlights.push((offset..offset + chunk_len, id));
+ }
+ offset += chunk_len;
+ }
+
+ // The match span, clamped into the displayed text. `clamp` bounds each
+ // endpoint to the line; `min`/`max` then keep the range well-ordered even
+ // for a malformed/inverted LSP range (clamping alone preserves bounds but
+ // not `start <= end`).
+ let clamped_start = start_offset.clamp(visible_start, visible_end) - visible_start;
+ let clamped_end = end_offset.clamp(visible_start, visible_end) - visible_start;
+ let match_range = clamped_start.min(clamped_end)..clamped_start.max(clamped_end);
+
+ matches.push(LocationMatch {
+ path,
+ buffer: location.buffer.clone(),
+ anchor_range: location.range.clone(),
+ range: start_offset..end_offset,
+ display_text,
+ syntax_highlights,
+ match_range,
+ line_number: row + 1,
+ });
+ }
+
+ // Group by file and order by position so the grouped display list is stable,
+ // then drop exact-duplicate ranges a server may report more than once.
+ matches.sort_by(|a, b| a.path.cmp(&b.path).then(a.range.start.cmp(&b.range.start)));
+ matches.dedup_by(|a, b| a.path == b.path && a.range == b.range);
+ matches
+}
+
+impl PickerDelegate for LspLocationsDelegate {
+ type ListItem = AnyElement;
+
+ fn name() -> &'static str {
+ "lsp locations picker"
+ }
+
+ fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> std::sync::Arc<str> {
+ self.kind.placeholder().into()
+ }
+
+ fn match_count(&self) -> usize {
+ self.entries.len()
+ }
+
+ fn can_select(&self, ix: usize, _window: &mut Window, _cx: &mut Context<Picker<Self>>) -> bool {
+ matches!(self.entries.get(ix), Some(Entry::Match(_)))
+ }
+
+ fn selected_index(&self) -> usize {
+ self.selected_index
+ }
+
+ fn select_on_hover(&self) -> bool {
+ false
+ }
+
+ fn set_selected_index(
+ &mut self,
+ ix: usize,
+ _window: &mut Window,
+ _cx: &mut Context<Picker<Self>>,
+ ) {
+ self.selected_index = ix;
+ }
+
+ fn update_matches(
+ &mut self,
+ query: String,
+ _window: &mut Window,
+ cx: &mut Context<Picker<Self>>,
+ ) -> Task<()> {
+ let query = query.trim().to_owned();
+ let candidates = self.candidates.clone();
+ cx.spawn(async move |picker, cx| {
+ let matches = if query.is_empty() {
+ (0..candidates.len()).collect()
+ } else {
+ let string_matches = fuzzy::match_strings(
+ &candidates,
+ &query,
+ false,
+ true,
+ candidates.len(),
+ &Default::default(),
+ cx.background_executor().clone(),
+ )
+ .await;
+ let mut indices = string_matches
+ .into_iter()
+ .map(|string_match| string_match.candidate_id)
+ .collect::<Vec<_>>();
+ // Restore the file-grouped, positional order (fuzzy returns by score).
+ indices.sort_unstable();
+ indices
+ };
+ picker
+ .update(cx, |picker, cx| {
+ picker.delegate.matches = matches;
+ picker.delegate.rebuild_entries();
+ cx.notify();
+ })
+ .ok();
+ })
+ }
+
+ fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
+ self.open_selected(secondary, window, cx);
+ }
+
+ fn dismissed(&mut self, _window: &mut Window, cx: &mut Context<Picker<Self>>) {
+ cx.emit(DismissEvent);
+ }
+
+ fn try_get_preview_data_for_match(&self, _cx: &App) -> Option<picker::PreviewUpdate> {
+ let location_match = self.selected_location_match()?;
+ Some(picker::PreviewUpdate::from_buffer(
+ location_match.buffer.clone(),
+ picker::MatchLocation {
+ anchor_range: location_match.anchor_range.clone(),
+ range: location_match.range.clone(),
+ },
+ ))
+ }
+
+ fn render_match(
+ &self,
+ ix: usize,
+ selected: bool,
+ _window: &mut Window,
+ cx: &mut Context<Picker<Self>>,
+ ) -> Option<Self::ListItem> {
+ match self.entries.get(ix)? {
+ Entry::Separator => Some(
+ div()
+ .py(DynamicSpacing::Base04.rems(cx))
+ .child(Divider::horizontal())
+ .into_any_element(),
+ ),
+ Entry::Header(path) => {
+ let path_style = self.project.read(cx).path_style(cx);
+ let file_name = path
+ .path
+ .file_name()
+ .map(|name| name.to_string())
+ .unwrap_or_default();
+ let directory = path
+ .path
+ .parent()
+ .map(|parent| parent.display(path_style))
+ .map(SharedString::new)
+ .unwrap_or_default();
+ let file_icon = ItemSettings::get_global(cx)
+ .file_icons
+ .then(|| FileIcons::get_icon(path.path.as_std_path(), cx))
+ .flatten()
+ .map(|icon| {
+ Icon::from_path(icon)
+ .color(Color::Muted)
+ .size(IconSize::Small)
+ });
+ Some(
+ h_flex()
+ .w_full()
+ .min_w_0()
+ .px(DynamicSpacing::Base06.rems(cx))
+ .py_1()
+ .gap_1p5()
+ .children(file_icon)
+ .child(
+ h_flex()
+ .gap_1()
+ .child(Label::new(file_name).size(LabelSize::Small))
+ .when(!directory.is_empty(), |this| {
+ this.child(
+ Label::new(directory)
+ .size(LabelSize::Small)
+ .color(Color::Muted)
+ .truncate_start(),
+ )
+ }),
+ )
+ .into_any_element(),
+ )
+ }
+ Entry::Match(match_index) => {
+ let location_match = self.all_matches.get(*match_index)?;
+ Some(
+ ListItem::new(ix)
+ .spacing(ListItemSpacing::Sparse)
+ .inset(true)
+ .toggle_state(selected)
+ .child(
+ h_flex()
+ .w_full()
+ .min_w_0()
+ .gap_2p5()
+ .text_sm()
+ .child(
+ h_flex()
+ .w(rems(
+ (self.max_line_number.max(1).ilog10() + 1) as f32 * 0.5,
+ ))
+ .justify_end()
+ .child(
+ Label::new(location_match.line_number.to_string())
+ .color(Color::Custom(
+ cx.theme().colors().text_muted.opacity(0.5),
+ )),
+ ),
+ )
+ .child(
+ div()
+ .flex_1()
+ .min_w_0()
+ .truncate()
+ .child(render_matched_line(location_match, cx)),
+ ),
+ )
+ .into_any_element(),
+ )
+ }
+ }
+ }
+}
+
+/// Renders the precomputed displayed line, resolving the stored syntax highlight
+/// ids against the current theme and overlaying the match with a highlighted
+/// background and bold weight.
+fn render_matched_line(location_match: &LocationMatch, cx: &App) -> StyledText {
+ let settings = ThemeSettings::get_global(cx);
+ let text_style = TextStyle {
+ color: cx.theme().colors().text,
+ font_family: settings.buffer_font.family.clone(),
+ font_features: settings.buffer_font.features.clone(),
+ font_fallbacks: settings.buffer_font.fallbacks.clone(),
+ font_size: settings.buffer_font_size(cx).into(),
+ font_weight: settings.buffer_font.weight,
+ line_height: relative(1.),
+ ..Default::default()
+ };
+
+ let syntax_theme = cx.theme().syntax();
+ let syntax_highlights = location_match
+ .syntax_highlights
+ .iter()
+ .filter_map(|(range, id)| Some((range.clone(), syntax_theme.get(*id).copied()?)))
+ .collect::<Vec<_>>();
+
+ let match_style = HighlightStyle {
+ background_color: Some(cx.theme().colors().search_match_background),
+ font_weight: Some(gpui::FontWeight::BOLD),
+ ..Default::default()
+ };
+ let match_highlight = (location_match.match_range.clone(), match_style);
+
+ let highlights = gpui::combine_highlights(syntax_highlights, [match_highlight]);
+ StyledText::new(location_match.display_text.clone())
+ .with_default_highlights(&text_style, highlights)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use editor::test::editor_lsp_test_context::EditorLspTestContext;
+ use gpui::TestAppContext;
+ use indoc::indoc;
+
+ async fn rust_cx(
+ capabilities: lsp::ServerCapabilities,
+ cx: &mut TestAppContext,
+ ) -> EditorLspTestContext {
+ EditorLspTestContext::new_rust(capabilities, cx).await
+ }
+
+ fn open(cx: &mut EditorLspTestContext, kind: LspPickerKind) {
+ let editor = cx.editor.clone();
+ let workspace = cx.workspace.clone();
+ cx.update(|window, cx| {
+ workspace.update(cx, |workspace, cx| {
+ LspLocationsPicker::open(kind, editor, workspace, window, cx);
+ });
+ });
+ cx.run_until_parked();
+ }
+
+ fn active_picker(cx: &mut EditorLspTestContext) -> Option<Entity<LspLocationsPicker>> {
+ let workspace = cx.workspace.clone();
+ cx.update(|_window, cx| workspace.read(cx).active_modal::<LspLocationsPicker>(cx))
+ }
+
+ fn references(uri: lsp::Uri, ranges: &[(u32, u32, u32)]) -> Vec<lsp::Location> {
+ ranges
+ .iter()
+ .map(|&(row, start, end)| lsp::Location {
+ uri: uri.clone(),
+ range: lsp::Range::new(
+ lsp::Position::new(row, start),
+ lsp::Position::new(row, end),
+ ),
+ })
+ .collect()
+ }
+
+ const SOURCE: &str = indoc! {r#"
+ fn main() {
+ let aˇbc = 123;
+ let xyz = abc;
+ }
+ "#};
+
+ #[gpui::test]
+ async fn test_multiple_references_open_picker(cx: &mut TestAppContext) {
+ let mut cx = rust_cx(
+ lsp::ServerCapabilities {
+ references_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+ cx.set_state(SOURCE);
+ cx.lsp
+ .set_request_handler::<lsp::request::References, _, _>(async move |params, _| {
+ let uri = params.text_document_position.text_document.uri;
+ Ok(Some(references(uri, &[(1, 8, 11), (2, 14, 17)])))
+ });
+
+ open(&mut cx, LspPickerKind::References);
+
+ assert!(
+ active_picker(&mut cx).is_some(),
+ "multiple references should open the picker"
+ );
+ }
+
+ #[gpui::test]
+ async fn test_single_result_jumps_without_picker(cx: &mut TestAppContext) {
+ let mut cx = rust_cx(
+ lsp::ServerCapabilities {
+ references_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+ cx.set_state(SOURCE);
+ cx.lsp
+ .set_request_handler::<lsp::request::References, _, _>(async move |params, _| {
+ let uri = params.text_document_position.text_document.uri;
+ Ok(Some(references(uri, &[(2, 14, 17)])))
+ });
+
+ open(&mut cx, LspPickerKind::References);
+
+ assert!(
+ active_picker(&mut cx).is_none(),
+ "a single result should jump directly instead of opening the picker"
+ );
+ // The lone result at row 2 should be selected directly, moving the
+ // cursor off its starting position on row 1.
+ cx.assert_editor_state(indoc! {r#"
+ fn main() {
+ let abc = 123;
+ let xyz = «abcˇ»;
+ }
+ "#});
+ }
+
+ #[gpui::test]
+ async fn test_no_results_does_not_open_picker(cx: &mut TestAppContext) {
+ let mut cx = rust_cx(
+ lsp::ServerCapabilities {
+ references_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+ cx.set_state(SOURCE);
+ cx.lsp
+ .set_request_handler::<lsp::request::References, _, _>(async move |_params, _| {
+ Ok(Some(Vec::new()))
+ });
+
+ open(&mut cx, LspPickerKind::References);
+
+ assert!(
+ active_picker(&mut cx).is_none(),
+ "an empty result should not open the picker"
+ );
+ }
+
+ #[gpui::test]
+ async fn test_definition_falls_back_to_references_picker(cx: &mut TestAppContext) {
+ let mut cx = rust_cx(
+ lsp::ServerCapabilities {
+ definition_provider: Some(lsp::OneOf::Left(true)),
+ references_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+ cx.set_state(SOURCE);
+ cx.lsp
+ .set_request_handler::<lsp::request::GotoDefinition, _, _>(async move |_params, _| {
+ Ok(None)
+ });
+ cx.lsp
+ .set_request_handler::<lsp::request::References, _, _>(async move |params, _| {
+ let uri = params.text_document_position.text_document.uri;
+ Ok(Some(references(uri, &[(1, 8, 11), (2, 14, 17)])))
+ });
+
+ open(&mut cx, LspPickerKind::Definition);
+
+ assert!(
+ active_picker(&mut cx).is_some(),
+ "an empty definition query should fall back to the references picker"
+ );
+ }
+
+ #[gpui::test]
+ async fn test_fuzzy_filter_matches_subsequence(cx: &mut TestAppContext) {
+ let mut cx = rust_cx(
+ lsp::ServerCapabilities {
+ references_provider: Some(lsp::OneOf::Left(true)),
+ ..Default::default()
+ },
+ cx,
+ )
+ .await;
+ cx.set_state(SOURCE);
+ cx.lsp
+ .set_request_handler::<lsp::request::References, _, _>(async move |params, _| {
+ let uri = params.text_document_position.text_document.uri;
+ Ok(Some(references(uri, &[(1, 8, 11), (2, 14, 17)])))
+ });
+
+ open(&mut cx, LspPickerKind::References);
+ let modal = active_picker(&mut cx).expect("multiple references should open the picker");
+ let picker = cx.update(|_window, cx| modal.read(cx).picker.clone());
+
+ let matches = |cx: &mut EditorLspTestContext, query: &str| -> usize {
+ cx.update(|window, cx| {
+ picker.update(cx, |picker, cx| picker.set_query(query, window, cx));
+ });
+ cx.run_until_parked();
+ cx.update(|_window, cx| picker.read(cx).delegate.matches.len())
+ };
+
+ // "lx" is a subsequence of "let xyz" but not a substring of either line,
+ // so it only matches with fuzzy matching.
+ assert_eq!(matches(&mut cx, "lx"), 1);
+ assert_eq!(matches(&mut cx, "zzzz"), 0);
+ assert_eq!(matches(&mut cx, ""), 2);
+ }
+}
diff --git a/crates/settings/src/vscode_import.rs b/crates/settings/src/vscode_import.rs
index 5d1a6285780..65fcb22c9bb 100644
--- a/crates/settings/src/vscode_import.rs
+++ b/crates/settings/src/vscode_import.rs
@@ -272,6 +272,7 @@ impl VsCodeSettings {
sticky_scroll: self.sticky_scroll_content(),
go_to_definition_fallback: None,
go_to_definition_scroll_strategy: None,
+ lsp_results_location: None,
gutter: self.gutter_content(),
horizontal_scroll_margin: None,
hover_popover_delay: self.read_u64("editor.hover.delay").map(Into::into),
diff --git a/crates/settings_content/src/editor.rs b/crates/settings_content/src/editor.rs
index 499fb10e3b6..14a594236a4 100644
--- a/crates/settings_content/src/editor.rs
+++ b/crates/settings_content/src/editor.rs
@@ -188,6 +188,14 @@ pub struct EditorSettingsContent {
/// Default: FindAllReferences
pub go_to_definition_fallback: Option<GoToDefinitionFallback>,
+ /// Where to show LSP results that can contain multiple locations
+ /// (Go to Definition, Go to Implementation, Find All References). A single
+ /// result always opens directly. Individual actions can override this with
+ /// their `open_results_in` argument.
+ ///
+ /// Default: multi_buffer
+ pub lsp_results_location: Option<OpenResultsIn>,
+
/// How to scroll the target into view when navigating to a definition or reference
/// (e.g. Go to Definition, Go to Type Definition, Find All References).
///
@@ -836,6 +844,30 @@ pub enum GoToDefinitionFallback {
FindAllReferences,
}
+/// Where to show LSP results that can contain multiple locations.
+#[derive(
+ Copy,
+ Clone,
+ Debug,
+ Default,
+ Serialize,
+ Deserialize,
+ PartialEq,
+ Eq,
+ JsonSchema,
+ MergeFrom,
+ strum::VariantArray,
+ strum::VariantNames,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum OpenResultsIn {
+ /// Open the results in a multibuffer.
+ #[default]
+ MultiBuffer,
+ /// Open the results in a filterable picker.
+ Picker,
+}
+
/// How to scroll the target into view when navigating to a definition or reference.
///
/// Default: center
diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rs
index ce7b51f2e90..3c1aa9708e2 100644
--- a/crates/settings_ui/src/page_data.rs
+++ b/crates/settings_ui/src/page_data.rs
@@ -10007,7 +10007,7 @@ fn language_settings_data() -> Box<[SettingsPageItem]> {
/// LanguageSettings items that should be included in the "Languages & Tools" page
/// not the "Editor" page
fn non_editor_language_settings_data() -> Box<[SettingsPageItem]> {
- fn lsp_section() -> [SettingsPageItem; 9] {
+ fn lsp_section() -> [SettingsPageItem; 10] {
[
SettingsPageItem::SectionHeader("LSP"),
SettingsPageItem::SettingItem(SettingItem {
@@ -10112,6 +10112,20 @@ fn non_editor_language_settings_data() -> Box<[SettingsPageItem]> {
metadata: None,
files: USER,
}),
+ SettingsPageItem::SettingItem(SettingItem {
+ title: "LSP Results Location",
+ description: "Where to show LSP results that can contain multiple locations (Go to Definition, Go to Implementation, Find All References).",
+ field: Box::new(SettingField {
+ organization_override: None,
+ json_path: Some("lsp_results_location"),
+ pick: |settings_content| settings_content.editor.lsp_results_location.as_ref(),
+ write: |settings_content, value, _| {
+ settings_content.editor.lsp_results_location = value;
+ },
+ }),
+ metadata: None,
+ files: USER,
+ }),
SettingsPageItem::SettingItem(SettingItem {
title: "Semantic Tokens",
description: {
diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rs
index 58e5d1f1b98..f3cf844d78e 100644
--- a/crates/settings_ui/src/settings_ui.rs
+++ b/crates/settings_ui/src/settings_ui.rs
@@ -567,6 +567,7 @@ fn init_renderers(cx: &mut App) {
.add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
.add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
.add_basic_renderer::<settings::GoToDefinitionScrollStrategy>(render_dropdown)
+ .add_basic_renderer::<settings::OpenResultsIn>(render_dropdown)
.add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
.add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
.add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.toml
index 213147207c3..f5f4a82dd8c 100644
--- a/crates/zed/Cargo.toml
+++ b/crates/zed/Cargo.toml
@@ -151,6 +151,7 @@ language_tools.workspace = true
languages = { workspace = true, features = ["load-grammars"] }
line_ending_selector.workspace = true
log.workspace = true
+lsp_locations.workspace = true
markdown.workspace = true
markdown_preview.workspace = true
menu.workspace = true
diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rs
index 1dcac5480f5..eb933cc16e6 100644
--- a/crates/zed/src/main.rs
+++ b/crates/zed/src/main.rs
@@ -748,6 +748,7 @@ fn main() {
snippets_ui::init(cx);
channel::init(&app_state.client.clone(), app_state.user_store.clone(), cx);
search::init(cx);
+ lsp_locations::init(cx);
cx.set_global(workspace::PaneSearchBarCallbacks {
setup_search_bar: |languages, toolbar, window, cx| {
let search_bar = cx.new(|cx| search::BufferSearchBar::new(languages, window, cx));
diff --git a/crates/zed/src/visual_test_runner.rs b/crates/zed/src/visual_test_runner.rs
index f7503760167..bbcd909315c 100644
--- a/crates/zed/src/visual_test_runner.rs
+++ b/crates/zed/src/visual_test_runner.rs
@@ -190,6 +190,7 @@ fn run_visual_tests(project_path: PathBuf, update_baseline: bool) -> Result<()>
terminal_view::init(cx);
image_viewer::init(cx);
search::init(cx);
+ lsp_locations::init(cx);
cx.set_global(workspace::PaneSearchBarCallbacks {
setup_search_bar: |languages, toolbar, window, cx| {
let search_bar = cx.new(|cx| search::BufferSearchBar::new(languages, window, cx));
diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rs
index 1029c82ef6c..79abe8949ee 100644
--- a/crates/zed/src/zed.rs
+++ b/crates/zed/src/zed.rs
@@ -5707,6 +5707,7 @@ mod tests {
debugger_ui::init(cx);
initialize_workspace(app_state.clone(), cx);
search::init(cx);
+ lsp_locations::init(cx);
cx.set_global(workspace::PaneSearchBarCallbacks {
setup_search_bar: |languages, toolbar, window, cx| {
let search_bar =
diff --git a/crates/zed/src/zed/app_menus.rs b/crates/zed/src/zed/app_menus.rs
index bb1f3ee7aa1..6e73536b1df 100644
--- a/crates/zed/src/zed/app_menus.rs
+++ b/crates/zed/src/zed/app_menus.rs
@@ -232,7 +232,10 @@ pub fn app_menus(cx: &mut App) -> Vec<Menu> {
),
MenuItem::action("Go to Line/Column...", editor::actions::ToggleGoToLine),
MenuItem::separator(),
- MenuItem::action("Go to Definition", editor::actions::GoToDefinition),
+ MenuItem::action(
+ "Go to Definition",
+ editor::actions::GoToDefinition::default(),
+ ),
MenuItem::action("Go to Declaration", editor::actions::GoToDeclaration),
MenuItem::action("Go to Type Definition", editor::actions::GoToTypeDefinition),
MenuItem::action(
diff --git a/crates/zed/src/zed/visual_tests.rs b/crates/zed/src/zed/visual_tests.rs
index 80e37a37989..bfe3d3b6f12 100644
--- a/crates/zed/src/zed/visual_tests.rs
+++ b/crates/zed/src/zed/visual_tests.rs
@@ -62,6 +62,7 @@ pub fn init_visual_test(cx: &mut VisualTestAppContext) -> Arc<AppState> {
terminal_view::init(cx);
image_viewer::init(cx);
search::init(cx);
+ lsp_locations::init(cx);
cx.set_global(workspace::PaneSearchBarCallbacks {
setup_search_bar: |languages, toolbar, window, cx| {
let search_bar = cx.new(|cx| search::BufferSearchBar::new(languages, window, cx));