1use crate::{
2 hover_popover::{self, InlayHover},
3 Anchor, Editor, EditorSnapshot, GoToDefinition, GoToTypeDefinition, InlayId, PointForPosition,
4 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::{maybe, 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(None, 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, cx)
385 else {
386 return;
387 };
388
389 let Some((excerpt_id, _, _)) = editor
390 .buffer()
391 .read(cx)
392 .excerpt_containing(*trigger_anchor, 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 range = maybe!({
428 let start =
429 snapshot.anchor_in_excerpt(excerpt_id, url_range.start)?;
430 let end = snapshot.anchor_in_excerpt(excerpt_id, url_range.end)?;
431 Some(RangeInEditor::Text(start..end))
432 });
433 (range, vec![HoverLink::Url(url)])
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().and_then(|origin| {
454 let start = snapshot.anchor_in_excerpt(
455 excerpt_id,
456 origin.range.start,
457 )?;
458 let end = snapshot
459 .anchor_in_excerpt(excerpt_id, origin.range.end)?;
460 Some(RangeInEditor::Text(start..end))
461 })
462 }),
463 definition_result.into_iter().map(HoverLink::Text).collect(),
464 )
465 })
466 } else {
467 None
468 }
469 }
470 TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
471 Some(RangeInEditor::Inlay(highlight.clone())),
472 vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
473 )),
474 };
475
476 this.update(&mut cx, |this, cx| {
477 // Clear any existing highlights
478 this.clear_highlights::<HoveredLinkState>(cx);
479 let Some(hovered_link_state) = this.hovered_link_state.as_mut() else {
480 return;
481 };
482 hovered_link_state.preferred_kind = preferred_kind;
483 hovered_link_state.symbol_range = result
484 .as_ref()
485 .and_then(|(symbol_range, _)| symbol_range.clone());
486
487 if let Some((symbol_range, definitions)) = result {
488 hovered_link_state.links = definitions.clone();
489
490 let buffer_snapshot = buffer.read(cx).snapshot();
491
492 // Only show highlight if there exists a definition to jump to that doesn't contain
493 // the current location.
494 let any_definition_does_not_contain_current_location =
495 definitions.iter().any(|definition| {
496 match &definition {
497 HoverLink::Text(link) => {
498 if link.target.buffer == buffer {
499 let range = &link.target.range;
500 // Expand range by one character as lsp definition ranges include positions adjacent
501 // but not contained by the symbol range
502 let start = buffer_snapshot.clip_offset(
503 range
504 .start
505 .to_offset(&buffer_snapshot)
506 .saturating_sub(1),
507 Bias::Left,
508 );
509 let end = buffer_snapshot.clip_offset(
510 range.end.to_offset(&buffer_snapshot) + 1,
511 Bias::Right,
512 );
513 let offset = buffer_position.to_offset(&buffer_snapshot);
514 !(start <= offset && end >= offset)
515 } else {
516 true
517 }
518 }
519 HoverLink::InlayHint(_, _) => true,
520 HoverLink::Url(_) => true,
521 }
522 });
523
524 if any_definition_does_not_contain_current_location {
525 let style = gpui::HighlightStyle {
526 underline: Some(gpui::UnderlineStyle {
527 thickness: px(1.),
528 ..Default::default()
529 }),
530 color: Some(cx.theme().colors().link_text_hover),
531 ..Default::default()
532 };
533 let highlight_range =
534 symbol_range.unwrap_or_else(|| match &trigger_point {
535 TriggerPoint::Text(trigger_anchor) => {
536 // If no symbol range returned from language server, use the surrounding word.
537 let (offset_range, _) =
538 snapshot.surrounding_word(*trigger_anchor);
539 RangeInEditor::Text(
540 snapshot.anchor_before(offset_range.start)
541 ..snapshot.anchor_after(offset_range.end),
542 )
543 }
544 TriggerPoint::InlayHint(highlight, _, _) => {
545 RangeInEditor::Inlay(highlight.clone())
546 }
547 });
548
549 match highlight_range {
550 RangeInEditor::Text(text_range) => {
551 this.highlight_text::<HoveredLinkState>(vec![text_range], style, cx)
552 }
553 RangeInEditor::Inlay(highlight) => this
554 .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
555 }
556 } else {
557 this.hide_hovered_link(cx);
558 }
559 }
560 })?;
561
562 Ok::<_, anyhow::Error>(())
563 }
564 .log_err()
565 }));
566
567 editor.hovered_link_state = Some(hovered_link_state);
568}
569
570pub(crate) fn find_url(
571 buffer: &Model<language::Buffer>,
572 position: text::Anchor,
573 mut cx: AsyncWindowContext,
574) -> Option<(Range<text::Anchor>, String)> {
575 const LIMIT: usize = 2048;
576
577 let Ok(snapshot) = buffer.update(&mut cx, |buffer, _| buffer.snapshot()) else {
578 return None;
579 };
580
581 let offset = position.to_offset(&snapshot);
582 let mut token_start = offset;
583 let mut token_end = offset;
584 let mut found_start = false;
585 let mut found_end = false;
586
587 for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
588 if ch.is_whitespace() {
589 found_start = true;
590 break;
591 }
592 token_start -= ch.len_utf8();
593 }
594 // Check if we didn't find the starting whitespace or if we didn't reach the start of the buffer
595 if !found_start && token_start != 0 {
596 return None;
597 }
598
599 for ch in snapshot
600 .chars_at(offset)
601 .take(LIMIT - (offset - token_start))
602 {
603 if ch.is_whitespace() {
604 found_end = true;
605 break;
606 }
607 token_end += ch.len_utf8();
608 }
609 // Check if we didn't find the ending whitespace or if we read more or equal than LIMIT
610 // which at this point would happen only if we reached the end of buffer
611 if !found_end && (token_end - token_start >= LIMIT) {
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 edit_debounce_ms: 0,
989 scroll_debounce_ms: 0,
990 show_type_hints: true,
991 show_parameter_hints: true,
992 show_other_hints: true,
993 })
994 });
995
996 let mut cx = EditorLspTestContext::new_rust(
997 lsp::ServerCapabilities {
998 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
999 ..Default::default()
1000 },
1001 cx,
1002 )
1003 .await;
1004 cx.set_state(indoc! {"
1005 struct TestStruct;
1006
1007 fn main() {
1008 let variableˇ = TestStruct;
1009 }
1010 "});
1011 let hint_start_offset = cx.ranges(indoc! {"
1012 struct TestStruct;
1013
1014 fn main() {
1015 let variableˇ = TestStruct;
1016 }
1017 "})[0]
1018 .start;
1019 let hint_position = cx.to_lsp(hint_start_offset);
1020 let target_range = cx.lsp_range(indoc! {"
1021 struct «TestStruct»;
1022
1023 fn main() {
1024 let variable = TestStruct;
1025 }
1026 "});
1027
1028 let expected_uri = cx.buffer_lsp_url.clone();
1029 let hint_label = ": TestStruct";
1030 cx.lsp
1031 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1032 let expected_uri = expected_uri.clone();
1033 async move {
1034 assert_eq!(params.text_document.uri, expected_uri);
1035 Ok(Some(vec![lsp::InlayHint {
1036 position: hint_position,
1037 label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1038 value: hint_label.to_string(),
1039 location: Some(lsp::Location {
1040 uri: params.text_document.uri,
1041 range: target_range,
1042 }),
1043 ..Default::default()
1044 }]),
1045 kind: Some(lsp::InlayHintKind::TYPE),
1046 text_edits: None,
1047 tooltip: None,
1048 padding_left: Some(false),
1049 padding_right: Some(false),
1050 data: None,
1051 }]))
1052 }
1053 })
1054 .next()
1055 .await;
1056 cx.background_executor.run_until_parked();
1057 cx.update_editor(|editor, cx| {
1058 let expected_layers = vec![hint_label.to_string()];
1059 assert_eq!(expected_layers, cached_hint_labels(editor));
1060 assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1061 });
1062
1063 let inlay_range = cx
1064 .ranges(indoc! {"
1065 struct TestStruct;
1066
1067 fn main() {
1068 let variable« »= TestStruct;
1069 }
1070 "})
1071 .get(0)
1072 .cloned()
1073 .unwrap();
1074 let midpoint = cx.update_editor(|editor, cx| {
1075 let snapshot = editor.snapshot(cx);
1076 let previous_valid = inlay_range.start.to_display_point(&snapshot);
1077 let next_valid = inlay_range.end.to_display_point(&snapshot);
1078 assert_eq!(previous_valid.row(), next_valid.row());
1079 assert!(previous_valid.column() < next_valid.column());
1080 DisplayPoint::new(
1081 previous_valid.row(),
1082 previous_valid.column() + (hint_label.len() / 2) as u32,
1083 )
1084 });
1085 // Press cmd to trigger highlight
1086 let hover_point = cx.pixel_position_for(midpoint);
1087 cx.simulate_mouse_move(hover_point, Modifiers::command());
1088 cx.background_executor.run_until_parked();
1089 cx.update_editor(|editor, cx| {
1090 let snapshot = editor.snapshot(cx);
1091 let actual_highlights = snapshot
1092 .inlay_highlights::<HoveredLinkState>()
1093 .into_iter()
1094 .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1095 .collect::<Vec<_>>();
1096
1097 let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1098 let expected_highlight = InlayHighlight {
1099 inlay: InlayId::Hint(0),
1100 inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1101 range: 0..hint_label.len(),
1102 };
1103 assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1104 });
1105
1106 cx.simulate_mouse_move(hover_point, Modifiers::none());
1107 // Assert no link highlights
1108 cx.update_editor(|editor, cx| {
1109 let snapshot = editor.snapshot(cx);
1110 let actual_ranges = snapshot
1111 .text_highlight_ranges::<HoveredLinkState>()
1112 .map(|ranges| ranges.as_ref().clone().1)
1113 .unwrap_or_default();
1114
1115 assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1116 });
1117
1118 cx.simulate_modifiers_change(Modifiers::command());
1119 cx.background_executor.run_until_parked();
1120 cx.simulate_click(hover_point, Modifiers::command());
1121 cx.background_executor.run_until_parked();
1122 cx.assert_editor_state(indoc! {"
1123 struct «TestStructˇ»;
1124
1125 fn main() {
1126 let variable = TestStruct;
1127 }
1128 "});
1129 }
1130
1131 #[gpui::test]
1132 async fn test_urls(cx: &mut gpui::TestAppContext) {
1133 init_test(cx, |_| {});
1134 let mut cx = EditorLspTestContext::new_rust(
1135 lsp::ServerCapabilities {
1136 ..Default::default()
1137 },
1138 cx,
1139 )
1140 .await;
1141
1142 cx.set_state(indoc! {"
1143 Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1144 "});
1145
1146 let screen_coord = cx.pixel_position(indoc! {"
1147 Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1148 "});
1149
1150 cx.simulate_mouse_move(screen_coord, Modifiers::command());
1151 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1152 Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1153 "});
1154
1155 cx.simulate_click(screen_coord, Modifiers::command());
1156 assert_eq!(
1157 cx.opened_url(),
1158 Some("https://zed.dev/channel/had-(oops)".into())
1159 );
1160 }
1161
1162 #[gpui::test]
1163 async fn test_urls_at_beginning_of_buffer(cx: &mut gpui::TestAppContext) {
1164 init_test(cx, |_| {});
1165 let mut cx = EditorLspTestContext::new_rust(
1166 lsp::ServerCapabilities {
1167 ..Default::default()
1168 },
1169 cx,
1170 )
1171 .await;
1172
1173 cx.set_state(indoc! {"https://zed.dev/releases is a cool ˇwebpage."});
1174
1175 let screen_coord =
1176 cx.pixel_position(indoc! {"https://zed.dev/relˇeases is a cool webpage."});
1177
1178 cx.simulate_mouse_move(screen_coord, Modifiers::command());
1179 cx.assert_editor_text_highlights::<HoveredLinkState>(
1180 indoc! {"«https://zed.dev/releasesˇ» is a cool webpage."},
1181 );
1182
1183 cx.simulate_click(screen_coord, Modifiers::command());
1184 assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1185 }
1186
1187 #[gpui::test]
1188 async fn test_urls_at_end_of_buffer(cx: &mut gpui::TestAppContext) {
1189 init_test(cx, |_| {});
1190 let mut cx = EditorLspTestContext::new_rust(
1191 lsp::ServerCapabilities {
1192 ..Default::default()
1193 },
1194 cx,
1195 )
1196 .await;
1197
1198 cx.set_state(indoc! {"A cool ˇwebpage is https://zed.dev/releases"});
1199
1200 let screen_coord =
1201 cx.pixel_position(indoc! {"A cool webpage is https://zed.dev/releˇases"});
1202
1203 cx.simulate_mouse_move(screen_coord, Modifiers::command());
1204 cx.assert_editor_text_highlights::<HoveredLinkState>(
1205 indoc! {"A cool webpage is «https://zed.dev/releasesˇ»"},
1206 );
1207
1208 cx.simulate_click(screen_coord, Modifiers::command());
1209 assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1210 }
1211}