1use crate::{
2 element::PointForPosition,
3 hover_popover::{self, InlayHover},
4 Anchor, Editor, EditorSnapshot, GoToDefinition, GoToTypeDefinition, InlayId, SelectPhase,
5};
6use gpui::{px, AsyncWindowContext, Model, Modifiers, Task, ViewContext};
7use language::{Bias, ToOffset};
8use linkify::{LinkFinder, LinkKind};
9use lsp::LanguageServerId;
10use project::{
11 HoverBlock, HoverBlockKind, InlayHintLabelPartTooltip, InlayHintTooltip, LocationLink,
12 ResolveState,
13};
14use std::ops::Range;
15use theme::ActiveTheme as _;
16use util::TryFutureExt;
17
18#[derive(Debug)]
19pub struct HoveredLinkState {
20 pub last_trigger_point: TriggerPoint,
21 pub preferred_kind: LinkDefinitionKind,
22 pub symbol_range: Option<RangeInEditor>,
23 pub links: Vec<HoverLink>,
24 pub task: Option<Task<Option<()>>>,
25}
26
27#[derive(Debug, Eq, PartialEq, Clone)]
28pub enum RangeInEditor {
29 Text(Range<Anchor>),
30 Inlay(InlayHighlight),
31}
32
33impl RangeInEditor {
34 pub fn as_text_range(&self) -> Option<Range<Anchor>> {
35 match self {
36 Self::Text(range) => Some(range.clone()),
37 Self::Inlay(_) => None,
38 }
39 }
40
41 fn point_within_range(&self, trigger_point: &TriggerPoint, snapshot: &EditorSnapshot) -> bool {
42 match (self, trigger_point) {
43 (Self::Text(range), TriggerPoint::Text(point)) => {
44 let point_after_start = range.start.cmp(point, &snapshot.buffer_snapshot).is_le();
45 point_after_start && range.end.cmp(point, &snapshot.buffer_snapshot).is_ge()
46 }
47 (Self::Inlay(highlight), TriggerPoint::InlayHint(point, _, _)) => {
48 highlight.inlay == point.inlay
49 && highlight.range.contains(&point.range.start)
50 && highlight.range.contains(&point.range.end)
51 }
52 (Self::Inlay(_), TriggerPoint::Text(_))
53 | (Self::Text(_), TriggerPoint::InlayHint(_, _, _)) => false,
54 }
55 }
56}
57
58#[derive(Debug, Clone)]
59pub enum HoverLink {
60 Url(String),
61 Text(LocationLink),
62 InlayHint(lsp::Location, LanguageServerId),
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub(crate) struct InlayHighlight {
67 pub inlay: InlayId,
68 pub inlay_position: Anchor,
69 pub range: Range<usize>,
70}
71
72#[derive(Debug, Clone, PartialEq)]
73pub enum TriggerPoint {
74 Text(Anchor),
75 InlayHint(InlayHighlight, lsp::Location, LanguageServerId),
76}
77
78impl TriggerPoint {
79 fn anchor(&self) -> &Anchor {
80 match self {
81 TriggerPoint::Text(anchor) => anchor,
82 TriggerPoint::InlayHint(inlay_range, _, _) => &inlay_range.inlay_position,
83 }
84 }
85}
86
87impl Editor {
88 pub(crate) fn update_hovered_link(
89 &mut self,
90 point_for_position: PointForPosition,
91 snapshot: &EditorSnapshot,
92 modifiers: Modifiers,
93 cx: &mut ViewContext<Self>,
94 ) {
95 if !modifiers.command || self.has_pending_selection() {
96 self.hide_hovered_link(cx);
97 return;
98 }
99
100 match point_for_position.as_valid() {
101 Some(point) => {
102 let trigger_point = TriggerPoint::Text(
103 snapshot
104 .buffer_snapshot
105 .anchor_before(point.to_offset(&snapshot.display_snapshot, Bias::Left)),
106 );
107
108 show_link_definition(modifiers.shift, self, trigger_point, snapshot, cx);
109 }
110 None => {
111 update_inlay_link_and_hover_points(
112 &snapshot,
113 point_for_position,
114 self,
115 modifiers.command,
116 modifiers.shift,
117 cx,
118 );
119 }
120 }
121 }
122
123 pub(crate) fn hide_hovered_link(&mut self, cx: &mut ViewContext<Self>) {
124 self.hovered_link_state.take();
125 self.clear_highlights::<HoveredLinkState>(cx);
126 }
127
128 pub(crate) fn handle_click_hovered_link(
129 &mut self,
130 point: PointForPosition,
131 modifiers: Modifiers,
132 cx: &mut ViewContext<Editor>,
133 ) {
134 if let Some(hovered_link_state) = self.hovered_link_state.take() {
135 self.hide_hovered_link(cx);
136 if !hovered_link_state.links.is_empty() {
137 if !self.focus_handle.is_focused(cx) {
138 cx.focus(&self.focus_handle);
139 }
140
141 self.navigate_to_hover_links(hovered_link_state.links, modifiers.alt, cx);
142 return;
143 }
144 }
145
146 // We don't have the correct kind of link cached, set the selection on
147 // click and immediately trigger GoToDefinition.
148 self.select(
149 SelectPhase::Begin {
150 position: point.next_valid,
151 add: false,
152 click_count: 1,
153 },
154 cx,
155 );
156
157 if point.as_valid().is_some() {
158 if modifiers.shift {
159 self.go_to_type_definition(&GoToTypeDefinition, cx)
160 } else {
161 self.go_to_definition(&GoToDefinition, cx)
162 }
163 }
164 }
165}
166
167pub fn update_inlay_link_and_hover_points(
168 snapshot: &EditorSnapshot,
169 point_for_position: PointForPosition,
170 editor: &mut Editor,
171 cmd_held: bool,
172 shift_held: bool,
173 cx: &mut ViewContext<'_, Editor>,
174) {
175 let hovered_offset = if point_for_position.column_overshoot_after_line_end == 0 {
176 Some(snapshot.display_point_to_inlay_offset(point_for_position.exact_unclipped, Bias::Left))
177 } else {
178 None
179 };
180 let mut go_to_definition_updated = false;
181 let mut hover_updated = false;
182 if let Some(hovered_offset) = hovered_offset {
183 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
184 let previous_valid_anchor = buffer_snapshot.anchor_at(
185 point_for_position.previous_valid.to_point(snapshot),
186 Bias::Left,
187 );
188 let next_valid_anchor = buffer_snapshot.anchor_at(
189 point_for_position.next_valid.to_point(snapshot),
190 Bias::Right,
191 );
192 if let Some(hovered_hint) = editor
193 .visible_inlay_hints(cx)
194 .into_iter()
195 .skip_while(|hint| {
196 hint.position
197 .cmp(&previous_valid_anchor, &buffer_snapshot)
198 .is_lt()
199 })
200 .take_while(|hint| {
201 hint.position
202 .cmp(&next_valid_anchor, &buffer_snapshot)
203 .is_le()
204 })
205 .max_by_key(|hint| hint.id)
206 {
207 let inlay_hint_cache = editor.inlay_hint_cache();
208 let excerpt_id = previous_valid_anchor.excerpt_id;
209 if let Some(cached_hint) = inlay_hint_cache.hint_by_id(excerpt_id, hovered_hint.id) {
210 match cached_hint.resolve_state {
211 ResolveState::CanResolve(_, _) => {
212 if let Some(buffer_id) = previous_valid_anchor.buffer_id {
213 inlay_hint_cache.spawn_hint_resolve(
214 buffer_id,
215 excerpt_id,
216 hovered_hint.id,
217 cx,
218 );
219 }
220 }
221 ResolveState::Resolved => {
222 let mut extra_shift_left = 0;
223 let mut extra_shift_right = 0;
224 if cached_hint.padding_left {
225 extra_shift_left += 1;
226 extra_shift_right += 1;
227 }
228 if cached_hint.padding_right {
229 extra_shift_right += 1;
230 }
231 match cached_hint.label {
232 project::InlayHintLabel::String(_) => {
233 if let Some(tooltip) = cached_hint.tooltip {
234 hover_popover::hover_at_inlay(
235 editor,
236 InlayHover {
237 excerpt: excerpt_id,
238 tooltip: match tooltip {
239 InlayHintTooltip::String(text) => HoverBlock {
240 text,
241 kind: HoverBlockKind::PlainText,
242 },
243 InlayHintTooltip::MarkupContent(content) => {
244 HoverBlock {
245 text: content.value,
246 kind: content.kind,
247 }
248 }
249 },
250 range: InlayHighlight {
251 inlay: hovered_hint.id,
252 inlay_position: hovered_hint.position,
253 range: extra_shift_left
254 ..hovered_hint.text.len() + extra_shift_right,
255 },
256 },
257 cx,
258 );
259 hover_updated = true;
260 }
261 }
262 project::InlayHintLabel::LabelParts(label_parts) => {
263 let hint_start =
264 snapshot.anchor_to_inlay_offset(hovered_hint.position);
265 if let Some((hovered_hint_part, part_range)) =
266 hover_popover::find_hovered_hint_part(
267 label_parts,
268 hint_start,
269 hovered_offset,
270 )
271 {
272 let highlight_start =
273 (part_range.start - hint_start).0 + extra_shift_left;
274 let highlight_end =
275 (part_range.end - hint_start).0 + extra_shift_right;
276 let highlight = InlayHighlight {
277 inlay: hovered_hint.id,
278 inlay_position: hovered_hint.position,
279 range: highlight_start..highlight_end,
280 };
281 if let Some(tooltip) = hovered_hint_part.tooltip {
282 hover_popover::hover_at_inlay(
283 editor,
284 InlayHover {
285 excerpt: excerpt_id,
286 tooltip: match tooltip {
287 InlayHintLabelPartTooltip::String(text) => {
288 HoverBlock {
289 text,
290 kind: HoverBlockKind::PlainText,
291 }
292 }
293 InlayHintLabelPartTooltip::MarkupContent(
294 content,
295 ) => HoverBlock {
296 text: content.value,
297 kind: content.kind,
298 },
299 },
300 range: highlight.clone(),
301 },
302 cx,
303 );
304 hover_updated = true;
305 }
306 if let Some((language_server_id, location)) =
307 hovered_hint_part.location
308 {
309 if cmd_held && !editor.has_pending_nonempty_selection() {
310 go_to_definition_updated = true;
311 show_link_definition(
312 shift_held,
313 editor,
314 TriggerPoint::InlayHint(
315 highlight,
316 location,
317 language_server_id,
318 ),
319 snapshot,
320 cx,
321 );
322 }
323 }
324 }
325 }
326 };
327 }
328 ResolveState::Resolving => {}
329 }
330 }
331 }
332 }
333
334 if !go_to_definition_updated {
335 editor.hide_hovered_link(cx)
336 }
337 if !hover_updated {
338 hover_popover::hover_at(editor, None, cx);
339 }
340}
341
342#[derive(Debug, Clone, Copy, PartialEq)]
343pub enum LinkDefinitionKind {
344 Symbol,
345 Type,
346}
347
348pub fn show_link_definition(
349 shift_held: bool,
350 editor: &mut Editor,
351 trigger_point: TriggerPoint,
352 snapshot: &EditorSnapshot,
353 cx: &mut ViewContext<Editor>,
354) {
355 let preferred_kind = match trigger_point {
356 TriggerPoint::Text(_) if !shift_held => LinkDefinitionKind::Symbol,
357 _ => LinkDefinitionKind::Type,
358 };
359
360 let (mut hovered_link_state, is_cached) =
361 if let Some(existing) = editor.hovered_link_state.take() {
362 (existing, true)
363 } else {
364 (
365 HoveredLinkState {
366 last_trigger_point: trigger_point.clone(),
367 symbol_range: None,
368 preferred_kind,
369 links: vec![],
370 task: None,
371 },
372 false,
373 )
374 };
375
376 if editor.pending_rename.is_some() {
377 return;
378 }
379
380 let trigger_anchor = trigger_point.anchor();
381 let Some((buffer, buffer_position)) = editor
382 .buffer
383 .read(cx)
384 .text_anchor_for_position(trigger_anchor.clone(), cx)
385 else {
386 return;
387 };
388
389 let Some((excerpt_id, _, _)) = editor
390 .buffer()
391 .read(cx)
392 .excerpt_containing(trigger_anchor.clone(), cx)
393 else {
394 return;
395 };
396
397 let Some(project) = editor.project.clone() else {
398 return;
399 };
400
401 let same_kind = hovered_link_state.preferred_kind == preferred_kind
402 || hovered_link_state
403 .links
404 .first()
405 .is_some_and(|d| matches!(d, HoverLink::Url(_)));
406
407 if same_kind {
408 if is_cached && (&hovered_link_state.last_trigger_point == &trigger_point)
409 || hovered_link_state
410 .symbol_range
411 .as_ref()
412 .is_some_and(|symbol_range| {
413 symbol_range.point_within_range(&trigger_point, &snapshot)
414 })
415 {
416 editor.hovered_link_state = Some(hovered_link_state);
417 return;
418 }
419 } else {
420 editor.hide_hovered_link(cx)
421 }
422
423 let snapshot = snapshot.buffer_snapshot.clone();
424 hovered_link_state.task = Some(cx.spawn(|this, mut cx| {
425 async move {
426 let result = match &trigger_point {
427 TriggerPoint::Text(_) => {
428 if let Some((url_range, url)) = find_url(&buffer, buffer_position, cx.clone()) {
429 this.update(&mut cx, |_, _| {
430 let start =
431 snapshot.anchor_in_excerpt(excerpt_id.clone(), url_range.start);
432 let end = snapshot.anchor_in_excerpt(excerpt_id.clone(), url_range.end);
433 (
434 Some(RangeInEditor::Text(start..end)),
435 vec![HoverLink::Url(url)],
436 )
437 })
438 .ok()
439 } else {
440 // query the LSP for definition info
441 project
442 .update(&mut cx, |project, cx| match preferred_kind {
443 LinkDefinitionKind::Symbol => {
444 project.definition(&buffer, buffer_position, cx)
445 }
446
447 LinkDefinitionKind::Type => {
448 project.type_definition(&buffer, buffer_position, cx)
449 }
450 })?
451 .await
452 .ok()
453 .map(|definition_result| {
454 (
455 definition_result.iter().find_map(|link| {
456 link.origin.as_ref().map(|origin| {
457 let start = snapshot.anchor_in_excerpt(
458 excerpt_id.clone(),
459 origin.range.start,
460 );
461 let end = snapshot.anchor_in_excerpt(
462 excerpt_id.clone(),
463 origin.range.end,
464 );
465 RangeInEditor::Text(start..end)
466 })
467 }),
468 definition_result.into_iter().map(HoverLink::Text).collect(),
469 )
470 })
471 }
472 }
473 TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
474 Some(RangeInEditor::Inlay(highlight.clone())),
475 vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
476 )),
477 };
478
479 this.update(&mut cx, |this, cx| {
480 // Clear any existing highlights
481 this.clear_highlights::<HoveredLinkState>(cx);
482 let Some(hovered_link_state) = this.hovered_link_state.as_mut() else {
483 return;
484 };
485 hovered_link_state.preferred_kind = preferred_kind;
486 hovered_link_state.symbol_range = result
487 .as_ref()
488 .and_then(|(symbol_range, _)| symbol_range.clone());
489
490 if let Some((symbol_range, definitions)) = result {
491 hovered_link_state.links = definitions.clone();
492
493 let buffer_snapshot = buffer.read(cx).snapshot();
494
495 // Only show highlight if there exists a definition to jump to that doesn't contain
496 // the current location.
497 let any_definition_does_not_contain_current_location =
498 definitions.iter().any(|definition| {
499 match &definition {
500 HoverLink::Text(link) => {
501 if link.target.buffer == buffer {
502 let range = &link.target.range;
503 // Expand range by one character as lsp definition ranges include positions adjacent
504 // but not contained by the symbol range
505 let start = buffer_snapshot.clip_offset(
506 range
507 .start
508 .to_offset(&buffer_snapshot)
509 .saturating_sub(1),
510 Bias::Left,
511 );
512 let end = buffer_snapshot.clip_offset(
513 range.end.to_offset(&buffer_snapshot) + 1,
514 Bias::Right,
515 );
516 let offset = buffer_position.to_offset(&buffer_snapshot);
517 !(start <= offset && end >= offset)
518 } else {
519 true
520 }
521 }
522 HoverLink::InlayHint(_, _) => true,
523 HoverLink::Url(_) => true,
524 }
525 });
526
527 if any_definition_does_not_contain_current_location {
528 let style = gpui::HighlightStyle {
529 underline: Some(gpui::UnderlineStyle {
530 thickness: px(1.),
531 ..Default::default()
532 }),
533 color: Some(cx.theme().colors().link_text_hover),
534 ..Default::default()
535 };
536 let highlight_range =
537 symbol_range.unwrap_or_else(|| match &trigger_point {
538 TriggerPoint::Text(trigger_anchor) => {
539 // If no symbol range returned from language server, use the surrounding word.
540 let (offset_range, _) =
541 snapshot.surrounding_word(*trigger_anchor);
542 RangeInEditor::Text(
543 snapshot.anchor_before(offset_range.start)
544 ..snapshot.anchor_after(offset_range.end),
545 )
546 }
547 TriggerPoint::InlayHint(highlight, _, _) => {
548 RangeInEditor::Inlay(highlight.clone())
549 }
550 });
551
552 match highlight_range {
553 RangeInEditor::Text(text_range) => {
554 this.highlight_text::<HoveredLinkState>(vec![text_range], style, cx)
555 }
556 RangeInEditor::Inlay(highlight) => this
557 .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
558 }
559 } else {
560 this.hide_hovered_link(cx);
561 }
562 }
563 })?;
564
565 Ok::<_, anyhow::Error>(())
566 }
567 .log_err()
568 }));
569
570 editor.hovered_link_state = Some(hovered_link_state);
571}
572
573fn find_url(
574 buffer: &Model<language::Buffer>,
575 position: text::Anchor,
576 mut cx: AsyncWindowContext,
577) -> Option<(Range<text::Anchor>, String)> {
578 const LIMIT: usize = 2048;
579
580 let Ok(snapshot) = buffer.update(&mut cx, |buffer, _| buffer.snapshot()) else {
581 return None;
582 };
583
584 let offset = position.to_offset(&snapshot);
585 let mut token_start = offset;
586 let mut token_end = offset;
587 let mut found_start = false;
588 let mut found_end = false;
589
590 for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
591 if ch.is_whitespace() {
592 found_start = true;
593 break;
594 }
595 token_start -= ch.len_utf8();
596 }
597 if !found_start {
598 return None;
599 }
600
601 for ch in snapshot
602 .chars_at(offset)
603 .take(LIMIT - (offset - token_start))
604 {
605 if ch.is_whitespace() {
606 found_end = true;
607 break;
608 }
609 token_end += ch.len_utf8();
610 }
611 if !found_end {
612 return None;
613 }
614
615 let mut finder = LinkFinder::new();
616 finder.kinds(&[LinkKind::Url]);
617 let input = snapshot
618 .text_for_range(token_start..token_end)
619 .collect::<String>();
620
621 let relative_offset = offset - token_start;
622 for link in finder.links(&input) {
623 if link.start() <= relative_offset && link.end() >= relative_offset {
624 let range = snapshot.anchor_before(token_start + link.start())
625 ..snapshot.anchor_after(token_start + link.end());
626 return Some((range, link.as_str().to_string()));
627 }
628 }
629 None
630}
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635 use crate::{
636 display_map::ToDisplayPoint,
637 editor_tests::init_test,
638 inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
639 test::editor_lsp_test_context::EditorLspTestContext,
640 DisplayPoint,
641 };
642 use futures::StreamExt;
643 use gpui::Modifiers;
644 use indoc::indoc;
645 use language::language_settings::InlayHintSettings;
646 use lsp::request::{GotoDefinition, GotoTypeDefinition};
647 use util::assert_set_eq;
648 use workspace::item::Item;
649
650 #[gpui::test]
651 async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
652 init_test(cx, |_| {});
653
654 let mut cx = EditorLspTestContext::new_rust(
655 lsp::ServerCapabilities {
656 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
657 type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
658 ..Default::default()
659 },
660 cx,
661 )
662 .await;
663
664 cx.set_state(indoc! {"
665 struct A;
666 let vˇariable = A;
667 "});
668 let screen_coord = cx.editor(|editor, cx| editor.pixel_position_of_cursor(cx));
669
670 // Basic hold cmd+shift, expect highlight in region if response contains type definition
671 let symbol_range = cx.lsp_range(indoc! {"
672 struct A;
673 let «variable» = A;
674 "});
675 let target_range = cx.lsp_range(indoc! {"
676 struct «A»;
677 let variable = A;
678 "});
679
680 cx.run_until_parked();
681
682 let mut requests =
683 cx.handle_request::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
684 Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
685 lsp::LocationLink {
686 origin_selection_range: Some(symbol_range),
687 target_uri: url.clone(),
688 target_range,
689 target_selection_range: target_range,
690 },
691 ])))
692 });
693
694 cx.cx
695 .cx
696 .simulate_mouse_move(screen_coord.unwrap(), Modifiers::command_shift());
697
698 requests.next().await;
699 cx.run_until_parked();
700 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
701 struct A;
702 let «variable» = A;
703 "});
704
705 cx.simulate_modifiers_change(Modifiers::command());
706 cx.run_until_parked();
707 // Assert no link highlights
708 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
709 struct A;
710 let variable = A;
711 "});
712
713 cx.cx
714 .cx
715 .simulate_click(screen_coord.unwrap(), Modifiers::command_shift());
716
717 cx.assert_editor_state(indoc! {"
718 struct «Aˇ»;
719 let variable = A;
720 "});
721 }
722
723 #[gpui::test]
724 async fn test_hover_links(cx: &mut gpui::TestAppContext) {
725 init_test(cx, |_| {});
726
727 let mut cx = EditorLspTestContext::new_rust(
728 lsp::ServerCapabilities {
729 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
730 ..Default::default()
731 },
732 cx,
733 )
734 .await;
735
736 cx.set_state(indoc! {"
737 fn ˇtest() { do_work(); }
738 fn do_work() { test(); }
739 "});
740
741 // Basic hold cmd, expect highlight in region if response contains definition
742 let hover_point = cx.pixel_position(indoc! {"
743 fn test() { do_wˇork(); }
744 fn do_work() { test(); }
745 "});
746 let symbol_range = cx.lsp_range(indoc! {"
747 fn test() { «do_work»(); }
748 fn do_work() { test(); }
749 "});
750 let target_range = cx.lsp_range(indoc! {"
751 fn test() { do_work(); }
752 fn «do_work»() { test(); }
753 "});
754
755 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
756 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
757 lsp::LocationLink {
758 origin_selection_range: Some(symbol_range),
759 target_uri: url.clone(),
760 target_range,
761 target_selection_range: target_range,
762 },
763 ])))
764 });
765
766 cx.simulate_mouse_move(hover_point, Modifiers::command());
767 requests.next().await;
768 cx.background_executor.run_until_parked();
769 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
770 fn test() { «do_work»(); }
771 fn do_work() { test(); }
772 "});
773
774 // Unpress cmd causes highlight to go away
775 cx.simulate_modifiers_change(Modifiers::none());
776 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
777 fn test() { do_work(); }
778 fn do_work() { test(); }
779 "});
780
781 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
782 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
783 lsp::LocationLink {
784 origin_selection_range: Some(symbol_range),
785 target_uri: url.clone(),
786 target_range,
787 target_selection_range: target_range,
788 },
789 ])))
790 });
791
792 cx.simulate_mouse_move(hover_point, Modifiers::command());
793 requests.next().await;
794 cx.background_executor.run_until_parked();
795 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
796 fn test() { «do_work»(); }
797 fn do_work() { test(); }
798 "});
799
800 // Moving mouse to location with no response dismisses highlight
801 let hover_point = cx.pixel_position(indoc! {"
802 fˇn test() { do_work(); }
803 fn do_work() { test(); }
804 "});
805 let mut requests = cx
806 .lsp
807 .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
808 // No definitions returned
809 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
810 });
811 cx.simulate_mouse_move(hover_point, Modifiers::command());
812
813 requests.next().await;
814 cx.background_executor.run_until_parked();
815
816 // Assert no link highlights
817 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
818 fn test() { do_work(); }
819 fn do_work() { test(); }
820 "});
821
822 // // Move mouse without cmd and then pressing cmd triggers highlight
823 let hover_point = cx.pixel_position(indoc! {"
824 fn test() { do_work(); }
825 fn do_work() { teˇst(); }
826 "});
827 cx.simulate_mouse_move(hover_point, Modifiers::none());
828
829 // Assert no link highlights
830 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
831 fn test() { do_work(); }
832 fn do_work() { test(); }
833 "});
834
835 let symbol_range = cx.lsp_range(indoc! {"
836 fn test() { do_work(); }
837 fn do_work() { «test»(); }
838 "});
839 let target_range = cx.lsp_range(indoc! {"
840 fn «test»() { do_work(); }
841 fn do_work() { test(); }
842 "});
843
844 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
845 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
846 lsp::LocationLink {
847 origin_selection_range: Some(symbol_range),
848 target_uri: url,
849 target_range,
850 target_selection_range: target_range,
851 },
852 ])))
853 });
854
855 cx.simulate_modifiers_change(Modifiers::command());
856
857 requests.next().await;
858 cx.background_executor.run_until_parked();
859
860 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
861 fn test() { do_work(); }
862 fn do_work() { «test»(); }
863 "});
864
865 cx.deactivate_window();
866 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
867 fn test() { do_work(); }
868 fn do_work() { test(); }
869 "});
870
871 cx.simulate_mouse_move(hover_point, Modifiers::command());
872 cx.background_executor.run_until_parked();
873 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
874 fn test() { do_work(); }
875 fn do_work() { «test»(); }
876 "});
877
878 // Moving again within the same symbol range doesn't re-request
879 let hover_point = cx.pixel_position(indoc! {"
880 fn test() { do_work(); }
881 fn do_work() { tesˇt(); }
882 "});
883 cx.simulate_mouse_move(hover_point, Modifiers::command());
884 cx.background_executor.run_until_parked();
885 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
886 fn test() { do_work(); }
887 fn do_work() { «test»(); }
888 "});
889
890 // Cmd click with existing definition doesn't re-request and dismisses highlight
891 cx.simulate_click(hover_point, Modifiers::command());
892 cx.lsp
893 .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
894 // Empty definition response to make sure we aren't hitting the lsp and using
895 // the cached location instead
896 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
897 });
898 cx.background_executor.run_until_parked();
899 cx.assert_editor_state(indoc! {"
900 fn «testˇ»() { do_work(); }
901 fn do_work() { test(); }
902 "});
903
904 // Assert no link highlights after jump
905 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
906 fn test() { do_work(); }
907 fn do_work() { test(); }
908 "});
909
910 // Cmd click without existing definition requests and jumps
911 let hover_point = cx.pixel_position(indoc! {"
912 fn test() { do_wˇork(); }
913 fn do_work() { test(); }
914 "});
915 let target_range = cx.lsp_range(indoc! {"
916 fn test() { do_work(); }
917 fn «do_work»() { test(); }
918 "});
919
920 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
921 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
922 lsp::LocationLink {
923 origin_selection_range: None,
924 target_uri: url,
925 target_range,
926 target_selection_range: target_range,
927 },
928 ])))
929 });
930 cx.simulate_click(hover_point, Modifiers::command());
931 requests.next().await;
932 cx.background_executor.run_until_parked();
933 cx.assert_editor_state(indoc! {"
934 fn test() { do_work(); }
935 fn «do_workˇ»() { test(); }
936 "});
937
938 // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
939 // 2. Selection is completed, hovering
940 let hover_point = cx.pixel_position(indoc! {"
941 fn test() { do_wˇork(); }
942 fn do_work() { test(); }
943 "});
944 let target_range = cx.lsp_range(indoc! {"
945 fn test() { do_work(); }
946 fn «do_work»() { test(); }
947 "});
948 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
949 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
950 lsp::LocationLink {
951 origin_selection_range: None,
952 target_uri: url,
953 target_range,
954 target_selection_range: target_range,
955 },
956 ])))
957 });
958
959 // create a pending selection
960 let selection_range = cx.ranges(indoc! {"
961 fn «test() { do_w»ork(); }
962 fn do_work() { test(); }
963 "})[0]
964 .clone();
965 cx.update_editor(|editor, cx| {
966 let snapshot = editor.buffer().read(cx).snapshot(cx);
967 let anchor_range = snapshot.anchor_before(selection_range.start)
968 ..snapshot.anchor_after(selection_range.end);
969 editor.change_selections(Some(crate::Autoscroll::fit()), cx, |s| {
970 s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
971 });
972 });
973 cx.simulate_mouse_move(hover_point, Modifiers::command());
974 cx.background_executor.run_until_parked();
975 assert!(requests.try_next().is_err());
976 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
977 fn test() { do_work(); }
978 fn do_work() { test(); }
979 "});
980 cx.background_executor.run_until_parked();
981 }
982
983 #[gpui::test]
984 async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
985 init_test(cx, |settings| {
986 settings.defaults.inlay_hints = Some(InlayHintSettings {
987 enabled: true,
988 show_type_hints: true,
989 show_parameter_hints: true,
990 show_other_hints: true,
991 })
992 });
993
994 let mut cx = EditorLspTestContext::new_rust(
995 lsp::ServerCapabilities {
996 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
997 ..Default::default()
998 },
999 cx,
1000 )
1001 .await;
1002 cx.set_state(indoc! {"
1003 struct TestStruct;
1004
1005 fn main() {
1006 let variableˇ = TestStruct;
1007 }
1008 "});
1009 let hint_start_offset = cx.ranges(indoc! {"
1010 struct TestStruct;
1011
1012 fn main() {
1013 let variableˇ = TestStruct;
1014 }
1015 "})[0]
1016 .start;
1017 let hint_position = cx.to_lsp(hint_start_offset);
1018 let target_range = cx.lsp_range(indoc! {"
1019 struct «TestStruct»;
1020
1021 fn main() {
1022 let variable = TestStruct;
1023 }
1024 "});
1025
1026 let expected_uri = cx.buffer_lsp_url.clone();
1027 let hint_label = ": TestStruct";
1028 cx.lsp
1029 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1030 let expected_uri = expected_uri.clone();
1031 async move {
1032 assert_eq!(params.text_document.uri, expected_uri);
1033 Ok(Some(vec![lsp::InlayHint {
1034 position: hint_position,
1035 label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1036 value: hint_label.to_string(),
1037 location: Some(lsp::Location {
1038 uri: params.text_document.uri,
1039 range: target_range,
1040 }),
1041 ..Default::default()
1042 }]),
1043 kind: Some(lsp::InlayHintKind::TYPE),
1044 text_edits: None,
1045 tooltip: None,
1046 padding_left: Some(false),
1047 padding_right: Some(false),
1048 data: None,
1049 }]))
1050 }
1051 })
1052 .next()
1053 .await;
1054 cx.background_executor.run_until_parked();
1055 cx.update_editor(|editor, cx| {
1056 let expected_layers = vec![hint_label.to_string()];
1057 assert_eq!(expected_layers, cached_hint_labels(editor));
1058 assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1059 });
1060
1061 let inlay_range = cx
1062 .ranges(indoc! {"
1063 struct TestStruct;
1064
1065 fn main() {
1066 let variable« »= TestStruct;
1067 }
1068 "})
1069 .get(0)
1070 .cloned()
1071 .unwrap();
1072 let midpoint = cx.update_editor(|editor, cx| {
1073 let snapshot = editor.snapshot(cx);
1074 let previous_valid = inlay_range.start.to_display_point(&snapshot);
1075 let next_valid = inlay_range.end.to_display_point(&snapshot);
1076 assert_eq!(previous_valid.row(), next_valid.row());
1077 assert!(previous_valid.column() < next_valid.column());
1078 DisplayPoint::new(
1079 previous_valid.row(),
1080 previous_valid.column() + (hint_label.len() / 2) as u32,
1081 )
1082 });
1083 // Press cmd to trigger highlight
1084 let hover_point = cx.pixel_position_for(midpoint);
1085 cx.simulate_mouse_move(hover_point, Modifiers::command());
1086 cx.background_executor.run_until_parked();
1087 cx.update_editor(|editor, cx| {
1088 let snapshot = editor.snapshot(cx);
1089 let actual_highlights = snapshot
1090 .inlay_highlights::<HoveredLinkState>()
1091 .into_iter()
1092 .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1093 .collect::<Vec<_>>();
1094
1095 let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1096 let expected_highlight = InlayHighlight {
1097 inlay: InlayId::Hint(0),
1098 inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1099 range: 0..hint_label.len(),
1100 };
1101 assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1102 });
1103
1104 cx.simulate_mouse_move(hover_point, Modifiers::none());
1105 // Assert no link highlights
1106 cx.update_editor(|editor, cx| {
1107 let snapshot = editor.snapshot(cx);
1108 let actual_ranges = snapshot
1109 .text_highlight_ranges::<HoveredLinkState>()
1110 .map(|ranges| ranges.as_ref().clone().1)
1111 .unwrap_or_default();
1112
1113 assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1114 });
1115
1116 cx.simulate_modifiers_change(Modifiers::command());
1117 cx.background_executor.run_until_parked();
1118 cx.simulate_click(hover_point, Modifiers::command());
1119 cx.background_executor.run_until_parked();
1120 cx.assert_editor_state(indoc! {"
1121 struct «TestStructˇ»;
1122
1123 fn main() {
1124 let variable = TestStruct;
1125 }
1126 "});
1127 }
1128
1129 #[gpui::test]
1130 async fn test_urls(cx: &mut gpui::TestAppContext) {
1131 init_test(cx, |_| {});
1132 let mut cx = EditorLspTestContext::new_rust(
1133 lsp::ServerCapabilities {
1134 ..Default::default()
1135 },
1136 cx,
1137 )
1138 .await;
1139
1140 cx.set_state(indoc! {"
1141 Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1142 "});
1143
1144 let screen_coord = cx.pixel_position(indoc! {"
1145 Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1146 "});
1147
1148 cx.simulate_mouse_move(screen_coord, Modifiers::command());
1149 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1150 Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1151 "});
1152
1153 cx.simulate_click(screen_coord, Modifiers::command());
1154 assert_eq!(
1155 cx.opened_url(),
1156 Some("https://zed.dev/channel/had-(oops)".into())
1157 );
1158 }
1159}