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 same_kind = hovered_link_state.preferred_kind == preferred_kind
398 || hovered_link_state
399 .links
400 .first()
401 .is_some_and(|d| matches!(d, HoverLink::Url(_)));
402
403 if same_kind {
404 if is_cached && (&hovered_link_state.last_trigger_point == &trigger_point)
405 || hovered_link_state
406 .symbol_range
407 .as_ref()
408 .is_some_and(|symbol_range| {
409 symbol_range.point_within_range(&trigger_point, &snapshot)
410 })
411 {
412 editor.hovered_link_state = Some(hovered_link_state);
413 return;
414 }
415 } else {
416 editor.hide_hovered_link(cx)
417 }
418 let project = editor.project.clone();
419
420 let snapshot = snapshot.buffer_snapshot.clone();
421 hovered_link_state.task = Some(cx.spawn(|this, mut cx| {
422 async move {
423 let result = match &trigger_point {
424 TriggerPoint::Text(_) => {
425 if let Some((url_range, url)) = find_url(&buffer, buffer_position, cx.clone()) {
426 this.update(&mut cx, |_, _| {
427 let start =
428 snapshot.anchor_in_excerpt(excerpt_id.clone(), url_range.start);
429 let end = snapshot.anchor_in_excerpt(excerpt_id.clone(), url_range.end);
430 (
431 Some(RangeInEditor::Text(start..end)),
432 vec![HoverLink::Url(url)],
433 )
434 })
435 .ok()
436 } else if let Some(project) = project {
437 // query the LSP for definition info
438 project
439 .update(&mut cx, |project, cx| match preferred_kind {
440 LinkDefinitionKind::Symbol => {
441 project.definition(&buffer, buffer_position, cx)
442 }
443
444 LinkDefinitionKind::Type => {
445 project.type_definition(&buffer, buffer_position, cx)
446 }
447 })?
448 .await
449 .ok()
450 .map(|definition_result| {
451 (
452 definition_result.iter().find_map(|link| {
453 link.origin.as_ref().map(|origin| {
454 let start = snapshot.anchor_in_excerpt(
455 excerpt_id.clone(),
456 origin.range.start,
457 );
458 let end = snapshot.anchor_in_excerpt(
459 excerpt_id.clone(),
460 origin.range.end,
461 );
462 RangeInEditor::Text(start..end)
463 })
464 }),
465 definition_result.into_iter().map(HoverLink::Text).collect(),
466 )
467 })
468 } else {
469 None
470 }
471 }
472 TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
473 Some(RangeInEditor::Inlay(highlight.clone())),
474 vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
475 )),
476 };
477
478 this.update(&mut cx, |this, cx| {
479 // Clear any existing highlights
480 this.clear_highlights::<HoveredLinkState>(cx);
481 let Some(hovered_link_state) = this.hovered_link_state.as_mut() else {
482 return;
483 };
484 hovered_link_state.preferred_kind = preferred_kind;
485 hovered_link_state.symbol_range = result
486 .as_ref()
487 .and_then(|(symbol_range, _)| symbol_range.clone());
488
489 if let Some((symbol_range, definitions)) = result {
490 hovered_link_state.links = definitions.clone();
491
492 let buffer_snapshot = buffer.read(cx).snapshot();
493
494 // Only show highlight if there exists a definition to jump to that doesn't contain
495 // the current location.
496 let any_definition_does_not_contain_current_location =
497 definitions.iter().any(|definition| {
498 match &definition {
499 HoverLink::Text(link) => {
500 if link.target.buffer == buffer {
501 let range = &link.target.range;
502 // Expand range by one character as lsp definition ranges include positions adjacent
503 // but not contained by the symbol range
504 let start = buffer_snapshot.clip_offset(
505 range
506 .start
507 .to_offset(&buffer_snapshot)
508 .saturating_sub(1),
509 Bias::Left,
510 );
511 let end = buffer_snapshot.clip_offset(
512 range.end.to_offset(&buffer_snapshot) + 1,
513 Bias::Right,
514 );
515 let offset = buffer_position.to_offset(&buffer_snapshot);
516 !(start <= offset && end >= offset)
517 } else {
518 true
519 }
520 }
521 HoverLink::InlayHint(_, _) => true,
522 HoverLink::Url(_) => true,
523 }
524 });
525
526 if any_definition_does_not_contain_current_location {
527 let style = gpui::HighlightStyle {
528 underline: Some(gpui::UnderlineStyle {
529 thickness: px(1.),
530 ..Default::default()
531 }),
532 color: Some(cx.theme().colors().link_text_hover),
533 ..Default::default()
534 };
535 let highlight_range =
536 symbol_range.unwrap_or_else(|| match &trigger_point {
537 TriggerPoint::Text(trigger_anchor) => {
538 // If no symbol range returned from language server, use the surrounding word.
539 let (offset_range, _) =
540 snapshot.surrounding_word(*trigger_anchor);
541 RangeInEditor::Text(
542 snapshot.anchor_before(offset_range.start)
543 ..snapshot.anchor_after(offset_range.end),
544 )
545 }
546 TriggerPoint::InlayHint(highlight, _, _) => {
547 RangeInEditor::Inlay(highlight.clone())
548 }
549 });
550
551 match highlight_range {
552 RangeInEditor::Text(text_range) => {
553 this.highlight_text::<HoveredLinkState>(vec![text_range], style, cx)
554 }
555 RangeInEditor::Inlay(highlight) => this
556 .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
557 }
558 } else {
559 this.hide_hovered_link(cx);
560 }
561 }
562 })?;
563
564 Ok::<_, anyhow::Error>(())
565 }
566 .log_err()
567 }));
568
569 editor.hovered_link_state = Some(hovered_link_state);
570}
571
572pub(crate) fn find_url(
573 buffer: &Model<language::Buffer>,
574 position: text::Anchor,
575 mut cx: AsyncWindowContext,
576) -> Option<(Range<text::Anchor>, String)> {
577 const LIMIT: usize = 2048;
578
579 let Ok(snapshot) = buffer.update(&mut cx, |buffer, _| buffer.snapshot()) else {
580 return None;
581 };
582
583 let offset = position.to_offset(&snapshot);
584 let mut token_start = offset;
585 let mut token_end = offset;
586 let mut found_start = false;
587 let mut found_end = false;
588
589 for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
590 if ch.is_whitespace() {
591 found_start = true;
592 break;
593 }
594 token_start -= ch.len_utf8();
595 }
596 if !found_start {
597 return None;
598 }
599
600 for ch in snapshot
601 .chars_at(offset)
602 .take(LIMIT - (offset - token_start))
603 {
604 if ch.is_whitespace() {
605 found_end = true;
606 break;
607 }
608 token_end += ch.len_utf8();
609 }
610 if !found_end {
611 return None;
612 }
613
614 let mut finder = LinkFinder::new();
615 finder.kinds(&[LinkKind::Url]);
616 let input = snapshot
617 .text_for_range(token_start..token_end)
618 .collect::<String>();
619
620 let relative_offset = offset - token_start;
621 for link in finder.links(&input) {
622 if link.start() <= relative_offset && link.end() >= relative_offset {
623 let range = snapshot.anchor_before(token_start + link.start())
624 ..snapshot.anchor_after(token_start + link.end());
625 return Some((range, link.as_str().to_string()));
626 }
627 }
628 None
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634 use crate::{
635 display_map::ToDisplayPoint,
636 editor_tests::init_test,
637 inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
638 test::editor_lsp_test_context::EditorLspTestContext,
639 DisplayPoint,
640 };
641 use futures::StreamExt;
642 use gpui::Modifiers;
643 use indoc::indoc;
644 use language::language_settings::InlayHintSettings;
645 use lsp::request::{GotoDefinition, GotoTypeDefinition};
646 use util::assert_set_eq;
647 use workspace::item::Item;
648
649 #[gpui::test]
650 async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
651 init_test(cx, |_| {});
652
653 let mut cx = EditorLspTestContext::new_rust(
654 lsp::ServerCapabilities {
655 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
656 type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
657 ..Default::default()
658 },
659 cx,
660 )
661 .await;
662
663 cx.set_state(indoc! {"
664 struct A;
665 let vˇariable = A;
666 "});
667 let screen_coord = cx.editor(|editor, cx| editor.pixel_position_of_cursor(cx));
668
669 // Basic hold cmd+shift, expect highlight in region if response contains type definition
670 let symbol_range = cx.lsp_range(indoc! {"
671 struct A;
672 let «variable» = A;
673 "});
674 let target_range = cx.lsp_range(indoc! {"
675 struct «A»;
676 let variable = A;
677 "});
678
679 cx.run_until_parked();
680
681 let mut requests =
682 cx.handle_request::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
683 Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
684 lsp::LocationLink {
685 origin_selection_range: Some(symbol_range),
686 target_uri: url.clone(),
687 target_range,
688 target_selection_range: target_range,
689 },
690 ])))
691 });
692
693 cx.cx
694 .cx
695 .simulate_mouse_move(screen_coord.unwrap(), Modifiers::command_shift());
696
697 requests.next().await;
698 cx.run_until_parked();
699 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
700 struct A;
701 let «variable» = A;
702 "});
703
704 cx.simulate_modifiers_change(Modifiers::command());
705 cx.run_until_parked();
706 // Assert no link highlights
707 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
708 struct A;
709 let variable = A;
710 "});
711
712 cx.cx
713 .cx
714 .simulate_click(screen_coord.unwrap(), Modifiers::command_shift());
715
716 cx.assert_editor_state(indoc! {"
717 struct «Aˇ»;
718 let variable = A;
719 "});
720 }
721
722 #[gpui::test]
723 async fn test_hover_links(cx: &mut gpui::TestAppContext) {
724 init_test(cx, |_| {});
725
726 let mut cx = EditorLspTestContext::new_rust(
727 lsp::ServerCapabilities {
728 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
729 ..Default::default()
730 },
731 cx,
732 )
733 .await;
734
735 cx.set_state(indoc! {"
736 fn ˇtest() { do_work(); }
737 fn do_work() { test(); }
738 "});
739
740 // Basic hold cmd, expect highlight in region if response contains definition
741 let hover_point = cx.pixel_position(indoc! {"
742 fn test() { do_wˇork(); }
743 fn do_work() { test(); }
744 "});
745 let symbol_range = cx.lsp_range(indoc! {"
746 fn test() { «do_work»(); }
747 fn do_work() { test(); }
748 "});
749 let target_range = cx.lsp_range(indoc! {"
750 fn test() { do_work(); }
751 fn «do_work»() { test(); }
752 "});
753
754 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
755 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
756 lsp::LocationLink {
757 origin_selection_range: Some(symbol_range),
758 target_uri: url.clone(),
759 target_range,
760 target_selection_range: target_range,
761 },
762 ])))
763 });
764
765 cx.simulate_mouse_move(hover_point, Modifiers::command());
766 requests.next().await;
767 cx.background_executor.run_until_parked();
768 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
769 fn test() { «do_work»(); }
770 fn do_work() { test(); }
771 "});
772
773 // Unpress cmd causes highlight to go away
774 cx.simulate_modifiers_change(Modifiers::none());
775 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
776 fn test() { do_work(); }
777 fn do_work() { test(); }
778 "});
779
780 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
781 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
782 lsp::LocationLink {
783 origin_selection_range: Some(symbol_range),
784 target_uri: url.clone(),
785 target_range,
786 target_selection_range: target_range,
787 },
788 ])))
789 });
790
791 cx.simulate_mouse_move(hover_point, Modifiers::command());
792 requests.next().await;
793 cx.background_executor.run_until_parked();
794 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
795 fn test() { «do_work»(); }
796 fn do_work() { test(); }
797 "});
798
799 // Moving mouse to location with no response dismisses highlight
800 let hover_point = cx.pixel_position(indoc! {"
801 fˇn test() { do_work(); }
802 fn do_work() { test(); }
803 "});
804 let mut requests = cx
805 .lsp
806 .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
807 // No definitions returned
808 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
809 });
810 cx.simulate_mouse_move(hover_point, Modifiers::command());
811
812 requests.next().await;
813 cx.background_executor.run_until_parked();
814
815 // Assert no link highlights
816 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
817 fn test() { do_work(); }
818 fn do_work() { test(); }
819 "});
820
821 // // Move mouse without cmd and then pressing cmd triggers highlight
822 let hover_point = cx.pixel_position(indoc! {"
823 fn test() { do_work(); }
824 fn do_work() { teˇst(); }
825 "});
826 cx.simulate_mouse_move(hover_point, Modifiers::none());
827
828 // Assert no link highlights
829 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
830 fn test() { do_work(); }
831 fn do_work() { test(); }
832 "});
833
834 let symbol_range = cx.lsp_range(indoc! {"
835 fn test() { do_work(); }
836 fn do_work() { «test»(); }
837 "});
838 let target_range = cx.lsp_range(indoc! {"
839 fn «test»() { do_work(); }
840 fn do_work() { test(); }
841 "});
842
843 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
844 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
845 lsp::LocationLink {
846 origin_selection_range: Some(symbol_range),
847 target_uri: url,
848 target_range,
849 target_selection_range: target_range,
850 },
851 ])))
852 });
853
854 cx.simulate_modifiers_change(Modifiers::command());
855
856 requests.next().await;
857 cx.background_executor.run_until_parked();
858
859 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
860 fn test() { do_work(); }
861 fn do_work() { «test»(); }
862 "});
863
864 cx.deactivate_window();
865 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
866 fn test() { do_work(); }
867 fn do_work() { test(); }
868 "});
869
870 cx.simulate_mouse_move(hover_point, Modifiers::command());
871 cx.background_executor.run_until_parked();
872 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
873 fn test() { do_work(); }
874 fn do_work() { «test»(); }
875 "});
876
877 // Moving again within the same symbol range doesn't re-request
878 let hover_point = cx.pixel_position(indoc! {"
879 fn test() { do_work(); }
880 fn do_work() { tesˇt(); }
881 "});
882 cx.simulate_mouse_move(hover_point, Modifiers::command());
883 cx.background_executor.run_until_parked();
884 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
885 fn test() { do_work(); }
886 fn do_work() { «test»(); }
887 "});
888
889 // Cmd click with existing definition doesn't re-request and dismisses highlight
890 cx.simulate_click(hover_point, Modifiers::command());
891 cx.lsp
892 .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
893 // Empty definition response to make sure we aren't hitting the lsp and using
894 // the cached location instead
895 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
896 });
897 cx.background_executor.run_until_parked();
898 cx.assert_editor_state(indoc! {"
899 fn «testˇ»() { do_work(); }
900 fn do_work() { test(); }
901 "});
902
903 // Assert no link highlights after jump
904 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
905 fn test() { do_work(); }
906 fn do_work() { test(); }
907 "});
908
909 // Cmd click without existing definition requests and jumps
910 let hover_point = cx.pixel_position(indoc! {"
911 fn test() { do_wˇork(); }
912 fn do_work() { test(); }
913 "});
914 let target_range = cx.lsp_range(indoc! {"
915 fn test() { do_work(); }
916 fn «do_work»() { test(); }
917 "});
918
919 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
920 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
921 lsp::LocationLink {
922 origin_selection_range: None,
923 target_uri: url,
924 target_range,
925 target_selection_range: target_range,
926 },
927 ])))
928 });
929 cx.simulate_click(hover_point, Modifiers::command());
930 requests.next().await;
931 cx.background_executor.run_until_parked();
932 cx.assert_editor_state(indoc! {"
933 fn test() { do_work(); }
934 fn «do_workˇ»() { test(); }
935 "});
936
937 // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
938 // 2. Selection is completed, hovering
939 let hover_point = cx.pixel_position(indoc! {"
940 fn test() { do_wˇork(); }
941 fn do_work() { test(); }
942 "});
943 let target_range = cx.lsp_range(indoc! {"
944 fn test() { do_work(); }
945 fn «do_work»() { test(); }
946 "});
947 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
948 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
949 lsp::LocationLink {
950 origin_selection_range: None,
951 target_uri: url,
952 target_range,
953 target_selection_range: target_range,
954 },
955 ])))
956 });
957
958 // create a pending selection
959 let selection_range = cx.ranges(indoc! {"
960 fn «test() { do_w»ork(); }
961 fn do_work() { test(); }
962 "})[0]
963 .clone();
964 cx.update_editor(|editor, cx| {
965 let snapshot = editor.buffer().read(cx).snapshot(cx);
966 let anchor_range = snapshot.anchor_before(selection_range.start)
967 ..snapshot.anchor_after(selection_range.end);
968 editor.change_selections(Some(crate::Autoscroll::fit()), cx, |s| {
969 s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
970 });
971 });
972 cx.simulate_mouse_move(hover_point, Modifiers::command());
973 cx.background_executor.run_until_parked();
974 assert!(requests.try_next().is_err());
975 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
976 fn test() { do_work(); }
977 fn do_work() { test(); }
978 "});
979 cx.background_executor.run_until_parked();
980 }
981
982 #[gpui::test]
983 async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
984 init_test(cx, |settings| {
985 settings.defaults.inlay_hints = Some(InlayHintSettings {
986 enabled: true,
987 show_type_hints: true,
988 show_parameter_hints: true,
989 show_other_hints: true,
990 })
991 });
992
993 let mut cx = EditorLspTestContext::new_rust(
994 lsp::ServerCapabilities {
995 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
996 ..Default::default()
997 },
998 cx,
999 )
1000 .await;
1001 cx.set_state(indoc! {"
1002 struct TestStruct;
1003
1004 fn main() {
1005 let variableˇ = TestStruct;
1006 }
1007 "});
1008 let hint_start_offset = cx.ranges(indoc! {"
1009 struct TestStruct;
1010
1011 fn main() {
1012 let variableˇ = TestStruct;
1013 }
1014 "})[0]
1015 .start;
1016 let hint_position = cx.to_lsp(hint_start_offset);
1017 let target_range = cx.lsp_range(indoc! {"
1018 struct «TestStruct»;
1019
1020 fn main() {
1021 let variable = TestStruct;
1022 }
1023 "});
1024
1025 let expected_uri = cx.buffer_lsp_url.clone();
1026 let hint_label = ": TestStruct";
1027 cx.lsp
1028 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1029 let expected_uri = expected_uri.clone();
1030 async move {
1031 assert_eq!(params.text_document.uri, expected_uri);
1032 Ok(Some(vec![lsp::InlayHint {
1033 position: hint_position,
1034 label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1035 value: hint_label.to_string(),
1036 location: Some(lsp::Location {
1037 uri: params.text_document.uri,
1038 range: target_range,
1039 }),
1040 ..Default::default()
1041 }]),
1042 kind: Some(lsp::InlayHintKind::TYPE),
1043 text_edits: None,
1044 tooltip: None,
1045 padding_left: Some(false),
1046 padding_right: Some(false),
1047 data: None,
1048 }]))
1049 }
1050 })
1051 .next()
1052 .await;
1053 cx.background_executor.run_until_parked();
1054 cx.update_editor(|editor, cx| {
1055 let expected_layers = vec![hint_label.to_string()];
1056 assert_eq!(expected_layers, cached_hint_labels(editor));
1057 assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1058 });
1059
1060 let inlay_range = cx
1061 .ranges(indoc! {"
1062 struct TestStruct;
1063
1064 fn main() {
1065 let variable« »= TestStruct;
1066 }
1067 "})
1068 .get(0)
1069 .cloned()
1070 .unwrap();
1071 let midpoint = cx.update_editor(|editor, cx| {
1072 let snapshot = editor.snapshot(cx);
1073 let previous_valid = inlay_range.start.to_display_point(&snapshot);
1074 let next_valid = inlay_range.end.to_display_point(&snapshot);
1075 assert_eq!(previous_valid.row(), next_valid.row());
1076 assert!(previous_valid.column() < next_valid.column());
1077 DisplayPoint::new(
1078 previous_valid.row(),
1079 previous_valid.column() + (hint_label.len() / 2) as u32,
1080 )
1081 });
1082 // Press cmd to trigger highlight
1083 let hover_point = cx.pixel_position_for(midpoint);
1084 cx.simulate_mouse_move(hover_point, Modifiers::command());
1085 cx.background_executor.run_until_parked();
1086 cx.update_editor(|editor, cx| {
1087 let snapshot = editor.snapshot(cx);
1088 let actual_highlights = snapshot
1089 .inlay_highlights::<HoveredLinkState>()
1090 .into_iter()
1091 .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1092 .collect::<Vec<_>>();
1093
1094 let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1095 let expected_highlight = InlayHighlight {
1096 inlay: InlayId::Hint(0),
1097 inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1098 range: 0..hint_label.len(),
1099 };
1100 assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1101 });
1102
1103 cx.simulate_mouse_move(hover_point, Modifiers::none());
1104 // Assert no link highlights
1105 cx.update_editor(|editor, cx| {
1106 let snapshot = editor.snapshot(cx);
1107 let actual_ranges = snapshot
1108 .text_highlight_ranges::<HoveredLinkState>()
1109 .map(|ranges| ranges.as_ref().clone().1)
1110 .unwrap_or_default();
1111
1112 assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1113 });
1114
1115 cx.simulate_modifiers_change(Modifiers::command());
1116 cx.background_executor.run_until_parked();
1117 cx.simulate_click(hover_point, Modifiers::command());
1118 cx.background_executor.run_until_parked();
1119 cx.assert_editor_state(indoc! {"
1120 struct «TestStructˇ»;
1121
1122 fn main() {
1123 let variable = TestStruct;
1124 }
1125 "});
1126 }
1127
1128 #[gpui::test]
1129 async fn test_urls(cx: &mut gpui::TestAppContext) {
1130 init_test(cx, |_| {});
1131 let mut cx = EditorLspTestContext::new_rust(
1132 lsp::ServerCapabilities {
1133 ..Default::default()
1134 },
1135 cx,
1136 )
1137 .await;
1138
1139 cx.set_state(indoc! {"
1140 Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1141 "});
1142
1143 let screen_coord = cx.pixel_position(indoc! {"
1144 Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1145 "});
1146
1147 cx.simulate_mouse_move(screen_coord, Modifiers::command());
1148 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1149 Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1150 "});
1151
1152 cx.simulate_click(screen_coord, Modifiers::command());
1153 assert_eq!(
1154 cx.opened_url(),
1155 Some("https://zed.dev/channel/had-(oops)".into())
1156 );
1157 }
1158}