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