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.

Support inlay hint edits via double clicks and `AcceptInlayHint` action (#64789)

Kirill Bulatov83b332342ff6
diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rs
index 61792abd2b2..570213c1395 100644
--- a/crates/agent_ui/src/message_editor.rs
+++ b/crates/agent_ui/src/message_editor.rs
@@ -674,6 +674,7 @@ impl MessageEditor {
padding_left: false,
padding_right: false,
tooltip: None,
+ text_edits: None,
resolve_state: project::ResolveState::Resolved,
},
))
diff --git a/crates/collab/tests/integration/editor_tests.rs b/crates/collab/tests/integration/editor_tests.rs
index b759961e545..c2e8779b153 100644
--- a/crates/collab/tests/integration/editor_tests.rs
+++ b/crates/collab/tests/integration/editor_tests.rs
@@ -17,7 +17,11 @@ use editor::{
},
};
use fs::Fs;
-use futures::{SinkExt, StreamExt, channel::mpsc, lock::Mutex};
+use futures::{
+ FutureExt as _, SinkExt, StreamExt,
+ channel::{mpsc, oneshot},
+ lock::Mutex,
+};
use git::repository::repo_path;
use gpui::{
App, AppContext as _, Entity, Rgba, SharedString, TestAppContext, UpdateGlobal, VisualContext,
@@ -41,13 +45,14 @@ use project::{
trusted_worktrees::{PathTrust, TrustedWorktrees},
};
use recent_projects::disconnected_overlay::DisconnectedOverlay;
-use rpc::RECEIVE_TIMEOUT;
+use rpc::{ProtoClient as _, RECEIVE_TIMEOUT};
use serde_json::json;
use settings::{
DocumentFoldingRanges, DocumentSymbols, InlayHintSettingsContent, InlineBlameSettings,
SemanticTokens, Settings as _, SettingsStore,
};
use std::{
+ any::TypeId,
collections::BTreeSet,
num::NonZeroU32,
ops::{Deref as _, Range},
@@ -3209,14 +3214,121 @@ async fn test_inlay_hint_refresh_is_forwarded(
});
let capabilities = lsp::ServerCapabilities {
- inlay_hint_provider: Some(lsp::OneOf::Left(true)),
+ inlay_hint_provider: Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ }),
+ )),
..lsp::ServerCapabilities::default()
};
client_a.language_registry().add(rust_lang());
+ let hint_phase = Arc::new(AtomicUsize::new(0));
+ let closure_hint_phase = Arc::clone(&hint_phase);
+ let (resolve_started_tx, resolve_started_rx) = async_channel::unbounded();
+ let (release_resolve, resolve_gate) = async_channel::bounded(1);
let mut fake_language_servers = client_a.language_registry().register_fake_lsp(
"Rust",
FakeLspAdapter {
capabilities: capabilities.clone(),
+ initializer: Some(Box::new(move |fake_language_server| {
+ let hint_phase = Arc::clone(&closure_hint_phase);
+ fake_language_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |params, _| {
+ let hint_phase = Arc::clone(&hint_phase);
+ async move {
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Uri::from_file_path(path!("/a/main.rs")).unwrap(),
+ );
+ let hint_phase = hint_phase.load(atomic::Ordering::Acquire);
+ let character = if hint_phase == 0 { 2 } else { 0 };
+ let label = match hint_phase {
+ 0 => "initial hint",
+ 1 => "other hint",
+ _ => "resolve hint",
+ };
+ Ok(Some(vec![
+ lsp::InlayHint {
+ position: lsp::Position::new(0, character),
+ label: lsp::InlayHintLabel::String(label.to_string()),
+ kind: None,
+ text_edits: (hint_phase < 2).then(|| {
+ vec![lsp::TextEdit {
+ range: lsp::Range::new(
+ lsp::Position::new(0, 0),
+ lsp::Position::new(0, 0),
+ ),
+ new_text: "pub ".to_string(),
+ }]
+ }),
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: (hint_phase == 2).then(|| json!("resolve edits")),
+ },
+ lsp::InlayHint {
+ position: lsp::Position::new(1090, 1090),
+ label: lsp::InlayHintLabel::String(
+ "out-of-bounds hint".to_string(),
+ ),
+ kind: None,
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ },
+ lsp::InlayHint {
+ position: lsp::Position::new(1091, 1091),
+ label: lsp::InlayHintLabel::String(
+ "out-of-bounds parameter hint".to_string(),
+ ),
+ kind: Some(lsp::InlayHintKind::PARAMETER),
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ },
+ ]))
+ }
+ },
+ );
+ let resolve_started_tx = resolve_started_tx.clone();
+ let resolve_gate = resolve_gate.clone();
+ fake_language_server
+ .set_request_handler::<lsp::request::InlayHintResolveRequest, _, _>(
+ move |mut hint, _| {
+ let resolve_started_tx = resolve_started_tx.clone();
+ let resolve_gate = resolve_gate.clone();
+ async move {
+ assert_eq!(hint.position, lsp::Position::new(0, 0));
+ assert_eq!(hint.data, Some(json!("resolve edits")));
+ assert_eq!(hint.text_edits, None);
+ resolve_started_tx.send(()).await.unwrap();
+ resolve_gate.recv().await.unwrap();
+ hint.text_edits = Some(vec![
+ lsp::TextEdit {
+ range: lsp::Range::new(
+ lsp::Position::new(0, 34),
+ lsp::Position::new(0, 35),
+ ),
+ new_text: "answer".to_string(),
+ },
+ lsp::TextEdit {
+ range: lsp::Range::new(
+ lsp::Position::new(0, 25),
+ lsp::Position::new(0, 25),
+ ),
+ new_text: ": &str".to_string(),
+ },
+ ]);
+ Ok(hint)
+ }
+ },
+ );
+ })),
..FakeLspAdapter::default()
},
);
@@ -3276,63 +3388,7 @@ async fn test_inlay_hint_refresh_is_forwarded(
.downcast::<Editor>()
.unwrap();
- let other_hints = Arc::new(AtomicBool::new(false));
let fake_language_server = fake_language_servers.next().await.unwrap();
- let closure_other_hints = Arc::clone(&other_hints);
- fake_language_server
- .set_request_handler::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
- let task_other_hints = Arc::clone(&closure_other_hints);
- async move {
- assert_eq!(
- params.text_document.uri,
- lsp::Uri::from_file_path(path!("/a/main.rs")).unwrap(),
- );
- let other_hints = task_other_hints.load(atomic::Ordering::Acquire);
- let character = if other_hints { 0 } else { 2 };
- let label = if other_hints {
- "other hint"
- } else {
- "initial hint"
- };
- Ok(Some(vec![
- lsp::InlayHint {
- position: lsp::Position::new(0, character),
- label: lsp::InlayHintLabel::String(label.to_string()),
- kind: None,
- text_edits: None,
- tooltip: None,
- padding_left: None,
- padding_right: None,
- data: None,
- },
- lsp::InlayHint {
- position: lsp::Position::new(1090, 1090),
- label: lsp::InlayHintLabel::String("out-of-bounds hint".to_string()),
- kind: None,
- text_edits: None,
- tooltip: None,
- padding_left: None,
- padding_right: None,
- data: None,
- },
- lsp::InlayHint {
- position: lsp::Position::new(1091, 1091),
- label: lsp::InlayHintLabel::String(
- "out-of-bounds parameter hint".to_string(),
- ),
- kind: Some(lsp::InlayHintKind::PARAMETER),
- text_edits: None,
- tooltip: None,
- padding_left: None,
- padding_right: None,
- data: None,
- },
- ]))
- }
- })
- .next()
- .await
- .unwrap();
executor.run_until_parked();
editor_a.update(cx_a, |editor, cx| {
@@ -3351,7 +3407,7 @@ async fn test_inlay_hint_refresh_is_forwarded(
);
});
- other_hints.fetch_or(true, atomic::Ordering::Release);
+ hint_phase.store(1, atomic::Ordering::Release);
fake_language_server
.request::<lsp::request::InlayHintRefreshRequest>((), DEFAULT_LSP_REQUEST_TIMEOUT)
.await
@@ -3373,6 +3429,142 @@ async fn test_inlay_hint_refresh_is_forwarded(
"Guest should get a /refresh LSP request propagated by host despite host hints are off"
);
});
+
+ cx_b.focus(&editor_b);
+ editor_b.update_in(cx_b, |editor, window, cx| {
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([Point::new(0, 0)..Point::new(0, 0)]);
+ });
+ });
+ cx_b.dispatch_action(editor::actions::AcceptInlayHint);
+
+ let expected_text =
+ "pub fn main() { a } // and some long comment to ensure inlay hints are not trimmed out";
+ assert_eq!(
+ editor_b.read_with(cx_b, |editor, cx| editor.text(cx)),
+ expected_text,
+ );
+ assert_eq!(
+ editor_a.read_with(cx_a, |editor, cx| editor.text(cx)),
+ expected_text,
+ );
+
+ let buffer_a = editor_a.read_with(cx_a, |editor, cx| {
+ editor.buffer().read(cx).as_singleton().unwrap()
+ });
+ let buffer_b = editor_b.read_with(cx_b, |editor, cx| {
+ editor.buffer().read(cx).as_singleton().unwrap()
+ });
+ let resolve_text = "pub fn main() { let value = \"😀\"; a }\n";
+ hint_phase.store(2, atomic::Ordering::Release);
+ buffer_a.update(cx_a, |buffer, cx| {
+ buffer.edit([(0..buffer.len(), resolve_text)], None, cx);
+ });
+ executor.run_until_parked();
+ editor_b.update_in(cx_b, |editor, window, cx| {
+ assert_eq!(extract_hint_labels(editor, cx), vec!["resolve hint"]);
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([Point::new(0, 0)..Point::new(0, 0)]);
+ });
+ });
+ let resolve_version = buffer_b.read_with(cx_b, |buffer, _| buffer.version());
+ assert_eq!(
+ buffer_a.read_with(cx_a, |buffer, _| buffer.version()),
+ resolve_version,
+ );
+ cx_b.dispatch_action(editor::actions::AcceptInlayHint);
+ resolve_started_rx.recv().await.unwrap();
+
+ let (release_updates, update_gate) = oneshot::channel();
+ let update_gate = update_gate.shared();
+ let update_message_type = TypeId::of::<rpc::proto::UpdateBuffer>();
+ let update_handler = {
+ let mut handlers = client_b.client().message_handler_set().lock();
+ let update_handler = handlers
+ .message_handlers
+ .remove(&update_message_type)
+ .unwrap();
+ handlers.message_handlers.insert(
+ update_message_type,
+ Arc::new({
+ let update_handler = update_handler.clone();
+ move |entity, message, client, cx| {
+ let update_handler = update_handler.clone();
+ let update_gate = update_gate.clone();
+ async move {
+ update_gate.await.unwrap();
+ update_handler(entity, message, client, cx).await
+ }
+ .boxed_local()
+ }
+ }),
+ );
+ update_handler
+ };
+ buffer_a.update(cx_a, |buffer, cx| {
+ buffer.edit([(buffer.len()..buffer.len(), "\n")], None, cx);
+ });
+ let response_version = buffer_a.read_with(cx_a, |buffer, _| buffer.version());
+ assert!(response_version.changed_since(&resolve_version));
+ release_resolve.send(()).await.unwrap();
+ executor.run_until_parked();
+ assert_eq!(
+ buffer_b.read_with(cx_b, |buffer, _| buffer.version()),
+ resolve_version,
+ );
+ assert_eq!(
+ editor_b.read_with(cx_b, |editor, cx| editor.text(cx)),
+ resolve_text,
+ );
+ let lsp_store_b = project_b.read_with(cx_b, |project, _| project.lsp_store());
+ lsp_store_b.update(cx_b, |lsp_store, cx| {
+ let hints = lsp_store
+ .latest_lsp_data(&buffer_b, cx)
+ .inlay_hints()
+ .all_cached_hints();
+ assert_eq!(
+ hints
+ .iter()
+ .map(|hint| &hint.resolve_state)
+ .collect::<Vec<_>>(),
+ vec![&project::ResolveState::Resolving],
+ );
+ });
+
+ client_b
+ .client()
+ .message_handler_set()
+ .lock()
+ .message_handlers
+ .insert(update_message_type, update_handler);
+ release_updates.send(()).unwrap();
+ executor.run_until_parked();
+ assert_eq!(
+ buffer_b.read_with(cx_b, |buffer, _| buffer.version()),
+ response_version,
+ );
+ let updated_text = "pub fn main() { let value = \"😀\"; a }\n\n";
+ assert_eq!(
+ editor_b.read_with(cx_b, |editor, cx| editor.text(cx)),
+ updated_text,
+ );
+ assert_eq!(
+ editor_a.read_with(cx_a, |editor, cx| editor.text(cx)),
+ updated_text,
+ );
+
+ release_resolve.send(()).await.unwrap();
+ cx_b.dispatch_action(editor::actions::AcceptInlayHint);
+ resolve_started_rx.recv().await.unwrap();
+ let expected_text = "pub fn main() { let value: &str = \"😀\"; answer }\n\n";
+ assert_eq!(
+ editor_b.read_with(cx_b, |editor, cx| editor.text(cx)),
+ expected_text,
+ );
+ assert_eq!(
+ editor_a.read_with(cx_a, |editor, cx| editor.text(cx)),
+ expected_text,
+ );
}
#[gpui::test(iterations = 10)]
diff --git a/crates/edit_prediction_ui/src/rate_prediction_modal.rs b/crates/edit_prediction_ui/src/rate_prediction_modal.rs
index 23607042c7b..2f4be716893 100644
--- a/crates/edit_prediction_ui/src/rate_prediction_modal.rs
+++ b/crates/edit_prediction_ui/src/rate_prediction_modal.rs
@@ -367,6 +367,7 @@ impl RatePredictionsModal {
padding_left: false,
padding_right: false,
tooltip: None,
+ text_edits: None,
resolve_state: ResolveState::Resolved,
},
),
@@ -380,6 +381,7 @@ impl RatePredictionsModal {
padding_left: false,
padding_right: false,
tooltip: None,
+ text_edits: None,
resolve_state: ResolveState::Resolved,
},
),
diff --git a/crates/editor/src/actions.rs b/crates/editor/src/actions.rs
index 4a0492af4b8..635f74ddaf2 100644
--- a/crates/editor/src/actions.rs
+++ b/crates/editor/src/actions.rs
@@ -427,6 +427,8 @@ actions!(
[
/// Accepts the full edit prediction.
AcceptEditPrediction,
+ /// Amends the editor text with hint's edit (if sent).
+ AcceptInlayHint,
/// Accepts a partial edit prediction.
#[action(deprecated_aliases = ["editor::AcceptPartialCopilotSuggestion"])]
AcceptNextWordEditPrediction,
diff --git a/crates/editor/src/config.rs b/crates/editor/src/config.rs
index 3e854935d3f..d8ec82ef429 100644
--- a/crates/editor/src/config.rs
+++ b/crates/editor/src/config.rs
@@ -43,7 +43,9 @@ impl Editor {
.filter(|_| self.is_empty(cx))
.unwrap_or(&self.display_map);
- display_map.update(cx, |map, cx| map.set_font(font, font_size, cx));
+ if display_map.update(cx, |map, cx| map.set_font(font, font_size, cx)) {
+ self.inlay_hint_visibility_changed(cx);
+ }
}
self.style = Some(style);
}
@@ -277,9 +279,9 @@ impl Editor {
// Called by the element. This method is not designed to be called outside of the editor
// element's layout code because it does not notify when rewrapping is computed synchronously.
- pub(super) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
+ pub(super) fn set_wrap_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>) -> bool {
let indent = self.soft_wrap_indent(cx);
- if self.is_empty(cx) {
+ let changed = if self.is_empty(cx) {
self.placeholder_display_map
.as_ref()
.map_or(false, |display_map| {
@@ -295,7 +297,11 @@ impl Editor {
let indent_changed = map.set_soft_wrap_indent(indent, cx);
wrap_width_changed || indent_changed
})
+ };
+ if changed {
+ self.inlay_hint_visibility_changed(cx);
}
+ changed
}
pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
diff --git a/crates/editor/src/display_map.rs b/crates/editor/src/display_map.rs
index b7cf32b60e5..b8c77c4af3e 100644
--- a/crates/editor/src/display_map.rs
+++ b/crates/editor/src/display_map.rs
@@ -128,6 +128,7 @@ use std::{
iter,
num::NonZeroU32,
ops::{self, Add, Range, RangeInclusive, Sub},
+ slice,
sync::Arc,
};
@@ -1285,7 +1286,7 @@ impl DisplayMap {
widths_changed
}
- pub(crate) fn current_inlays(&self) -> impl Iterator<Item = &Inlay> + Default {
+ pub(crate) fn current_inlays(&self) -> slice::Iter<'_, Inlay> {
self.inlay_map.current_inlays()
}
@@ -1524,6 +1525,66 @@ impl DisplaySnapshot {
self.companion_display_snapshot.as_deref()
}
+ pub fn inlay_hint_at(&self, point: DisplayPoint) -> Option<(&Inlay, usize)> {
+ if point.row() > self.max_point().row()
+ || self.is_block_line(point.row())
+ || point.column() >= self.line_len(point.row())
+ {
+ return None;
+ }
+ let wrap_row = self
+ .block_snapshot
+ .to_wrap_point(BlockPoint::new(BlockRow(point.row().0), 0), Bias::Left)
+ .row();
+ let wrap_indent = wrap_row
+ .0
+ .checked_sub(1)
+ .and_then(|previous_row| self.wrap_snapshot().soft_wrap_indent(WrapRow(previous_row)));
+ if wrap_indent.is_some_and(|indent| point.column() < indent) {
+ return None;
+ }
+ let fold_point = self.display_point_to_fold_point(point, Bias::Left);
+ if self
+ .fold_snapshot()
+ .placeholder_range_at(fold_point)
+ .is_some()
+ {
+ return None;
+ }
+ let inlay_offset = self
+ .inlay_snapshot()
+ .to_offset(fold_point.to_inlay_point(self.fold_snapshot()));
+ if self.fold_snapshot().is_inlay_offset_folded(inlay_offset) {
+ return None;
+ }
+ self.inlay_snapshot().inlay_hint_at_offset(inlay_offset)
+ }
+
+ pub fn is_inlay_visible(&self, inlay_id: InlayId, position: Anchor) -> bool {
+ if !position.is_valid(self.buffer_snapshot()) {
+ return false;
+ }
+ let Some(rendered_range) = self.inlay_snapshot().inlay_offset_range(inlay_id, position)
+ else {
+ return false;
+ };
+ let start = self.inlay_offset_to_display_point(rendered_range.start, Bias::Right);
+ let end = self.inlay_offset_to_display_point(rendered_range.end, Bias::Left);
+ (start.row().0..=end.row().0).any(|row| {
+ let row = DisplayRow(row);
+ if self.is_block_line(row) {
+ return false;
+ }
+ let point = if row == start.row() {
+ start
+ } else {
+ DisplayPoint::new(row, 0)
+ };
+ let offset = self.display_point_to_inlay_offset(point, Bias::Left);
+ rendered_range.contains(&offset) && !self.fold_snapshot().is_inlay_offset_folded(offset)
+ })
+ }
+
fn diagnostic_severity_is_visible(&self, severity: lsp::DiagnosticSeverity) -> bool {
self.diagnostics_max_severity
.into_lsp()
@@ -2503,6 +2564,12 @@ impl DisplaySnapshot {
let rows = start_row..=end_row;
rows.contains(&row).then_some(rows)
}
+
+ fn inlay_offset_to_display_point(&self, offset: InlayOffset, bias: Bias) -> DisplayPoint {
+ let inlay_point = self.inlay_snapshot().to_point(offset);
+ let fold_point = self.fold_snapshot().to_fold_point(inlay_point, bias);
+ self.fold_point_to_display_point(fold_point)
+ }
}
fn diagnostic_style(severity: lsp::DiagnosticSeverity, colors: &StatusColors) -> Hsla {
@@ -3200,6 +3267,310 @@ pub mod tests {
);
}
+ #[gpui::test]
+ fn test_inlay_hint_at(cx: &mut App) {
+ init_test(cx, &|_| {});
+ for tab_size in [1, 4, 16] {
+ cx.update_global::<SettingsStore, _>(|store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.tab_size = NonZeroU32::new(tab_size);
+ });
+ });
+ let buffer = MultiBuffer::build_simple("ab\ncd", cx);
+ let buffer_snapshot = buffer.read(cx).snapshot(cx);
+ let position = buffer_snapshot.anchor_after(MultiBufferOffset(1));
+ let end_position = buffer_snapshot.anchor_after(buffer_snapshot.len());
+ let map = inlay_test_map(buffer.clone(), test_font(), px(14.0), None, cx);
+ let snapshot = map.update(cx, |map, cx| {
+ map.splice_inlays(
+ &[],
+ vec![
+ Inlay::mock_hint(0, position, " é界🙂 "),
+ Inlay::mock_hint(1, position, "λ"),
+ Inlay::edit_prediction(0, position, "P"),
+ Inlay::mock_hint(2, end_position, "z"),
+ ],
+ cx,
+ );
+ map.snapshot(cx)
+ });
+ assert_eq!(snapshot.text(), "a é界🙂 λPb\ncdz");
+ for (row, column, expected) in [
+ (0, 0, None),
+ (0, 1, Some((InlayId::Hint(0), 0))),
+ (0, 2, Some((InlayId::Hint(0), 1))),
+ (0, 4, Some((InlayId::Hint(0), 3))),
+ (0, 7, Some((InlayId::Hint(0), 6))),
+ (0, 11, Some((InlayId::Hint(0), 10))),
+ (0, 12, Some((InlayId::Hint(1), 0))),
+ (0, 14, None),
+ (0, 15, None),
+ (0, 16, None),
+ (1, 0, None),
+ (1, 1, None),
+ (1, 2, Some((InlayId::Hint(2), 0))),
+ (1, 3, None),
+ ] {
+ let point = DisplayPoint::new(DisplayRow(row), column);
+ assert_eq!(
+ snapshot
+ .inlay_hint_at(point)
+ .map(|(hint, offset)| (hint.id, offset)),
+ expected,
+ "point {point:?}"
+ );
+ }
+
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(Point::new(1, 0)..Point::new(1, 2), "\t")], None, cx);
+ });
+ let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
+ let expected_line = " ".repeat(tab_size as usize) + "z";
+ assert_eq!(snapshot.line(DisplayRow(1)), expected_line);
+ for column in 0..=tab_size + 1 {
+ let point = DisplayPoint::new(DisplayRow(1), column);
+ assert_eq!(
+ snapshot
+ .inlay_hint_at(point)
+ .map(|(hint, offset)| (hint.id, offset)),
+ (column == tab_size).then_some((InlayId::Hint(2), 0)),
+ "tab size {tab_size}, point {point:?}"
+ );
+ }
+ }
+ }
+
+ #[gpui::test]
+ fn test_inlay_hint_at_soft_wrap_indent(cx: &mut App) {
+ init_test(cx, &|_| {});
+ let buffer = MultiBuffer::build_simple(" ab", cx);
+ let buffer_snapshot = buffer.read(cx).snapshot(cx);
+ let position = buffer_snapshot.anchor_after(MultiBufferOffset(3));
+ let map = inlay_test_map(buffer, font("Courier"), px(16.0), Some(px(40.0)), cx);
+ let snapshot = map.update(cx, |map, cx| {
+ map.splice_inlays(&[], vec![Inlay::mock_hint(0, position, "wxyz")], cx);
+ map.snapshot(cx)
+ });
+ assert_eq!(snapshot.text(), " aw\n xy\n zb");
+ for (row, column, expected) in [
+ (0, 2, None),
+ (0, 3, Some(0)),
+ (0, 4, None),
+ (1, 0, None),
+ (1, 1, None),
+ (1, 2, Some(1)),
+ (1, 3, Some(2)),
+ (1, 4, None),
+ (2, 0, None),
+ (2, 1, None),
+ (2, 2, Some(3)),
+ (2, 3, None),
+ (2, 4, None),
+ ] {
+ let point = DisplayPoint::new(DisplayRow(row), column);
+ assert_eq!(
+ snapshot.inlay_hint_at(point).map(|(_, offset)| offset),
+ expected,
+ "point {point:?}"
+ );
+ }
+ }
+
+ #[gpui::test]
+ fn test_inlay_hint_at_fold_placeholder(cx: &mut App) {
+ init_test(cx, &|_| {});
+ for (text, fold_range, hints, expected_text, visible_hint) in [
+ (
+ "ab\ncd\nef",
+ MultiBufferPoint::new(0, 1)..MultiBufferPoint::new(2, 1),
+ vec![(1, "X"), (8, "Y")],
+ "a⋯fY",
+ (5, InlayId::Hint(1)),
+ ),
+ (
+ "ab",
+ MultiBufferPoint::new(0, 0)..MultiBufferPoint::new(0, 1),
+ vec![(1, "H")],
+ "⋯Hb",
+ (3, InlayId::Hint(0)),
+ ),
+ ] {
+ let buffer = MultiBuffer::build_simple(text, cx);
+ let buffer_snapshot = buffer.read(cx).snapshot(cx);
+ let map = inlay_test_map(buffer, test_font(), px(14.0), None, cx);
+ let snapshot = map.update(cx, |map, cx| {
+ map.splice_inlays(
+ &[],
+ hints
+ .into_iter()
+ .enumerate()
+ .map(|(id, (offset, text))| {
+ Inlay::mock_hint(
+ id,
+ buffer_snapshot.anchor_after(MultiBufferOffset(offset)),
+ text,
+ )
+ })
+ .collect(),
+ cx,
+ );
+ map.fold(
+ vec![Crease::simple(fold_range, FoldPlaceholder::test())],
+ cx,
+ );
+ map.snapshot(cx)
+ });
+ assert_eq!(snapshot.text(), expected_text);
+ for column in 0..=expected_text.len() as u32 {
+ let point = DisplayPoint::new(DisplayRow(0), column);
+ let expected = (column == visible_hint.0).then_some((visible_hint.1, 0));
+ assert_eq!(
+ snapshot
+ .inlay_hint_at(point)
+ .map(|(hint, offset)| (hint.id, offset)),
+ expected,
+ "point {point:?} in {expected_text:?}"
+ );
+ }
+ }
+ }
+
+ #[gpui::test]
+ fn test_is_inlay_visible(cx: &mut App) {
+ init_test(cx, &|_| {});
+ let buffer = MultiBuffer::build_simple("abcd\nef\nz", cx);
+ let buffer_snapshot = buffer.read(cx).snapshot(cx);
+ let hint = Inlay::mock_hint(0, buffer_snapshot.anchor_after(MultiBufferOffset(2)), "X");
+ let newline =
+ Inlay::edit_prediction(1, buffer_snapshot.anchor_after(MultiBufferOffset(1)), "\n");
+ let map = inlay_test_map(buffer, test_font(), px(14.0), None, cx);
+ let snapshot = map.update(cx, |map, cx| {
+ map.splice_inlays(&[], vec![hint.clone(), newline], cx);
+ map.snapshot(cx)
+ });
+ assert_eq!(snapshot.text(), "a\nbXcd\nef\nz");
+ assert!(snapshot.is_inlay_visible(hint.id, hint.position));
+
+ let snapshot = map.update(cx, |map, cx| {
+ map.fold(
+ vec![Crease::simple(
+ MultiBufferPoint::new(0, 3)..MultiBufferPoint::new(1, 1),
+ FoldPlaceholder::test(),
+ )],
+ cx,
+ );
+ map.snapshot(cx)
+ });
+ assert_eq!(snapshot.text(), "a\nbXc⋯f\nz");
+ assert!(snapshot.is_inlay_visible(hint.id, hint.position));
+
+ let snapshot = map.update(cx, |map, cx| {
+ map.insert_blocks(
+ [BlockProperties {
+ placement: BlockPlacement::Replace(
+ buffer_snapshot.anchor_before(Point::new(1, 0))
+ ..=buffer_snapshot.anchor_after(Point::new(1, 2)),
+ ),
+ height: Some(1),
+ style: BlockStyle::Fixed,
+ render: Arc::new(|_| div().into_any()),
+ priority: 0,
+ }],
+ cx,
+ );
+ map.snapshot(cx)
+ });
+ assert_eq!(snapshot.text(), "a\n\nz");
+ assert!(!snapshot.is_inlay_visible(hint.id, hint.position));
+
+ for (hint_text, wrap_width, end_bias, expected_text) in [
+ ("X\nY", None, Bias::Right, "\nY\ncd"),
+ ("WXYZ", Some(px(40.0)), Bias::Left, "\nYZ\ncd"),
+ ] {
+ let buffer = MultiBuffer::build_simple("ab\ncd", cx);
+ let buffer_snapshot = buffer.read(cx).snapshot(cx);
+ let hint = Inlay::mock_hint(
+ 0,
+ buffer_snapshot.anchor_after(MultiBufferOffset(2)),
+ hint_text,
+ );
+ let map = inlay_test_map(buffer, font("Courier"), px(16.0), wrap_width, cx);
+ let snapshot = map.update(cx, |map, cx| {
+ map.splice_inlays(&[], vec![hint.clone()], cx);
+ map.insert_blocks(
+ [BlockProperties {
+ placement: BlockPlacement::Replace(
+ buffer_snapshot.anchor_before(Point::new(0, 0))
+ ..=buffer_snapshot.anchor_at(Point::new(0, 2), end_bias),
+ ),
+ height: Some(1),
+ style: BlockStyle::Fixed,
+ render: Arc::new(|_| div().into_any()),
+ priority: 0,
+ }],
+ cx,
+ );
+ map.snapshot(cx)
+ });
+ assert_eq!(snapshot.text(), expected_text);
+ assert!(snapshot.is_inlay_visible(hint.id, hint.position));
+ assert_eq!(
+ snapshot
+ .inlay_hint_at(DisplayPoint::new(DisplayRow(1), 0))
+ .map(|(hint, offset)| (hint.id, offset)),
+ Some((InlayId::Hint(0), 2))
+ );
+ }
+ }
+
+ #[gpui::test]
+ fn test_inlay_hint_at_after_replace_block(cx: &mut App) {
+ init_test(cx, &|_| {});
+ let buffer = MultiBuffer::build_simple(" abcd\nz", cx);
+ let buffer_snapshot = buffer.read(cx).snapshot(cx);
+ let map = inlay_test_map(buffer, font("Courier"), px(16.0), Some(px(40.0)), cx);
+ let snapshot = map.update(cx, |map, cx| {
+ map.splice_inlays(
+ &[],
+ vec![Inlay::mock_hint(
+ 0,
+ buffer_snapshot.anchor_before(Point::new(1, 0)),
+ "XY",
+ )],
+ cx,
+ );
+ map.insert_blocks(
+ [BlockProperties {
+ placement: BlockPlacement::Replace(
+ buffer_snapshot.anchor_before(Point::new(0, 0))
+ ..=buffer_snapshot.anchor_after(Point::new(0, 6)),
+ ),
+ height: Some(1),
+ style: BlockStyle::Fixed,
+ render: Arc::new(|_| div().into_any()),
+ priority: 0,
+ }],
+ cx,
+ );
+ map.snapshot(cx)
+ });
+ assert_eq!(snapshot.text(), "\nXYz");
+ for (row, column, expected) in [
+ (0, 0, None),
+ (1, 0, Some(0)),
+ (1, 1, Some(1)),
+ (1, 2, None),
+ (1, 3, None),
+ ] {
+ let point = DisplayPoint::new(DisplayRow(row), column);
+ assert_eq!(
+ snapshot.inlay_hint_at(point).map(|(_, offset)| offset),
+ expected,
+ "point {point:?}"
+ );
+ }
+ }
+
#[gpui::test]
fn test_inlays_with_newlines_after_blocks(cx: &mut gpui::TestAppContext) {
cx.update(|cx| init_test(cx, &|_| {}));
@@ -4581,4 +4952,26 @@ pub mod tests {
let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
assert_eq!(snapshot.text(), "prefix more initial");
}
+
+ fn inlay_test_map(
+ buffer: Entity<MultiBuffer>,
+ font: Font,
+ font_size: Pixels,
+ wrap_width: Option<Pixels>,
+ cx: &mut App,
+ ) -> Entity<DisplayMap> {
+ cx.new(|cx| {
+ DisplayMap::new(
+ buffer,
+ font,
+ font_size,
+ wrap_width,
+ 1,
+ 1,
+ FoldPlaceholder::test(),
+ DiagnosticSeverity::Warning,
+ cx,
+ )
+ })
+ }
}
diff --git a/crates/editor/src/display_map/fold_map.rs b/crates/editor/src/display_map/fold_map.rs
index ce99a61623b..32a810d650e 100644
--- a/crates/editor/src/display_map/fold_map.rs
+++ b/crates/editor/src/display_map/fold_map.rs
@@ -768,6 +768,13 @@ impl FoldSnapshot {
&self.inlay_snapshot.buffer
}
+ pub(super) fn is_inlay_offset_folded(&self, offset: InlayOffset) -> bool {
+ let (_, _, item) = self
+ .transforms
+ .find::<InlayOffset, _>((), &offset, Bias::Right);
+ item.is_some_and(|transform| transform.placeholder.is_some())
+ }
+
#[ztracing::instrument(skip_all)]
fn fold_width(&self, fold_id: &FoldId) -> Option<Pixels> {
self.fold_metadata_by_id.get(fold_id)?.width
@@ -948,10 +955,7 @@ impl FoldSnapshot {
{
let buffer_offset = offset.to_offset(&self.inlay_snapshot.buffer);
let inlay_offset = self.inlay_snapshot.to_inlay_offset(buffer_offset);
- let (_, _, item) = self
- .transforms
- .find::<InlayOffset, _>((), &inlay_offset, Bias::Right);
- item.is_some_and(|t| t.placeholder.is_some())
+ self.is_inlay_offset_folded(inlay_offset)
}
#[ztracing::instrument(skip_all)]
diff --git a/crates/editor/src/display_map/inlay_map.rs b/crates/editor/src/display_map/inlay_map.rs
index 8528188cc7b..39b941fc12f 100644
--- a/crates/editor/src/display_map/inlay_map.rs
+++ b/crates/editor/src/display_map/inlay_map.rs
@@ -12,7 +12,7 @@ use crate::{
use collections::BTreeSet;
use language::{Chunk, Edit, LanguageAwareStyling, Point, TextSummary};
use multi_buffer::{
- MBTextSummary, MultiBufferOffset, MultiBufferRow, MultiBufferRows, MultiBufferSnapshot,
+ Anchor, MBTextSummary, MultiBufferOffset, MultiBufferRow, MultiBufferRows, MultiBufferSnapshot,
RowInfo, ToOffset,
};
use project::InlayId;
@@ -20,6 +20,7 @@ use smallvec::SmallVec;
use std::{
cmp, iter,
ops::{Add, AddAssign, Range, Sub, SubAssign},
+ slice,
sync::Arc,
};
use sum_tree::{Bias, Cursor, Dimensions, SumTree};
@@ -778,7 +779,7 @@ impl InlayMap {
}
#[ztracing::instrument(skip_all)]
- pub fn current_inlays(&self) -> impl Iterator<Item = &Inlay> + Default {
+ pub fn current_inlays(&self) -> slice::Iter<'_, Inlay> {
self.inlays.iter()
}
@@ -1294,6 +1295,42 @@ impl InlaySnapshot {
.collect()
}
+ pub(super) fn inlay_offset_range(
+ &self,
+ inlay_id: InlayId,
+ position: Anchor,
+ ) -> Option<Range<InlayOffset>> {
+ let buffer_offset = position.to_offset(&self.buffer);
+ let mut cursor = self
+ .transforms
+ .cursor::<Dimensions<MultiBufferOffset, InlayOffset>>(());
+ cursor.seek(&buffer_offset, Bias::Left);
+ while let Some(transform) = cursor.item() {
+ if cursor.start().0 > buffer_offset {
+ break;
+ }
+ if let Transform::Inlay(inlay) = transform
+ && inlay.id == inlay_id
+ {
+ return Some(cursor.start().1..cursor.end().1);
+ }
+ cursor.next();
+ }
+ None
+ }
+
+ pub(super) fn inlay_hint_at_offset(&self, offset: InlayOffset) -> Option<(&Inlay, usize)> {
+ let (start, _, transform) =
+ self.transforms
+ .find::<InlayOffset, _>((), &offset, Bias::Right);
+ match transform {
+ Some(Transform::Inlay(inlay)) if matches!(inlay.id, InlayId::Hint(_)) => {
+ Some((inlay, offset - start))
+ }
+ _ => None,
+ }
+ }
+
#[ztracing::instrument(skip_all)]
fn check_invariants(&self) {
#[cfg(any(debug_assertions, feature = "test-support"))]
@@ -1479,6 +1516,7 @@ mod tests {
Anchor::Min,
&InlayHint {
label: InlayHintLabel::String("a".to_string()),
+ text_edits: None,
position: text::Anchor::min_for_buffer(BufferId::new(1).unwrap()),
padding_left: false,
padding_right: false,
@@ -1499,6 +1537,7 @@ mod tests {
Anchor::Min,
&InlayHint {
label: InlayHintLabel::String("a".to_string()),
+ text_edits: None,
position: text::Anchor::min_for_buffer(BufferId::new(1).unwrap()),
padding_left: true,
padding_right: true,
@@ -1519,6 +1558,7 @@ mod tests {
Anchor::Min,
&InlayHint {
label: InlayHintLabel::String(" a ".to_string()),
+ text_edits: None,
position: text::Anchor::min_for_buffer(BufferId::new(1).unwrap()),
padding_left: false,
padding_right: false,
@@ -1539,6 +1579,7 @@ mod tests {
Anchor::Min,
&InlayHint {
label: InlayHintLabel::String(" a ".to_string()),
+ text_edits: None,
position: text::Anchor::min_for_buffer(BufferId::new(1).unwrap()),
padding_left: true,
padding_right: true,
@@ -1562,6 +1603,7 @@ mod tests {
Anchor::Min,
&InlayHint {
label: InlayHintLabel::String("🎨".to_string()),
+ text_edits: None,
position: text::Anchor::min_for_buffer(BufferId::new(1).unwrap()),
padding_left: true,
padding_right: true,
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index bff66cb0f8b..6051d7f4848 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -4164,6 +4164,7 @@ impl Editor {
self.update_hovered_link(
position_map.point_for_position(mouse_position),
+ position_map.inlay_hint_glyph_for_position(mouse_position),
Some(mouse_position),
&position_map.snapshot,
modifiers,
@@ -8836,6 +8837,7 @@ impl Editor {
let blocks = self
.display_map
.update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
+ self.inlay_hint_visibility_changed(cx);
if let Some(autoscroll) = autoscroll {
self.request_autoscroll(autoscroll, cx);
}
@@ -8880,6 +8882,7 @@ impl Editor {
self.display_map.update(cx, |display_map, cx| {
display_map.remove_blocks(block_ids, cx)
});
+ self.inlay_hint_visibility_changed(cx);
if let Some(autoscroll) = autoscroll {
self.request_autoscroll(autoscroll, cx);
}
@@ -10090,6 +10093,7 @@ impl Editor {
self.detect_buffer_language(buffer_id, cx);
}
+ self.inlay_hint_visibility_changed(cx);
cx.emit(EditorEvent::BufferEdited);
cx.emit(SearchEvent::MatchesInvalidated);
@@ -10121,6 +10125,7 @@ impl Editor {
self.register_visible_buffers(cx);
self.update_lsp_data(Some(buffer_id), window, cx);
self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
+ self.inlay_hint_visibility_changed(cx);
self.refresh_runnables(None, window, cx);
self.bracket_fetched_tree_sitter_chunks
.retain(|range, _| range.start.buffer_id != buffer_id);
@@ -10156,6 +10161,7 @@ impl Editor {
self.display_map.update(cx, |display_map, cx| {
display_map.unfold_buffers(removed_buffer_ids.iter().copied(), cx);
});
+ self.inlay_hint_visibility_changed(cx);
jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
cx.emit(EditorEvent::BuffersRemoved {
@@ -10166,6 +10172,7 @@ impl Editor {
self.display_map.update(cx, |map, cx| {
map.unfold_buffers(buffer_ids.iter().copied(), cx)
});
+ self.inlay_hint_visibility_changed(cx);
cx.emit(EditorEvent::BuffersEdited {
buffer_ids: buffer_ids.clone(),
});
@@ -10235,6 +10242,7 @@ impl Editor {
_: &mut Window,
cx: &mut Context<Self>,
) {
+ self.inlay_hint_visibility_changed(cx);
cx.notify();
}
diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs
index 56663881ff0..77aa1dbe9fe 100644
--- a/crates/editor/src/element.rs
+++ b/crates/editor/src/element.rs
@@ -607,6 +607,9 @@ impl EditorElement {
register_action(editor, window, Editor::toggle_edit_predictions);
if editor.read(cx).lsp_data_enabled() {
register_action(editor, window, Editor::toggle_inlay_hints);
+ if editor.read(cx).can_accept_inlay_hint(cx) {
+ register_action(editor, window, Editor::accept_inlay_hint);
+ }
register_action(editor, window, Editor::toggle_code_lens_action);
register_action(editor, window, Editor::toggle_semantic_highlights);
register_action(editor, window, Editor::toggle_diagnostics);
@@ -5867,11 +5870,11 @@ impl EditorElement {
);
} else if !window.modifiers().modified()
&& let Some(hovered_command) = editor.hovered_inlay_hint_command()
- && hovered_command.contains_point(
+ && hovered_command.contains_glyph(
&layout.position_map.snapshot,
layout
.position_map
- .point_for_position(window.mouse_position()),
+ .inlay_hint_glyph_for_position(window.mouse_position()),
)
{
window.set_cursor_style(
@@ -9949,6 +9952,7 @@ impl Element for EditorElement {
snapshot,
text_align: self.style.text.text_align,
content_width: text_hitbox.size.width,
+ content_origin,
gutter_hitbox: gutter_hitbox.clone(),
text_hitbox: text_hitbox.clone(),
inline_blame_bounds: inline_blame_layout
@@ -10711,6 +10715,7 @@ pub(crate) struct PositionMap {
pub snapshot: EditorSnapshot,
pub text_align: TextAlign,
pub content_width: Pixels,
+ pub content_origin: gpui::Point<Pixels>,
pub text_hitbox: Hitbox,
pub gutter_hitbox: Hitbox,
pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
@@ -10765,6 +10770,26 @@ impl PointForPosition {
}
impl PositionMap {
+ pub(crate) fn inlay_hint_glyph_for_position(
+ &self,
+ position: gpui::Point<Pixels>,
+ ) -> Option<DisplayPoint> {
+ let position = position - self.content_origin;
+ if position.y < Pixels::ZERO {
+ return None;
+ }
+ let row = ((position.y / self.line_height) as f64 + self.scroll_position.y) as u32;
+ let line_index = row.checked_sub(self.visible_row_range.start.0)?;
+ let line = self.line_layouts.get(line_index as usize)?;
+ let x = position.x + (self.scroll_position.x as f32 * self.em_layout_width)
+ - line.alignment_offset(self.text_align, self.content_width);
+ if x < Pixels::ZERO {
+ return None;
+ }
+ let glyph = DisplayPoint::new(DisplayRow(row), line.index_for_x(x)? as u32);
+ self.snapshot.inlay_hint_at(glyph).map(|_| glyph)
+ }
+
pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
let text_bounds = self.text_hitbox.bounds;
let scroll_position = self.scroll_position;
diff --git a/crates/editor/src/element/mouse.rs b/crates/editor/src/element/mouse.rs
index 52f9677d391..1d8bb5dc65a 100644
--- a/crates/editor/src/element/mouse.rs
+++ b/crates/editor/src/element/mouse.rs
@@ -22,7 +22,8 @@ use crate::{
EditorSettings, EditorSnapshot, GutterHoverButton, HoveredCursor, JumpData,
PhantomDiffReviewIndicator, SelectPhase, Selection, SelectionDragState,
display_map::ToDisplayPoint, editor_settings::DoubleClickInMultibuffer,
- hover_popover::hover_at, mouse_context_menu, scroll::ScrollPixelOffset,
+ hover_popover::hover_at, inlays::inlay_hints::HintTarget, mouse_context_menu,
+ scroll::ScrollPixelOffset,
};
impl EditorElement {
@@ -240,8 +241,10 @@ impl EditorElement {
// Don't trigger hover popover if mouse is hovering over context menu
if text_hovered {
+ let hint_glyph = position_map.inlay_hint_glyph_for_position(event.position);
editor.update_hovered_link(
point_for_position,
+ hint_glyph,
Some(event.position),
&position_map.snapshot,
modifiers,
@@ -249,7 +252,9 @@ impl EditorElement {
cx,
);
- if let Some(point) = point_for_position.as_valid() {
+ if hint_glyph.is_none()
+ && let Some(point) = point_for_position.as_valid()
+ {
let anchor = position_map
.snapshot
.buffer_snapshot()
@@ -259,7 +264,7 @@ impl EditorElement {
} else {
editor.update_inlay_link_and_hover_points(
&position_map.snapshot,
- point_for_position,
+ hint_glyph,
Some(event.position),
modifiers.secondary(),
modifiers.shift,
@@ -613,16 +618,52 @@ impl EditorElement {
return;
}
+ let hint_glyph = text_hitbox
+ .is_hovered(window)
+ .then(|| position_map.inlay_hint_glyph_for_position(event.position))
+ .flatten();
if !event.modifiers.modified()
- && text_hitbox.is_hovered(window)
- && editor.hovered_inlay_hint_command().is_some_and(|command| {
- command.contains_point(&position_map.snapshot, point_for_position)
- })
+ && editor
+ .hovered_inlay_hint_command()
+ .is_some_and(|command| command.contains_glyph(&position_map.snapshot, hint_glyph))
{
cx.stop_propagation();
return;
}
+ let is_singleton = editor.buffer().read(cx).is_singleton();
+ let double_click_selects = is_singleton
+ || EditorSettings::get_global(cx).double_click_in_multibuffer
+ == DoubleClickInMultibuffer::Select;
+
+ if click_count == 2
+ && double_click_selects
+ && !modifiers.modified()
+ && let Some((hint, offset_in_hint)) =
+ hint_glyph.and_then(|glyph| position_map.snapshot.inlay_hint_at(glyph))
+ && let Some(buffer_id) = hint
+ .position
+ .raw_text_anchor()
+ .map(|anchor| anchor.buffer_id)
+ {
+ let resolved = editor.is_inlay_hint_resolved(buffer_id, hint.id, cx);
+ let accepting = editor.apply_inlay_hint_text_edits(
+ [HintTarget {
+ buffer_id,
+ hint_id: hint.id,
+ position: hint.position,
+ }]
+ .into_iter(),
+ Some(offset_in_hint),
+ window,
+ cx,
+ );
+ if accepting && resolved {
+ cx.stop_propagation();
+ return;
+ }
+ }
+
if EditorSettings::get_global(cx)
.drag_and_drop_selection
.enabled
@@ -643,8 +684,6 @@ impl EditorElement {
}
}
- let is_singleton = editor.buffer().read(cx).is_singleton();
-
if click_count == 2 && !is_singleton {
match EditorSettings::get_global(cx).double_click_in_multibuffer {
DoubleClickInMultibuffer::Select => {
@@ -966,8 +1005,8 @@ impl EditorElement {
&& !mouse_event.up.modifiers.modified()
&& editor.activate_hovered_inlay_hint_command(
&position_map.snapshot,
- position_map.point_for_position(mouse_event.down.position),
- point,
+ position_map.inlay_hint_glyph_for_position(mouse_event.down.position),
+ position_map.inlay_hint_glyph_for_position(mouse_position),
cx,
)
{
diff --git a/crates/editor/src/fold.rs b/crates/editor/src/fold.rs
index 73aa6b30586..cd7437d01e5 100644
--- a/crates/editor/src/fold.rs
+++ b/crates/editor/src/fold.rs
@@ -597,6 +597,7 @@ impl Editor {
self.scrollbar_marker_state.dirty = true;
self.update_data_on_scroll(false, window, cx);
self.folds_did_change(cx);
+ self.inlay_hint_visibility_changed(cx);
}
/// Removes any folds whose ranges intersect any of the given ranges.
@@ -611,6 +612,7 @@ impl Editor {
map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx);
});
self.folds_did_change(cx);
+ self.inlay_hint_visibility_changed(cx);
}
pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
@@ -654,6 +656,7 @@ impl Editor {
ids: ids_to_fold,
folded: true,
});
+ self.inlay_hint_visibility_changed(cx);
cx.notify();
}
@@ -668,6 +671,7 @@ impl Editor {
ids: vec![buffer_id],
folded: false,
});
+ self.inlay_hint_visibility_changed(cx);
cx.notify();
}
@@ -705,6 +709,7 @@ impl Editor {
map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
});
self.folds_did_change(cx);
+ self.inlay_hint_visibility_changed(cx);
}
pub fn update_renderer_widths(
diff --git a/crates/editor/src/hover_links.rs b/crates/editor/src/hover_links.rs
index 289eee9b202..262d1ae65cd 100644
--- a/crates/editor/src/hover_links.rs
+++ b/crates/editor/src/hover_links.rs
@@ -1,6 +1,6 @@
use crate::{
- Anchor, Editor, EditorSettings, EditorSnapshot, FindAllReferences, GotoDefinitionKind,
- HighlightKey, Navigated, PointForPosition, SelectPhase,
+ Anchor, DisplayPoint, Editor, EditorSettings, EditorSnapshot, FindAllReferences,
+ GotoDefinitionKind, HighlightKey, Navigated, PointForPosition, SelectPhase,
editor_settings::GoToDefinitionFallback, scroll::ScrollAmount,
};
use gpui::{
@@ -176,6 +176,7 @@ impl Editor {
pub(crate) fn update_hovered_link(
&mut self,
point_for_position: PointForPosition,
+ hint_glyph: Option<DisplayPoint>,
mouse_position: Option<gpui::Point<Pixels>>,
snapshot: &EditorSnapshot,
modifiers: Modifiers,
@@ -194,7 +195,7 @@ impl Editor {
}
match point_for_position.as_valid() {
- Some(point) => {
+ Some(point) if hint_glyph.is_none() => {
let trigger_point = TriggerPoint::Text(
snapshot
.buffer_snapshot()
@@ -203,10 +204,10 @@ impl Editor {
show_link_definition(modifiers.shift, self, trigger_point, snapshot, window, cx);
}
- None => {
+ _ => {
self.update_inlay_link_and_hover_points(
snapshot,
- point_for_position,
+ hint_glyph,
mouse_position,
hovered_link_modifier,
modifiers.shift,
@@ -1200,25 +1201,29 @@ fn surrounding_filename(
mod tests {
use super::*;
use crate::{
- DisplayPoint,
- display_map::ToDisplayPoint,
- editor_tests::init_test,
+ AcceptInlayHint, DisplayPoint, DisplayRow, SelectionEffects, Undo,
+ display_map::{BlockPlacement, BlockProperties, BlockStyle, ToDisplayPoint},
+ editor_tests::{init_test, update_test_language_settings},
inlays::inlay_hints::tests::{cached_hint_labels, visible_hint_labels},
test::editor_lsp_test_context::EditorLspTestContext,
};
- use futures::StreamExt;
+ use futures::{StreamExt, channel::oneshot};
use gpui::{
- Modifiers, MouseButton, MouseDownEvent, MousePressureEvent, MouseUpEvent, PlatformInput,
- PressureStage,
+ AppContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MousePressureEvent,
+ MouseUpEvent, PlatformInput, PressureStage,
};
use indoc::indoc;
- use language::Point;
+ use language::{
+ Capability, FakeLspAdapter, Point, language_settings::InlayHintKind, rust_lang,
+ };
use lsp::request::{GotoDefinition, GotoTypeDefinition, References};
use multi_buffer::{MultiBufferOffset, PathKey};
+ use parking_lot::Mutex;
use settings::InlayHintSettingsContent;
use std::str::FromStr;
use std::sync::Arc;
- use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+ use std::time::Duration;
use util::{assert_set_eq, path};
use workspace::item::Item;
@@ -1387,6 +1392,7 @@ mod tests {
editor.update_hovered_link(
point_for_position(link_start),
None,
+ None,
&old_snapshot,
modifiers,
window,
@@ -1399,6 +1405,7 @@ mod tests {
editor.update_hovered_link(
point_for_position(link_end),
None,
+ None,
&old_snapshot,
modifiers,
window,
@@ -1966,6 +1973,1072 @@ mod tests {
cx.background_executor.run_until_parked();
}
+ #[gpui::test]
+ async fn test_accept_inlay_hint(cx: &mut gpui::TestAppContext) {
+ init_test(cx, |settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(0),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ });
+ });
+ let hints = Arc::new(Mutex::new(None::<Vec<lsp::InlayHint>>));
+ let hints_gate = Arc::new(Mutex::new(None::<oneshot::Receiver<()>>));
+ let resolve_gate = Arc::new(Mutex::new(None::<oneshot::Receiver<()>>));
+ let resolve_count = Arc::new(AtomicUsize::new(0));
+ let fail_next_resolve = Arc::new(AtomicBool::new(false));
+ let mut cx = EditorLspTestContext::new_with_adapter(
+ Arc::into_inner(rust_lang()).expect("test language"),
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ inlay_hint_provider: Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ }),
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new({
+ let hints = hints.clone();
+ let hints_gate = hints_gate.clone();
+ let resolve_gate = resolve_gate.clone();
+ let resolve_count = resolve_count.clone();
+ let fail_next_resolve = fail_next_resolve.clone();
+ move |server| {
+ let hints = hints.clone();
+ let hints_gate = hints_gate.clone();
+ server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |_, _| {
+ let hints = hints.lock().take();
+ let hints_gate = hints_gate.lock().take();
+ async move {
+ if let Some(hints_gate) = hints_gate {
+ hints_gate.await?;
+ }
+ Ok(hints)
+ }
+ },
+ );
+ let resolve_gate = resolve_gate.clone();
+ let resolve_count = resolve_count.clone();
+ let fail_next_resolve = fail_next_resolve.clone();
+ server.set_request_handler::<lsp::request::InlayHintResolveRequest, _, _>(
+ move |mut hint, _| {
+ resolve_count.fetch_add(1, Ordering::Release);
+ let resolve_gate = resolve_gate.lock().take();
+ let fail_resolve = fail_next_resolve.swap(false, Ordering::AcqRel);
+ if hint.data == Some(serde_json::Value::Bool(true))
+ && let lsp::InlayHintLabel::String(label) = &hint.label
+ {
+ hint.text_edits = Some(type_hint_edits(hint.position, label));
+ }
+ if hint.data == Some(serde_json::Value::String("command".into()))
+ && let lsp::InlayHintLabel::String(label) = &hint.label
+ {
+ hint.text_edits = Some(type_hint_edits(hint.position, label));
+ hint.label = lsp::InlayHintLabel::LabelParts(vec![
+ lsp::InlayHintLabelPart {
+ value: label.clone(),
+ command: Some(lsp::Command {
+ title: "Run".to_string(),
+ command: "run".to_string(),
+ arguments: None,
+ }),
+ ..lsp::InlayHintLabelPart::default()
+ },
+ ]);
+ }
+ async move {
+ if let Some(resolve_gate) = resolve_gate {
+ resolve_gate.await?;
+ }
+ anyhow::ensure!(!fail_resolve, "injected resolve failure");
+ Ok(hint)
+ }
+ },
+ );
+ }
+ })),
+ ..FakeLspAdapter::default()
+ },
+ cx,
+ )
+ .await;
+
+ let source = "fn main() { let valueˇ = 1; }\n";
+ let accepted = "use std::primitive::u32;\nfn main() { let value: u32 = 1; }\n";
+
+ for selection in [
+ "«ˇfn main() { let value» = 1; }\n",
+ "fn main() { let value« = 1; }ˇ»\n",
+ "fn main() { «let valueˇ»« = 1;ˇ» }\n",
+ ] {
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state(selection);
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), accepted, "{selection}");
+ }
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state("fn main() { «lˇ»et value = 1; }\n");
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, _| {
+ editor.selections.set_line_mode(true);
+ });
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ assert!(window.is_action_available(&AcceptInlayHint, cx));
+ });
+ cx.update_editor(|editor, window, cx| {
+ editor.selections.set_line_mode(false);
+ window.dispatch_action(Box::new(AcceptInlayHint), cx);
+ });
+ cx.run_until_parked();
+ assert_eq!(
+ cx.buffer_text(),
+ "fn main() { let value = 1; }\n",
+ "accepting before repaint must use the current selection mode"
+ );
+
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ cx.buffer_text(),
+ "fn main() { let value = 1; }\n",
+ "leaving line mode without moving the selection must not accept the hint outside it"
+ );
+ cx.update_editor(|editor, _, _| {
+ editor.selections.set_line_mode(true);
+ });
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ assert!(
+ window.is_action_available(&AcceptInlayHint, cx),
+ "the action remains available in line mode"
+ );
+ });
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), accepted, "line mode selection");
+ cx.update_editor(|editor, _, _| {
+ editor.selections.set_line_mode(false);
+ });
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ cx.update_editor(|editor, window, cx| {
+ editor.with_selection_effects_deferred(window, cx, |editor, window, cx| {
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([Point::new(0, 0)..Point::new(0, 0)]);
+ });
+ editor.accept_inlay_hint(&AcceptInlayHint, window, cx);
+ assert_eq!(editor.text(cx), "fn main() { let value = 1; }\n");
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([Point::new(0, 21)..Point::new(0, 21)]);
+ });
+ let display_map = editor.display_map.clone();
+ display_map.update(cx, |_, cx| {
+ assert!(editor.can_accept_inlay_hint(cx));
+ });
+ editor.accept_inlay_hint(&AcceptInlayHint, window, cx);
+ });
+ });
+ assert_eq!(cx.buffer_text(), accepted);
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state("«fn main() { let value = 1; }ˇ»\n");
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ assert!(window.is_action_available(&AcceptInlayHint, cx));
+ });
+ cx.update_editor(|editor, window, cx| {
+ editor.fold_ranges(
+ vec![Point::new(0, 11)..Point::new(0, 27)],
+ false,
+ window,
+ cx,
+ );
+ });
+ cx.run_until_parked();
+
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), "fn main() { let value = 1; }\n");
+ cx.update_editor(|editor, window, cx| editor.unfold_all(&crate::UnfoldAll, window, cx));
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), accepted, "after unfolding");
+
+ for (fold_range, expected_text) in [
+ (Point::new(0, 2)..Point::new(0, 3), "f(value: 1)\n"),
+ (Point::new(0, 0)..Point::new(0, 2), "f(1)\n"),
+ ] {
+ *hints.lock() = Some(vec![parameter_hint(2, "value")]);
+ cx.set_state("«f(1)ˇ»\n");
+ cx.run_until_parked();
+ cx.update_editor(|editor, window, cx| {
+ editor.fold_ranges(vec![fold_range.clone()], false, window, cx);
+ });
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), expected_text, "fold {fold_range:?}");
+ cx.update_editor(|editor, window, cx| editor.unfold_all(&crate::UnfoldAll, window, cx));
+ }
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state("«fn main() { let value = 1; }ˇ»\n");
+ cx.run_until_parked();
+ let block_ids = cx.update_editor(|editor, _, cx| {
+ let snapshot = editor.buffer().read(cx).snapshot(cx);
+ editor.insert_blocks(
+ [BlockProperties {
+ placement: BlockPlacement::Replace(
+ snapshot.anchor_before(Point::new(0, 0))
+ ..=snapshot.anchor_after(Point::new(0, 28)),
+ ),
+ height: Some(1),
+ style: BlockStyle::Fixed,
+ render: Arc::new(|_| gpui::IntoElement::into_any_element(gpui::div())),
+ priority: 0,
+ }],
+ None,
+ cx,
+ )
+ });
+ cx.run_until_parked();
+
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), "fn main() { let value = 1; }\n");
+ cx.update_editor(|editor, _, cx| {
+ editor.remove_blocks(block_ids.into_iter().collect(), None, cx);
+ });
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ cx.buffer_text(),
+ accepted,
+ "after removing the replace block"
+ );
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ cx.update_buffer(|buffer, cx| buffer.set_capability(Capability::ReadOnly, cx));
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ assert!(!window.is_action_available(&AcceptInlayHint, cx));
+ });
+ cx.update_buffer(|buffer, cx| buffer.set_capability(Capability::ReadWrite, cx));
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ assert!(
+ window.is_action_available(&AcceptInlayHint, cx),
+ "restoring write access re-enables the action without moving the caret"
+ );
+ });
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), accepted, "after write access restored");
+
+ for second_hint_edits in [HintEdits::InResponse, HintEdits::OnResolve] {
+ let mut first_hint = type_hint(17, "u32", HintEdits::InResponse);
+ let end = lsp::Position::new(1, 0);
+ first_hint
+ .text_edits
+ .as_mut()
+ .expect("first hint edits")
+ .push(lsp::TextEdit {
+ range: lsp::Range::new(end, end),
+ new_text: "fn helper() {}\n".to_string(),
+ });
+ *hints.lock() = Some(vec![
+ first_hint,
+ type_hint(20, "display only", HintEdits::None),
+ type_hint(28, "u64", second_hint_edits),
+ ]);
+ cx.set_state("fn main() { «let a = 1; let b = 2;ˇ» }\n");
+ cx.run_until_parked();
+ *hints.lock() = Some(vec![
+ type_hint_at(1, 25, "display only", HintEdits::None),
+ type_hint_at(1, 33, "u16", second_hint_edits),
+ ]);
+ let (release_hints, gate) = oneshot::channel();
+ *hints_gate.lock() = Some(gate);
+ let previous_resolve_count = resolve_count.load(Ordering::Acquire);
+ let after_first = "use std::primitive::u32;\nfn main() { let a: u32 = 1; let b = 2; }\nfn helper() {}\n";
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ cx.buffer_text(),
+ after_first,
+ "one invocation accepts the first selected hint only: {second_hint_edits:?}"
+ );
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ cx.buffer_text(),
+ after_first,
+ "old hints must not be reused while replacements are pending"
+ );
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ previous_resolve_count
+ );
+ release_hints.send(()).expect("replacement hints gate");
+ cx.run_until_parked();
+ assert_eq!(
+ cx.buffer_text(),
+ "use std::primitive::u16;\nuse std::primitive::u32;\nfn main() { let a: u32 = 1; let b: u16 = 2; }\nfn helper() {}\n",
+ "the next invocation accepts the replacement hint with its new edits: {second_hint_edits:?}"
+ );
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ previous_resolve_count + 1 + usize::from(second_hint_edits == HintEdits::OnResolve),
+ );
+ cx.dispatch_action(Undo);
+ assert_eq!(
+ cx.buffer_text(),
+ "use std::primitive::u32;\nfn main() { let a: u32 = 1; let b = 2; }\nfn helper() {}\n",
+ "each accepted hint is its own undo step: {second_hint_edits:?}"
+ );
+ }
+
+ *hints.lock() = Some(vec![
+ type_hint(17, "u32", HintEdits::None),
+ type_hint(28, "u64", HintEdits::None),
+ ]);
+ let uneditable_selection = "fn main() { «let a = 1; let b = 2;ˇ» }\n";
+ cx.set_state(uneditable_selection);
+ cx.run_until_parked();
+ let expected_resolve_count = resolve_count.load(Ordering::Acquire) + 2;
+ for _ in 0..2 {
+ cx.dispatch_action(AcceptInlayHint);
+ cx.assert_editor_state(uneditable_selection);
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ expected_resolve_count
+ );
+ }
+
+ let mut crlf_hint = type_hint(21, "u32", HintEdits::InResponse);
+ for edit in crlf_hint.text_edits.iter_mut().flatten() {
+ edit.new_text = edit.new_text.replace('\n', "\r\n");
+ }
+ *hints.lock() = Some(vec![crlf_hint]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), accepted, "line endings are normalized");
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ for (read_only, lsp_enabled) in [(true, true), (false, false)] {
+ cx.update_editor(|editor, _, cx| {
+ editor.set_read_only(read_only);
+ editor.enable_lsp_data = lsp_enabled;
+ cx.notify();
+ });
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ assert!(!window.is_action_available(&AcceptInlayHint, cx));
+ });
+ cx.dispatch_action(AcceptInlayHint);
+ cx.assert_editor_state(source);
+ }
+ cx.update_editor(|editor, _, cx| {
+ editor.set_read_only(false);
+ editor.enable_lsp_data = true;
+ cx.notify();
+ });
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let hint_start = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 21));
+ let glyph_width = cx
+ .pixel_position_for(DisplayPoint::new(DisplayRow(0), 22))
+ .x
+ - hint_start.x;
+ let line_height = cx.update_editor(|editor, window, cx| {
+ editor
+ .style(cx)
+ .text
+ .line_height_in_pixels(window.rem_size())
+ });
+ let below_end_of_file = gpui::point(hint_start.x, hint_start.y + line_height * 3.);
+ cx.simulate_mouse_move(below_end_of_file, None, Modifiers::none());
+ cx.simulate_click(below_end_of_file, Modifiers::none());
+ simulate_double_click(&mut cx, below_end_of_file);
+ assert_eq!(cx.buffer_text(), "fn main() { let value = 1; }\n");
+ for (x_offset, expected_text) in [
+ (-glyph_width / 4., "fn main() { let «valueˇ» = 1; }\n"),
+ (
+ glyph_width / 4.,
+ "use std::primitive::u32;\nfn main() { let value: u32ˇ = 1; }\n",
+ ),
+ (
+ glyph_width * 2.5,
+ "use std::primitive::u32;\nfn main() { let value: u32ˇ = 1; }\n",
+ ),
+ ] {
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::InResponse)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let point = gpui::point(hint_start.x + x_offset, hint_start.y);
+ cx.simulate_mouse_move(point, None, Modifiers::none());
+ cx.simulate_click(point, Modifiers::none());
+ simulate_double_click(&mut cx, point);
+ cx.assert_editor_state(expected_text);
+ }
+
+ for read_only_while_resolving in [true, false] {
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::OnResolve)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ let previous_resolve_count = resolve_count.load(Ordering::Acquire);
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ previous_resolve_count + 1
+ );
+ cx.assert_editor_state(source);
+ cx.update_editor(|editor, _, _| editor.set_read_only(read_only_while_resolving));
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ if read_only_while_resolving {
+ cx.assert_editor_state(source);
+ cx.update_editor(|editor, _, _| editor.set_read_only(false));
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), accepted, "accept after read-only");
+ } else {
+ assert_eq!(cx.buffer_text(), accepted);
+ }
+ }
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::OnResolve)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ fail_next_resolve.store(true, Ordering::Release);
+ let previous_resolve_count = resolve_count.load(Ordering::Acquire);
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ previous_resolve_count + 1
+ );
+ cx.assert_editor_state(source);
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ previous_resolve_count + 2
+ );
+ assert_eq!(cx.buffer_text(), accepted);
+
+ for (second_hint_edits, hover_second_first, expected_text) in [
+ (
+ HintEdits::None,
+ false,
+ "fn main() { let a = 1; let b = 2; }\n",
+ ),
+ (
+ HintEdits::None,
+ true,
+ "fn main() { let a = 1; let b = 2; }\n",
+ ),
+ (
+ HintEdits::InResponse,
+ false,
+ "use std::primitive::u64;\nfn main() { let a = 1; let b: u64 = 2; }\n",
+ ),
+ ] {
+ *hints.lock() = Some(vec![
+ type_hint(17, "u32", HintEdits::OnResolve),
+ type_hint(28, "u64", second_hint_edits),
+ ]);
+ cx.set_state("fn main() { let aˇ = 1; let b = 2; }\n");
+ cx.run_until_parked();
+ if hover_second_first {
+ let second_hint_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 34));
+ cx.simulate_mouse_move(second_hint_point, None, Modifiers::none());
+ cx.update_editor(|editor, _, cx| {
+ let buffer_id = editor
+ .buffer()
+ .read(cx)
+ .as_singleton()
+ .unwrap()
+ .read(cx)
+ .remote_id();
+ let second_hint = editor
+ .all_inlays(cx)
+ .into_iter()
+ .find(|inlay| inlay.text().to_string() == ": u64")
+ .expect("second hint");
+ assert!(editor.is_inlay_hint_resolved(buffer_id, second_hint.id, cx));
+ });
+ }
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ cx.dispatch_action(AcceptInlayHint);
+ cx.update_editor(|editor, window, cx| {
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([Point::new(0, 28)..Point::new(0, 28)]);
+ });
+ });
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ cx.buffer_text(),
+ expected_text,
+ "{second_hint_edits:?}, hovered first: {hover_second_first}"
+ );
+ release_resolve.send(()).ok();
+ cx.run_until_parked();
+ assert_eq!(
+ cx.buffer_text(),
+ expected_text,
+ "a later acceptance replaces the pending one: {second_hint_edits:?}, hovered first: {hover_second_first}"
+ );
+ }
+
+ *hints.lock() = Some(vec![type_hint(17, "u32", HintEdits::OnResolve)]);
+ cx.set_state("fn main() { let aˇ = 1; let b = 2; }\n");
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ cx.dispatch_action(AcceptInlayHint);
+ *hints.lock() = Some(vec![type_hint(32, "u64", HintEdits::InResponse)]);
+ cx.update_buffer(|buffer, cx| buffer.edit([(0..0, "pub ")], None, cx));
+ cx.run_until_parked();
+ cx.update_editor(|editor, window, cx| {
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([Point::new(0, 32)..Point::new(0, 32)]);
+ });
+ });
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ cx.buffer_text(),
+ "use std::primitive::u64;\npub fn main() { let a = 1; let b: u64 = 2; }\n"
+ );
+ drop(release_resolve);
+ cx.run_until_parked();
+ assert_eq!(
+ cx.buffer_text(),
+ "use std::primitive::u64;\npub fn main() { let a = 1; let b: u64 = 2; }\n"
+ );
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::None)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ cx.assert_editor_state(source);
+ let point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 23));
+ cx.simulate_click(point, Modifiers::none());
+ simulate_double_click(&mut cx, point);
+ cx.assert_editor_state("fn main() { let «valueˇ» = 1; }\n");
+
+ let word_selected = "fn main() { let «valueˇ» = 1; }\n";
+ for (edits, expected_state) in [
+ (
+ HintEdits::OnResolve,
+ "use std::primitive::u32;\nfn main() { let «valueˇ»: u32 = 1; }\n",
+ ),
+ (HintEdits::None, word_selected),
+ ] {
+ *hints.lock() = Some(vec![type_hint(21, "u32", edits)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ cx.simulate_mouse_move(point, None, Modifiers::none());
+ cx.simulate_click(point, Modifiers::none());
+ simulate_double_click(&mut cx, point);
+ cx.assert_editor_state(word_selected);
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ cx.assert_editor_state(expected_state);
+ }
+
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::OnResolve)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ let word_start = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 18));
+ cx.simulate_mouse_move(word_start, None, Modifiers::none());
+ cx.simulate_click(word_start, Modifiers::none());
+ cx.simulate_event(MouseDownEvent {
+ position: word_start,
+ modifiers: Modifiers::none(),
+ button: MouseButton::Left,
+ click_count: 2,
+ first_mouse: false,
+ });
+ let drag_end = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 30));
+ cx.simulate_event(MouseMoveEvent {
+ position: drag_end,
+ pressed_button: Some(MouseButton::Left),
+ modifiers: Modifiers::none(),
+ });
+ cx.simulate_event(MouseUpEvent {
+ position: drag_end,
+ modifiers: Modifiers::none(),
+ button: MouseButton::Left,
+ click_count: 2,
+ });
+ cx.assert_editor_state("fn main() { let «value = 1ˇ»; }\n");
+ drop(release_resolve);
+
+ for (eager_edits, resolve_fails) in [(false, false), (true, false), (true, true)] {
+ let mut command_hint = type_hint(
+ 21,
+ "u32",
+ if eager_edits {
+ HintEdits::InResponse
+ } else {
+ HintEdits::None
+ },
+ );
+ command_hint.data = Some(serde_json::Value::String("command".into()));
+ *hints.lock() = Some(vec![command_hint]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ fail_next_resolve.store(resolve_fails, Ordering::Release);
+ cx.simulate_mouse_move(point, None, Modifiers::none());
+ cx.simulate_click(point, Modifiers::none());
+ simulate_double_click(&mut cx, point);
+ cx.assert_editor_state(word_selected);
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ cx.assert_editor_state(word_selected);
+ if !resolve_fails {
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), accepted, "eager_edits: {eager_edits}");
+ }
+ }
+
+ let mut command_hint = type_hint(21, "u32", HintEdits::InResponse);
+ command_hint.data = Some(serde_json::Value::String("command".into()));
+ *hints.lock() = Some(vec![command_hint]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ cx.simulate_mouse_move(point, None, Modifiers::none());
+ cx.simulate_click(point, Modifiers::none());
+ simulate_double_click(&mut cx, point);
+ cx.assert_editor_state(word_selected);
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ cx.buffer_text(),
+ accepted,
+ "an explicit accept overrides the pending click's command check"
+ );
+ release_resolve.send(()).ok();
+ cx.run_until_parked();
+ assert_eq!(cx.buffer_text(), accepted);
+
+ for (fragments, expected) in [
+ (
+ [
+ (0, 0, "use std::primitive::{"),
+ (0, 0, "u32"),
+ (0, 0, "};\n"),
+ ],
+ "use std::primitive::{u32};\nfn main() { let value = 1; }\n",
+ ),
+ (
+ [(21, 21, ": u32"), (0, 0, "use x;\r"), (0, 0, "\n")],
+ "use x;\nfn main() { let value: u32 = 1; }\n",
+ ),
+ (
+ [(21, 21, ": u32"), (0, 0, "X\r"), (0, 1, "\nY")],
+ "X\nYn main() { let value: u32 = 1; }\n",
+ ),
+ ] {
+ let mut hint = type_hint(21, "u32", HintEdits::InResponse);
+ hint.text_edits = Some(
+ fragments
+ .into_iter()
+ .map(|(start, end, new_text)| lsp::TextEdit {
+ range: lsp::Range::new(
+ lsp::Position::new(0, start),
+ lsp::Position::new(0, end),
+ ),
+ new_text: new_text.to_string(),
+ })
+ .collect(),
+ );
+ *hints.lock() = Some(vec![hint]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), expected);
+ }
+
+ update_test_language_settings(&mut cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(700),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ });
+ });
+ *hints.lock() = Some(vec![type_hint(21, "u32", HintEdits::OnResolve)]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ cx.dispatch_action(AcceptInlayHint);
+ cx.lsp
+ .request::<lsp::request::InlayHintRefreshRequest>((), lsp::DEFAULT_LSP_REQUEST_TIMEOUT)
+ .await
+ .into_response()
+ .expect("inlay hint refresh request");
+ cx.run_until_parked();
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ cx.assert_editor_state(source);
+ cx.background_executor
+ .advance_clock(std::time::Duration::from_millis(700));
+ cx.assert_editor_state(source);
+ update_test_language_settings(&mut cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(0),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ });
+ });
+
+ *hints.lock() = Some(vec![
+ type_hint(17, "u32", HintEdits::OnResolve),
+ parameter_hint(27, "b"),
+ ]);
+ cx.set_state("fn main() { let aˇ = 1; foo(2); }\n");
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ cx.dispatch_action(AcceptInlayHint);
+ cx.update_editor(|editor, window, cx| {
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
+ s.select_ranges([Point::new(0, 27)..Point::new(0, 27)]);
+ });
+ });
+ update_test_language_settings(&mut cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ show_type_hints: Some(false),
+ edit_debounce_ms: Some(0),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ });
+ });
+ cx.run_until_parked();
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), "fn main() { let a = 1; foo(b: 2); }\n");
+ drop(release_resolve);
+ update_test_language_settings(&mut cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(0),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ });
+ });
+
+ *hints.lock() = Some(vec![
+ type_hint(17, "u32", HintEdits::OnResolve),
+ type_hint(28, "u64", HintEdits::InResponse),
+ ]);
+ cx.set_state("fn main() { «let a = 1; let b = 2;ˇ» }\n");
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ cx.dispatch_action(AcceptInlayHint);
+ cx.assert_editor_state("fn main() { «let a = 1; let b = 2;ˇ» }\n");
+ cx.update_editor(|editor, window, cx| {
+ editor.fold_ranges(
+ vec![Point::new(0, 16)..Point::new(0, 18)],
+ false,
+ window,
+ cx,
+ );
+ });
+ cx.run_until_parked();
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ assert_eq!(
+ cx.buffer_text(),
+ "fn main() { let a = 1; let b = 2; }\n",
+ "folding the pending hint cancels its acceptance"
+ );
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(
+ cx.buffer_text(),
+ "use std::primitive::u64;\nfn main() { let a = 1; let b: u64 = 2; }\n",
+ "the folded hint is skipped in favor of the next visible one"
+ );
+
+ let mut command_hint = type_hint(21, "u32", HintEdits::None);
+ command_hint.data = Some(serde_json::Value::String("command".into()));
+ *hints.lock() = Some(vec![command_hint]);
+ cx.set_state(source);
+ cx.run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ cx.simulate_mouse_move(point, None, Modifiers::none());
+ let notifications = Arc::new(AtomicUsize::new(0));
+ let editor = cx.editor.clone();
+ let _notifications_subscription = cx.update(|_, cx| {
+ let notifications = notifications.clone();
+ cx.observe(&editor, move |_, _| {
+ notifications.fetch_add(1, Ordering::Release);
+ })
+ });
+ cx.update_editor(|editor, _, _| {
+ assert!(editor.hovered_inlay_hint_command().is_none());
+ });
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, _| {
+ assert!(editor.hovered_inlay_hint_command().is_some());
+ });
+ assert_eq!(
+ notifications.load(Ordering::Acquire),
+ 1,
+ "resolving a hovered command-only hint repaints the editor"
+ );
+
+ *hints.lock() = Some(vec![
+ type_hint_at(1, 0, "u32", HintEdits::InResponse),
+ type_hint_at(2, 1, "u64", HintEdits::InResponse),
+ ]);
+ cx.set_state("aa\nbb\ncˇc");
+ cx.set_head_text("aa\nold\nbb\ncc");
+ cx.dispatch_action(crate::ExpandAllDiffHunks);
+ let cloned_editor = cx.update_editor(|editor, window, cx| {
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([
+ Point::new(1, 1)..Point::new(1, 1),
+ Point::new(3, 1)..Point::new(3, 1),
+ ]);
+ });
+ assert!(editor.can_accept_inlay_hint(cx));
+ let cloned_editor = cx.new(|cx| editor.clone(window, cx));
+ assert_eq!(editor.buffer(), cloned_editor.read(cx).buffer());
+ cloned_editor
+ });
+ cx.update(|window, cx| {
+ let cloned_editor = cloned_editor.clone();
+ cx.defer(move |cx| {
+ cloned_editor.update(cx, |editor, cx| {
+ assert!(editor.clear_expanded_diff_hunks(cx));
+ });
+ });
+ window.dispatch_action(Box::new(AcceptInlayHint), cx);
+ });
+ cx.run_until_parked();
+ assert_eq!(
+ cx.buffer_text(),
+ "use std::primitive::u32;\naa\n: u32bb\ncc",
+ "collapsing deleted text through a clone changes the original editor's selected hint before the next action"
+ );
+
+ drop(cloned_editor);
+ cx.set_state("ˇ");
+ cx.run_until_parked();
+ update_test_language_settings(&mut cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(700),
+ scroll_debounce_ms: Some(50),
+ ..InlayHintSettingsContent::default()
+ });
+ });
+ let repeated_hints = [1, 2, 3].map(|row| {
+ let mut hint = type_hint_at(row, 11, "i32", HintEdits::InResponse);
+ hint.text_edits.as_mut().expect("inline edits").truncate(1);
+ hint
+ });
+ let previous_resolve_count = resolve_count.load(Ordering::Acquire);
+ *hints.lock() = Some(repeated_hints.to_vec());
+ let (release_initial_hints, gate) = oneshot::channel();
+ *hints_gate.lock() = Some(gate);
+ let initial = indoc! {"
+ «fn main() {
+ let one = 1;
+ let one = 1;
+ let one = 1;
+ }ˇ»
+ "};
+ let after_first = indoc! {"
+ «fn main() {
+ let one: i32 = 1;
+ let one = 1;
+ let one = 1;
+ }ˇ»
+ "};
+ cx.set_state(initial);
+ cx.run_until_parked();
+ cx.background_executor
+ .advance_clock(Duration::from_millis(700));
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(visible_hint_labels(editor, cx), Vec::<String>::new());
+ });
+ assert!(hints_gate.lock().is_none());
+ assert_inlay_hint_acceptance_available(&mut cx);
+ cx.dispatch_action(AcceptInlayHint);
+ cx.assert_editor_state(initial);
+ release_initial_hints
+ .send(())
+ .expect("initial hint response");
+ cx.run_until_parked();
+ cx.assert_editor_state(after_first);
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ previous_resolve_count
+ );
+
+ *hints.lock() = Some(repeated_hints[1..].to_vec());
+ let (release_hints, gate) = oneshot::channel();
+ *hints_gate.lock() = Some(gate);
+ cx.dispatch_action(AcceptInlayHint);
+ cx.dispatch_action(AcceptInlayHint);
+ cx.assert_editor_state(after_first);
+ assert_inlay_hint_acceptance_available(&mut cx);
+ cx.background_executor
+ .advance_clock(Duration::from_millis(699));
+ cx.run_until_parked();
+ assert!(hints_gate.lock().is_some());
+ cx.assert_editor_state(after_first);
+ cx.background_executor
+ .advance_clock(Duration::from_millis(1));
+ cx.run_until_parked();
+ assert!(hints_gate.lock().is_none());
+ *hints.lock() = Some(repeated_hints[1..].to_vec());
+ cx.lsp
+ .request::<lsp::request::InlayHintRefreshRequest>((), lsp::DEFAULT_LSP_REQUEST_TIMEOUT)
+ .await
+ .into_response()
+ .expect("overlapping workspace inlay hint refresh");
+ cx.run_until_parked();
+ assert_inlay_hint_acceptance_available(&mut cx);
+ cx.background_executor
+ .advance_clock(Duration::from_millis(700));
+ cx.run_until_parked();
+ assert_eq!(hints.lock().as_ref().map(Vec::len), Some(2));
+ cx.assert_editor_state(after_first);
+ release_hints.send(()).expect("pending hint response");
+ cx.run_until_parked();
+ cx.assert_editor_state(indoc! {"
+ «fn main() {
+ let one: i32 = 1;
+ let one: i32 = 1;
+ let one = 1;
+ }ˇ»
+ "});
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ previous_resolve_count
+ );
+
+ *hints.lock() = Some(vec![repeated_hints[2].clone()]);
+ let hint_start = cx.pixel_position_for(DisplayPoint::new(DisplayRow(3), 11));
+ let next_column = cx.pixel_position_for(DisplayPoint::new(DisplayRow(3), 12));
+ let point = gpui::point((hint_start.x + next_column.x) / 2., hint_start.y);
+ cx.simulate_mouse_move(point, None, Modifiers::none());
+ cx.simulate_click(point, Modifiers::none());
+ simulate_double_click(&mut cx, point);
+ assert_eq!(
+ cx.buffer_text(),
+ indoc! {"
+ fn main() {
+ let one: i32 = 1;
+ let one: i32 = 1;
+ let one = 1;
+ }
+ "}
+ );
+ cx.background_executor
+ .advance_clock(Duration::from_millis(700));
+ cx.run_until_parked();
+ let accepted_text = indoc! {"
+ fn main() {
+ let one: i32 = 1;
+ let one: i32 = 1;
+ let one: i32 = 1;
+ }
+ "};
+ assert_eq!(cx.buffer_text(), accepted_text);
+ let expected_resolve_count = previous_resolve_count + 1;
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ expected_resolve_count
+ );
+ cx.background_executor
+ .advance_clock(Duration::from_millis(700));
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(visible_hint_labels(editor, cx), Vec::<String>::new());
+ });
+ assert_inlay_hint_acceptance_available(&mut cx);
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), accepted_text);
+
+ for edit_buffer in [false, true] {
+ cx.set_state("ˇ");
+ let mut hint = type_hint(19, "i32", HintEdits::InResponse);
+ hint.text_edits.as_mut().expect("inline edits").truncate(1);
+ *hints.lock() = Some(vec![hint]);
+ let (release_hints, gate) = oneshot::channel();
+ *hints_gate.lock() = Some(gate);
+ cx.set_state("«fn main() { let one = 1; }ˇ»\n");
+ cx.background_executor
+ .advance_clock(Duration::from_millis(700));
+ cx.run_until_parked();
+ assert!(hints_gate.lock().is_none());
+ assert_inlay_hint_acceptance_available(&mut cx);
+ cx.dispatch_action(AcceptInlayHint);
+ if edit_buffer {
+ cx.update_buffer(|buffer, cx| buffer.edit([(0..0, "pub ")], None, cx));
+ } else {
+ cx.update_editor(|editor, window, cx| {
+ editor.change_selections(
+ SelectionEffects::no_scroll(),
+ window,
+ cx,
+ |selections| {
+ selections.select_ranges([Point::new(0, 0)..Point::new(0, 0)]);
+ },
+ );
+ });
+ }
+ release_hints
+ .send(())
+ .expect("cancelled acceptance hint response");
+ cx.run_until_parked();
+ cx.background_executor
+ .advance_clock(Duration::from_millis(700));
+ cx.run_until_parked();
+ assert_eq!(
+ cx.buffer_text(),
+ if edit_buffer {
+ "pub fn main() { let one = 1; }\n"
+ } else {
+ "fn main() { let one = 1; }\n"
+ }
+ );
+ assert_eq!(
+ resolve_count.load(Ordering::Acquire),
+ expected_resolve_count
+ );
+ }
+ }
+
#[gpui::test]
async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
init_test(cx, |settings| {
@@ -2042,7 +3115,10 @@ mod tests {
..lsp::InlayHintLabelPart::default()
}]),
kind: Some(lsp::InlayHintKind::TYPE),
- text_edits: None,
+ text_edits: Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(hint_position, hint_position),
+ new_text: ": TestStruct".to_string(),
+ }]),
tooltip: None,
padding_left: Some(false),
padding_right: Some(false),
@@ -2135,6 +3211,12 @@ mod tests {
editor.hovered_inlay_hint_command().is_none(),
"replacing the hovered inlay should clear its command"
);
+ editor
+ .inlay_hints
+ .as_mut()
+ .expect("inlay hints enabled")
+ .added_hints
+ .insert(hovered_inlay_id, Some(InlayHintKind::Type));
});
cx.simulate_click(hover_point, Modifiers::none());
cx.background_executor.run_until_parked();
@@ -2159,24 +3241,19 @@ mod tests {
}
"});
- cx.simulate_event(MouseDownEvent {
- position: hover_point,
- modifiers: Modifiers::none(),
- button: MouseButton::Left,
- click_count: 2,
- first_mouse: false,
- });
- cx.simulate_event(MouseUpEvent {
- position: hover_point,
- modifiers: Modifiers::none(),
- button: MouseButton::Left,
- click_count: 2,
- });
+ simulate_double_click(&mut cx, hover_point);
cx.background_executor.run_until_parked();
assert!(
command_requests.try_recv().is_err(),
"Second click of a double click should not re-run the inlay hint command"
);
+ cx.assert_editor_state(indoc! {"
+ struct TestStruct;
+
+ fn main() {
+ let variableˇ = TestStruct;
+ }
+ "});
cx.simulate_modifiers_change(Modifiers::secondary_key());
cx.background_executor.run_until_parked();
@@ -3807,4 +4884,95 @@ Sentence ending file2.rs.
);
});
}
+
+ #[derive(Debug, Clone, Copy, PartialEq)]
+ enum HintEdits {
+ InResponse,
+ OnResolve,
+ None,
+ }
+
+ fn type_hint(column: u32, type_name: &str, edits: HintEdits) -> lsp::InlayHint {
+ type_hint_at(0, column, type_name, edits)
+ }
+
+ fn type_hint_at(line: u32, column: u32, type_name: &str, edits: HintEdits) -> lsp::InlayHint {
+ let position = lsp::Position::new(line, column);
+ let label = format!(": {type_name}");
+ lsp::InlayHint {
+ position,
+ text_edits: (edits == HintEdits::InResponse).then(|| type_hint_edits(position, &label)),
+ label: lsp::InlayHintLabel::String(label),
+ kind: Some(lsp::InlayHintKind::TYPE),
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: (edits == HintEdits::OnResolve).then_some(serde_json::Value::Bool(true)),
+ }
+ }
+
+ fn parameter_hint(column: u32, name: &str) -> lsp::InlayHint {
+ let position = lsp::Position::new(0, column);
+ let label = format!("{name}: ");
+ lsp::InlayHint {
+ position,
+ text_edits: Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(position, position),
+ new_text: label.clone(),
+ }]),
+ label: lsp::InlayHintLabel::String(label),
+ kind: Some(lsp::InlayHintKind::PARAMETER),
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ }
+ }
+
+ fn type_hint_edits(position: lsp::Position, label: &str) -> Vec<lsp::TextEdit> {
+ let type_name = label.trim_start_matches(": ");
+ vec![
+ lsp::TextEdit {
+ range: lsp::Range::new(position, position),
+ new_text: label.to_string(),
+ },
+ lsp::TextEdit {
+ range: lsp::Range::default(),
+ new_text: format!("use std::primitive::{type_name};\n"),
+ },
+ ]
+ }
+
+ #[track_caller]
+ fn assert_inlay_hint_acceptance_available(cx: &mut EditorLspTestContext) {
+ cx.update_editor(|editor, _, cx| {
+ assert!(editor.can_accept_inlay_hint(cx));
+ });
+ cx.update(|window, cx| {
+ assert_eq!(
+ window
+ .available_actions(cx)
+ .into_iter()
+ .filter(|action| action.as_any().is::<AcceptInlayHint>())
+ .count(),
+ 1,
+ );
+ });
+ }
+
+ fn simulate_double_click(cx: &mut EditorLspTestContext, position: gpui::Point<Pixels>) {
+ cx.simulate_event(MouseDownEvent {
+ position,
+ modifiers: Modifiers::none(),
+ button: MouseButton::Left,
+ click_count: 2,
+ first_mouse: false,
+ });
+ cx.simulate_event(MouseUpEvent {
+ position,
+ modifiers: Modifiers::none(),
+ button: MouseButton::Left,
+ click_count: 2,
+ });
+ }
}
diff --git a/crates/editor/src/hover_popover.rs b/crates/editor/src/hover_popover.rs
index f3d0c6c2c33..43c28b2cdde 100644
--- a/crates/editor/src/hover_popover.rs
+++ b/crates/editor/src/hover_popover.rs
@@ -1,7 +1,7 @@
use crate::{
Anchor, AnchorRangeExt, DisplayPoint, DisplayRow, Editor, EditorSettings, EditorSnapshot,
GlobalDiagnosticRenderer, HighlightKey, Hover,
- display_map::{InlayOffset, ToDisplayPoint, is_invisible},
+ display_map::{ToDisplayPoint, is_invisible},
editor_settings::EditorSettingsScrollbarProxy,
hover_links::{InlayHighlight, RangeInEditor},
movement::TextLayoutDetails,
@@ -53,6 +53,7 @@ pub fn hover_at(
window: &mut Window,
cx: &mut Context<Editor>,
) {
+ editor.hover_state.hint_hover_task = None;
if EditorSettings::get_global(cx).hover_popover_enabled {
if show_keyboard_hover(editor, window, cx) {
return;
@@ -86,7 +87,7 @@ pub fn hover_at(
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(delay).await;
this.update(cx, |editor, cx| {
- hide_hover(editor, cx);
+ hide_popovers(editor, cx);
})
.ok();
});
@@ -137,22 +138,15 @@ pub struct InlayHover {
pub fn find_hovered_hint_part(
label_parts: Vec<InlayHintLabelPart>,
- hint_start: InlayOffset,
- hovered_offset: InlayOffset,
-) -> Option<(InlayHintLabelPart, Range<InlayOffset>)> {
- if hovered_offset >= hint_start {
- let mut offset_in_hint = hovered_offset - hint_start;
- let mut part_start = hint_start;
- for part in label_parts {
- let part_len = part.value.len();
- if offset_in_hint >= part_len {
- offset_in_hint -= part_len;
- part_start.0 += part_len;
- } else {
- let part_end = InlayOffset(part_start.0 + part_len);
- return Some((part, part_start..part_end));
- }
+ offset_in_label: usize,
+) -> Option<(InlayHintLabelPart, Range<usize>)> {
+ let mut part_start = 0;
+ for part in label_parts {
+ let part_end = part_start + part.value.len();
+ if (part_start..part_end).contains(&offset_in_label) {
+ return Some((part, part_start..part_end));
}
+ part_start = part_end;
}
None
}
@@ -162,107 +156,64 @@ pub fn hover_at_inlay(
inlay_hover: InlayHover,
window: &mut Window,
cx: &mut Context<Editor>,
-) {
- if EditorSettings::get_global(cx).hover_popover_enabled {
- if editor.pending_rename.is_some() {
- return;
- }
-
- let Some(project) = editor.project.clone() else {
- return;
- };
-
- if editor
- .hover_state
- .info_popovers
- .iter()
- .any(|InfoPopover { symbol_range, .. }| {
- if let RangeInEditor::Inlay(range) = symbol_range
- && range == &inlay_hover.range
- {
- // Hover triggered from same location as last time. Don't show again.
- return true;
- }
- false
- })
- {
- return;
- }
-
- let hover_popover_delay = EditorSettings::get_global(cx).hover_popover_delay.0;
+) -> Option<Task<()>> {
+ if !EditorSettings::get_global(cx).hover_popover_enabled || editor.pending_rename.is_some() {
+ return None;
+ }
+ let project = editor.project.clone()?;
+ let symbol_range = RangeInEditor::Inlay(inlay_hover.range);
+ if editor
+ .hover_state
+ .info_popovers
+ .iter()
+ .any(|popover| popover.symbol_range == symbol_range)
+ {
editor.hover_state.hiding_delay_task = None;
- editor.hover_state.closest_mouse_distance = None;
-
- let task = cx.spawn_in(window, async move |this, cx| {
- async move {
- cx.background_executor()
- .timer(Duration::from_millis(hover_popover_delay))
- .await;
- this.update(cx, |this, _| {
- this.hover_state.diagnostic_popover = None;
- })?;
-
- let language_registry = project.read_with(cx, |p, _| p.languages().clone());
- let blocks = vec![inlay_hover.tooltip];
- let parsed_content = parse_blocks(&blocks, Some(&language_registry), None, cx);
+ return Some(Task::ready(()));
+ }
- let scroll_handle = ScrollHandle::new();
+ let hover_popover_delay = EditorSettings::get_global(cx).hover_popover_delay.0;
- let subscription = this
- .update(cx, |_, cx| {
- parsed_content.as_ref().map(|parsed_content| {
- cx.observe(parsed_content, |_, _, cx| cx.notify())
- })
- })
- .ok()
- .flatten();
+ editor.hover_state.info_task = None;
+ editor.hover_state.hiding_delay_task = None;
+ editor.hover_state.closest_mouse_distance = None;
- let hover_popover = InfoPopover {
- symbol_range: RangeInEditor::Inlay(inlay_hover.range.clone()),
+ Some(cx.spawn_in(window, async move |editor, cx| {
+ cx.background_executor()
+ .timer(Duration::from_millis(hover_popover_delay))
+ .await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ let parsed_content =
+ parse_blocks(&[inlay_hover.tooltip], Some(&language_registry), None, cx);
+
+ editor
+ .update(cx, |editor, cx| {
+ let subscription = parsed_content
+ .as_ref()
+ .map(|parsed_content| cx.observe(parsed_content, |_, _, cx| cx.notify()));
+ editor.hover_state.diagnostic_popover = None;
+ editor.hover_state.info_popovers = vec![InfoPopover {
+ symbol_range,
parsed_content,
- scroll_handle,
+ scroll_handle: ScrollHandle::new(),
keyboard_grace: Rc::new(RefCell::new(false)),
anchor: None,
last_bounds: Rc::new(Cell::new(None)),
_subscription: subscription,
- };
-
- this.update(cx, |this, cx| {
- // TODO: no background highlights happen for inlays currently
- this.hover_state.info_popovers = vec![hover_popover];
- cx.notify();
- })?;
-
- anyhow::Ok(())
- }
- .log_err()
- .await
- });
-
- editor.hover_state.info_task = Some(task);
- }
+ }];
+ cx.notify();
+ })
+ .ok();
+ }))
}
/// Hides the type information popup.
/// Triggered by the `Hover` action when the cursor is not over a symbol or when the
/// selections changed.
pub fn hide_hover(editor: &mut Editor, cx: &mut Context<Editor>) -> bool {
- let info_popovers = editor.hover_state.info_popovers.drain(..);
- let diagnostics_popover = editor.hover_state.diagnostic_popover.take();
- let did_hide = info_popovers.count() > 0 || diagnostics_popover.is_some();
-
- editor.hover_state.info_task = None;
- editor.hover_state.hiding_delay_task = None;
- editor.hover_state.closest_mouse_distance = None;
-
- editor.clear_background_highlights(HighlightKey::HoverState, cx);
-
- if did_hide {
- cx.notify();
- }
-
- did_hide
+ editor.hover_state.hint_hover_task = None;
+ hide_popovers(editor, cx)
}
/// Queries the LSP and shows type info and documentation
@@ -275,6 +226,7 @@ fn show_hover(
window: &mut Window,
cx: &mut Context<Editor>,
) -> Option<()> {
+ editor.hover_state.hint_hover_task = None;
if editor.pending_rename.is_some() {
return None;
}
@@ -1087,6 +1039,7 @@ pub struct HoverState {
pub info_task: Option<Task<Option<()>>>,
pub closest_mouse_distance: Option<Pixels>,
pub hiding_delay_task: Option<Task<()>>,
+ pub(crate) hint_hover_task: Option<Task<()>>,
}
impl HoverState {
@@ -1288,6 +1241,7 @@ impl InfoPopover {
this.update(cx, |editor, _| {
editor.hover_state.closest_mouse_distance = Some(px(0.0));
editor.hover_state.hiding_delay_task = None;
+ editor.hover_state.hint_hover_task = None;
})
.ok();
cx.stop_propagation()
@@ -1400,6 +1354,7 @@ impl DiagnosticPopover {
this.update(cx, |editor, _| {
editor.hover_state.closest_mouse_distance = Some(px(0.0));
editor.hover_state.hiding_delay_task = None;
+ editor.hover_state.hint_hover_task = None;
})
.ok();
cx.stop_propagation()
@@ -1472,21 +1427,40 @@ impl DiagnosticPopover {
}
}
+fn hide_popovers(editor: &mut Editor, cx: &mut Context<Editor>) -> bool {
+ let info_popovers = editor.hover_state.info_popovers.drain(..);
+ let diagnostics_popover = editor.hover_state.diagnostic_popover.take();
+ let did_hide = info_popovers.count() > 0 || diagnostics_popover.is_some();
+
+ editor.hover_state.info_task = None;
+ editor.hover_state.hiding_delay_task = None;
+ editor.hover_state.closest_mouse_distance = None;
+
+ editor.clear_background_highlights(HighlightKey::HoverState, cx);
+
+ if did_hide {
+ cx.notify();
+ }
+
+ did_hide
+}
+
#[cfg(test)]
mod tests {
use super::*;
use crate::{
- PointForPosition,
- actions::ConfirmCompletion,
+ actions::{Cancel, ConfirmCompletion},
editor_tests::{handle_completion_request, init_test},
inlays::inlay_hints::tests::{cached_hint_labels, visible_hint_labels},
test::editor_lsp_test_context::EditorLspTestContext,
};
use collections::BTreeSet;
- use futures::stream::StreamExt;
- use gpui::App;
+ use futures::{channel::oneshot, stream::StreamExt};
+ use gpui::{App, Modifiers};
use indoc::indoc;
+ use language::{FakeLspAdapter, rust_lang};
use markdown::parser::MarkdownEvent;
+ use parking_lot::Mutex;
use project::InlayId;
use settings::InlayHintSettingsContent;
use settings::{DelayMs, SettingsStore};
@@ -2504,15 +2478,39 @@ mod tests {
})
});
- let mut cx = EditorLspTestContext::new_rust(
- lsp::ServerCapabilities {
- inlay_hint_provider: Some(lsp::OneOf::Right(
- lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
- resolve_provider: Some(true),
- ..Default::default()
- }),
- )),
- ..Default::default()
+ let resolved_hint_label = Arc::new(Mutex::new(None::<lsp::InlayHintLabel>));
+ let mut cx = EditorLspTestContext::new_with_adapter(
+ Arc::into_inner(rust_lang()).expect("test language"),
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ inlay_hint_provider: Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ }),
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new({
+ let resolved_hint_label = resolved_hint_label.clone();
+ move |server| {
+ let resolved_hint_label = resolved_hint_label.clone();
+ let mut resolved_hint_positions = BTreeSet::new();
+ server.set_request_handler::<lsp::request::InlayHintResolveRequest, _, _>(
+ move |mut hint_to_resolve, _| {
+ let inserted =
+ resolved_hint_positions.insert(hint_to_resolve.position);
+ assert!(inserted, "Hint {hint_to_resolve:?} was resolved twice");
+ hint_to_resolve.label = resolved_hint_label
+ .lock()
+ .clone()
+ .expect("resolved hint label");
+ async move { Ok(hint_to_resolve) }
+ },
+ );
+ }
+ })),
+ ..FakeLspAdapter::default()
},
cx,
)
@@ -2570,6 +2568,46 @@ mod tests {
let new_type_label = "TestNewType";
let struct_label = "TestStruct";
let entire_hint_label = ": TestNewType<TestStruct>";
+ // `: TestNewType<TestStruct>`
+ *resolved_hint_label.lock() = Some(lsp::InlayHintLabel::LabelParts(vec![
+ lsp::InlayHintLabelPart {
+ value: ": ".to_string(),
+ ..lsp::InlayHintLabelPart::default()
+ },
+ lsp::InlayHintLabelPart {
+ value: new_type_label.to_string(),
+ location: Some(lsp::Location {
+ uri: uri.clone(),
+ range: new_type_target_range,
+ }),
+ tooltip: Some(lsp::InlayHintLabelPartTooltip::String(format!(
+ "A tooltip for `{new_type_label}`"
+ ))),
+ ..lsp::InlayHintLabelPart::default()
+ },
+ lsp::InlayHintLabelPart {
+ value: "<".to_string(),
+ ..lsp::InlayHintLabelPart::default()
+ },
+ lsp::InlayHintLabelPart {
+ value: struct_label.to_string(),
+ location: Some(lsp::Location {
+ uri: uri.clone(),
+ range: struct_target_range,
+ }),
+ tooltip: Some(lsp::InlayHintLabelPartTooltip::MarkupContent(
+ lsp::MarkupContent {
+ kind: lsp::MarkupKind::Markdown,
+ value: format!("A tooltip for `{struct_label}`"),
+ },
+ )),
+ ..lsp::InlayHintLabelPart::default()
+ },
+ lsp::InlayHintLabelPart {
+ value: ">".to_string(),
+ ..lsp::InlayHintLabelPart::default()
+ },
+ ]));
let closure_uri = uri.clone();
cx.lsp
.set_request_handler::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
@@ -2615,289 +2653,408 @@ mod tests {
.first()
.cloned()
.unwrap();
- let new_type_hint_part_hover_position = cx.update_editor(|editor, window, cx| {
- let snapshot = editor.snapshot(window, cx);
- let previous_valid = MultiBufferOffset(inlay_range.start).to_display_point(&snapshot);
- let next_valid = MultiBufferOffset(inlay_range.end).to_display_point(&snapshot);
- assert_eq!(previous_valid.row(), next_valid.row());
- assert!(previous_valid.column() < next_valid.column());
- let exact_unclipped = DisplayPoint::new(
- previous_valid.row(),
- previous_valid.column()
- + (entire_hint_label.find(new_type_label).unwrap() + new_type_label.len() / 2)
- as u32,
- );
- PointForPosition {
- previous_valid,
- next_valid,
- nearest_valid: previous_valid,
- exact_unclipped,
- column_overshoot_after_line_end: 0,
- }
- });
- cx.update_editor(|editor, window, cx| {
- editor.update_inlay_link_and_hover_points(
- &editor.snapshot(window, cx),
- new_type_hint_part_hover_position,
- None,
- true,
- false,
- window,
- cx,
- );
- });
+ for (label, range) in [(new_type_label, 2..13), (struct_label, 14..24)] {
+ cx.update_editor(|editor, window, cx| {
+ let snapshot = editor.snapshot(window, cx);
+ let start = MultiBufferOffset(inlay_range.start).to_display_point(&snapshot);
+ let hover_position = DisplayPoint::new(
+ start.row(),
+ start.column() + ((range.start + range.end) / 2) as u32,
+ );
+ editor.update_inlay_link_and_hover_points(
+ &snapshot,
+ Some(hover_position),
+ None,
+ true,
+ false,
+ window,
+ cx,
+ );
+ });
+ cx.background_executor
+ .advance_clock(Duration::from_millis(get_hover_popover_delay(&cx) + 100));
+ cx.update_editor(|editor, _, cx| {
+ assert!(editor.hover_state.diagnostic_popover.is_none());
+ assert_eq!(editor.hover_state.info_popovers.len(), 1);
+ let popover = &editor.hover_state.info_popovers[0];
+ let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
+ assert_eq!(
+ popover.symbol_range,
+ RangeInEditor::Inlay(InlayHighlight {
+ inlay: InlayId::Hint(0),
+ inlay_position: buffer_snapshot
+ .anchor_after(MultiBufferOffset(inlay_range.start)),
+ range,
+ }),
+ "{label}"
+ );
+ assert_eq!(
+ popover.get_rendered_text(cx),
+ format!("A tooltip for {label}")
+ );
+ });
+ }
+ }
- let resolve_closure_uri = uri.clone();
- cx.lsp
- .set_request_handler::<lsp::request::InlayHintResolveRequest, _, _>(
- move |mut hint_to_resolve, _| {
- let mut resolved_hint_positions = BTreeSet::new();
- let task_uri = resolve_closure_uri.clone();
- async move {
- let inserted = resolved_hint_positions.insert(hint_to_resolve.position);
- assert!(inserted, "Hint {hint_to_resolve:?} was resolved twice");
-
- // `: TestNewType<TestStruct>`
- hint_to_resolve.label = lsp::InlayHintLabel::LabelParts(vec![
- lsp::InlayHintLabelPart {
- value: ": ".to_string(),
- ..Default::default()
- },
- lsp::InlayHintLabelPart {
- value: new_type_label.to_string(),
- location: Some(lsp::Location {
- uri: task_uri.clone(),
- range: new_type_target_range,
- }),
- tooltip: Some(lsp::InlayHintLabelPartTooltip::String(format!(
- "A tooltip for `{new_type_label}`"
- ))),
- ..Default::default()
- },
- lsp::InlayHintLabelPart {
- value: "<".to_string(),
- ..Default::default()
+ #[gpui::test]
+ async fn test_hover_pending_hint_survives_previous_popover_hiding(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ init_test(cx, |settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(0),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ })
+ });
+ let resolve_gate = Arc::new(Mutex::new(None::<oneshot::Receiver<()>>));
+ let hover_gate = Arc::new(Mutex::new(None::<oneshot::Receiver<()>>));
+ let mut cx = EditorLspTestContext::new_with_adapter(
+ Arc::into_inner(rust_lang()).expect("test language"),
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
+ inlay_hint_provider: Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ }),
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new({
+ let resolve_gate = resolve_gate.clone();
+ let hover_gate = hover_gate.clone();
+ move |server| {
+ server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |_, _| async move {
+ Ok(Some(
+ [
+ (17, "a", false),
+ (28, "b", true),
+ (39, "c", true),
+ (50, "d", true),
+ (61, "e", false),
+ (72, "f", true),
+ (83, "g", true),
+ (94, "h", true),
+ ]
+ .into_iter()
+ .map(|(column, name, resolve_tooltip)| lsp::InlayHint {
+ position: lsp::Position::new(0, column),
+ label: lsp::InlayHintLabel::String(format!(": {name}")),
+ kind: Some(lsp::InlayHintKind::TYPE),
+ text_edits: None,
+ tooltip: (!resolve_tooltip).then(|| {
+ lsp::InlayHintTooltip::String(format!("tooltip {name}"))
+ }),
+ padding_left: None,
+ padding_right: None,
+ data: resolve_tooltip
+ .then_some(serde_json::Value::Bool(true)),
+ })
+ .collect(),
+ ))
},
- lsp::InlayHintLabelPart {
- value: struct_label.to_string(),
- location: Some(lsp::Location {
- uri: task_uri,
- range: struct_target_range,
- }),
- tooltip: Some(lsp::InlayHintLabelPartTooltip::MarkupContent(
- lsp::MarkupContent {
- kind: lsp::MarkupKind::Markdown,
- value: format!("A tooltip for `{struct_label}`"),
- },
- )),
- ..Default::default()
+ );
+ let resolve_gate = resolve_gate.clone();
+ server.set_request_handler::<lsp::request::InlayHintResolveRequest, _, _>(
+ move |mut hint, _| {
+ let resolve_gate = resolve_gate.lock().take();
+ if hint.data.is_some()
+ && let lsp::InlayHintLabel::String(label) = &hint.label
+ {
+ hint.tooltip = Some(lsp::InlayHintTooltip::String(format!(
+ "tooltip {}",
+ label.trim_start_matches(": ")
+ )));
+ }
+ async move {
+ if let Some(resolve_gate) = resolve_gate {
+ resolve_gate.await?;
+ }
+ Ok(hint)
+ }
},
- lsp::InlayHintLabelPart {
- value: ">".to_string(),
- ..Default::default()
+ );
+ let hover_gate = hover_gate.clone();
+ server.set_request_handler::<lsp::request::HoverRequest, _, _>(
+ move |_, _| {
+ let hover_gate = hover_gate.lock().take();
+ async move {
+ if let Some(hover_gate) = hover_gate {
+ hover_gate.await?;
+ }
+ Ok(Some(lsp::Hover {
+ contents: lsp::HoverContents::Scalar(
+ lsp::MarkedString::String("text hover".to_string()),
+ ),
+ range: Some(lsp::Range::new(
+ lsp::Position::new(0, 3),
+ lsp::Position::new(0, 7),
+ )),
+ }))
+ }
},
- ]);
-
- Ok(hint_to_resolve)
+ );
}
- },
- )
- .next()
- .await;
- cx.background_executor.run_until_parked();
-
- cx.update_editor(|editor, window, cx| {
- editor.update_inlay_link_and_hover_points(
- &editor.snapshot(window, cx),
- new_type_hint_part_hover_position,
- None,
- true,
- false,
- window,
- cx,
+ })),
+ ..FakeLspAdapter::default()
+ },
+ cx,
+ )
+ .await;
+ cx.set_state(
+ "fn main() { let aˇ = 1; let b = 2; let c = 3; let d = 4; let e = 5; let f = 6; let g = 7; let h = 8; }\n",
+ );
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(
+ visible_hint_labels(editor, cx),
+ vec![": a", ": b", ": c", ": d", ": e", ": f", ": g", ": h"]
);
});
- cx.background_executor
- .advance_clock(Duration::from_millis(get_hover_popover_delay(&cx) + 100));
- cx.background_executor.run_until_parked();
+ let hover_delay = Duration::from_millis(get_hover_popover_delay(&cx) + 100);
+ let hiding_delay = cx.read(|cx| {
+ Duration::from_millis(EditorSettings::get_global(cx).hover_popover_hiding_delay.0 + 100)
+ });
+
+ let hint_a_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 18));
+ cx.simulate_mouse_move(hint_a_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(rendered_popovers(editor, cx), vec!["tooltip a"]);
+ });
+
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ let hint_b_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 33));
+ cx.simulate_mouse_move(hint_b_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hiding_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(rendered_popovers(editor, cx), Vec::<String>::new());
+ });
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(rendered_popovers(editor, cx), vec!["tooltip b"]);
+ });
+
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ let hint_c_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 46));
+ cx.simulate_mouse_move(hint_c_point, None, Modifiers::none());
+ cx.dispatch_action(Cancel);
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(rendered_popovers(editor, cx), Vec::<String>::new());
+ });
+
+ cx.simulate_mouse_move(hint_a_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ let popover_a_center = cx.update_editor(|editor, _, cx| {
+ assert_eq!(rendered_popovers(editor, cx), vec!["tooltip a"]);
+ editor.hover_state.info_popovers[0]
+ .last_bounds
+ .get()
+ .expect("painted popover bounds")
+ .center()
+ });
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ let hint_d_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 60));
+ cx.simulate_mouse_move(hint_d_point, None, Modifiers::none());
+ cx.update_editor(|editor, _, _| {
+ assert!(editor.hover_state.hint_hover_task.is_some());
+ });
+ cx.simulate_mouse_move(popover_a_center, None, Modifiers::none());
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.background_executor.advance_clock(hover_delay);
cx.update_editor(|editor, _, cx| {
- let hover_state = &editor.hover_state;
- assert!(
- hover_state.diagnostic_popover.is_none() && hover_state.info_popovers.len() == 1
- );
- let popover = hover_state.info_popovers.first().unwrap();
- let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
assert_eq!(
- popover.symbol_range,
- RangeInEditor::Inlay(InlayHighlight {
- inlay: InlayId::Hint(0),
- inlay_position: buffer_snapshot
- .anchor_after(MultiBufferOffset(inlay_range.start)),
- range: ": ".len()..": ".len() + new_type_label.len(),
- }),
- "Popover range should match the new type label part"
+ rendered_popovers(editor, cx),
+ vec!["tooltip a"],
+ "entering the shown popover cancels the pending hint hover"
);
+ });
+
+ let hint_e_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 74));
+ cx.simulate_mouse_move(hint_e_point, None, Modifiers::none());
+ cx.update_editor(|editor, _, _| {
+ assert!(editor.hover_state.hint_hover_task.is_some());
+ });
+ cx.simulate_mouse_move(popover_a_center, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
assert_eq!(
- popover.get_rendered_text(cx),
- format!("A tooltip for {new_type_label}"),
+ rendered_popovers(editor, cx),
+ vec!["tooltip a"],
+ "entering the shown popover cancels the delayed resolved hint hover"
);
});
- let struct_hint_part_hover_position = cx.update_editor(|editor, window, cx| {
- let snapshot = editor.snapshot(window, cx);
- let previous_valid = MultiBufferOffset(inlay_range.start).to_display_point(&snapshot);
- let next_valid = MultiBufferOffset(inlay_range.end).to_display_point(&snapshot);
- assert_eq!(previous_valid.row(), next_valid.row());
- assert!(previous_valid.column() < next_valid.column());
- let exact_unclipped = DisplayPoint::new(
- previous_valid.row(),
- previous_valid.column()
- + (entire_hint_label.find(struct_label).unwrap() + struct_label.len() / 2)
- as u32,
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ let hint_f_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 88));
+ cx.simulate_mouse_move(hint_f_point, None, Modifiers::none());
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, cx| {
+ assert!(editor.hover_state.hint_hover_task.is_some());
+ assert_eq!(rendered_popovers(editor, cx), vec!["tooltip a"]);
+ });
+ cx.simulate_mouse_move(hint_a_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(
+ rendered_popovers(editor, cx),
+ vec!["tooltip a"],
+ "returning to the shown hint cancels the delayed hover of the hint left behind"
);
- PointForPosition {
- previous_valid,
- next_valid,
- nearest_valid: previous_valid,
- exact_unclipped,
- column_overshoot_after_line_end: 0,
- }
});
- cx.update_editor(|editor, window, cx| {
- editor.update_inlay_link_and_hover_points(
- &editor.snapshot(window, cx),
- struct_hint_part_hover_position,
- None,
- true,
- false,
- window,
- cx,
+
+ let text_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 4));
+ cx.simulate_mouse_move(text_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(rendered_popovers(editor, cx), vec!["text hover"]);
+ });
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ let hint_g_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 102));
+ cx.simulate_mouse_move(hint_g_point, None, Modifiers::none());
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, cx| {
+ assert!(editor.hover_state.hint_hover_task.is_some());
+ assert_eq!(rendered_popovers(editor, cx), vec!["text hover"]);
+ });
+ cx.simulate_mouse_move(text_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(
+ rendered_popovers(editor, cx),
+ vec!["text hover"],
+ "returning to the hovered text cancels the delayed hover of the hint left behind"
);
});
- cx.background_executor
- .advance_clock(Duration::from_millis(get_hover_popover_delay(&cx) + 100));
- cx.background_executor.run_until_parked();
+
+ cx.dispatch_action(Cancel);
+ cx.update(|_, cx| crate::set_diagnostic_renderer(TestDiagnosticRenderer, cx));
+ cx.lsp
+ .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
+ uri: cx.buffer_lsp_url.clone(),
+ diagnostics: vec![lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 7)),
+ severity: Some(lsp::DiagnosticSeverity::ERROR),
+ message: lsp::DiagnosticMessage::from("diagnostic".to_string()),
+ ..lsp::Diagnostic::default()
+ }],
+ version: None,
+ });
+ cx.run_until_parked();
+ cx.simulate_mouse_move(text_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ let diagnostic_popover_center = cx.update_editor(|editor, _, cx| {
+ assert_eq!(rendered_popovers(editor, cx), vec!["text hover"]);
+ editor
+ .hover_state
+ .diagnostic_popover
+ .as_ref()
+ .expect("diagnostic popover")
+ .last_bounds
+ .get()
+ .expect("painted diagnostic popover bounds")
+ .center()
+ });
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ let hint_h_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(0), 116));
+ cx.simulate_mouse_move(hint_h_point, None, Modifiers::none());
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, _| {
+ assert!(editor.hover_state.hint_hover_task.is_some());
+ assert!(editor.hover_state.diagnostic_popover.is_some());
+ });
+ cx.simulate_mouse_move(diagnostic_popover_center, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
cx.update_editor(|editor, _, cx| {
- let hover_state = &editor.hover_state;
assert!(
- hover_state.diagnostic_popover.is_none() && hover_state.info_popovers.len() == 1
- );
- let popover = hover_state.info_popovers.first().unwrap();
- let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
- assert_eq!(
- popover.symbol_range,
- RangeInEditor::Inlay(InlayHighlight {
- inlay: InlayId::Hint(0),
- inlay_position: buffer_snapshot
- .anchor_after(MultiBufferOffset(inlay_range.start)),
- range: ": ".len() + new_type_label.len() + "<".len()
- ..": ".len() + new_type_label.len() + "<".len() + struct_label.len(),
- }),
- "Popover range should match the struct label part"
+ editor.hover_state.diagnostic_popover.is_some(),
+ "entering the diagnostic popover cancels the delayed hint hover"
);
+ assert_eq!(rendered_popovers(editor, cx), vec!["text hover"]);
+ });
+
+ cx.dispatch_action(Cancel);
+ let (release_hover, gate) = oneshot::channel();
+ *hover_gate.lock() = Some(gate);
+ cx.simulate_mouse_move(text_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert!(editor.hover_state.info_task.is_some());
+ assert_eq!(rendered_popovers(editor, cx), Vec::<String>::new());
+ });
+ cx.simulate_mouse_move(hint_e_point, None, Modifiers::none());
+ cx.background_executor.advance_clock(hover_delay);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(rendered_popovers(editor, cx), vec!["tooltip e"]);
+ });
+ release_hover.send(()).ok();
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, cx| {
assert_eq!(
- popover.get_rendered_text(cx),
- format!("A tooltip for {struct_label}"),
- "Rendered markdown element should remove backticks from text"
+ rendered_popovers(editor, cx),
+ vec!["tooltip e"],
+ "a pending text hover must not replace the hint tooltip"
);
});
}
#[test]
fn test_find_hovered_hint_part_with_multibyte_characters() {
- use crate::display_map::InlayOffset;
- use multi_buffer::MultiBufferOffset;
- use project::InlayHintLabelPart;
-
- // Test with multi-byte UTF-8 character "→" (3 bytes, 1 character)
- let label = "→ app/Livewire/UserProfile.php";
- let label_parts = vec![InlayHintLabelPart {
- value: label.to_string(),
- tooltip: None,
- location: None,
- command: None,
- }];
-
- let hint_start = InlayOffset(MultiBufferOffset(100));
-
- // Verify the label has more bytes than characters (due to "→")
- assert_eq!(label.len(), 32); // bytes
- assert_eq!(label.chars().count(), 30); // characters
-
- // Test hovering at the last byte (should find the part)
- let last_byte_offset = InlayOffset(MultiBufferOffset(100 + label.len() - 1));
- let result = find_hovered_hint_part(label_parts.clone(), hint_start, last_byte_offset);
- assert!(
- result.is_some(),
- "Should find part when hovering at last byte"
- );
- let (part, range) = result.unwrap();
- assert_eq!(part.value, label);
- assert_eq!(range.start, hint_start);
- assert_eq!(range.end, InlayOffset(MultiBufferOffset(100 + label.len())));
-
- // Test hovering at the first byte of "→" (byte 0)
- let first_byte_offset = InlayOffset(MultiBufferOffset(100));
- let result = find_hovered_hint_part(label_parts.clone(), hint_start, first_byte_offset);
- assert!(
- result.is_some(),
- "Should find part when hovering at first byte"
- );
-
- // Test hovering in the middle of "→" (byte 1, still part of the arrow character)
- let mid_arrow_offset = InlayOffset(MultiBufferOffset(101));
- let result = find_hovered_hint_part(label_parts, hint_start, mid_arrow_offset);
- assert!(
- result.is_some(),
- "Should find part when hovering in middle of multi-byte char"
- );
-
- // Test with multiple parts containing multi-byte characters
- // Part ranges are [start, end) - start inclusive, end exclusive
- // "→ " occupies bytes [0, 4), "path" occupies bytes [4, 8)
- let parts = vec![
- InlayHintLabelPart {
- value: "→ ".to_string(), // 4 bytes (3 + 1)
- tooltip: None,
- location: None,
- command: None,
- },
- InlayHintLabelPart {
- value: "path".to_string(), // 4 bytes
- tooltip: None,
- location: None,
- command: None,
- },
- ];
-
- // Hover at byte 3 (last byte of "→ ", the space character)
- let arrow_last_byte = InlayOffset(MultiBufferOffset(100 + 3));
- let result = find_hovered_hint_part(parts.clone(), hint_start, arrow_last_byte);
- assert!(result.is_some(), "Should find first part at its last byte");
- let (part, range) = result.unwrap();
- assert_eq!(part.value, "→ ");
- assert_eq!(
- range,
- InlayOffset(MultiBufferOffset(100))..InlayOffset(MultiBufferOffset(104))
- );
-
- // Hover at byte 4 (first byte of "path", at the boundary)
- let path_start_offset = InlayOffset(MultiBufferOffset(100 + 4));
- let result = find_hovered_hint_part(parts.clone(), hint_start, path_start_offset);
- assert!(result.is_some(), "Should find second part at boundary");
- let (part, _) = result.unwrap();
- assert_eq!(part.value, "path");
-
- // Hover at byte 7 (last byte of "path")
- let path_end_offset = InlayOffset(MultiBufferOffset(100 + 7));
- let result = find_hovered_hint_part(parts, hint_start, path_end_offset);
- assert!(result.is_some(), "Should find second part at last byte");
- let (part, range) = result.unwrap();
- assert_eq!(part.value, "path");
- assert_eq!(
- range,
- InlayOffset(MultiBufferOffset(104))..InlayOffset(MultiBufferOffset(108))
- );
+ for (parts, end) in [
+ (vec![("→ app/Livewire/UserProfile.php", 0..32)], 32),
+ (
+ vec![
+ ("", 0..0),
+ ("→ ", 0..4),
+ ("", 4..4),
+ ("path", 4..8),
+ ("", 8..8),
+ ],
+ 8,
+ ),
+ (vec![("é", 0..2), ("🦀", 2..6)], 6),
+ (vec![("", 0..0)], 0),
+ (Vec::new(), 0),
+ ] {
+ let label_parts = parts
+ .iter()
+ .map(|(value, _)| InlayHintLabelPart {
+ value: value.to_string(),
+ tooltip: None,
+ location: None,
+ command: None,
+ })
+ .collect::<Vec<_>>();
+ for (value, range) in parts {
+ for offset in range.clone() {
+ let result = find_hovered_hint_part(label_parts.clone(), offset);
+ assert_eq!(
+ result.map(|(part, range)| (part.value, range)),
+ Some((value.to_string(), range.clone())),
+ "offset {offset}"
+ );
+ }
+ }
+ for offset in [end, usize::MAX] {
+ assert!(find_hovered_hint_part(label_parts.clone(), offset).is_none());
+ }
+ }
}
#[gpui::test]
@@ -3348,4 +3505,49 @@ mod tests {
);
assert_eq!(parse_file_link("http://example.com/"), None,);
}
+
+ struct TestDiagnosticRenderer;
+
+ impl crate::DiagnosticRenderer for TestDiagnosticRenderer {
+ fn render_group(
+ &self,
+ _: Vec<language::DiagnosticEntryRef<'_, text::Point>>,
+ _: text::BufferId,
+ _: EditorSnapshot,
+ _: gpui::WeakEntity<Editor>,
+ _: Option<std::sync::Arc<language::LanguageRegistry>>,
+ _: &mut App,
+ ) -> Vec<crate::display_map::BlockProperties<Anchor>> {
+ Vec::new()
+ }
+
+ fn render_hover(
+ &self,
+ _: Vec<language::DiagnosticEntryRef<'_, text::Point>>,
+ _: Range<text::Point>,
+ _: text::BufferId,
+ _: Option<std::sync::Arc<language::LanguageRegistry>>,
+ cx: &mut App,
+ ) -> Option<Entity<Markdown>> {
+ Some(cx.new(|cx| Markdown::new("diagnostic".into(), None, None, cx)))
+ }
+
+ fn open_link(
+ &self,
+ _: &mut Editor,
+ _: SharedString,
+ _: &mut Window,
+ _: &mut Context<Editor>,
+ ) {
+ }
+ }
+
+ fn rendered_popovers(editor: &Editor, cx: &mut App) -> Vec<String> {
+ editor
+ .hover_state
+ .info_popovers
+ .iter()
+ .map(|popover| popover.get_rendered_text(cx))
+ .collect()
+ }
}
diff --git a/crates/editor/src/inlays.rs b/crates/editor/src/inlays.rs
index f1e107529c4..4c42ee50259 100644
--- a/crates/editor/src/inlays.rs
+++ b/crates/editor/src/inlays.rs
@@ -160,9 +160,13 @@ impl Editor {
for id_to_remove in to_remove {
inlay_hints.remove_inlay(id_to_remove);
}
+ inlay_hints.remove_pending_text_edit(|target| {
+ to_remove.contains(&target.hint_id)
+ && !to_insert.iter().any(|inlay| inlay.id == target.hint_id)
+ });
}
self.display_map.update(cx, |display_map, cx| {
- display_map.splice_inlays(to_remove, to_insert, cx)
+ display_map.splice_inlays(to_remove, to_insert, cx);
});
cx.notify();
}
diff --git a/crates/editor/src/inlays/inlay_hints.rs b/crates/editor/src/inlays/inlay_hints.rs
index 7a819c46a6d..cc9c02eee6e 100644
--- a/crates/editor/src/inlays/inlay_hints.rs
+++ b/crates/editor/src/inlays/inlay_hints.rs
@@ -6,7 +6,11 @@ use std::{
use clock::Global;
use collections::{HashMap, HashSet};
-use futures::future::join_all;
+use futures::{
+ FutureExt as _,
+ channel::oneshot,
+ future::{Shared, join_all},
+};
use gpui::{App, Entity, Pixels, Task, TaskExt};
use itertools::Itertools;
use language::{
@@ -18,16 +22,16 @@ use multi_buffer::{Anchor, MultiBufferSnapshot};
use project::{
CodeAction, HoverBlock, HoverBlockKind, InlayHint, InlayHintLabel, InlayHintLabelPartTooltip,
InlayHintTooltip, InvalidationStrategy, LspAction, ResolveState,
- lsp_store::{CacheInlayHints, ResolvedHint},
+ lsp_store::{CacheInlayHints, LspStore, ResolvedHint},
};
use text::{Bias, BufferId, ToOffset};
use ui::{Context, Window};
-use util::debug_panic;
use super::{Inlay, InlayId};
use crate::{
- Editor, EditorSnapshot, PointForPosition, ToggleInlayHints, ToggleInlineValues, debounce_value,
- display_map::{DisplayMap, InlayOffset},
+ AcceptInlayHint, DisplayPoint, Editor, EditorSnapshot, ToggleInlayHints, ToggleInlineValues,
+ debounce_value,
+ display_map::{DisplayMap, DisplaySnapshot},
hover_links::{InlayHighlight, TriggerPoint, show_link_definition},
hover_popover::{self, InlayHover},
inlays::InlaySplice,
@@ -41,23 +45,20 @@ pub(crate) struct HoveredInlayHintCommand {
}
impl HoveredInlayHintCommand {
- pub(crate) fn contains_point(
+ pub(crate) fn contains_glyph(
&self,
snapshot: &EditorSnapshot,
- point_for_position: PointForPosition,
+ hint_glyph: Option<DisplayPoint>,
) -> bool {
- if point_for_position.column_overshoot_after_line_end != 0
- || point_for_position.as_valid().is_some()
- || !snapshot.can_resolve(&self.highlight.inlay_position)
- {
+ if !snapshot.can_resolve(&self.highlight.inlay_position) {
return false;
}
- let hovered_offset =
- snapshot.display_point_to_inlay_offset(point_for_position.exact_unclipped, Bias::Left);
- let hint_start = snapshot.anchor_to_inlay_offset(self.highlight.inlay_position);
- let part_range = InlayOffset(hint_start.0 + self.highlight.range.start)
- ..InlayOffset(hint_start.0 + self.highlight.range.end);
- part_range.contains(&hovered_offset)
+ let Some((hint, offset_in_hint)) =
+ hint_glyph.and_then(|glyph| snapshot.inlay_hint_at(glyph))
+ else {
+ return false;
+ };
+ hint.id == self.highlight.inlay && self.highlight.range.contains(&offset_in_hint)
}
}
@@ -77,11 +78,32 @@ pub struct LspInlayHintData {
allowed_hint_kinds: HashSet<Option<InlayHintKind>>,
invalidate_debounce: Option<Duration>,
append_debounce: Option<Duration>,
- hint_refresh_tasks: HashMap<BufferId, Vec<Task<()>>>,
+ hint_refresh_tasks: HashMap<BufferId, Vec<HintRefreshTask>>,
hint_chunk_fetching: HashMap<BufferId, (Global, HashSet<Range<BufferRow>>)>,
invalidate_hints_for_buffers: HashSet<BufferId>,
pub added_hints: HashMap<InlayId, Option<InlayHintKind>>,
hovered_command: Option<HoveredInlayHintCommand>,
+ pending_text_edit: Option<PendingHintTextEdit>,
+ pending_refresh_acceptance: Option<(HashSet<BufferId>, Task<()>)>,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct HintTarget {
+ pub buffer_id: BufferId,
+ pub hint_id: InlayId,
+ pub position: Anchor,
+}
+
+#[derive(Debug)]
+struct HintRefreshTask {
+ task: Task<()>,
+ finished: Shared<oneshot::Receiver<()>>,
+}
+
+#[derive(Debug)]
+struct PendingHintTextEdit {
+ target: HintTarget,
+ _apply_task: Task<()>,
}
impl LspInlayHintData {
@@ -98,6 +120,8 @@ impl LspInlayHintData {
append_debounce: debounce_value(settings.scroll_debounce_ms),
allowed_hint_kinds: settings.enabled_inlay_hint_kinds(),
hovered_command: None,
+ pending_text_edit: None,
+ pending_refresh_acceptance: None,
}
}
@@ -131,6 +155,8 @@ impl LspInlayHintData {
self.hint_chunk_fetching.clear();
self.added_hints.clear();
self.hovered_command = None;
+ self.pending_text_edit = None;
+ self.pending_refresh_acceptance = None;
}
/// Like `clear`, but only wipes tracking state for the given buffer IDs.
@@ -149,6 +175,14 @@ impl LspInlayHintData {
{
self.hovered_command = None;
}
+ self.remove_pending_text_edit(|target| buffer_ids.contains(&target.buffer_id));
+ if self
+ .pending_refresh_acceptance
+ .as_ref()
+ .is_some_and(|(pending_buffers, _)| !pending_buffers.is_disjoint(buffer_ids))
+ {
+ self.pending_refresh_acceptance = None;
+ }
for buffer_id in buffer_ids {
self.hint_refresh_tasks.remove(buffer_id);
self.hint_chunk_fetching.remove(buffer_id);
@@ -162,6 +196,44 @@ impl LspInlayHintData {
}
}
+ pub(crate) fn remove_inlay_chunk_data<'a>(
+ &'a mut self,
+ removed_buffer_ids: impl IntoIterator<Item = &'a BufferId> + 'a,
+ ) {
+ for buffer_id in removed_buffer_ids {
+ if self
+ .pending_refresh_acceptance
+ .as_ref()
+ .is_some_and(|(pending_buffers, _)| pending_buffers.contains(buffer_id))
+ {
+ self.pending_refresh_acceptance = None;
+ }
+ self.hint_refresh_tasks.remove(buffer_id);
+ self.hint_chunk_fetching.remove(buffer_id);
+ }
+ }
+
+ pub(super) fn remove_pending_text_edit(&mut self, remove: impl FnOnce(&HintTarget) -> bool) {
+ if self
+ .pending_text_edit
+ .as_ref()
+ .is_some_and(|pending| remove(&pending.target))
+ {
+ self.pending_text_edit = None;
+ }
+ }
+
+ pub(super) fn remove_inlay(&mut self, inlay_id: &InlayId) {
+ self.added_hints.remove(inlay_id);
+ if self
+ .hovered_command
+ .as_ref()
+ .is_some_and(|command| command.highlight.inlay == *inlay_id)
+ {
+ self.hovered_command = None;
+ }
+ }
+
/// Checks inlay hint settings for enabled hint kinds and general enabled state.
/// Generates corresponding inlay_map splice updates on settings changes.
/// Does not update inlay hint cache state on disabling or inlay hint kinds change: only reenabling forces new LSP queries.
@@ -252,25 +324,17 @@ impl LspInlayHintData {
}
}
- pub(crate) fn remove_inlay_chunk_data<'a>(
- &'a mut self,
- removed_buffer_ids: impl IntoIterator<Item = &'a BufferId> + 'a,
- ) {
- for buffer_id in removed_buffer_ids {
- self.hint_refresh_tasks.remove(buffer_id);
- self.hint_chunk_fetching.remove(buffer_id);
- }
- }
-
- pub(super) fn remove_inlay(&mut self, inlay_id: &InlayId) {
- self.added_hints.remove(inlay_id);
- if self
- .hovered_command
- .as_ref()
- .is_some_and(|command| command.highlight.inlay == *inlay_id)
- {
- self.hovered_command = None;
- }
+ fn pending_refreshes(
+ &self,
+ buffer_ids: &HashSet<BufferId>,
+ ) -> Vec<Shared<oneshot::Receiver<()>>> {
+ self.hint_refresh_tasks
+ .iter()
+ .filter(|(buffer_id, _)| buffer_ids.contains(buffer_id))
+ .flat_map(|(_, refreshes)| refreshes)
+ .filter(|refresh| !refresh.task.is_ready())
+ .map(|refresh| refresh.finished.clone())
+ .collect()
}
fn should_refresh(&self) -> bool {
@@ -334,10 +398,401 @@ impl Editor {
);
}
+ pub fn accept_inlay_hint(
+ &mut self,
+ _: &AcceptInlayHint,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !self.can_accept_inlay_hint(cx) {
+ return;
+ }
+ if let Some(inlay_hints) = self.inlay_hints.as_mut() {
+ inlay_hints.pending_text_edit = None;
+ inlay_hints.pending_refresh_acceptance = None;
+ }
+ self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
+ if self.accept_inlay_hint_after_refresh(None, window, cx) {
+ return;
+ }
+ let display_snapshot = self.display_snapshot(cx);
+ let targets = self
+ .inlay_hints_at_selections(&display_snapshot, cx)
+ .collect::<Vec<_>>();
+ self.apply_inlay_hint_text_edits(targets.into_iter(), None, window, cx);
+ }
+
pub fn inlay_hints_enabled(&self) -> bool {
self.inlay_hints.as_ref().is_some_and(|cache| cache.enabled)
}
+ pub fn clear_inlay_hints(&mut self, cx: &mut Context<Self>) {
+ let to_remove = Self::visible_inlay_hints(self.display_map.read(cx))
+ .map(|inlay| inlay.id)
+ .collect::<Vec<_>>();
+ self.splice_inlays(&to_remove, Vec::new(), cx);
+ }
+
+ pub fn update_inlay_link_and_hover_points(
+ &mut self,
+ snapshot: &EditorSnapshot,
+ hint_glyph: Option<DisplayPoint>,
+ mouse_position: Option<gpui::Point<Pixels>>,
+ secondary_held: bool,
+ shift_held: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.hover_state.hint_hover_task = None;
+ let hovered_hint = hint_glyph.and_then(|glyph| snapshot.inlay_hint_at(glyph));
+ let resolved_hint = hovered_hint.and_then(|(hint, _)| {
+ if !self.lsp_data_enabled() {
+ return None;
+ }
+ let buffer_id = hint.position.raw_text_anchor()?.buffer_id;
+ let lsp_store = self.project()?.read(cx).lsp_store();
+ let resolved = lsp_store.update(cx, |lsp_store, cx| {
+ lsp_store.resolved_hint(buffer_id, hint.id, cx)
+ })?;
+ Some((hint.id, buffer_id, resolved))
+ });
+ let Some((hint_id, buffer_id, resolved_hint)) = resolved_hint else {
+ self.hide_hovered_link(cx);
+ hover_popover::hover_at(self, None, mouse_position, window, cx);
+ if let Some(inlay_hints) = self.inlay_hints.as_mut() {
+ inlay_hints.hovered_command = None;
+ }
+ return;
+ };
+ if let ResolvedHint::Resolving(_) = &resolved_hint {
+ self.hide_hovered_link(cx);
+ hover_popover::hover_at(self, None, mouse_position, window, cx);
+ if let Some(inlay_hints) = self.inlay_hints.as_mut() {
+ inlay_hints.hovered_command = None;
+ }
+ }
+ let scroll_position = snapshot.scroll_position();
+ let update_hover = move |editor: &mut Editor,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ cached_hint: InlayHint,
+ secondary_held: bool,
+ shift_held: bool|
+ -> Option<Task<()>> {
+ let snapshot = editor.snapshot(window, cx);
+ if snapshot.scroll_position() != scroll_position
+ || !editor.lsp_data_enabled()
+ || !editor
+ .inlay_hints
+ .as_ref()
+ .is_some_and(|hints| hints.added_hints.contains_key(&hint_id))
+ {
+ return None;
+ }
+ let (hovered_hint, offset_in_hint) = hint_glyph
+ .and_then(|glyph| snapshot.inlay_hint_at(glyph))
+ .filter(|(hint, _)| hint.id == hint_id)?;
+ let mut go_to_definition_updated = false;
+ let mut hover_task = None;
+ let mut inlay_command_updated = false;
+ let previous_command_highlight = editor
+ .inlay_hints
+ .as_ref()
+ .and_then(|inlay_hints| inlay_hints.hovered_command.as_ref())
+ .map(|command| command.highlight.clone());
+ let original_text = cached_hint.text();
+ let actual_left_padding = if cached_hint.padding_left && !original_text.starts_with(" ")
+ {
+ 1
+ } else {
+ 0
+ };
+ let actual_right_padding = if cached_hint.padding_right && !original_text.ends_with(" ")
+ {
+ 1
+ } else {
+ 0
+ };
+ match cached_hint.label {
+ InlayHintLabel::String(_) => {
+ if let Some(tooltip) = cached_hint.tooltip {
+ hover_task = hover_popover::hover_at_inlay(
+ editor,
+ InlayHover {
+ tooltip: match tooltip {
+ InlayHintTooltip::String(text) => HoverBlock {
+ text,
+ kind: HoverBlockKind::PlainText,
+ },
+ InlayHintTooltip::MarkupContent(content) => HoverBlock {
+ text: content.value,
+ kind: content.kind,
+ },
+ },
+ range: InlayHighlight {
+ inlay: hovered_hint.id,
+ inlay_position: hovered_hint.position,
+ range: actual_left_padding
+ ..hovered_hint.text().len() - actual_right_padding,
+ },
+ },
+ window,
+ cx,
+ );
+ }
+ }
+ InlayHintLabel::LabelParts(label_parts) => {
+ if let Some(offset_in_label) = offset_in_hint.checked_sub(actual_left_padding)
+ && let Some((hovered_hint_part, part_range)) =
+ hover_popover::find_hovered_hint_part(label_parts, offset_in_label)
+ {
+ let highlight_start = actual_left_padding + part_range.start;
+ let highlight_end = actual_left_padding + part_range.end;
+ let highlight = InlayHighlight {
+ inlay: hovered_hint.id,
+ inlay_position: hovered_hint.position,
+ range: highlight_start..highlight_end,
+ };
+ if let Some((server_id, command)) = hovered_hint_part.command
+ && let Some(inlay_hints) = editor.inlay_hints.as_mut()
+ {
+ inlay_command_updated = true;
+ inlay_hints.hovered_command = Some(HoveredInlayHintCommand {
+ highlight: highlight.clone(),
+ buffer_id,
+ action: CodeAction {
+ server_id,
+ range: cached_hint.position..cached_hint.position,
+ lsp_action: LspAction::Command(command),
+ resolved: true,
+ },
+ });
+ }
+ if let Some(tooltip) = hovered_hint_part.tooltip {
+ hover_task = hover_popover::hover_at_inlay(
+ editor,
+ InlayHover {
+ tooltip: match tooltip {
+ InlayHintLabelPartTooltip::String(text) => HoverBlock {
+ text,
+ kind: HoverBlockKind::PlainText,
+ },
+ InlayHintLabelPartTooltip::MarkupContent(content) => {
+ HoverBlock {
+ text: content.value,
+ kind: content.kind,
+ }
+ }
+ },
+ range: highlight.clone(),
+ },
+ window,
+ cx,
+ );
+ }
+ if let Some((language_server_id, location)) = hovered_hint_part.location
+ && secondary_held
+ && !editor.has_pending_nonempty_selection()
+ {
+ go_to_definition_updated = true;
+ show_link_definition(
+ shift_held,
+ editor,
+ TriggerPoint::InlayHint(highlight, location, language_server_id),
+ &snapshot,
+ window,
+ cx,
+ );
+ }
+ }
+ }
+ };
+
+ if !go_to_definition_updated {
+ editor.hide_hovered_link(cx);
+ }
+ if hover_task.is_none() {
+ hover_popover::hover_at(editor, None, mouse_position, window, cx);
+ }
+ if !inlay_command_updated && let Some(inlay_hints) = editor.inlay_hints.as_mut() {
+ inlay_hints.hovered_command = None;
+ }
+ let command_highlight = editor
+ .inlay_hints
+ .as_ref()
+ .and_then(|inlay_hints| inlay_hints.hovered_command.as_ref())
+ .map(|command| &command.highlight);
+ if command_highlight != previous_command_highlight.as_ref() {
+ cx.notify();
+ }
+ hover_task
+ };
+ self.hover_state.hint_hover_task = match resolved_hint {
+ ResolvedHint::Resolved(hint) => {
+ update_hover(self, window, cx, hint, secondary_held, shift_held)
+ }
+ ResolvedHint::Resolving(task) => Some(cx.spawn_in(window, async move |editor, cx| {
+ let Some(hint) = task.await else {
+ return;
+ };
+ let Some(show_hover) = editor
+ .update_in(cx, |editor, window, cx| {
+ let modifiers = window.modifiers();
+ let secondary_held = Editor::is_cmd_or_ctrl_pressed(&modifiers, cx);
+ update_hover(editor, window, cx, hint, secondary_held, modifiers.shift)
+ })
+ .ok()
+ .flatten()
+ else {
+ return;
+ };
+ show_hover.await;
+ })),
+ };
+ }
+
+ pub(crate) fn can_accept_inlay_hint(&self, cx: &App) -> bool {
+ self.lsp_data_enabled()
+ && !self.read_only(cx)
+ && self.project().is_some()
+ && self
+ .inlay_hints
+ .as_ref()
+ .is_some_and(|inlay_hints| inlay_hints.should_show())
+ }
+
+ pub(crate) fn inlay_hint_visibility_changed(&mut self, cx: &mut Context<Self>) {
+ if self
+ .inlay_hints
+ .as_ref()
+ .is_none_or(|inlay_hints| inlay_hints.pending_text_edit.is_none())
+ {
+ return;
+ }
+ let display_snapshot = self.display_snapshot(cx);
+ if let Some(inlay_hints) = &mut self.inlay_hints {
+ inlay_hints.remove_pending_text_edit(|target| {
+ !display_snapshot.is_inlay_visible(target.hint_id, target.position)
+ });
+ }
+ }
+
+ pub(crate) fn is_inlay_hint_resolved(
+ &self,
+ buffer_id: BufferId,
+ hint_id: InlayId,
+ cx: &App,
+ ) -> bool {
+ self.project().is_some_and(|project| {
+ project
+ .read(cx)
+ .lsp_store()
+ .read(cx)
+ .cached_inlay_hint(buffer_id, hint_id)
+ .is_some_and(|hint| hint.resolve_state == ResolveState::Resolved)
+ })
+ }
+
+ pub(crate) fn apply_inlay_hint_text_edits(
+ &mut self,
+ mut targets: impl Iterator<Item = HintTarget> + 'static,
+ clicked_label_offset: Option<usize>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> bool {
+ let Some(inlay_hints) = self.inlay_hints.as_mut() else {
+ return false;
+ };
+ inlay_hints.pending_text_edit = None;
+ inlay_hints.pending_refresh_acceptance = None;
+ if !self.lsp_data_enabled() || self.read_only(cx) {
+ return false;
+ }
+ let Some(lsp_store) = self.project().map(|project| project.read(cx).lsp_store()) else {
+ return false;
+ };
+ while let Some(target) = targets.next() {
+ if self.is_buffer_read_only(target.buffer_id, cx) {
+ continue;
+ }
+ let Some((has_text_edits, resolved)) = lsp_store
+ .read(cx)
+ .cached_inlay_hint(target.buffer_id, target.hint_id)
+ .map(|hint| {
+ (
+ hint.has_text_edits(),
+ hint.resolve_state == ResolveState::Resolved,
+ )
+ })
+ else {
+ if self.accept_inlay_hint_after_refresh(
+ clicked_label_offset.map(|offset| (target, offset)),
+ window,
+ cx,
+ ) {
+ return true;
+ }
+ continue;
+ };
+ let needs_resolve = !has_text_edits || (clicked_label_offset.is_some() && !resolved);
+ let resolve = if needs_resolve {
+ match lsp_store.update(cx, |lsp_store, cx| {
+ lsp_store.resolved_hint(target.buffer_id, target.hint_id, cx)
+ }) {
+ Some(ResolvedHint::Resolving(resolve)) => Some(resolve),
+ Some(ResolvedHint::Resolved(_)) if has_text_edits => None,
+ Some(ResolvedHint::Resolved(_)) | None => continue,
+ }
+ } else {
+ None
+ };
+ if let Some(resolve) = resolve {
+ let Some(inlay_hints) = self.inlay_hints.as_mut() else {
+ return false;
+ };
+ inlay_hints.pending_text_edit = Some(PendingHintTextEdit {
+ target,
+ _apply_task: cx.spawn_in(window, async move |editor, cx| {
+ let resolved = resolve.await;
+ editor
+ .update_in(cx, |editor, window, cx| {
+ let Some(pending) = editor
+ .inlay_hints
+ .as_mut()
+ .and_then(|inlay_hints| inlay_hints.pending_text_edit.take())
+ else {
+ return;
+ };
+ if resolved.is_some()
+ && !editor.apply_inlay_hint_text_edit(
+ &lsp_store,
+ pending.target,
+ clicked_label_offset,
+ window,
+ cx,
+ )
+ {
+ editor.apply_inlay_hint_text_edits(
+ targets,
+ clicked_label_offset,
+ window,
+ cx,
+ );
+ }
+ })
+ .ok();
+ }),
+ });
+ return true;
+ }
+ if self.apply_inlay_hint_text_edit(&lsp_store, target, clicked_label_offset, window, cx)
+ {
+ return true;
+ }
+ }
+ false
+ }
+
/// Updates inlay hints for the visible ranges of the singleton buffer(s).
/// Based on its parameters, either invalidates the previous data, or appends to it.
pub(crate) fn refresh_inlay_hints(
@@ -513,28 +968,273 @@ impl Editor {
}
}
- pub fn clear_inlay_hints(&mut self, cx: &mut Context<Self>) {
- let to_remove = Self::visible_inlay_hints(self.display_map.read(cx))
- .map(|inlay| inlay.id)
- .collect::<Vec<_>>();
- self.splice_inlays(&to_remove, Vec::new(), cx);
+ pub(crate) fn hovered_inlay_hint_command(&self) -> Option<&HoveredInlayHintCommand> {
+ self.inlay_hints.as_ref()?.hovered_command.as_ref()
}
- fn refresh_editor_data(
+ pub(crate) fn activate_hovered_inlay_hint_command(
&mut self,
- reason: &InlayHintRefreshReason,
- cx: &mut Context<'_, Editor>,
- ) -> Option<InvalidationStrategy> {
- let Some(inlay_hints) = self.inlay_hints.as_mut() else {
- return None;
+ snapshot: &EditorSnapshot,
+ down: Option<DisplayPoint>,
+ up: Option<DisplayPoint>,
+ cx: &mut Context<Self>,
+ ) -> bool {
+ let Some(state) = self.hovered_inlay_hint_command().filter(|state| {
+ state.contains_glyph(snapshot, down) && state.contains_glyph(snapshot, up)
+ }) else {
+ return false;
+ };
+ let Some(buffer) = self.buffer().read(cx).buffer(state.buffer_id) else {
+ return false;
+ };
+ let Some(project) = self.project().cloned() else {
+ return false;
};
+ let action = state.action.clone();
+ project
+ .update(cx, |project, cx| {
+ project.apply_code_action(buffer, action, true, cx)
+ })
+ .detach_and_log_err(cx);
+ true
+ }
- let invalidate_cache = match reason {
- InlayHintRefreshReason::ModifiersChanged(enabled) => {
- match inlay_hints.modifiers_override(*enabled) {
- Some(enabled) => {
- if enabled {
- InvalidationStrategy::None
+ fn is_buffer_read_only(&self, buffer_id: BufferId, cx: &App) -> bool {
+ self.buffer
+ .read(cx)
+ .buffer(buffer_id)
+ .is_none_or(|buffer| buffer.read(cx).read_only())
+ }
+
+ fn apply_inlay_hint_text_edit(
+ &mut self,
+ lsp_store: &Entity<LspStore>,
+ target: HintTarget,
+ clicked_label_offset: Option<usize>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> bool {
+ if !self.lsp_data_enabled() || self.read_only(cx) {
+ return false;
+ }
+ let HintTarget {
+ buffer_id,
+ hint_id,
+ position,
+ } = target;
+ let display_snapshot = self.display_snapshot(cx);
+ if !self
+ .inlay_hints
+ .as_ref()
+ .is_some_and(|inlay_hints| inlay_hints.added_hints.contains_key(&hint_id))
+ || !display_snapshot.is_inlay_visible(hint_id, position)
+ {
+ return false;
+ }
+ let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
+ return false;
+ };
+ let buffer_snapshot = buffer.read(cx);
+ let Some(cached_hint) = lsp_store.read(cx).cached_inlay_hint(buffer_id, hint_id) else {
+ return false;
+ };
+ if clicked_label_offset.is_some_and(|offset| {
+ cached_hint.resolve_state != ResolveState::Resolved
+ || label_part_has_command(cached_hint, offset)
+ }) {
+ return false;
+ }
+ let Some(text_edits) = cached_hint
+ .text_edits
+ .clone()
+ .filter(|text_edits| !text_edits.edits.is_empty())
+ else {
+ return false;
+ };
+ if buffer_snapshot.read_only()
+ || !buffer_snapshot
+ .version()
+ .observed_all(&text_edits.buffer_version)
+ {
+ return false;
+ }
+ self.finalize_last_transaction(cx);
+ self.transact(window, cx, |_, _, cx| {
+ buffer.update(cx, |buffer, cx| buffer.edit(text_edits.edits, None, cx));
+ });
+ self.finalize_last_transaction(cx);
+ self.splice_inlays(&[hint_id], Vec::new(), cx);
+ true
+ }
+
+ fn accept_inlay_hint_after_refresh(
+ &mut self,
+ clicked_hint: Option<(HintTarget, usize)>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> bool {
+ let snapshot = self.display_snapshot(cx);
+ let clicked_hint = if let Some((target, offset)) = clicked_hint {
+ if !snapshot.is_inlay_visible(target.hint_id, target.position) {
+ return false;
+ }
+ let Some(text) = Self::visible_inlay_hints(self.display_map.read(cx))
+ .find(|hint| hint.id == target.hint_id)
+ .map(|hint| hint.text().clone())
+ else {
+ return false;
+ };
+ Some((target, offset, text))
+ } else {
+ None
+ };
+ let buffer_ids = if let Some((target, _, _)) = &clicked_hint {
+ HashSet::from_iter([target.buffer_id])
+ } else {
+ self.selections
+ .all_adjusted(&snapshot)
+ .into_iter()
+ .flat_map(|selection| {
+ snapshot
+ .buffer_snapshot()
+ .range_to_buffer_ranges(selection.range())
+ })
+ .map(|(buffer, _, _)| buffer.remote_id())
+ .collect::<HashSet<_>>()
+ };
+ let Some(inlay_hints) = self.inlay_hints.as_ref() else {
+ return false;
+ };
+ let mut refreshes = inlay_hints.pending_refreshes(&buffer_ids);
+ if refreshes.is_empty() {
+ return false;
+ }
+ let edit_count = snapshot.buffer_snapshot().edit_count();
+ let selections = self.selections.all_anchors(&snapshot);
+ let line_mode = self.selections.line_mode();
+ let task = cx.spawn_in(window, {
+ let buffer_ids = buffer_ids.clone();
+ async move |editor, cx| {
+ let refreshed = loop {
+ if join_all(refreshes).await.iter().any(Result::is_err) {
+ break false;
+ }
+ let Ok(Some(pending)) = editor.read_with(cx, |editor, _| {
+ Some(editor.inlay_hints.as_ref()?.pending_refreshes(&buffer_ids))
+ }) else {
+ return;
+ };
+ if pending.is_empty() {
+ break true;
+ }
+ refreshes = pending;
+ };
+ editor
+ .update_in(cx, |editor, window, cx| {
+ editor.inlay_hints.as_mut()?.pending_refresh_acceptance = None;
+ if !refreshed || !editor.can_accept_inlay_hint(cx) {
+ return None;
+ }
+ let snapshot = editor.display_snapshot(cx);
+ if snapshot.buffer_snapshot().edit_count() != edit_count {
+ return None;
+ }
+ let targets = if let Some((target, _, text)) = &clicked_hint {
+ if !snapshot.buffer_snapshot().can_resolve(&target.position) {
+ return None;
+ }
+ let buffer_snapshot = snapshot.buffer_snapshot();
+ let position = target.position.bias_right(buffer_snapshot);
+ let hint = Self::visible_inlay_hints(editor.display_map.read(cx))
+ .filter(|hint| {
+ hint.position
+ .bias_right(buffer_snapshot)
+ .cmp(&position, buffer_snapshot)
+ .is_eq()
+ && hint.text().chars().eq(text.chars())
+ && snapshot.is_inlay_visible(hint.id, hint.position)
+ })
+ .exactly_one()
+ .ok()?;
+ vec![HintTarget {
+ hint_id: hint.id,
+ position: hint.position,
+ ..*target
+ }]
+ } else {
+ if editor.selections.all_anchors(&snapshot) != selections
+ || editor.selections.line_mode() != line_mode
+ {
+ return None;
+ }
+ editor
+ .inlay_hints_at_selections(&snapshot, cx)
+ .collect::<Vec<_>>()
+ };
+ editor.apply_inlay_hint_text_edits(
+ targets.into_iter(),
+ clicked_hint.as_ref().map(|(_, offset, _)| *offset),
+ window,
+ cx,
+ );
+ Some(())
+ })
+ .ok();
+ }
+ });
+ if let Some(inlay_hints) = &mut self.inlay_hints {
+ inlay_hints.pending_refresh_acceptance = Some((buffer_ids, task));
+ }
+ true
+ }
+
+ fn inlay_hints_at_selections<'a>(
+ &'a self,
+ display_snapshot: &'a DisplaySnapshot,
+ cx: &'a App,
+ ) -> impl Iterator<Item = HintTarget> + 'a {
+ let inlays = self.display_map.read(cx).current_inlays().as_slice();
+ let buffer_snapshot = display_snapshot.buffer_snapshot();
+ self.selections
+ .all_adjusted(display_snapshot)
+ .into_iter()
+ .flat_map(move |selection| {
+ let start = buffer_snapshot.anchor_before(selection.start);
+ let end = buffer_snapshot.anchor_after(selection.end);
+ let first_inlay = inlays
+ .partition_point(|inlay| inlay.position.cmp(&start, buffer_snapshot).is_lt());
+ inlays[first_inlay..]
+ .iter()
+ .take_while(move |inlay| inlay.position.cmp(&end, buffer_snapshot).is_le())
+ .filter(|inlay| matches!(inlay.id, InlayId::Hint(_)))
+ .filter(move |inlay| {
+ display_snapshot.is_inlay_visible(inlay.id, inlay.position)
+ })
+ .filter_map(|inlay| {
+ Some(HintTarget {
+ buffer_id: inlay.position.raw_text_anchor()?.buffer_id,
+ hint_id: inlay.id,
+ position: inlay.position,
+ })
+ })
+ })
+ }
+
+ fn refresh_editor_data(
+ &mut self,
+ reason: &InlayHintRefreshReason,
+ cx: &mut Context<'_, Editor>,
+ ) -> Option<InvalidationStrategy> {
+ let Some(inlay_hints) = self.inlay_hints.as_mut() else {
+ return None;
+ };
+
+ let invalidate_cache = match reason {
+ InlayHintRefreshReason::ModifiersChanged(enabled) => {
+ match inlay_hints.modifiers_override(*enabled) {
+ Some(enabled) => {
+ if enabled {
+ InvalidationStrategy::None
} else {
self.clear_inlay_hints(cx);
return None;
@@ -625,244 +1325,6 @@ impl Editor {
.cloned()
}
- pub fn update_inlay_link_and_hover_points(
- &mut self,
- snapshot: &EditorSnapshot,
- point_for_position: PointForPosition,
- mouse_position: Option<gpui::Point<Pixels>>,
- secondary_held: bool,
- shift_held: bool,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- let Some(lsp_store) = self.project().map(|project| project.read(cx).lsp_store()) else {
- return;
- };
- let hovered_offset = if point_for_position.column_overshoot_after_line_end == 0 {
- Some(
- snapshot
- .display_point_to_inlay_offset(point_for_position.exact_unclipped, Bias::Left),
- )
- } else {
- None
- };
- let mut go_to_definition_updated = false;
- let mut hover_updated = false;
- let mut inlay_command_updated = false;
- if let Some(hovered_offset) = hovered_offset {
- let buffer_snapshot = self.buffer().read(cx).snapshot(cx);
- let previous_valid_anchor = buffer_snapshot.anchor_at(
- point_for_position.previous_valid.to_point(snapshot),
- Bias::Left,
- );
- let next_valid_anchor = buffer_snapshot.anchor_at(
- point_for_position.next_valid.to_point(snapshot),
- Bias::Right,
- );
- if let Some(hovered_hint) = Self::visible_inlay_hints(self.display_map.read(cx))
- .filter(|hint| snapshot.can_resolve(&hint.position))
- .skip_while(|hint| {
- hint.position
- .cmp(&previous_valid_anchor, &buffer_snapshot)
- .is_lt()
- })
- .take_while(|hint| {
- hint.position
- .cmp(&next_valid_anchor, &buffer_snapshot)
- .is_le()
- })
- .max_by_key(|hint| hint.id)
- {
- if let Some((buffer_anchor, _)) =
- buffer_snapshot.anchor_to_buffer_anchor(hovered_hint.position)
- && let Some(ResolvedHint::Resolved(cached_hint)) =
- lsp_store.update(cx, |lsp_store, cx| {
- lsp_store.resolved_hint(buffer_anchor.buffer_id, hovered_hint.id, cx)
- })
- {
- match cached_hint.resolve_state {
- ResolveState::Resolved => {
- let original_text = cached_hint.text();
- let actual_left_padding =
- if cached_hint.padding_left && !original_text.starts_with(" ") {
- 1
- } else {
- 0
- };
- let actual_right_padding =
- if cached_hint.padding_right && !original_text.ends_with(" ") {
- 1
- } else {
- 0
- };
- match cached_hint.label {
- InlayHintLabel::String(_) => {
- if let Some(tooltip) = cached_hint.tooltip {
- hover_popover::hover_at_inlay(
- self,
- InlayHover {
- tooltip: match tooltip {
- InlayHintTooltip::String(text) => HoverBlock {
- text,
- kind: HoverBlockKind::PlainText,
- },
- InlayHintTooltip::MarkupContent(content) => {
- HoverBlock {
- text: content.value,
- kind: content.kind,
- }
- }
- },
- range: InlayHighlight {
- inlay: hovered_hint.id,
- inlay_position: hovered_hint.position,
- range: actual_left_padding
- ..hovered_hint.text().len()
- - actual_right_padding,
- },
- },
- window,
- cx,
- );
- hover_updated = true;
- }
- }
- InlayHintLabel::LabelParts(label_parts) => {
- let hint_start =
- snapshot.anchor_to_inlay_offset(hovered_hint.position);
- let content_start =
- InlayOffset(hint_start.0 + actual_left_padding);
- if let Some((hovered_hint_part, part_range)) =
- hover_popover::find_hovered_hint_part(
- label_parts,
- content_start,
- hovered_offset,
- )
- {
- let highlight_start = part_range.start - hint_start;
- let highlight_end = part_range.end - hint_start;
- let highlight = InlayHighlight {
- inlay: hovered_hint.id,
- inlay_position: hovered_hint.position,
- range: highlight_start..highlight_end,
- };
- if let Some((server_id, command)) =
- hovered_hint_part.command
- && let Some(inlay_hints) = self.inlay_hints.as_mut()
- {
- inlay_command_updated = true;
- inlay_hints.hovered_command =
- Some(HoveredInlayHintCommand {
- highlight: highlight.clone(),
- buffer_id: buffer_anchor.buffer_id,
- action: CodeAction {
- server_id,
- range: cached_hint.position
- ..cached_hint.position,
- lsp_action: LspAction::Command(command),
- resolved: true,
- },
- });
- }
- if let Some(tooltip) = hovered_hint_part.tooltip {
- hover_popover::hover_at_inlay(
- self,
- InlayHover {
- tooltip: match tooltip {
- InlayHintLabelPartTooltip::String(text) => {
- HoverBlock {
- text,
- kind: HoverBlockKind::PlainText,
- }
- }
- InlayHintLabelPartTooltip::MarkupContent(
- content,
- ) => HoverBlock {
- text: content.value,
- kind: content.kind,
- },
- },
- range: highlight.clone(),
- },
- window,
- cx,
- );
- hover_updated = true;
- }
- if let Some((language_server_id, location)) =
- hovered_hint_part.location
- && secondary_held
- && !self.has_pending_nonempty_selection()
- {
- go_to_definition_updated = true;
- show_link_definition(
- shift_held,
- self,
- TriggerPoint::InlayHint(
- highlight,
- location,
- language_server_id,
- ),
- snapshot,
- window,
- cx,
- );
- }
- }
- }
- };
- }
- ResolveState::CanResolve(_, _) => debug_panic!(
- "Expected resolved_hint retrieval to return a resolved hint"
- ),
- ResolveState::Resolving => {}
- }
- }
- }
- }
-
- if !go_to_definition_updated {
- self.hide_hovered_link(cx)
- }
- if !hover_updated {
- hover_popover::hover_at(self, None, mouse_position, window, cx);
- }
- if !inlay_command_updated && let Some(inlay_hints) = self.inlay_hints.as_mut() {
- inlay_hints.hovered_command = None;
- }
- }
-
- pub(crate) fn hovered_inlay_hint_command(&self) -> Option<&HoveredInlayHintCommand> {
- self.inlay_hints.as_ref()?.hovered_command.as_ref()
- }
-
- pub(crate) fn activate_hovered_inlay_hint_command(
- &mut self,
- snapshot: &EditorSnapshot,
- down: PointForPosition,
- up: PointForPosition,
- cx: &mut Context<Self>,
- ) -> bool {
- let Some(state) = self.hovered_inlay_hint_command().filter(|state| {
- state.contains_point(snapshot, down) && state.contains_point(snapshot, up)
- }) else {
- return false;
- };
- let Some(buffer) = self.buffer().read(cx).buffer(state.buffer_id) else {
- return false;
- };
- let Some(project) = self.project().cloned() else {
- return false;
- };
- let action = state.action.clone();
- project
- .update(cx, |project, cx| {
- project.apply_code_action(buffer, action, true, cx)
- })
- .detach_and_log_err(cx);
- true
- }
-
fn inlay_hints_for_buffer(
&mut self,
invalidate_cache: InvalidationStrategy,
@@ -1178,6 +1640,19 @@ fn normalize_hint_biases(
.collect()
}
+fn label_part_has_command(hint: &InlayHint, offset_in_hint: usize) -> bool {
+ let InlayHintLabel::LabelParts(label_parts) = &hint.label else {
+ return false;
+ };
+ let left_padding = usize::from(hint.padding_left && !hint.text().starts_with(" "));
+ offset_in_hint
+ .checked_sub(left_padding)
+ .and_then(|offset_in_label| {
+ hover_popover::find_hovered_hint_part(label_parts.clone(), offset_in_label)
+ })
+ .is_some_and(|(part, _)| part.command.is_some())
+}
+
#[derive(Debug)]
struct VisibleExcerpts {
ranges: Vec<Range<text::Anchor>>,
@@ -1193,8 +1668,9 @@ fn spawn_editor_hints_refresh(
known_chunks: Option<(Global, HashSet<Range<BufferRow>>)>,
applicable_chunks: Vec<Range<BufferRow>>,
cx: &mut Context<'_, Editor>,
-) -> Task<()> {
- cx.spawn(async move |editor, cx| {
+) -> HintRefreshTask {
+ let (finished_sender, finished) = oneshot::channel();
+ let task = cx.spawn(async move |editor, cx| {
if let Some(debounce) = debounce {
cx.background_executor().timer(debounce).await;
}
@@ -1237,23 +1713,33 @@ fn spawn_editor_hints_refresh(
);
})
.ok();
- })
+ finished_sender.send(()).ok();
+ });
+ HintRefreshTask {
+ task,
+ finished: finished.shared(),
+ }
}
#[cfg(test)]
pub mod tests {
- use super::{HoveredInlayHintCommand, LspInlayHintData};
- use crate::editor_tests::update_test_language_settings;
+ use super::{HintTarget, HoveredInlayHintCommand, LspInlayHintData};
+ use crate::editor_tests::{update_test_editor_settings, update_test_language_settings};
use crate::hover_links::InlayHighlight;
use crate::inlays::inlay_hints::InlayHintRefreshReason;
use crate::scroll::Autoscroll;
use crate::scroll::ScrollAmount;
use crate::test::editor_lsp_test_context::EditorLspTestContext;
- use crate::{Editor, SelectionEffects};
+ use crate::test::editor_test_context::EditorTestContext;
+ use crate::{AcceptInlayHint, Editor, SelectionEffects};
+ use crate::{DisplayPoint, DisplayRow};
use collections::HashSet;
use futures::channel::oneshot;
use futures::{StreamExt, future};
- use gpui::{AppContext as _, Context, TestAppContext, UpdateGlobal, WindowHandle};
+ use gpui::{
+ AppContext as _, Context, Modifiers, MouseButton, MouseDownEvent, MouseUpEvent,
+ TestAppContext, UpdateGlobal, Window, WindowHandle,
+ };
use itertools::Itertools as _;
use language::language_settings::{ConfiguredLanguageServer, InlayHintKind, InlayHintSettings};
use language::{Capability, FakeLspAdapter};
@@ -1266,13 +1752,14 @@ pub mod tests {
use project::{CodeAction, FakeFs, InlayId, InvalidationStrategy, LspAction, Project};
use serde_json::json;
use settings::{
- AllLanguageSettingsContent, InlayHintSettingsContent, SettingsContent, SettingsStore,
+ AllLanguageSettingsContent, DoubleClickInMultibuffer, InlayHintSettingsContent,
+ SettingsContent, SettingsStore,
};
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::time::Duration;
- use text::{BufferId, OffsetRangeExt, Point};
+ use text::{Bias, BufferId, OffsetRangeExt, Point, ReplicaId};
use ui::App;
use util::path;
use util::paths::natural_sort;
@@ -2841,22 +3328,6 @@ pub mod tests {
}).unwrap();
}
- fn editor_visible_range(
- editor: &WindowHandle<Editor>,
- cx: &mut gpui::TestAppContext,
- ) -> Range<Point> {
- let ranges = editor
- .update(cx, |editor, _window, cx| editor.visible_buffer_ranges(cx))
- .unwrap();
- assert_eq!(
- ranges.len(),
- 1,
- "Single buffer should produce a single excerpt with visible range"
- );
- let (buffer_snapshot, visible_range, _) = ranges.into_iter().next().unwrap();
- visible_range.to_point(&buffer_snapshot)
- }
-
#[gpui::test]
async fn test_multiple_excerpts_large_multibuffer(cx: &mut gpui::TestAppContext) {
init_test(cx, &|settings| {
@@ -5025,52 +5496,688 @@ let c = 3;"#
server_a_request_count.fetch_add(1, Ordering::Release) + 1;
async move {
Ok(Some(vec![lsp::InlayHint {
- position: lsp::Position::new(0, 9),
- label: lsp::InlayHintLabel::String(format!(
- "server_a_{count}"
- )),
+ position: lsp::Position::new(0, 9),
+ label: lsp::InlayHintLabel::String(format!(
+ "server_a_{count}"
+ )),
+ kind: Some(lsp::InlayHintKind::TYPE),
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ }]))
+ }
+ },
+ );
+ }
+ })),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ // Server B returns a hint labeled "server_b" at a different position.
+ let server_b_request_count = Arc::new(AtomicU32::new(0));
+ let server_b_resolve_gate = Arc::new(Mutex::new(None::<oneshot::Receiver<()>>));
+ let mut fake_servers_b = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "secondary-ls",
+ capabilities: lsp::ServerCapabilities {
+ inlay_hint_provider: Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ }),
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new({
+ let server_b_request_count = server_b_request_count.clone();
+ let server_b_resolve_gate = server_b_resolve_gate.clone();
+ move |fake_server| {
+ let server_b_resolve_gate = server_b_resolve_gate.clone();
+ fake_server
+ .set_request_handler::<lsp::request::InlayHintResolveRequest, _, _>(
+ move |mut hint, _| {
+ let gate = server_b_resolve_gate.lock().take();
+ hint.text_edits = Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(hint.position, hint.position),
+ new_text: ": u32".to_string(),
+ }]);
+ async move {
+ if let Some(gate) = gate {
+ gate.await?;
+ }
+ Ok(hint)
+ }
+ },
+ );
+ let server_b_request_count = server_b_request_count.clone();
+ fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |_params, _| {
+ let count =
+ server_b_request_count.fetch_add(1, Ordering::Release) + 1;
+ async move {
+ Ok(Some(vec![lsp::InlayHint {
+ position: lsp::Position::new(0, 17),
+ label: lsp::InlayHintLabel::String(format!(
+ "server_b_{count}"
+ )),
+ kind: Some(lsp::InlayHintKind::TYPE),
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ }]))
+ }
+ },
+ );
+ }
+ })),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _buffer_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/a/main.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let editor =
+ cx.add_window(|window, cx| Editor::for_buffer(buffer, Some(project), window, cx));
+ cx.executor().run_until_parked();
+
+ let fake_server_a = fake_servers_a.next().await.unwrap();
+ let _fake_server_b = fake_servers_b.next().await.unwrap();
+
+ editor
+ .update(cx, |editor, window, cx| {
+ editor.set_visible_line_count(50.0, window, cx);
+ editor.set_visible_column_count(120.0);
+ editor.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
+ })
+ .unwrap();
+ cx.executor().advance_clock(Duration::from_millis(100));
+ cx.executor().run_until_parked();
+
+ // Verify both servers' hints are present initially.
+ editor
+ .update(cx, |editor, _window, cx| {
+ let visible = visible_hint_labels(editor, cx);
+ let has_a = visible.iter().any(|h| h.starts_with("server_a"));
+ let has_b = visible.iter().any(|h| h.starts_with("server_b"));
+ assert!(
+ has_a && has_b,
+ "Both servers should have hints initially. Got: {visible:?}"
+ );
+ })
+ .unwrap();
+
+ // Trigger RefreshRequested from server A. This should re-fetch server A's
+ // hints while keeping server B's hints intact.
+ fake_server_a
+ .request::<lsp::request::InlayHintRefreshRequest>((), lsp::DEFAULT_LSP_REQUEST_TIMEOUT)
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().advance_clock(Duration::from_millis(100));
+ cx.executor().run_until_parked();
+
+ // Also trigger NewLinesShown to give the system a chance to recover
+ // any chunks that might have been cleared.
+ editor
+ .update(cx, |editor, _window, cx| {
+ editor.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
+ })
+ .unwrap();
+ cx.executor().advance_clock(Duration::from_millis(100));
+ cx.executor().run_until_parked();
+
+ editor
+ .update(cx, |editor, _window, cx| {
+ let visible = visible_hint_labels(editor, cx);
+ let has_a = visible.iter().any(|h| h.starts_with("server_a"));
+ let has_b = visible.iter().any(|h| h.starts_with("server_b"));
+ assert!(
+ has_a,
+ "Server A hints should be present after its own refresh. Got: {visible:?}"
+ );
+ assert!(
+ has_b,
+ "Server B hints should NOT be lost when server A triggers \
+ RefreshRequested. Bug 2: clear() wipes all tracking, then \
+ LspStore filters out server B's cached hints via the for_server \
+ guard, and apply_fetched_hints removes all visible hints but only \
+ adds back server A's. Got: {visible:?}"
+ );
+ })
+ .unwrap();
+
+ let (release_resolve, gate) = oneshot::channel();
+ *server_b_resolve_gate.lock() = Some(gate);
+ editor
+ .update(cx, |editor, window, cx| {
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([Point::new(0, 17)..Point::new(0, 17)]);
+ });
+ assert!(editor.can_accept_inlay_hint(cx));
+ editor
+ .inlay_hints
+ .as_mut()
+ .expect("inlay hints enabled")
+ .invalidate_debounce = Some(Duration::from_secs(1));
+ editor.accept_inlay_hint(&AcceptInlayHint, window, cx);
+ })
+ .unwrap();
+ cx.executor().run_until_parked();
+ fake_server_a
+ .request::<lsp::request::InlayHintRefreshRequest>((), lsp::DEFAULT_LSP_REQUEST_TIMEOUT)
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+ editor
+ .update(cx, |editor, _, cx| {
+ assert_eq!(
+ editor.text(cx),
+ "fn main() { let x = 1; } // padding to keep hints from being trimmed",
+ );
+ })
+ .unwrap();
+ release_resolve
+ .send(())
+ .expect("server B resolve must survive server A's refresh");
+ cx.executor().run_until_parked();
+ editor
+ .update(cx, |editor, _, cx| {
+ assert_eq!(
+ editor.text(cx),
+ "fn main() { let x: u32 = 1; } // padding to keep hints from being trimmed",
+ );
+ assert_eq!(
+ visible_hint_labels(editor, cx),
+ vec![format!(
+ "server_a_{}",
+ server_a_request_count.load(Ordering::Acquire)
+ )],
+ );
+ })
+ .unwrap();
+ }
+
+ #[gpui::test]
+ async fn test_accept_inlay_hints_across_buffers(cx: &mut gpui::TestAppContext) {
+ init_test(cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(0),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ })
+ });
+ let fs = FakeFs::new(cx.background_executor.clone());
+ fs.insert_tree(
+ path!("/a"),
+ json!({
+ "first.rs": "fn first() { let a = 1; }\nfn third() { let c = 3; }\n",
+ "second.rs": "fn second() { let b = 2; }\n",
+ }),
+ )
+ .await;
+ let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let resolve_gate = Arc::new(Mutex::new(None::<oneshot::Receiver<()>>));
+ let eager_file = Arc::new(Mutex::new("first.rs"));
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ inlay_hint_provider: Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ }),
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new({
+ let resolve_gate = resolve_gate.clone();
+ let eager_file = eager_file.clone();
+ move |server| {
+ let eager_file = eager_file.clone();
+ server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |params, _| {
+ let uri = params.text_document.uri.to_string();
+ let first = uri.ends_with("first.rs");
+ let eager = uri.ends_with(*eager_file.lock());
+ async move {
+ let (column, type_name) =
+ if first { (18, "u32") } else { (19, "u64") };
+ let position = lsp::Position::new(0, column);
+ Ok(Some(vec![lsp::InlayHint {
+ position,
+ label: lsp::InlayHintLabel::String(format!(
+ ": {type_name}"
+ )),
+ kind: Some(lsp::InlayHintKind::TYPE),
+ text_edits: eager.then(|| {
+ vec![lsp::TextEdit {
+ range: lsp::Range::new(position, position),
+ new_text: format!(": {type_name}"),
+ }]
+ }),
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ }]))
+ }
+ },
+ );
+ let resolve_gate = resolve_gate.clone();
+ server.set_request_handler::<lsp::request::InlayHintResolveRequest, _, _>(
+ move |mut hint, _| {
+ let resolve_gate = resolve_gate.lock().take();
+ if let lsp::InlayHintLabel::String(label) = &hint.label {
+ hint.text_edits = Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(hint.position, hint.position),
+ new_text: label.clone(),
+ }]);
+ }
+ async move {
+ if let Some(resolve_gate) = resolve_gate {
+ resolve_gate.await?;
+ }
+ Ok(hint)
+ }
+ },
+ );
+ }
+ })),
+ ..FakeLspAdapter::default()
+ },
+ );
+ let (first_buffer, _first_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/a/first.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let (second_buffer, _second_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/a/second.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let multi_buffer = cx.new(|cx| {
+ let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
+ multibuffer.set_excerpts_for_path(
+ PathKey::sorted(0),
+ first_buffer.clone(),
+ [Point::new(0, 0)..Point::new(1, 0)],
+ 0,
+ cx,
+ );
+ multibuffer.set_excerpts_for_path(
+ PathKey::sorted(1),
+ second_buffer.clone(),
+ [Point::new(0, 0)..Point::new(1, 0)],
+ 0,
+ cx,
+ );
+ multibuffer
+ });
+ cx.executor().run_until_parked();
+ let editor = cx.add_window(|window, cx| {
+ Editor::for_multibuffer(multi_buffer, Some(project.clone()), window, cx)
+ });
+ let fake_server = fake_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+ editor
+ .update(cx, |editor, _, cx| {
+ assert_eq!(visible_hint_labels(editor, cx), vec![": u32", ": u64"]);
+ })
+ .unwrap();
+
+ let select_hints = |editor: &mut Editor, window: &mut Window, cx: &mut Context<Editor>| {
+ let snapshot = editor.buffer().read(cx).snapshot(cx);
+ let first_hint = snapshot.text().find("a = 1").expect("first hint anchor") + 1;
+ let second_hint = snapshot.text().find("b = 2").expect("second hint anchor") + 1;
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([
+ MultiBufferOffset(first_hint)..MultiBufferOffset(first_hint),
+ MultiBufferOffset(second_hint)..MultiBufferOffset(second_hint),
+ ]);
+ });
+ };
+ let buffer_texts = |cx: &mut TestAppContext| {
+ (
+ first_buffer.read_with(cx, |buffer, _| buffer.text()),
+ second_buffer.read_with(cx, |buffer, _| buffer.text()),
+ )
+ };
+ let original_texts = (
+ "fn first() { let a = 1; }\nfn third() { let c = 3; }\n".to_string(),
+ "fn second() { let b = 2; }\n".to_string(),
+ );
+ editor
+ .update(cx, |editor, window, cx| {
+ select_hints(editor, window, cx);
+ editor.accept_inlay_hint(&AcceptInlayHint, window, cx);
+ })
+ .unwrap();
+ cx.executor().run_until_parked();
+ assert_eq!(
+ buffer_texts(cx),
+ (
+ "fn first() { let a: u32 = 1; }\nfn third() { let c = 3; }\n".to_string(),
+ original_texts.1.clone()
+ ),
+ "only the first selected hint is accepted"
+ );
+ editor
+ .update(cx, |editor, window, cx| {
+ editor.undo(&crate::Undo, window, cx)
+ })
+ .unwrap();
+ cx.executor().run_until_parked();
+ assert_eq!(buffer_texts(cx), original_texts);
+
+ *eager_file.lock() = "second.rs";
+ fake_server
+ .request::<lsp::request::InlayHintRefreshRequest>((), lsp::DEFAULT_LSP_REQUEST_TIMEOUT)
+ .await
+ .into_response()
+ .expect("inlay hint refresh request");
+ cx.executor().run_until_parked();
+ let (release_resolve, gate) = oneshot::channel();
+ *resolve_gate.lock() = Some(gate);
+ editor
+ .update(cx, |editor, window, cx| {
+ select_hints(editor, window, cx);
+ editor.accept_inlay_hint(&AcceptInlayHint, window, cx);
+ editor.buffer().update(cx, |multi_buffer, cx| {
+ multi_buffer.set_excerpts_for_path(
+ PathKey::sorted(0),
+ first_buffer.clone(),
+ [Point::new(1, 0)..Point::new(2, 0)],
+ 0,
+ cx,
+ );
+ });
+ })
+ .unwrap();
+ cx.executor().run_until_parked();
+ assert_eq!(buffer_texts(cx), original_texts);
+ release_resolve.send(()).expect("pending resolve gate");
+ cx.executor().run_until_parked();
+ assert_eq!(
+ buffer_texts(cx),
+ original_texts,
+ "a pending hint hidden by excerpt replacement is skipped"
+ );
+ editor
+ .update(cx, |editor, window, cx| {
+ assert_eq!(
+ editor.text(cx),
+ "fn third() { let c = 3; }\n\nfn second() { let b = 2; }\n"
+ );
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([MultiBufferOffset(0)..MultiBufferOffset(0)]);
+ });
+ editor.accept_inlay_hint(&AcceptInlayHint, window, cx);
+ })
+ .unwrap();
+ cx.executor().run_until_parked();
+ assert_eq!(buffer_texts(cx), original_texts);
+
+ editor
+ .update(cx, |editor, window, cx| {
+ let snapshot = editor.buffer().read(cx).snapshot(cx);
+ let second_hint = snapshot.text().find("b = 2").expect("second hint anchor") + 1;
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([
+ MultiBufferOffset(second_hint)..MultiBufferOffset(second_hint)
+ ]);
+ });
+ editor.accept_inlay_hint(&AcceptInlayHint, window, cx);
+ })
+ .unwrap();
+ cx.executor().run_until_parked();
+ let accepted_texts = (
+ original_texts.0,
+ "fn second() { let b: u64 = 2; }\n".to_string(),
+ );
+ assert_eq!(buffer_texts(cx), accepted_texts);
+
+ update_test_editor_settings(cx, &|settings| {
+ settings.double_click_in_multibuffer = Some(DoubleClickInMultibuffer::Open);
+ });
+ let mut cx = EditorTestContext::for_editor(editor, cx).await;
+ cx.update_editor(|editor, window, cx| {
+ window.focus(&editor.focus_handle, cx);
+ });
+ cx.run_until_parked();
+ let hint_row = cx
+ .display_text()
+ .lines()
+ .position(|line| line == "fn second() { let b: u64: u64 = 2; }")
+ .expect("second excerpt with the hint rendered") as u32;
+ let hint_point = cx.pixel_position_for(DisplayPoint::new(DisplayRow(hint_row), 20));
+ cx.simulate_mouse_move(hint_point, None, Modifiers::none());
+ cx.simulate_click(hint_point, Modifiers::none());
+ cx.simulate_event(MouseDownEvent {
+ position: hint_point,
+ modifiers: Modifiers::none(),
+ button: MouseButton::Left,
+ click_count: 2,
+ first_mouse: false,
+ });
+ cx.simulate_event(MouseUpEvent {
+ position: hint_point,
+ modifiers: Modifiers::none(),
+ button: MouseButton::Left,
+ click_count: 2,
+ });
+ assert_eq!(
+ (
+ cx.read(|cx| first_buffer.read(cx).text()),
+ cx.read(|cx| second_buffer.read(cx).text()),
+ ),
+ accepted_texts,
+ "double-clicking a hint with double_click_in_multibuffer=open must not insert it"
+ );
+ }
+
+ #[gpui::test]
+ async fn test_resolve_hint_after_concurrent_no_op_edit(cx: &mut gpui::TestAppContext) {
+ init_test(cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(0),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ })
+ });
+ let hint_requests = Arc::new(AtomicUsize::new(0));
+ let resolve_requests = Arc::new(AtomicUsize::new(0));
+ let mut cx = EditorLspTestContext::new_with_adapter(
+ Arc::into_inner(rust_lang()).expect("test language"),
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ inlay_hint_provider: Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ }),
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new({
+ let hint_requests = hint_requests.clone();
+ let resolve_requests = resolve_requests.clone();
+ move |server| {
+ let hint_requests = hint_requests.clone();
+ server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |_, _| {
+ hint_requests.fetch_add(1, Ordering::Release);
+ async move {
+ Ok(Some(vec![lsp::InlayHint {
+ position: lsp::Position::new(0, 21),
+ label: lsp::InlayHintLabel::String(": u32".to_string()),
kind: Some(lsp::InlayHintKind::TYPE),
text_edits: None,
tooltip: None,
padding_left: None,
padding_right: None,
- data: None,
+ data: Some(serde_json::Value::Bool(true)),
}]))
}
},
);
+ let resolve_requests = resolve_requests.clone();
+ server.set_request_handler::<lsp::request::InlayHintResolveRequest, _, _>(
+ move |mut hint, _| {
+ resolve_requests.fetch_add(1, Ordering::Release);
+ hint.text_edits = Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(hint.position, hint.position),
+ new_text: ": u32".to_string(),
+ }]);
+ async move { Ok(hint) }
+ },
+ );
}
})),
..FakeLspAdapter::default()
},
+ cx,
+ )
+ .await;
+ cx.set_state("fn main() { let valueˇ = 1; }\n");
+ cx.run_until_parked();
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(visible_hint_labels(editor, cx), vec![": u32"]);
+ });
+
+ let buffer =
+ cx.multibuffer(|multibuffer, _| multibuffer.as_singleton().expect("singleton"));
+ let (replica_state, replica_ops) = cx.update(|_, cx| {
+ let buffer = buffer.read(cx);
+ (buffer.to_proto(cx), buffer.serialize_ops(None, cx))
+ });
+ let replica_ops = replica_ops.await;
+ let replica = cx.update(|_, cx| {
+ cx.new(|cx| {
+ let mut replica = language::Buffer::from_proto(
+ ReplicaId::new(1),
+ Capability::ReadWrite,
+ replica_state,
+ None,
+ cx,
+ )
+ .expect("replica buffer");
+ replica.apply_ops(
+ replica_ops
+ .into_iter()
+ .map(|op| language::proto::deserialize_operation(op).expect("replica op")),
+ cx,
+ );
+ replica
+ })
+ });
+ let text_len = cx.buffer_text().len();
+ let trailing_newline = text_len - 1..text_len;
+
+ cx.update_buffer(|buffer, cx| {
+ buffer.edit([(trailing_newline.clone(), "")], None, cx);
+ });
+ cx.run_until_parked();
+ let hint_requests_after_edit = hint_requests.load(Ordering::Acquire);
+ let version_after_edit = cx.buffer(|buffer, _| buffer.version());
+
+ let concurrent_ops = cx.update(|_, cx| {
+ let version_before = replica.read(cx).version();
+ replica.update(cx, |replica, cx| {
+ replica.edit([(trailing_newline, "")], None, cx);
+ });
+ replica.read(cx).serialize_ops(Some(version_before), cx)
+ });
+ let concurrent_ops = concurrent_ops.await;
+ cx.update_buffer(|buffer, cx| {
+ buffer.apply_ops(
+ concurrent_ops
+ .into_iter()
+ .map(|op| language::proto::deserialize_operation(op).expect("concurrent op")),
+ cx,
+ );
+ });
+ cx.run_until_parked();
+ assert_eq!(cx.buffer_text(), "fn main() { let value = 1; }");
+ assert_eq!(
+ hint_requests.load(Ordering::Acquire),
+ hint_requests_after_edit,
+ "a text-preserving operation must not refetch hints"
+ );
+ assert!(
+ cx.buffer(|buffer, _| buffer.version())
+ .changed_since(&version_after_edit),
+ "the concurrent operation must advance the buffer version"
);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(visible_hint_labels(editor, cx), vec![": u32"]);
+ });
- // Server B returns a hint labeled "server_b" at a different position.
- let server_b_request_count = Arc::new(AtomicU32::new(0));
- let mut fake_servers_b = language_registry.register_fake_lsp(
- "Rust",
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(resolve_requests.load(Ordering::Acquire), 1);
+ assert_eq!(cx.buffer_text(), "fn main() { let value: u32 = 1; }");
+ }
+
+ #[gpui::test]
+ async fn test_refresh_requested_blocks_stale_hint_acceptance(cx: &mut gpui::TestAppContext) {
+ let debounce = Duration::from_millis(700);
+ init_test(cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(debounce.as_millis() as u64),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ })
+ });
+ let hint_requests = Arc::new(AtomicUsize::new(0));
+ let mut cx = EditorLspTestContext::new_with_adapter(
+ Arc::into_inner(rust_lang()).expect("test language"),
FakeLspAdapter {
- name: "secondary-ls",
capabilities: lsp::ServerCapabilities {
- inlay_hint_provider: Some(lsp::OneOf::Left(true)),
+ inlay_hint_provider: Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
+ resolve_provider: Some(false),
+ ..lsp::InlayHintOptions::default()
+ }),
+ )),
..lsp::ServerCapabilities::default()
},
initializer: Some(Box::new({
- let server_b_request_count = server_b_request_count.clone();
- move |fake_server| {
- let server_b_request_count = server_b_request_count.clone();
- fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
- move |_params, _| {
- let count =
- server_b_request_count.fetch_add(1, Ordering::Release) + 1;
+ let hint_requests = hint_requests.clone();
+ move |server| {
+ let hint_requests = hint_requests.clone();
+ server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |_, _| {
+ let request = hint_requests.fetch_add(1, Ordering::AcqRel);
async move {
+ let label = if request == 0 { ": u32" } else { ": u64" };
+ let position = lsp::Position::new(0, 21);
Ok(Some(vec![lsp::InlayHint {
- position: lsp::Position::new(0, 22),
- label: lsp::InlayHintLabel::String(format!(
- "server_b_{count}"
- )),
+ position,
+ label: lsp::InlayHintLabel::String(label.to_string()),
kind: Some(lsp::InlayHintKind::TYPE),
- text_edits: None,
+ text_edits: Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(position, position),
+ new_text: label.to_string(),
+ }]),
tooltip: None,
padding_left: None,
padding_right: None,
@@ -5083,81 +6190,143 @@ let c = 3;"#
})),
..FakeLspAdapter::default()
},
- );
+ cx,
+ )
+ .await;
+ cx.set_state("fn main() { let valueˇ = 1; }\n");
+ cx.background_executor.advance_clock(debounce);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(visible_hint_labels(editor, cx), vec![": u32"]);
+ });
+ cx.update(|window, cx| {
+ assert!(window.is_action_available(&AcceptInlayHint, cx));
+ });
- let (buffer, _buffer_handle) = project
- .update(cx, |project, cx| {
- project.open_local_buffer_with_lsp(path!("/a/main.rs"), cx)
- })
+ cx.lsp
+ .request::<lsp::request::InlayHintRefreshRequest>((), DEFAULT_LSP_REQUEST_TIMEOUT)
.await
- .unwrap();
- let editor =
- cx.add_window(|window, cx| Editor::for_buffer(buffer, Some(project), window, cx));
- cx.executor().run_until_parked();
+ .into_response()
+ .expect("inlay hint refresh request");
+ cx.run_until_parked();
+ assert_eq!(hint_requests.load(Ordering::Acquire), 1);
+ cx.update_editor(|editor, _, cx| {
+ assert_eq!(visible_hint_labels(editor, cx), vec![": u32"]);
+ cx.notify();
+ });
+ cx.run_until_parked();
+ cx.update(|window, cx| {
+ assert!(
+ window.is_action_available(&AcceptInlayHint, cx),
+ "displayed hints keep the action available during refresh"
+ );
+ });
+ cx.dispatch_action(AcceptInlayHint);
+ assert_eq!(cx.buffer_text(), "fn main() { let value = 1; }\n");
- let fake_server_a = fake_servers_a.next().await.unwrap();
- let _fake_server_b = fake_servers_b.next().await.unwrap();
+ cx.background_executor.advance_clock(debounce);
+ assert_eq!(hint_requests.load(Ordering::Acquire), 2);
+ assert_eq!(cx.buffer_text(), "fn main() { let value: u64 = 1; }\n");
+ }
- editor
- .update(cx, |editor, window, cx| {
- editor.set_visible_line_count(50.0, window, cx);
- editor.set_visible_column_count(120.0);
- editor.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
+ #[gpui::test]
+ async fn test_accept_clicked_hint_after_bias_changing_refresh(cx: &mut TestAppContext) {
+ let debounce = Duration::from_millis(700);
+ init_test(cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(debounce.as_millis() as u64),
+ scroll_debounce_ms: Some(0),
+ show_type_hints: Some(false),
+ ..InlayHintSettingsContent::default()
})
- .unwrap();
- cx.executor().advance_clock(Duration::from_millis(100));
- cx.executor().run_until_parked();
-
- // Verify both servers' hints are present initially.
- editor
- .update(cx, |editor, _window, cx| {
- let visible = visible_hint_labels(editor, cx);
- let has_a = visible.iter().any(|h| h.starts_with("server_a"));
- let has_b = visible.iter().any(|h| h.starts_with("server_b"));
- assert!(
- has_a && has_b,
- "Both servers should have hints initially. Got: {visible:?}"
+ });
+ let (_, editor, fake_server) = prepare_test_objects_with_text(
+ cx,
+ "fn main() { let value = 1; }\n",
+ |fake_server, _| {
+ let hint_requests = AtomicUsize::new(0);
+ fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |_, _| {
+ let request = hint_requests.fetch_add(1, Ordering::AcqRel);
+ async move {
+ let position = lsp::Position::new(0, 21);
+ let mut hints = vec![lsp::InlayHint {
+ position,
+ label: lsp::InlayHintLabel::String(": u32".to_string()),
+ kind: Some(lsp::InlayHintKind::PARAMETER),
+ text_edits: Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(position, position),
+ new_text: ": u32".to_string(),
+ }]),
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ }];
+ if request > 0 {
+ hints.push(lsp::InlayHint {
+ position,
+ label: lsp::InlayHintLabel::String("hidden".to_string()),
+ kind: Some(lsp::InlayHintKind::TYPE),
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ });
+ }
+ Ok(Some(hints))
+ }
+ },
);
+ },
+ )
+ .await;
+ let target = editor
+ .update(cx, |editor, _, cx| {
+ let hint = Editor::visible_inlay_hints(editor.display_map.read(cx))
+ .exactly_one()
+ .ok()
+ .expect("one visible hint");
+ assert_eq!(hint.position.bias(), Bias::Left);
+ HintTarget {
+ buffer_id: hint.position.buffer_id().expect("hint buffer"),
+ hint_id: hint.id,
+ position: hint.position,
+ }
})
.unwrap();
- // Trigger RefreshRequested from server A. This should re-fetch server A's
- // hints while keeping server B's hints intact.
- fake_server_a
- .request::<lsp::request::InlayHintRefreshRequest>((), lsp::DEFAULT_LSP_REQUEST_TIMEOUT)
+ fake_server
+ .request::<lsp::request::InlayHintRefreshRequest>((), DEFAULT_LSP_REQUEST_TIMEOUT)
.await
.into_response()
- .unwrap();
- cx.executor().advance_clock(Duration::from_millis(100));
+ .expect("inlay hint refresh request");
cx.executor().run_until_parked();
-
- // Also trigger NewLinesShown to give the system a chance to recover
- // any chunks that might have been cleared.
editor
- .update(cx, |editor, _window, cx| {
- editor.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
+ .update(cx, |editor, window, cx| {
+ assert!(editor.apply_inlay_hint_text_edits(
+ [target].into_iter(),
+ Some(0),
+ window,
+ cx,
+ ));
+ assert!(
+ editor
+ .inlay_hints
+ .as_ref()
+ .expect("inlay hints enabled")
+ .pending_refresh_acceptance
+ .is_some()
+ );
+ assert_eq!(editor.text(cx), "fn main() { let value = 1; }\n");
})
.unwrap();
- cx.executor().advance_clock(Duration::from_millis(100));
+ cx.executor().advance_clock(debounce);
cx.executor().run_until_parked();
-
editor
- .update(cx, |editor, _window, cx| {
- let visible = visible_hint_labels(editor, cx);
- let has_a = visible.iter().any(|h| h.starts_with("server_a"));
- let has_b = visible.iter().any(|h| h.starts_with("server_b"));
- assert!(
- has_a,
- "Server A hints should be present after its own refresh. Got: {visible:?}"
- );
- assert!(
- has_b,
- "Server B hints should NOT be lost when server A triggers \
- RefreshRequested. Bug 2: clear() wipes all tracking, then \
- LspStore filters out server B's cached hints via the for_server \
- guard, and apply_fetched_hints removes all visible hints but only \
- adds back server A's. Got: {visible:?}"
- );
+ .update(cx, |editor, _, cx| {
+ assert_eq!(editor.text(cx), "fn main() { let value: u32 = 1; }\n");
})
.unwrap();
}
@@ -5820,6 +6989,37 @@ let c = 3;"#
.unwrap();
}
+ pub fn cached_hint_labels(editor: &Editor, cx: &mut App) -> Vec<String> {
+ let lsp_store = editor.project().unwrap().read(cx).lsp_store();
+
+ let mut all_cached_labels = Vec::new();
+ let mut all_fetched_hints = Vec::new();
+ for buffer in editor.buffer.read(cx).all_buffers() {
+ lsp_store.update(cx, |lsp_store, cx| {
+ let hints = lsp_store.latest_lsp_data(&buffer, cx).inlay_hints();
+ all_cached_labels.extend(hints.all_cached_hints().into_iter().map(|hint| {
+ let mut label = hint.text().to_string();
+ if hint.padding_left {
+ label.insert(0, ' ');
+ }
+ if hint.padding_right {
+ label.push_str(" ");
+ }
+ label
+ }));
+ all_fetched_hints.extend(hints.all_fetched_hints());
+ });
+ }
+
+ all_cached_labels
+ }
+
+ pub fn visible_hint_labels(editor: &Editor, cx: &Context<Editor>) -> Vec<String> {
+ Editor::visible_inlay_hints(editor.display_map.read(cx))
+ .map(|hint| hint.text().to_string())
+ .collect()
+ }
+
pub(crate) fn init_test(cx: &mut TestAppContext, f: &dyn Fn(&mut AllLanguageSettingsContent)) {
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
@@ -5832,6 +7032,22 @@ let c = 3;"#
update_test_language_settings(cx, f);
}
+ fn editor_visible_range(
+ editor: &WindowHandle<Editor>,
+ cx: &mut gpui::TestAppContext,
+ ) -> Range<Point> {
+ let ranges = editor
+ .update(cx, |editor, _window, cx| editor.visible_buffer_ranges(cx))
+ .unwrap();
+ assert_eq!(
+ ranges.len(),
+ 1,
+ "Single buffer should produce a single excerpt with visible range"
+ );
+ let (buffer_snapshot, visible_range, _) = ranges.into_iter().next().unwrap();
+ visible_range.to_point(&buffer_snapshot)
+ }
+
async fn prepare_test_objects(
cx: &mut TestAppContext,
initialize: impl 'static + Send + Fn(&mut FakeLanguageServer, &'static str) + Send + Sync,
@@ -6160,37 +7376,6 @@ let c = 3;"#
labels
}
- pub fn cached_hint_labels(editor: &Editor, cx: &mut App) -> Vec<String> {
- let lsp_store = editor.project().unwrap().read(cx).lsp_store();
-
- let mut all_cached_labels = Vec::new();
- let mut all_fetched_hints = Vec::new();
- for buffer in editor.buffer.read(cx).all_buffers() {
- lsp_store.update(cx, |lsp_store, cx| {
- let hints = lsp_store.latest_lsp_data(&buffer, cx).inlay_hints();
- all_cached_labels.extend(hints.all_cached_hints().into_iter().map(|hint| {
- let mut label = hint.text().to_string();
- if hint.padding_left {
- label.insert(0, ' ');
- }
- if hint.padding_right {
- label.push_str(" ");
- }
- label
- }));
- all_fetched_hints.extend(hints.all_fetched_hints());
- });
- }
-
- all_cached_labels
- }
-
- pub fn visible_hint_labels(editor: &Editor, cx: &Context<Editor>) -> Vec<String> {
- Editor::visible_inlay_hints(editor.display_map.read(cx))
- .map(|hint| hint.text().to_string())
- .collect()
- }
-
fn allowed_hint_kinds_for_editor(editor: &Editor) -> HashSet<Option<InlayHintKind>> {
editor
.inlay_hints
diff --git a/crates/editor/src/split.rs b/crates/editor/src/split.rs
index a06d729e6a2..6ed6849dbe0 100644
--- a/crates/editor/src/split.rs
+++ b/crates/editor/src/split.rs
@@ -782,6 +782,12 @@ impl SplittableEditor {
}
}
+ EditorEvent::BufferFoldToggled { .. } => {
+ this.rhs_editor.update(cx, |editor, cx| {
+ editor.inlay_hint_visibility_changed(cx);
+ });
+ cx.emit(event.clone());
+ }
EditorEvent::OpenExcerptsRequested {
selections_by_buffer,
split,
@@ -860,6 +866,9 @@ impl SplittableEditor {
rhs_display_map.update(cx, |dm, cx| {
dm.set_companion(Some((lhs_display_map, companion.clone())), cx);
});
+ self.rhs_editor.update(cx, |editor, cx| {
+ editor.inlay_hint_visibility_changed(cx);
+ });
let lhs = self.lhs.as_ref().unwrap();
@@ -1175,6 +1184,7 @@ impl SplittableEditor {
rhs.display_map.update(cx, |dm, cx| {
dm.set_companion(None, cx);
});
+ rhs.inlay_hint_visibility_changed(cx);
});
cx.notify();
}
diff --git a/crates/project/src/debugger/dap_store.rs b/crates/project/src/debugger/dap_store.rs
index 01aedbbad02..751e028823a 100644
--- a/crates/project/src/debugger/dap_store.rs
+++ b/crates/project/src/debugger/dap_store.rs
@@ -691,6 +691,7 @@ impl DapStore {
padding_left: false,
padding_right: false,
tooltip: None,
+ text_edits: None,
resolve_state: ResolveState::Resolved,
});
}
@@ -712,6 +713,7 @@ impl DapStore {
padding_left: false,
padding_right: false,
tooltip: None,
+ text_edits: None,
resolve_state: ResolveState::Resolved,
});
};
diff --git a/crates/project/src/lsp_command.rs b/crates/project/src/lsp_command.rs
index 6d77cececab..d8b973cf15f 100644
--- a/crates/project/src/lsp_command.rs
+++ b/crates/project/src/lsp_command.rs
@@ -3,9 +3,9 @@ pub mod signature_help;
use crate::{
CodeAction, CompletionSource, CoreCompletion, CoreCompletionResponse, DocumentColor,
DocumentHighlight, DocumentSymbol, Hover, HoverBlock, HoverBlockKind, InlayHint,
- InlayHintLabel, InlayHintLabelPart, InlayHintLabelPartTooltip, InlayHintTooltip, Location,
- LocationLink, LspAction, LspPullDiagnostics, MarkupContent, PrepareRenameResponse, ProjectPath,
- ProjectTransaction, PulledDiagnostics, ResolveState,
+ InlayHintLabel, InlayHintLabelPart, InlayHintLabelPartTooltip, InlayHintTextEdits,
+ InlayHintTooltip, Location, LocationLink, LspAction, LspPullDiagnostics, MarkupContent,
+ PrepareRenameResponse, ProjectPath, ProjectTransaction, PulledDiagnostics, ResolveState,
lsp_store::{LanguageServerToQuery, LocalLspStore, LspDocumentLink, LspFoldingRange, LspStore},
};
use anyhow::{Context as _, Result};
@@ -3935,16 +3935,68 @@ impl InlayHints {
pub fn lsp_to_project_hint(
lsp_hint: lsp::InlayHint,
position: Anchor,
+ snapshot: &BufferSnapshot,
server_id: LanguageServerId,
resolve_state: ResolveState,
force_no_type_left_padding: bool,
- ) -> InlayHint {
+ ) -> anyhow::Result<InlayHint> {
let kind = lsp_hint.kind.and_then(|kind| match kind {
lsp::InlayHintKind::TYPE => Some(InlayHintKind::Type),
lsp::InlayHintKind::PARAMETER => Some(InlayHintKind::Parameter),
_ => None,
});
+ let text_edits = lsp_hint
+ .text_edits
+ .map(|edits| {
+ let mut edits = edits
+ .into_iter()
+ .map(|edit| {
+ let range = range_from_lsp(edit.range);
+ let start = snapshot.clip_point_utf16(range.start, Bias::Left);
+ let end = snapshot.clip_point_utf16(range.end, Bias::Left);
+ anyhow::ensure!(
+ start <= end,
+ "invalid inlay hint text edit range: {:?}",
+ edit.range
+ );
+ Ok((start..end, edit.new_text))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ edits.sort_by_key(|(range, _)| (range.start, range.end));
+ anyhow::ensure!(
+ edits
+ .windows(2)
+ .all(|edits| edits[0].0.end <= edits[1].0.start),
+ "overlapping inlay hint text edits"
+ );
+ edits.dedup_by(|(range, new_text), (previous_range, previous_text)| {
+ let adjacent = previous_range.end == range.start;
+ if adjacent {
+ previous_range.end = range.end;
+ previous_text.push_str(new_text);
+ }
+ adjacent
+ });
+ let edits = edits
+ .into_iter()
+ .map(|(range, mut new_text)| {
+ LineEnding::normalize(&mut new_text);
+ let start = snapshot.anchor_after(range.start);
+ let end = if range.is_empty() {
+ start
+ } else {
+ snapshot.anchor_before(range.end)
+ };
+ (start..end, new_text)
+ })
+ .collect();
+ anyhow::Ok(InlayHintTextEdits {
+ edits,
+ buffer_version: snapshot.version().clone(),
+ })
+ })
+ .transpose()?;
let label = Self::lsp_inlay_label_to_project(lsp_hint.label, server_id);
let padding_left = if force_no_type_left_padding && kind == Some(InlayHintKind::Type) {
false
@@ -3952,8 +4004,9 @@ impl InlayHints {
lsp_hint.padding_left.unwrap_or(false)
};
- InlayHint {
+ Ok(InlayHint {
position,
+ text_edits,
padding_left,
padding_right: lsp_hint.padding_right.unwrap_or(false),
label,
@@ -3971,7 +4024,25 @@ impl InlayHints {
}
}),
resolve_state,
+ })
+ }
+
+ pub async fn wait_for_hints_version(
+ message_hints: &[proto::InlayHint],
+ buffer_version: &[proto::VectorClockEntry],
+ buffer: &Entity<Buffer>,
+ cx: &mut AsyncApp,
+ ) -> anyhow::Result<()> {
+ let mut buffer_version = deserialize_version(buffer_version);
+ for text_edits in message_hints
+ .iter()
+ .filter_map(|hint| hint.text_edits.as_ref())
+ {
+ buffer_version.join(&deserialize_version(&text_edits.buffer_version));
}
+ buffer
+ .update(cx, |buffer, _| buffer.wait_for_version(buffer_version))
+ .await
}
fn lsp_inlay_label_to_project(
@@ -4031,6 +4102,13 @@ impl InlayHints {
lsp_resolve_state,
});
proto::InlayHint {
+ text_edits: response_hint.text_edits.map(|text_edits| proto::InlayHintTextEdits {
+ edits: text_edits.edits.into_iter().map(|(range, new_text)| proto::InlayHintTextEdit {
+ range: Some(serialize_anchor_range(range)),
+ new_text,
+ }).collect(),
+ buffer_version: serialize_version(&text_edits.buffer_version),
+ }),
position: Some(language::proto::serialize_anchor(&response_hint.position)),
padding_left: response_hint.padding_left,
padding_right: response_hint.padding_right,
@@ -4118,7 +4196,27 @@ impl InlayHints {
anyhow::bail!("Unexpected resolve state {invalid} for hint {message_hint:?}")
}
};
+ let text_edits = message_hint
+ .text_edits
+ .map(|text_edits| {
+ let edits = text_edits
+ .edits
+ .into_iter()
+ .map(|edit| {
+ let range = deserialize_anchor_range(
+ edit.range.context("missing inlay hint text edit range")?,
+ )?;
+ Ok((range, edit.new_text))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ anyhow::Ok(InlayHintTextEdits {
+ edits,
+ buffer_version: deserialize_version(&text_edits.buffer_version),
+ })
+ })
+ .transpose()?;
Ok(InlayHint {
+ text_edits,
position: message_hint
.position
.and_then(language::proto::deserialize_anchor)
@@ -4231,14 +4329,46 @@ impl InlayHints {
})
}
- pub fn project_to_lsp_hint(hint: InlayHint, snapshot: &BufferSnapshot) -> lsp::InlayHint {
- lsp::InlayHint {
+ pub fn project_to_lsp_hint(
+ hint: InlayHint,
+ snapshot: &BufferSnapshot,
+ ) -> Result<lsp::InlayHint> {
+ anyhow::ensure!(
+ snapshot.can_resolve(&hint.position),
+ "invalid inlay hint position anchor"
+ );
+ Ok(lsp::InlayHint {
position: point_to_lsp(hint.position.to_point_utf16(snapshot)),
kind: hint.kind.map(|kind| match kind {
InlayHintKind::Type => lsp::InlayHintKind::TYPE,
InlayHintKind::Parameter => lsp::InlayHintKind::PARAMETER,
}),
- text_edits: None,
+ text_edits: hint
+ .text_edits
+ .map(|text_edits| {
+ text_edits
+ .edits
+ .into_iter()
+ .map(|(range, new_text)| {
+ anyhow::ensure!(
+ snapshot.can_resolve(&range.start),
+ "invalid inlay hint text edit start anchor"
+ );
+ anyhow::ensure!(
+ snapshot.can_resolve(&range.end),
+ "invalid inlay hint text edit end anchor"
+ );
+ let start = range.start.to_point_utf16(snapshot);
+ let end = range.end.to_point_utf16(snapshot);
+ anyhow::ensure!(start <= end, "reversed inlay hint text edit range");
+ Ok(lsp::TextEdit {
+ range: lsp::Range::new(point_to_lsp(start), point_to_lsp(end)),
+ new_text,
+ })
+ })
+ .collect::<Result<Vec<_>>>()
+ })
+ .transpose()?,
tooltip: hint.tooltip.and_then(|tooltip| {
Some(match tooltip {
InlayHintTooltip::String(s) => lsp::InlayHintTooltip::String(s),
@@ -4296,7 +4426,7 @@ impl InlayHints {
ResolveState::CanResolve(_, data) => data,
ResolveState::Resolving | ResolveState::Resolved => None,
},
- }
+ })
}
pub fn can_resolve_inlays(capabilities: &ServerCapabilities) -> bool {
@@ -4391,7 +4521,7 @@ impl LspCommand for InlayHints {
.unwrap_or_default()
.into_iter()
.filter(|lsp_hint| lsp_hint.position.line <= last_row)
- .map(|lsp_hint| {
+ .filter_map(|lsp_hint| {
let resolve_state = if can_resolve {
ResolveState::CanResolve(lsp_server.server_id(), lsp_hint.data.clone())
} else {
@@ -4401,10 +4531,13 @@ impl LspCommand for InlayHints {
InlayHints::lsp_to_project_hint(
lsp_hint,
snapshot.anchor_at(position, bias),
+ &snapshot,
server_id,
resolve_state,
force_no_type_left_padding,
)
+ .context("lsp to project inlay hint conversion")
+ .log_err()
})
.collect();
@@ -4467,18 +4600,13 @@ impl LspCommand for InlayHints {
buffer: Entity<Buffer>,
mut cx: AsyncApp,
) -> anyhow::Result<Vec<InlayHint>> {
- buffer
- .update(&mut cx, |buffer, _| {
- buffer.wait_for_version(deserialize_version(&message.version))
- })
+ InlayHints::wait_for_hints_version(&message.hints, &message.version, &buffer, &mut cx)
.await?;
-
- let mut hints = Vec::new();
- for message_hint in message.hints {
- hints.push(InlayHints::proto_to_project_hint(message_hint)?);
- }
-
- Ok(hints)
+ message
+ .hints
+ .into_iter()
+ .map(InlayHints::proto_to_project_hint)
+ .collect()
}
fn buffer_id_from_proto(message: &proto::InlayHints) -> Result<BufferId> {
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index 6c7c4a2b182..8060738d850 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -4987,6 +4987,10 @@ impl LspStore {
}
}
+ pub fn cached_inlay_hint(&self, buffer_id: BufferId, id: InlayId) -> Option<&InlayHint> {
+ self.lsp_data.get(&buffer_id)?.inlay_hints.cached_hint(id)
+ }
+
fn send_lsp_proto_request<R: LspCommand>(
&self,
buffer: Entity<Buffer>,
@@ -6889,44 +6893,51 @@ impl LspStore {
buffer_lsp_hints.hint_resolves.get(&id)?.clone(),
));
}
- ResolveState::CanResolve(server_id, resolve_data) => (*server_id, resolve_data.clone()),
+ ResolveState::CanResolve(server_id, resolve_data)
+ if !buffer.read(cx).has_edits_since(&lsp_data.buffer_version) =>
+ {
+ (*server_id, resolve_data.clone())
+ }
+ ResolveState::CanResolve(_, _) => return None,
};
let resolve_task = self.resolve_inlay_hint(hint, buffer, server_id, cx);
- let buffer_lsp_hints = &mut self.lsp_data.get_mut(&buffer_id)?.inlay_hints;
- let previous_task = buffer_lsp_hints.hint_resolves.insert(
- id,
- cx.spawn(async move |lsp_store, cx| {
+ let resolve_task = cx
+ .spawn(async move |lsp_store, cx| {
let resolved_hint = resolve_task.await;
lsp_store
.update(cx, |lsp_store, _| {
- if let Some(old_inlay_hint) = lsp_store
- .lsp_data
- .get_mut(&buffer_id)
- .and_then(|buffer_lsp_data| buffer_lsp_data.inlay_hints.hint_for_id(id))
- {
- match resolved_hint {
- Ok(resolved_hint) => {
- *old_inlay_hint = resolved_hint;
- }
- Err(e) => {
- old_inlay_hint.resolve_state =
- ResolveState::CanResolve(server_id, resolve_data);
- log::error!("Inlay hint resolve failed: {e:#}");
- }
+ let buffer_lsp_hints =
+ &mut lsp_store.lsp_data.get_mut(&buffer_id)?.inlay_hints;
+ buffer_lsp_hints.hint_resolves.remove(&id);
+ let old_inlay_hint = buffer_lsp_hints.hint_for_id(id)?;
+ match resolved_hint {
+ Ok(resolved_hint) => {
+ *old_inlay_hint = resolved_hint.clone();
+ Some(resolved_hint)
+ }
+ Err(error) => {
+ old_inlay_hint.resolve_state =
+ ResolveState::CanResolve(server_id, resolve_data);
+ log::error!("Inlay hint resolve failed: {error:#}");
+ None
}
}
})
- .ok();
+ .ok()
+ .flatten()
})
- .shared(),
- );
+ .shared();
+ let buffer_lsp_hints = &mut self.lsp_data.get_mut(&buffer_id)?.inlay_hints;
+ let previous_task = buffer_lsp_hints
+ .hint_resolves
+ .insert(id, resolve_task.clone());
debug_assert!(
previous_task.is_none(),
"Did not change hint's resolve state after spawning its resolve"
);
buffer_lsp_hints.hint_for_id(id)?.resolve_state = ResolveState::Resolving;
- None
+ Some(ResolvedHint::Resolving(resolve_task))
}
pub(crate) fn linked_edits(
@@ -16325,7 +16336,7 @@ impl From<lsp::Documentation> for CompletionDocumentation {
pub enum ResolvedHint {
Resolved(InlayHint),
- Resolving(Shared<Task<()>>),
+ Resolving(Shared<Task<Option<InlayHint>>>),
}
pub fn glob_literal_prefix(glob: &Path) -> PathBuf {
@@ -16913,6 +16924,249 @@ fn extend_formatting_transaction(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::{InlayHintLabel, InlayHintTextEdits, Project};
+ use fs::FakeFs;
+ use futures::future;
+ use gpui::TestAppContext;
+ use settings::SettingsStore;
+ use text::Point;
+
+ #[gpui::test]
+ fn test_inlay_hint_server_removal_retires_ids_and_resolves(cx: &mut TestAppContext) {
+ let buffer = cx.new(|cx| Buffer::local("x", cx));
+ let position = buffer.read_with(cx, |buffer, _| buffer.anchor_after(0));
+ let mut hints = cx.update(|cx| BufferInlayHints::new(&buffer, cx));
+ let chunk = hints
+ .applicable_chunks(&[Point::new(0, 0)..Point::new(0, 1)])
+ .next()
+ .expect("inlay chunk");
+ let server_id = LanguageServerId(1);
+ let other_server_id = LanguageServerId(2);
+ let old_id = InlayId::Hint(1);
+ let other_id = InlayId::Hint(2);
+ let new_id = InlayId::Hint(3);
+ let old_hint = inlay_hint_for_test(position, "old");
+ let other_hint = inlay_hint_for_test(position, "other");
+ let new_hint = inlay_hint_for_test(position, "new");
+ hints.insert_new_hints(chunk, server_id, vec![(old_id, old_hint)]);
+ hints.insert_new_hints(chunk, other_server_id, vec![(other_id, other_hint.clone())]);
+ let cancelled = Arc::new(AtomicUsize::new(0));
+ let resolve = cx.background_executor.spawn({
+ let cancelled = cancelled.clone();
+ async move {
+ let _cancelled = defer(move || {
+ cancelled.fetch_add(1, atomic::Ordering::SeqCst);
+ });
+ future::pending::<Option<InlayHint>>().await
+ }
+ });
+ hints.hint_resolves.insert(old_id, resolve.shared());
+ hints
+ .hint_resolves
+ .insert(other_id, Task::ready(None).shared());
+ cx.run_until_parked();
+
+ hints.remove_server_data(server_id);
+ hints.insert_new_hints(chunk, server_id, vec![(new_id, new_hint.clone())]);
+ assert_eq!(hints.cached_hint(old_id), None);
+ assert_eq!(hints.hint_for_id(old_id), None);
+ assert_eq!(hints.cached_hint(new_id), Some(&new_hint));
+ assert_eq!(hints.cached_hint(other_id), Some(&other_hint));
+ assert_eq!(
+ hints.hint_resolves.keys().copied().collect::<Vec<_>>(),
+ vec![other_id]
+ );
+ cx.run_until_parked();
+ assert_eq!(cancelled.load(atomic::Ordering::SeqCst), 1);
+ }
+
+ #[gpui::test]
+ async fn test_inlay_hint_resolve_retires_task_without_losing_waiters(cx: &mut TestAppContext) {
+ cx.update(|cx| {
+ let settings_store = SettingsStore::test(cx);
+ cx.set_global(settings_store);
+ });
+ let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs, [], cx).await;
+ let buffer = project.update(cx, |project, cx| {
+ project.create_local_buffer("x", None, false, cx)
+ });
+ let (buffer_id, position) =
+ buffer.read_with(cx, |buffer, _| (buffer.remote_id(), buffer.anchor_after(0)));
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ let id = InlayId::Hint(1);
+ let server_id = LanguageServerId(1);
+ let expected = inlay_hint_for_test(position, "hint");
+ let (resolve, other_resolve) = lsp_store.update(cx, |lsp_store, cx| {
+ let hints = &mut lsp_store.latest_lsp_data(&buffer, cx).inlay_hints;
+ let chunk = hints
+ .applicable_chunks(&[Point::new(0, 0)..Point::new(0, 1)])
+ .next()
+ .expect("inlay chunk");
+ let mut hint = expected.clone();
+ hint.resolve_state = ResolveState::CanResolve(server_id, None);
+ hints.insert_new_hints(chunk, server_id, vec![(id, hint)]);
+ let Some(ResolvedHint::Resolving(resolve)) = lsp_store.resolved_hint(buffer_id, id, cx)
+ else {
+ panic!("expected a pending resolve");
+ };
+ let Some(ResolvedHint::Resolving(other_resolve)) =
+ lsp_store.resolved_hint(buffer_id, id, cx)
+ else {
+ panic!("expected a shared pending resolve");
+ };
+ assert_eq!(
+ lsp_store.lsp_data[&buffer_id]
+ .inlay_hints
+ .hint_resolves
+ .len(),
+ 1
+ );
+ (resolve, other_resolve)
+ });
+ assert_eq!(resolve.await, Some(expected.clone()));
+ assert_eq!(other_resolve.await, Some(expected.clone()));
+ lsp_store.update(cx, |lsp_store, cx| {
+ assert!(
+ lsp_store.lsp_data[&buffer_id]
+ .inlay_hints
+ .hint_resolves
+ .is_empty()
+ );
+ assert_eq!(lsp_store.cached_inlay_hint(buffer_id, id), Some(&expected));
+ let Some(ResolvedHint::Resolved(hint)) = lsp_store.resolved_hint(buffer_id, id, cx)
+ else {
+ panic!("expected a cached resolved hint");
+ };
+ assert_eq!(hint, expected);
+ });
+ }
+
+ #[gpui::test]
+ async fn test_inlay_hint_rejects_malformed_edit_anchors(cx: &mut TestAppContext) {
+ let buffer = cx.new(|cx| Buffer::local("a😀b", cx));
+ let position = buffer.read_with(cx, |buffer, _| buffer.anchor_after(1));
+ let other_buffer = cx.new(|cx| Buffer::local("a😀b", cx));
+ let invalid_anchor = other_buffer.read_with(cx, |buffer, _| buffer.anchor_after(1));
+ let mut async_cx = cx.to_async();
+ for (hint_position, start, end, expected) in [
+ (
+ position,
+ invalid_anchor,
+ position,
+ "invalid inlay hint text edit start anchor",
+ ),
+ (
+ position,
+ position,
+ invalid_anchor,
+ "invalid inlay hint text edit end anchor",
+ ),
+ (
+ invalid_anchor,
+ position,
+ position,
+ "invalid inlay hint position anchor",
+ ),
+ ] {
+ let mut hint = inlay_hint_for_test(hint_position, "hint");
+ hint.text_edits = Some(InlayHintTextEdits {
+ edits: vec![(start..end, "replacement".to_string())],
+ buffer_version: Global::new(),
+ });
+ let message = InlayHints::project_to_proto_hint(hint);
+ InlayHints::wait_for_hints_version(
+ std::slice::from_ref(&message),
+ &[],
+ &buffer,
+ &mut async_cx,
+ )
+ .await
+ .expect("empty versions");
+ let hint = InlayHints::proto_to_project_hint(message).expect("hint payload");
+ let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
+ let result = InlayHints::project_to_lsp_hint(hint, &snapshot);
+
+ assert_eq!(
+ result.map(|_| ()).map_err(|error| error.to_string()),
+ Err(expected.to_string()),
+ );
+ }
+ }
+
+ #[gpui::test]
+ fn test_inlay_hint_rejects_reversed_edit_ranges(cx: &mut TestAppContext) {
+ let buffer = cx.new(|cx| Buffer::local("a😀b", cx));
+ let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
+ let ranges = [
+ snapshot.anchor_after(5)..snapshot.anchor_before(1),
+ snapshot.anchor_after(1)..snapshot.anchor_before(1),
+ ];
+ let version = snapshot.version().clone();
+ buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "x")], None, cx));
+ let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
+ assert_eq!(snapshot.text(), "ax😀b");
+ for range in ranges {
+ let mut hint = inlay_hint_for_test(snapshot.anchor_after(1), "hint");
+ hint.text_edits = Some(InlayHintTextEdits {
+ edits: vec![(range, "replacement".to_string())],
+ buffer_version: version.clone(),
+ });
+ assert_eq!(
+ InlayHints::project_to_lsp_hint(hint, &snapshot)
+ .map(|_| ())
+ .map_err(|error| error.to_string()),
+ Err("reversed inlay hint text edit range".to_string()),
+ );
+ }
+ }
+
+ #[gpui::test]
+ fn test_inlay_hint_converts_valid_edit_anchors(cx: &mut TestAppContext) {
+ let buffer = cx.new(|cx| Buffer::local("a😀b", cx));
+ let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
+ let mut hint = inlay_hint_for_test(snapshot.anchor_after(5), "hint");
+ hint.text_edits = Some(InlayHintTextEdits {
+ edits: vec![(
+ snapshot.anchor_after(1)..snapshot.anchor_before(5),
+ "z".to_string(),
+ )],
+ buffer_version: snapshot.version().clone(),
+ });
+ for (edit, position, start) in [
+ (None, lsp::Position::new(0, 3), lsp::Position::new(0, 1)),
+ (
+ Some((0..0, "é")),
+ lsp::Position::new(0, 4),
+ lsp::Position::new(0, 2),
+ ),
+ (
+ Some((0..0, "\n")),
+ lsp::Position::new(1, 4),
+ lsp::Position::new(1, 2),
+ ),
+ (
+ Some((4..8, "")),
+ lsp::Position::new(1, 2),
+ lsp::Position::new(1, 2),
+ ),
+ ] {
+ if let Some(edit) = edit {
+ buffer.update(cx, |buffer, cx| buffer.edit([edit], None, cx));
+ }
+ let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
+ let converted = InlayHints::project_to_lsp_hint(hint.clone(), &snapshot)
+ .expect("valid hint anchors in a later snapshot");
+ assert_eq!(converted.position, position);
+ assert_eq!(
+ converted.text_edits,
+ Some(vec![lsp::TextEdit {
+ range: lsp::Range::new(start, position),
+ new_text: "z".to_string(),
+ }])
+ );
+ }
+ }
#[gpui::test]
async fn test_fetch_inlay_hints_after_buffer_edit(cx: &mut gpui::TestAppContext) {
@@ -17249,4 +17503,17 @@ mod tests {
response_error.data = data;
anyhow::Error::new(response_error)
}
+
+ fn inlay_hint_for_test(position: Anchor, label: &str) -> InlayHint {
+ InlayHint {
+ position,
+ label: InlayHintLabel::String(label.to_string()),
+ kind: None,
+ padding_left: false,
+ padding_right: false,
+ tooltip: None,
+ text_edits: None,
+ resolve_state: ResolveState::Resolved,
+ }
+ }
}
diff --git a/crates/project/src/lsp_store/inlay_hints.rs b/crates/project/src/lsp_store/inlay_hints.rs
index 27bb427ce1a..3ceb317caf5 100644
--- a/crates/project/src/lsp_store/inlay_hints.rs
+++ b/crates/project/src/lsp_store/inlay_hints.rs
@@ -1,4 +1,4 @@
-use std::{collections::hash_map, ops::Range, sync::Arc};
+use std::{collections::hash_map, ops::Range, slice, sync::Arc};
use anyhow::{Context as _, Result};
use collections::{HashMap, HashSet};
@@ -6,6 +6,7 @@ use futures::future::Shared;
use gpui::{App, AppContext as _, AsyncApp, Context, Entity, Task};
use language::{
Buffer,
+ proto::serialize_version,
row_chunk::{RowChunk, RowChunks},
};
use lsp::LanguageServerId;
@@ -85,7 +86,7 @@ pub struct BufferInlayHints {
pending_refreshes: HashSet<LanguageServerId>,
work_end_refreshes: HashSet<LanguageServerId>,
pub(super) fetched_servers: HashSet<LanguageServerId>,
- pub(super) hint_resolves: HashMap<InlayId, Shared<Task<()>>>,
+ pub(super) hint_resolves: HashMap<InlayId, Shared<Task<Option<InlayHint>>>>,
}
#[derive(Debug, Clone, Copy)]
@@ -156,16 +157,24 @@ impl BufferInlayHints {
}
pub fn remove_server_data(&mut self, for_server: LanguageServerId) {
- for (chunk_index, hints) in self.hints_by_chunks.iter_mut().enumerate() {
- if let Some(hints) = hints {
- if hints.remove(&for_server).is_some() {
- self.fetches_by_chunks[chunk_index] = None;
- }
- }
- }
+ self.remove_hints_for_server(for_server);
self.pending_refreshes.remove(&for_server);
self.work_end_refreshes.remove(&for_server);
- self.fetched_servers.remove(&for_server);
+ }
+
+ pub fn cached_hint(&self, id: InlayId) -> Option<&InlayHint> {
+ let hint_for_id = self.hints_by_id.get(&id)?;
+ if self.pending_refreshes.contains(&hint_for_id.server_id) {
+ return None;
+ }
+ let (hint_id, hint) = self
+ .hints_by_chunks
+ .get(hint_for_id.chunk_id)?
+ .as_ref()?
+ .get(&hint_for_id.server_id)?
+ .get(hint_for_id.position)?;
+ debug_assert_eq!(*hint_id, id, "Invalid pointer {hint_for_id:?}");
+ Some(hint)
}
fn mark_refresh_pending(&mut self, server_id: LanguageServerId) {
@@ -248,6 +257,21 @@ impl BufferInlayHints {
return false;
}
+ self.remove_hints_for_server(for_server);
+ true
+ }
+
+ pub(crate) fn invalidate_for_chunk(&mut self, chunk: RowChunk) {
+ self.fetches_by_chunks[chunk.id] = None;
+ if let Some(hints_by_server) = self.hints_by_chunks[chunk.id].take() {
+ for (hint_id, _) in hints_by_server.into_values().flatten() {
+ self.hints_by_id.remove(&hint_id);
+ self.hint_resolves.remove(&hint_id);
+ }
+ }
+ }
+
+ fn remove_hints_for_server(&mut self, for_server: LanguageServerId) {
for (chunk_id, chunk_data) in self.hints_by_chunks.iter_mut().enumerate() {
if let Some(removed_hints) = chunk_data
.as_mut()
@@ -261,18 +285,6 @@ impl BufferInlayHints {
}
}
self.fetched_servers.remove(&for_server);
-
- true
- }
-
- pub(crate) fn invalidate_for_chunk(&mut self, chunk: RowChunk) {
- self.fetches_by_chunks[chunk.id] = None;
- if let Some(hints_by_server) = self.hints_by_chunks[chunk.id].take() {
- for (hint_id, _) in hints_by_server.into_values().flatten() {
- self.hints_by_id.remove(&hint_id);
- self.hint_resolves.remove(&hint_id);
- }
- }
}
}
@@ -301,17 +313,25 @@ impl LspStore {
buffer_id: buffer.read(cx).remote_id().into(),
language_server_id: server_id.0 as u64,
hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
+ version: serialize_version(&buffer.read(cx).version()),
};
- cx.background_spawn(async move {
+ cx.spawn(async move |_, cx| {
let response = upstream_client
.request(request)
.await
.context("inlay hints proto request")?;
- match response.hint {
- Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
- .context("inlay hints proto resolve response conversion"),
- None => Ok(hint),
- }
+ let Some(resolved_hint) = response.hint else {
+ return Ok(hint);
+ };
+ InlayHints::wait_for_hints_version(
+ slice::from_ref(&resolved_hint),
+ &response.version,
+ &buffer,
+ cx,
+ )
+ .await?;
+ InlayHints::proto_to_project_hint(resolved_hint)
+ .context("inlay hints proto resolve response conversion")
})
} else {
let Some(lang_server) = buffer.update(cx, |buffer, cx| {
@@ -327,20 +347,21 @@ impl LspStore {
let origin_position = hint.position;
cx.background_spawn(async move {
let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
- InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
+ InlayHints::project_to_lsp_hint(hint, &buffer_snapshot)?,
request_timeout,
);
let resolved_hint = resolve_task
.await
.into_response()
.context("inlay hint resolve LSP request")?;
- Ok(InlayHints::lsp_to_project_hint(
+ InlayHints::lsp_to_project_hint(
resolved_hint,
origin_position,
+ &buffer_snapshot,
server_id,
ResolveState::Resolved,
false,
- ))
+ )
})
}
}
@@ -415,17 +436,24 @@ impl LspStore {
.payload
.hint
.expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
- let hint = InlayHints::proto_to_project_hint(proto_hint)
- .context("resolved proto inlay hint conversion")?;
let buffer = lsp_store.update(&mut cx, |lsp_store, cx| {
let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
lsp_store.buffer_store.read(cx).get_existing(buffer_id)
})?;
+ InlayHints::wait_for_hints_version(
+ slice::from_ref(&proto_hint),
+ &envelope.payload.version,
+ &buffer,
+ &mut cx,
+ )
+ .await?;
+ let hint = InlayHints::proto_to_project_hint(proto_hint)
+ .context("resolved proto inlay hint conversion")?;
let response_hint = lsp_store
.update(&mut cx, |lsp_store, cx| {
lsp_store.resolve_inlay_hint(
hint,
- buffer,
+ buffer.clone(),
LanguageServerId(envelope.payload.language_server_id as usize),
cx,
)
@@ -434,6 +462,7 @@ impl LspStore {
.context("inlay hints fetch")?;
Ok(proto::ResolveInlayHintResponse {
hint: Some(InlayHints::project_to_proto_hint(response_hint)),
+ version: buffer.read_with(&cx, |buffer, _| serialize_version(&buffer.version())),
})
}
}
diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs
index b85cf191e02..9e8fc893671 100644
--- a/crates/project/src/project.rs
+++ b/crates/project/src/project.rs
@@ -505,10 +505,10 @@ pub enum PrepareRenameResponse {
pub enum InlayId {
EditPrediction(usize),
DebuggerValue(usize),
+ ReplResult(usize),
// LSP
Hint(usize),
Color(usize),
- ReplResult(usize),
}
impl InlayId {
@@ -531,9 +531,16 @@ pub struct InlayHint {
pub padding_left: bool,
pub padding_right: bool,
pub tooltip: Option<InlayHintTooltip>,
+ pub text_edits: Option<InlayHintTextEdits>,
pub resolve_state: ResolveState,
}
+#[derive(Debug, Clone, PartialEq)]
+pub struct InlayHintTextEdits {
+ pub edits: Vec<(Range<Anchor>, String)>,
+ pub buffer_version: clock::Global,
+}
+
/// The user's intent behind a given completion confirmation.
#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
pub enum CompletionIntent {
@@ -855,6 +862,12 @@ impl InlayHint {
InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &*part.value).collect(),
}
}
+
+ pub fn has_text_edits(&self) -> bool {
+ self.text_edits
+ .as_ref()
+ .is_some_and(|text_edits| !text_edits.edits.is_empty())
+ }
}
#[derive(Debug, Clone, PartialEq)]
diff --git a/crates/proto/proto/lsp.proto b/crates/proto/proto/lsp.proto
index 12e2b9a003d..5a5dfa4069f 100644
--- a/crates/proto/proto/lsp.proto
+++ b/crates/proto/proto/lsp.proto
@@ -552,6 +552,17 @@ message InlayHint {
bool padding_right = 5;
InlayHintTooltip tooltip = 6;
ResolveState resolve_state = 7;
+ InlayHintTextEdits text_edits = 8;
+}
+
+message InlayHintTextEdits {
+ repeated InlayHintTextEdit edits = 1;
+ repeated VectorClockEntry buffer_version = 2;
+}
+
+message InlayHintTextEdit {
+ AnchorRange range = 1;
+ string new_text = 2;
}
message InlayHintLabel {
@@ -631,10 +642,12 @@ message ResolveInlayHint {
uint64 buffer_id = 2;
uint64 language_server_id = 3;
InlayHint hint = 4;
+ repeated VectorClockEntry version = 5;
}
message ResolveInlayHintResponse {
InlayHint hint = 1;
+ repeated VectorClockEntry version = 2;
}
message RefreshInlayHints {
diff --git a/docs/src/configuring-languages.md b/docs/src/configuring-languages.md
index 1d9897dadda..96d8ba45b4a 100644
--- a/docs/src/configuring-languages.md
+++ b/docs/src/configuring-languages.md
@@ -490,6 +490,11 @@ Inlay hints provide additional information inline in your code, such as paramete
}
```
+Hover a hint to see its tooltip, and double-click it to insert it into the code, if the language server provides the edits for that (for example, rust-analyzer's type hints).
+If a hint has a command, clicking it runs that command instead.
+
+{#action editor::AcceptInlayHint} inserts the first editable hint within the selection, one hint per invocation.
+
For language-specific inlay hint settings, refer to the documentation for each language.
### Code Actions