1use crate::{
2 hover_popover::{self, InlayHover},
3 scroll::ScrollAmount,
4 Anchor, Editor, EditorSnapshot, FindAllReferences, GoToDefinition, GoToTypeDefinition, InlayId,
5 PointForPosition, SelectPhase,
6};
7use gpui::{px, AppContext, AsyncWindowContext, Model, Modifiers, Task, ViewContext};
8use language::{Bias, ToOffset};
9use linkify::{LinkFinder, LinkKind};
10use lsp::LanguageServerId;
11use project::{
12 HoverBlock, HoverBlockKind, InlayHintLabelPartTooltip, InlayHintTooltip, LocationLink,
13 ResolveState,
14};
15use std::ops::Range;
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 pub fn point_within_range(
43 &self,
44 trigger_point: &TriggerPoint,
45 snapshot: &EditorSnapshot,
46 ) -> bool {
47 match (self, trigger_point) {
48 (Self::Text(range), TriggerPoint::Text(point)) => {
49 let point_after_start = range.start.cmp(point, &snapshot.buffer_snapshot).is_le();
50 point_after_start && range.end.cmp(point, &snapshot.buffer_snapshot).is_ge()
51 }
52 (Self::Inlay(highlight), TriggerPoint::InlayHint(point, _, _)) => {
53 highlight.inlay == point.inlay
54 && highlight.range.contains(&point.range.start)
55 && highlight.range.contains(&point.range.end)
56 }
57 (Self::Inlay(_), TriggerPoint::Text(_))
58 | (Self::Text(_), TriggerPoint::InlayHint(_, _, _)) => false,
59 }
60 }
61}
62
63#[derive(Debug, Clone)]
64pub enum HoverLink {
65 Url(String),
66 Text(LocationLink),
67 InlayHint(lsp::Location, LanguageServerId),
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub(crate) struct InlayHighlight {
72 pub inlay: InlayId,
73 pub inlay_position: Anchor,
74 pub range: Range<usize>,
75}
76
77#[derive(Debug, Clone, PartialEq)]
78pub enum TriggerPoint {
79 Text(Anchor),
80 InlayHint(InlayHighlight, lsp::Location, LanguageServerId),
81}
82
83impl TriggerPoint {
84 fn anchor(&self) -> &Anchor {
85 match self {
86 TriggerPoint::Text(anchor) => anchor,
87 TriggerPoint::InlayHint(inlay_range, _, _) => &inlay_range.inlay_position,
88 }
89 }
90}
91
92pub fn exclude_link_to_position(
93 buffer: &Model<language::Buffer>,
94 current_position: &text::Anchor,
95 location: &LocationLink,
96 cx: &AppContext,
97) -> bool {
98 // Exclude definition links that points back to cursor position.
99 // (i.e., currently cursor upon definition).
100 let snapshot = buffer.read(cx).snapshot();
101 !(buffer == &location.target.buffer
102 && current_position
103 .bias_right(&snapshot)
104 .cmp(&location.target.range.start, &snapshot)
105 .is_ge()
106 && current_position
107 .cmp(&location.target.range.end, &snapshot)
108 .is_le())
109}
110
111impl Editor {
112 pub(crate) fn update_hovered_link(
113 &mut self,
114 point_for_position: PointForPosition,
115 snapshot: &EditorSnapshot,
116 modifiers: Modifiers,
117 cx: &mut ViewContext<Self>,
118 ) {
119 if !modifiers.secondary() || self.has_pending_selection() {
120 self.hide_hovered_link(cx);
121 return;
122 }
123
124 match point_for_position.as_valid() {
125 Some(point) => {
126 let trigger_point = TriggerPoint::Text(
127 snapshot
128 .buffer_snapshot
129 .anchor_before(point.to_offset(&snapshot.display_snapshot, Bias::Left)),
130 );
131
132 show_link_definition(modifiers.shift, self, trigger_point, snapshot, cx);
133 }
134 None => {
135 update_inlay_link_and_hover_points(
136 &snapshot,
137 point_for_position,
138 self,
139 modifiers.secondary(),
140 modifiers.shift,
141 cx,
142 );
143 }
144 }
145 }
146
147 pub(crate) fn hide_hovered_link(&mut self, cx: &mut ViewContext<Self>) {
148 self.hovered_link_state.take();
149 self.clear_highlights::<HoveredLinkState>(cx);
150 }
151
152 pub(crate) fn handle_click_hovered_link(
153 &mut self,
154 point: PointForPosition,
155 modifiers: Modifiers,
156 cx: &mut ViewContext<Editor>,
157 ) {
158 let reveal_task = self.cmd_click_reveal_task(point, modifiers, cx);
159 cx.spawn(|editor, mut cx| async move {
160 let definition_revealed = reveal_task.await.log_err().unwrap_or(false);
161 let find_references = editor
162 .update(&mut cx, |editor, cx| {
163 if definition_revealed {
164 return None;
165 }
166 editor.find_all_references(&FindAllReferences, cx)
167 })
168 .ok()
169 .flatten();
170 if let Some(find_references) = find_references {
171 find_references.await.log_err();
172 }
173 })
174 .detach();
175 }
176
177 pub fn scroll_hover(&mut self, amount: &ScrollAmount, cx: &mut ViewContext<Self>) -> bool {
178 let selection = self.selections.newest_anchor().head();
179 let snapshot = self.snapshot(cx);
180
181 let Some(popover) = self.hover_state.info_popovers.iter().find(|popover| {
182 popover
183 .symbol_range
184 .point_within_range(&TriggerPoint::Text(selection), &snapshot)
185 }) else {
186 return false;
187 };
188 popover.scroll(amount, cx);
189 true
190 }
191
192 fn cmd_click_reveal_task(
193 &mut self,
194 point: PointForPosition,
195 modifiers: Modifiers,
196 cx: &mut ViewContext<Editor>,
197 ) -> Task<anyhow::Result<bool>> {
198 if let Some(hovered_link_state) = self.hovered_link_state.take() {
199 self.hide_hovered_link(cx);
200 if !hovered_link_state.links.is_empty() {
201 if !self.focus_handle.is_focused(cx) {
202 cx.focus(&self.focus_handle);
203 }
204
205 // exclude links pointing back to the current anchor
206 let current_position = point
207 .next_valid
208 .to_point(&self.snapshot(cx).display_snapshot);
209 let Some((buffer, anchor)) = self
210 .buffer()
211 .read(cx)
212 .text_anchor_for_position(current_position, cx)
213 else {
214 return Task::ready(Ok(false));
215 };
216 let links = hovered_link_state
217 .links
218 .into_iter()
219 .filter(|link| {
220 if let HoverLink::Text(location) = link {
221 exclude_link_to_position(&buffer, &anchor, location, cx)
222 } else {
223 true
224 }
225 })
226 .collect();
227
228 return self.navigate_to_hover_links(None, links, modifiers.alt, cx);
229 }
230 }
231
232 // We don't have the correct kind of link cached, set the selection on
233 // click and immediately trigger GoToDefinition.
234 self.select(
235 SelectPhase::Begin {
236 position: point.next_valid,
237 add: false,
238 click_count: 1,
239 },
240 cx,
241 );
242
243 if point.as_valid().is_some() {
244 if modifiers.shift {
245 self.go_to_type_definition(&GoToTypeDefinition, cx)
246 } else {
247 self.go_to_definition(&GoToDefinition, cx)
248 }
249 } else {
250 Task::ready(Ok(false))
251 }
252 }
253}
254
255pub fn update_inlay_link_and_hover_points(
256 snapshot: &EditorSnapshot,
257 point_for_position: PointForPosition,
258 editor: &mut Editor,
259 secondary_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 tooltip: match tooltip {
326 InlayHintTooltip::String(text) => HoverBlock {
327 text,
328 kind: HoverBlockKind::PlainText,
329 },
330 InlayHintTooltip::MarkupContent(content) => {
331 HoverBlock {
332 text: content.value,
333 kind: content.kind,
334 }
335 }
336 },
337 range: InlayHighlight {
338 inlay: hovered_hint.id,
339 inlay_position: hovered_hint.position,
340 range: extra_shift_left
341 ..hovered_hint.text.len() + extra_shift_right,
342 },
343 },
344 cx,
345 );
346 hover_updated = true;
347 }
348 }
349 project::InlayHintLabel::LabelParts(label_parts) => {
350 let hint_start =
351 snapshot.anchor_to_inlay_offset(hovered_hint.position);
352 if let Some((hovered_hint_part, part_range)) =
353 hover_popover::find_hovered_hint_part(
354 label_parts,
355 hint_start,
356 hovered_offset,
357 )
358 {
359 let highlight_start =
360 (part_range.start - hint_start).0 + extra_shift_left;
361 let highlight_end =
362 (part_range.end - hint_start).0 + extra_shift_right;
363 let highlight = InlayHighlight {
364 inlay: hovered_hint.id,
365 inlay_position: hovered_hint.position,
366 range: highlight_start..highlight_end,
367 };
368 if let Some(tooltip) = hovered_hint_part.tooltip {
369 hover_popover::hover_at_inlay(
370 editor,
371 InlayHover {
372 tooltip: match tooltip {
373 InlayHintLabelPartTooltip::String(text) => {
374 HoverBlock {
375 text,
376 kind: HoverBlockKind::PlainText,
377 }
378 }
379 InlayHintLabelPartTooltip::MarkupContent(
380 content,
381 ) => HoverBlock {
382 text: content.value,
383 kind: content.kind,
384 },
385 },
386 range: highlight.clone(),
387 },
388 cx,
389 );
390 hover_updated = true;
391 }
392 if let Some((language_server_id, location)) =
393 hovered_hint_part.location
394 {
395 if secondary_held
396 && !editor.has_pending_nonempty_selection()
397 {
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::request::{GotoDefinition, GotoTypeDefinition};
704 use util::assert_set_eq;
705 use workspace::item::Item;
706
707 #[gpui::test]
708 async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
709 init_test(cx, |_| {});
710
711 let mut cx = EditorLspTestContext::new_rust(
712 lsp::ServerCapabilities {
713 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
714 type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
715 ..Default::default()
716 },
717 cx,
718 )
719 .await;
720
721 cx.set_state(indoc! {"
722 struct A;
723 let vˇariable = A;
724 "});
725 let screen_coord = cx.editor(|editor, cx| editor.pixel_position_of_cursor(cx));
726
727 // Basic hold cmd+shift, expect highlight in region if response contains type definition
728 let symbol_range = cx.lsp_range(indoc! {"
729 struct A;
730 let «variable» = A;
731 "});
732 let target_range = cx.lsp_range(indoc! {"
733 struct «A»;
734 let variable = A;
735 "});
736
737 cx.run_until_parked();
738
739 let mut requests =
740 cx.handle_request::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
741 Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
742 lsp::LocationLink {
743 origin_selection_range: Some(symbol_range),
744 target_uri: url.clone(),
745 target_range,
746 target_selection_range: target_range,
747 },
748 ])))
749 });
750
751 cx.cx
752 .cx
753 .simulate_mouse_move(screen_coord.unwrap(), None, Modifiers::command_shift());
754
755 requests.next().await;
756 cx.run_until_parked();
757 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
758 struct A;
759 let «variable» = A;
760 "});
761
762 cx.simulate_modifiers_change(Modifiers::secondary_key());
763 cx.run_until_parked();
764 // Assert no link highlights
765 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
766 struct A;
767 let variable = A;
768 "});
769
770 cx.cx
771 .cx
772 .simulate_click(screen_coord.unwrap(), Modifiers::command_shift());
773
774 cx.assert_editor_state(indoc! {"
775 struct «Aˇ»;
776 let variable = A;
777 "});
778 }
779
780 #[gpui::test]
781 async fn test_hover_links(cx: &mut gpui::TestAppContext) {
782 init_test(cx, |_| {});
783
784 let mut cx = EditorLspTestContext::new_rust(
785 lsp::ServerCapabilities {
786 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
787 ..Default::default()
788 },
789 cx,
790 )
791 .await;
792
793 cx.set_state(indoc! {"
794 fn ˇtest() { do_work(); }
795 fn do_work() { test(); }
796 "});
797
798 // Basic hold cmd, expect highlight in region if response contains definition
799 let hover_point = cx.pixel_position(indoc! {"
800 fn test() { do_wˇork(); }
801 fn do_work() { test(); }
802 "});
803 let symbol_range = cx.lsp_range(indoc! {"
804 fn test() { «do_work»(); }
805 fn do_work() { test(); }
806 "});
807 let target_range = cx.lsp_range(indoc! {"
808 fn test() { do_work(); }
809 fn «do_work»() { test(); }
810 "});
811
812 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
813 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
814 lsp::LocationLink {
815 origin_selection_range: Some(symbol_range),
816 target_uri: url.clone(),
817 target_range,
818 target_selection_range: target_range,
819 },
820 ])))
821 });
822
823 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
824 requests.next().await;
825 cx.background_executor.run_until_parked();
826 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
827 fn test() { «do_work»(); }
828 fn do_work() { test(); }
829 "});
830
831 // Unpress cmd causes highlight to go away
832 cx.simulate_modifiers_change(Modifiers::none());
833 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
834 fn test() { do_work(); }
835 fn do_work() { test(); }
836 "});
837
838 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
839 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
840 lsp::LocationLink {
841 origin_selection_range: Some(symbol_range),
842 target_uri: url.clone(),
843 target_range,
844 target_selection_range: target_range,
845 },
846 ])))
847 });
848
849 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
850 requests.next().await;
851 cx.background_executor.run_until_parked();
852 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
853 fn test() { «do_work»(); }
854 fn do_work() { test(); }
855 "});
856
857 // Moving mouse to location with no response dismisses highlight
858 let hover_point = cx.pixel_position(indoc! {"
859 fˇn test() { do_work(); }
860 fn do_work() { test(); }
861 "});
862 let mut requests = cx
863 .lsp
864 .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
865 // No definitions returned
866 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
867 });
868 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
869
870 requests.next().await;
871 cx.background_executor.run_until_parked();
872
873 // Assert no link highlights
874 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
875 fn test() { do_work(); }
876 fn do_work() { test(); }
877 "});
878
879 // // Move mouse without cmd and then pressing cmd triggers highlight
880 let hover_point = cx.pixel_position(indoc! {"
881 fn test() { do_work(); }
882 fn do_work() { teˇst(); }
883 "});
884 cx.simulate_mouse_move(hover_point, None, Modifiers::none());
885
886 // Assert no link highlights
887 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
888 fn test() { do_work(); }
889 fn do_work() { test(); }
890 "});
891
892 let symbol_range = cx.lsp_range(indoc! {"
893 fn test() { do_work(); }
894 fn do_work() { «test»(); }
895 "});
896 let target_range = cx.lsp_range(indoc! {"
897 fn «test»() { do_work(); }
898 fn do_work() { test(); }
899 "});
900
901 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
902 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
903 lsp::LocationLink {
904 origin_selection_range: Some(symbol_range),
905 target_uri: url,
906 target_range,
907 target_selection_range: target_range,
908 },
909 ])))
910 });
911
912 cx.simulate_modifiers_change(Modifiers::secondary_key());
913
914 requests.next().await;
915 cx.background_executor.run_until_parked();
916
917 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
918 fn test() { do_work(); }
919 fn do_work() { «test»(); }
920 "});
921
922 cx.deactivate_window();
923 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
924 fn test() { do_work(); }
925 fn do_work() { test(); }
926 "});
927
928 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
929 cx.background_executor.run_until_parked();
930 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
931 fn test() { do_work(); }
932 fn do_work() { «test»(); }
933 "});
934
935 // Moving again within the same symbol range doesn't re-request
936 let hover_point = cx.pixel_position(indoc! {"
937 fn test() { do_work(); }
938 fn do_work() { tesˇt(); }
939 "});
940 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
941 cx.background_executor.run_until_parked();
942 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
943 fn test() { do_work(); }
944 fn do_work() { «test»(); }
945 "});
946
947 // Cmd click with existing definition doesn't re-request and dismisses highlight
948 cx.simulate_click(hover_point, Modifiers::secondary_key());
949 cx.lsp
950 .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
951 // Empty definition response to make sure we aren't hitting the lsp and using
952 // the cached location instead
953 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
954 });
955 cx.background_executor.run_until_parked();
956 cx.assert_editor_state(indoc! {"
957 fn «testˇ»() { do_work(); }
958 fn do_work() { test(); }
959 "});
960
961 // Assert no link highlights after jump
962 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
963 fn test() { do_work(); }
964 fn do_work() { test(); }
965 "});
966
967 // Cmd click without existing definition requests and jumps
968 let hover_point = cx.pixel_position(indoc! {"
969 fn test() { do_wˇork(); }
970 fn do_work() { test(); }
971 "});
972 let target_range = cx.lsp_range(indoc! {"
973 fn test() { do_work(); }
974 fn «do_work»() { test(); }
975 "});
976
977 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
978 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
979 lsp::LocationLink {
980 origin_selection_range: None,
981 target_uri: url,
982 target_range,
983 target_selection_range: target_range,
984 },
985 ])))
986 });
987 cx.simulate_click(hover_point, Modifiers::secondary_key());
988 requests.next().await;
989 cx.background_executor.run_until_parked();
990 cx.assert_editor_state(indoc! {"
991 fn test() { do_work(); }
992 fn «do_workˇ»() { test(); }
993 "});
994
995 // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
996 // 2. Selection is completed, hovering
997 let hover_point = cx.pixel_position(indoc! {"
998 fn test() { do_wˇork(); }
999 fn do_work() { test(); }
1000 "});
1001 let target_range = cx.lsp_range(indoc! {"
1002 fn test() { do_work(); }
1003 fn «do_work»() { test(); }
1004 "});
1005 let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
1006 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1007 lsp::LocationLink {
1008 origin_selection_range: None,
1009 target_uri: url,
1010 target_range,
1011 target_selection_range: target_range,
1012 },
1013 ])))
1014 });
1015
1016 // create a pending selection
1017 let selection_range = cx.ranges(indoc! {"
1018 fn «test() { do_w»ork(); }
1019 fn do_work() { test(); }
1020 "})[0]
1021 .clone();
1022 cx.update_editor(|editor, cx| {
1023 let snapshot = editor.buffer().read(cx).snapshot(cx);
1024 let anchor_range = snapshot.anchor_before(selection_range.start)
1025 ..snapshot.anchor_after(selection_range.end);
1026 editor.change_selections(Some(crate::Autoscroll::fit()), cx, |s| {
1027 s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
1028 });
1029 });
1030 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1031 cx.background_executor.run_until_parked();
1032 assert!(requests.try_next().is_err());
1033 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1034 fn test() { do_work(); }
1035 fn do_work() { test(); }
1036 "});
1037 cx.background_executor.run_until_parked();
1038 }
1039
1040 #[gpui::test]
1041 async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
1042 init_test(cx, |settings| {
1043 settings.defaults.inlay_hints = Some(InlayHintSettings {
1044 enabled: true,
1045 edit_debounce_ms: 0,
1046 scroll_debounce_ms: 0,
1047 show_type_hints: true,
1048 show_parameter_hints: true,
1049 show_other_hints: true,
1050 })
1051 });
1052
1053 let mut cx = EditorLspTestContext::new_rust(
1054 lsp::ServerCapabilities {
1055 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
1056 ..Default::default()
1057 },
1058 cx,
1059 )
1060 .await;
1061 cx.set_state(indoc! {"
1062 struct TestStruct;
1063
1064 fn main() {
1065 let variableˇ = TestStruct;
1066 }
1067 "});
1068 let hint_start_offset = cx.ranges(indoc! {"
1069 struct TestStruct;
1070
1071 fn main() {
1072 let variableˇ = TestStruct;
1073 }
1074 "})[0]
1075 .start;
1076 let hint_position = cx.to_lsp(hint_start_offset);
1077 let target_range = cx.lsp_range(indoc! {"
1078 struct «TestStruct»;
1079
1080 fn main() {
1081 let variable = TestStruct;
1082 }
1083 "});
1084
1085 let expected_uri = cx.buffer_lsp_url.clone();
1086 let hint_label = ": TestStruct";
1087 cx.lsp
1088 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1089 let expected_uri = expected_uri.clone();
1090 async move {
1091 assert_eq!(params.text_document.uri, expected_uri);
1092 Ok(Some(vec![lsp::InlayHint {
1093 position: hint_position,
1094 label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1095 value: hint_label.to_string(),
1096 location: Some(lsp::Location {
1097 uri: params.text_document.uri,
1098 range: target_range,
1099 }),
1100 ..Default::default()
1101 }]),
1102 kind: Some(lsp::InlayHintKind::TYPE),
1103 text_edits: None,
1104 tooltip: None,
1105 padding_left: Some(false),
1106 padding_right: Some(false),
1107 data: None,
1108 }]))
1109 }
1110 })
1111 .next()
1112 .await;
1113 cx.background_executor.run_until_parked();
1114 cx.update_editor(|editor, cx| {
1115 let expected_layers = vec![hint_label.to_string()];
1116 assert_eq!(expected_layers, cached_hint_labels(editor));
1117 assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1118 });
1119
1120 let inlay_range = cx
1121 .ranges(indoc! {"
1122 struct TestStruct;
1123
1124 fn main() {
1125 let variable« »= TestStruct;
1126 }
1127 "})
1128 .get(0)
1129 .cloned()
1130 .unwrap();
1131 let midpoint = cx.update_editor(|editor, cx| {
1132 let snapshot = editor.snapshot(cx);
1133 let previous_valid = inlay_range.start.to_display_point(&snapshot);
1134 let next_valid = inlay_range.end.to_display_point(&snapshot);
1135 assert_eq!(previous_valid.row(), next_valid.row());
1136 assert!(previous_valid.column() < next_valid.column());
1137 DisplayPoint::new(
1138 previous_valid.row(),
1139 previous_valid.column() + (hint_label.len() / 2) as u32,
1140 )
1141 });
1142 // Press cmd to trigger highlight
1143 let hover_point = cx.pixel_position_for(midpoint);
1144 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1145 cx.background_executor.run_until_parked();
1146 cx.update_editor(|editor, cx| {
1147 let snapshot = editor.snapshot(cx);
1148 let actual_highlights = snapshot
1149 .inlay_highlights::<HoveredLinkState>()
1150 .into_iter()
1151 .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1152 .collect::<Vec<_>>();
1153
1154 let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1155 let expected_highlight = InlayHighlight {
1156 inlay: InlayId::Hint(0),
1157 inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1158 range: 0..hint_label.len(),
1159 };
1160 assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1161 });
1162
1163 cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1164 // Assert no link highlights
1165 cx.update_editor(|editor, cx| {
1166 let snapshot = editor.snapshot(cx);
1167 let actual_ranges = snapshot
1168 .text_highlight_ranges::<HoveredLinkState>()
1169 .map(|ranges| ranges.as_ref().clone().1)
1170 .unwrap_or_default();
1171
1172 assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1173 });
1174
1175 cx.simulate_modifiers_change(Modifiers::secondary_key());
1176 cx.background_executor.run_until_parked();
1177 cx.simulate_click(hover_point, Modifiers::secondary_key());
1178 cx.background_executor.run_until_parked();
1179 cx.assert_editor_state(indoc! {"
1180 struct «TestStructˇ»;
1181
1182 fn main() {
1183 let variable = TestStruct;
1184 }
1185 "});
1186 }
1187
1188 #[gpui::test]
1189 async fn test_urls(cx: &mut gpui::TestAppContext) {
1190 init_test(cx, |_| {});
1191 let mut cx = EditorLspTestContext::new_rust(
1192 lsp::ServerCapabilities {
1193 ..Default::default()
1194 },
1195 cx,
1196 )
1197 .await;
1198
1199 cx.set_state(indoc! {"
1200 Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1201 "});
1202
1203 let screen_coord = cx.pixel_position(indoc! {"
1204 Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1205 "});
1206
1207 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1208 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1209 Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1210 "});
1211
1212 cx.simulate_click(screen_coord, Modifiers::secondary_key());
1213 assert_eq!(
1214 cx.opened_url(),
1215 Some("https://zed.dev/channel/had-(oops)".into())
1216 );
1217 }
1218
1219 #[gpui::test]
1220 async fn test_urls_at_beginning_of_buffer(cx: &mut gpui::TestAppContext) {
1221 init_test(cx, |_| {});
1222 let mut cx = EditorLspTestContext::new_rust(
1223 lsp::ServerCapabilities {
1224 ..Default::default()
1225 },
1226 cx,
1227 )
1228 .await;
1229
1230 cx.set_state(indoc! {"https://zed.dev/releases is a cool ˇwebpage."});
1231
1232 let screen_coord =
1233 cx.pixel_position(indoc! {"https://zed.dev/relˇeases is a cool webpage."});
1234
1235 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1236 cx.assert_editor_text_highlights::<HoveredLinkState>(
1237 indoc! {"«https://zed.dev/releasesˇ» is a cool webpage."},
1238 );
1239
1240 cx.simulate_click(screen_coord, Modifiers::secondary_key());
1241 assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1242 }
1243
1244 #[gpui::test]
1245 async fn test_urls_at_end_of_buffer(cx: &mut gpui::TestAppContext) {
1246 init_test(cx, |_| {});
1247 let mut cx = EditorLspTestContext::new_rust(
1248 lsp::ServerCapabilities {
1249 ..Default::default()
1250 },
1251 cx,
1252 )
1253 .await;
1254
1255 cx.set_state(indoc! {"A cool ˇwebpage is https://zed.dev/releases"});
1256
1257 let screen_coord =
1258 cx.pixel_position(indoc! {"A cool webpage is https://zed.dev/releˇases"});
1259
1260 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1261 cx.assert_editor_text_highlights::<HoveredLinkState>(
1262 indoc! {"A cool webpage is «https://zed.dev/releasesˇ»"},
1263 );
1264
1265 cx.simulate_click(screen_coord, Modifiers::secondary_key());
1266 assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1267 }
1268}