1use crate::{
2 Anchor, Editor, EditorSettings, EditorSnapshot, FindAllReferences, GoToDefinition,
3 GoToTypeDefinition, GotoDefinitionKind, InlayId, Navigated, PointForPosition, SelectPhase,
4 display_map::InlayOffset,
5 editor_settings::GoToDefinitionFallback,
6 hover_popover::{self, InlayHover},
7 scroll::ScrollAmount,
8};
9use gpui::{App, AsyncWindowContext, Context, Entity, Modifiers, Task, Window, px};
10use language::{Bias, ToOffset, point_from_lsp};
11use linkify::{LinkFinder, LinkKind};
12use lsp::LanguageServerId;
13use project::{
14 HoverBlock, HoverBlockKind, InlayHintLabelPartTooltip, InlayHintTooltip, LocationLink, Project,
15 ResolveState, ResolvedPath,
16};
17use settings::Settings;
18use std::ops::Range;
19use text;
20use theme::ActiveTheme as _;
21use util::{ResultExt, TryFutureExt as _, maybe};
22
23#[derive(Debug)]
24pub struct HoveredLinkState {
25 pub last_trigger_point: TriggerPoint,
26 pub preferred_kind: GotoDefinitionKind,
27 pub symbol_range: Option<RangeInEditor>,
28 pub links: Vec<HoverLink>,
29 pub task: Option<Task<Option<()>>>,
30}
31
32#[derive(Debug, Eq, PartialEq, Clone)]
33pub enum RangeInEditor {
34 Text(Range<Anchor>),
35 Inlay(InlayHighlight),
36}
37
38impl RangeInEditor {
39 pub fn as_text_range(&self) -> Option<Range<Anchor>> {
40 match self {
41 Self::Text(range) => Some(range.clone()),
42 Self::Inlay(_) => None,
43 }
44 }
45
46 pub fn point_within_range(
47 &self,
48 trigger_point: &TriggerPoint,
49 snapshot: &EditorSnapshot,
50 ) -> bool {
51 match (self, trigger_point) {
52 (Self::Text(range), TriggerPoint::Text(point)) => {
53 let point_after_start = range.start.cmp(point, &snapshot.buffer_snapshot).is_le();
54 point_after_start && range.end.cmp(point, &snapshot.buffer_snapshot).is_ge()
55 }
56 (Self::Inlay(highlight), TriggerPoint::InlayHint(point, _, _)) => {
57 highlight.inlay == point.inlay
58 && highlight.range.contains(&point.range.start)
59 && highlight.range.contains(&point.range.end)
60 }
61 (Self::Inlay(_), TriggerPoint::Text(_))
62 | (Self::Text(_), TriggerPoint::InlayHint(_, _, _)) => false,
63 }
64 }
65}
66
67#[derive(Debug, Clone)]
68pub enum HoverLink {
69 Url(String),
70 File(ResolvedPath),
71 Text(LocationLink),
72 InlayHint(lsp::Location, LanguageServerId),
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct InlayHighlight {
77 pub inlay: InlayId,
78 pub inlay_position: Anchor,
79 pub range: Range<usize>,
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub enum TriggerPoint {
84 Text(Anchor),
85 InlayHint(InlayHighlight, lsp::Location, LanguageServerId),
86}
87
88impl TriggerPoint {
89 fn anchor(&self) -> &Anchor {
90 match self {
91 TriggerPoint::Text(anchor) => anchor,
92 TriggerPoint::InlayHint(inlay_range, _, _) => &inlay_range.inlay_position,
93 }
94 }
95}
96
97pub fn exclude_link_to_position(
98 buffer: &Entity<language::Buffer>,
99 current_position: &text::Anchor,
100 location: &LocationLink,
101 cx: &App,
102) -> bool {
103 // Exclude definition links that points back to cursor position.
104 // (i.e., currently cursor upon definition).
105 let snapshot = buffer.read(cx).snapshot();
106 !(buffer == &location.target.buffer
107 && current_position
108 .bias_right(&snapshot)
109 .cmp(&location.target.range.start, &snapshot)
110 .is_ge()
111 && current_position
112 .cmp(&location.target.range.end, &snapshot)
113 .is_le())
114}
115
116impl Editor {
117 pub(crate) fn update_hovered_link(
118 &mut self,
119 point_for_position: PointForPosition,
120 snapshot: &EditorSnapshot,
121 modifiers: Modifiers,
122 window: &mut Window,
123 cx: &mut Context<Self>,
124 ) {
125 let hovered_link_modifier = Editor::multi_cursor_modifier(false, &modifiers, cx);
126
127 // Allow inlay hover points to be updated even without modifier key
128 if point_for_position.as_valid().is_none() {
129 // Hovering over inlay - check for hover tooltips
130 update_inlay_link_and_hover_points(
131 snapshot,
132 point_for_position,
133 self,
134 hovered_link_modifier,
135 modifiers.shift,
136 window,
137 cx,
138 );
139 return;
140 }
141
142 if !hovered_link_modifier || self.has_pending_selection() {
143 self.hide_hovered_link(cx);
144 return;
145 }
146
147 match point_for_position.as_valid() {
148 Some(point) => {
149 let trigger_point = TriggerPoint::Text(
150 snapshot
151 .buffer_snapshot
152 .anchor_before(point.to_offset(&snapshot.display_snapshot, Bias::Left)),
153 );
154
155 show_link_definition(modifiers.shift, self, trigger_point, snapshot, window, cx);
156 }
157 None => {
158 // This case should not be reached anymore as we handle it above
159 unreachable!("Invalid position should have been handled earlier");
160 }
161 }
162 }
163
164 pub(crate) fn hide_hovered_link(&mut self, cx: &mut Context<Self>) {
165 self.hovered_link_state.take();
166 self.clear_highlights::<HoveredLinkState>(cx);
167 }
168
169 pub(crate) fn handle_click_hovered_link(
170 &mut self,
171 point: PointForPosition,
172 modifiers: Modifiers,
173 window: &mut Window,
174 cx: &mut Context<Editor>,
175 ) {
176 let reveal_task = self.cmd_click_reveal_task(point, modifiers, window, cx);
177 cx.spawn_in(window, async move |editor, cx| {
178 let definition_revealed = reveal_task.await.log_err().unwrap_or(Navigated::No);
179 let find_references = editor
180 .update_in(cx, |editor, window, cx| {
181 if definition_revealed == Navigated::Yes {
182 return None;
183 }
184 match EditorSettings::get_global(cx).go_to_definition_fallback {
185 GoToDefinitionFallback::None => None,
186 GoToDefinitionFallback::FindAllReferences => {
187 editor.find_all_references(&FindAllReferences, window, cx)
188 }
189 }
190 })
191 .ok()
192 .flatten();
193 if let Some(find_references) = find_references {
194 find_references.await.log_err();
195 }
196 })
197 .detach();
198 }
199
200 pub fn scroll_hover(
201 &mut self,
202 amount: &ScrollAmount,
203 window: &mut Window,
204 cx: &mut Context<Self>,
205 ) -> bool {
206 let selection = self.selections.newest_anchor().head();
207 let snapshot = self.snapshot(window, cx);
208
209 let Some(popover) = self.hover_state.info_popovers.iter().find(|popover| {
210 popover
211 .symbol_range
212 .point_within_range(&TriggerPoint::Text(selection), &snapshot)
213 }) else {
214 return false;
215 };
216 popover.scroll(amount, window, cx);
217 true
218 }
219
220 fn cmd_click_reveal_task(
221 &mut self,
222 point: PointForPosition,
223 modifiers: Modifiers,
224 window: &mut Window,
225 cx: &mut Context<Editor>,
226 ) -> Task<anyhow::Result<Navigated>> {
227 if let Some(hovered_link_state) = self.hovered_link_state.take() {
228 self.hide_hovered_link(cx);
229 if !hovered_link_state.links.is_empty() {
230 if !self.focus_handle.is_focused(window) {
231 window.focus(&self.focus_handle);
232 }
233
234 // exclude links pointing back to the current anchor
235 let current_position = point
236 .next_valid
237 .to_point(&self.snapshot(window, cx).display_snapshot);
238 let Some((buffer, anchor)) = self
239 .buffer()
240 .read(cx)
241 .text_anchor_for_position(current_position, cx)
242 else {
243 return Task::ready(Ok(Navigated::No));
244 };
245 let links = hovered_link_state
246 .links
247 .into_iter()
248 .filter(|link| {
249 if let HoverLink::Text(location) = link {
250 exclude_link_to_position(&buffer, &anchor, location, cx)
251 } else {
252 true
253 }
254 })
255 .collect();
256 let navigate_task =
257 self.navigate_to_hover_links(None, links, modifiers.alt, window, cx);
258 self.select(SelectPhase::End, window, cx);
259 return navigate_task;
260 }
261 }
262
263 // We don't have the correct kind of link cached, set the selection on
264 // click and immediately trigger GoToDefinition.
265 self.select(
266 SelectPhase::Begin {
267 position: point.next_valid,
268 add: false,
269 click_count: 1,
270 },
271 window,
272 cx,
273 );
274
275 let navigate_task = if point.as_valid().is_some() {
276 if modifiers.shift {
277 self.go_to_type_definition(&GoToTypeDefinition, window, cx)
278 } else {
279 self.go_to_definition(&GoToDefinition, window, cx)
280 }
281 } else {
282 Task::ready(Ok(Navigated::No))
283 };
284 self.select(SelectPhase::End, window, cx);
285 return navigate_task;
286 }
287}
288
289pub fn update_inlay_link_and_hover_points(
290 snapshot: &EditorSnapshot,
291 point_for_position: PointForPosition,
292 editor: &mut Editor,
293 secondary_held: bool,
294 shift_held: bool,
295 window: &mut Window,
296 cx: &mut Context<Editor>,
297) {
298 // For inlay hints, we need to use the exact position where the mouse is
299 // But we must clip it to valid bounds to avoid panics
300 let clipped_point = snapshot.clip_point(point_for_position.exact_unclipped, Bias::Left);
301 let hovered_offset = snapshot.display_point_to_inlay_offset(clipped_point, Bias::Left);
302
303 let mut go_to_definition_updated = false;
304 let mut hover_updated = false;
305
306 // Get all visible inlay hints
307 let visible_hints = editor.visible_inlay_hints(cx);
308
309 // Find if we're hovering over an inlay hint
310 if let Some(hovered_inlay) = visible_hints.into_iter().find(|inlay| {
311 // Only process hint inlays
312 if !matches!(inlay.id, InlayId::Hint(_)) {
313 return false;
314 }
315
316 // Check if the hovered position falls within this inlay's display range
317 let inlay_start = snapshot.anchor_to_inlay_offset(inlay.position);
318 let inlay_end = InlayOffset(inlay_start.0 + inlay.text.len());
319
320 hovered_offset >= inlay_start && hovered_offset < inlay_end
321 }) {
322 let inlay_hint_cache = editor.inlay_hint_cache();
323 let excerpt_id = hovered_inlay.position.excerpt_id;
324
325 // Extract the hint ID from the inlay
326 if let InlayId::Hint(_hint_id) = hovered_inlay.id {
327 if let Some(cached_hint) = inlay_hint_cache.hint_by_id(excerpt_id, hovered_inlay.id) {
328 // Check if we should process this hint for hover
329 let should_process_hint = match cached_hint.resolve_state {
330 ResolveState::CanResolve(_, _) => {
331 // For unresolved hints, spawn resolution
332 if let Some(buffer_id) = hovered_inlay.position.buffer_id {
333 inlay_hint_cache.spawn_hint_resolve(
334 buffer_id,
335 excerpt_id,
336 hovered_inlay.id,
337 window,
338 cx,
339 );
340 // Don't clear hover while resolution is starting
341 hover_updated = true;
342 }
343 false // Don't process unresolved hints
344 }
345 ResolveState::Resolved => true,
346 ResolveState::Resolving => {
347 // Don't clear hover while resolving
348 hover_updated = true;
349 false // Don't process further
350 }
351 };
352
353 if should_process_hint {
354 let mut extra_shift_left = 0;
355 let mut extra_shift_right = 0;
356 if cached_hint.padding_left {
357 extra_shift_left += 1;
358 extra_shift_right += 1;
359 }
360 if cached_hint.padding_right {
361 extra_shift_right += 1;
362 }
363 match cached_hint.label {
364 project::InlayHintLabel::String(_) => {
365 if let Some(tooltip) = cached_hint.tooltip {
366 hover_popover::hover_at_inlay(
367 editor,
368 InlayHover {
369 tooltip: match tooltip {
370 InlayHintTooltip::String(text) => HoverBlock {
371 text,
372 kind: HoverBlockKind::PlainText,
373 },
374 InlayHintTooltip::MarkupContent(content) => {
375 HoverBlock {
376 text: content.value,
377 kind: content.kind,
378 }
379 }
380 },
381 range: InlayHighlight {
382 inlay: hovered_inlay.id,
383 inlay_position: hovered_inlay.position,
384 range: extra_shift_left
385 ..hovered_inlay.text.len() + extra_shift_right,
386 },
387 },
388 window,
389 cx,
390 );
391 hover_updated = true;
392 }
393 }
394 project::InlayHintLabel::LabelParts(label_parts) => {
395 // VS Code shows hover for the meaningful part regardless of where you hover
396 // Find the first part with actual hover information (tooltip or location)
397 let _hint_start =
398 snapshot.anchor_to_inlay_offset(hovered_inlay.position);
399 let mut part_offset = 0;
400
401 for part in label_parts {
402 let part_len = part.value.chars().count();
403
404 if part.tooltip.is_some() || part.location.is_some() {
405 // Found the meaningful part - show hover for it
406 let highlight_start = part_offset + extra_shift_left;
407 let highlight_end = part_offset + part_len + extra_shift_right;
408
409 let highlight = InlayHighlight {
410 inlay: hovered_inlay.id,
411 inlay_position: hovered_inlay.position,
412 range: highlight_start..highlight_end,
413 };
414
415 if let Some(tooltip) = part.tooltip {
416 hover_popover::hover_at_inlay(
417 editor,
418 InlayHover {
419 tooltip: match tooltip {
420 InlayHintLabelPartTooltip::String(text) => {
421 HoverBlock {
422 text,
423 kind: HoverBlockKind::PlainText,
424 }
425 }
426 InlayHintLabelPartTooltip::MarkupContent(
427 content,
428 ) => HoverBlock {
429 text: content.value,
430 kind: content.kind,
431 },
432 },
433 range: highlight.clone(),
434 },
435 window,
436 cx,
437 );
438 hover_updated = true;
439 } else if let Some((_language_server_id, location)) =
440 part.location.clone()
441 {
442 // When there's no tooltip but we have a location, perform a "Go to Definition" style operation
443 let filename = location
444 .uri
445 .path()
446 .split('/')
447 .next_back()
448 .unwrap_or("unknown")
449 .to_string();
450
451 // Prepare data needed for the async task
452 let project = editor.project.clone().unwrap();
453 let hint_value = part.value.clone();
454 let highlight = highlight.clone();
455 let filename = filename.clone();
456
457 // Spawn async task to fetch documentation
458 cx.spawn_in(window, async move |editor, cx| {
459 // Convert LSP URL to file path
460 let file_path = location.uri.to_file_path()
461 .map_err(|_| anyhow::anyhow!("Invalid file URL"))?;
462
463 // Open the definition file
464 let definition_buffer = project
465 .update(cx, |project, cx| {
466 project.open_local_buffer(file_path, cx)
467 })?
468 .await?;
469
470 // Register the buffer with language servers
471 let _lsp_handle = project.update(cx, |project, cx| {
472 project.register_buffer_with_language_servers(&definition_buffer, cx)
473 })?;
474
475 // Give LSP a moment to process the didOpen notification
476 cx.background_executor()
477 .timer(std::time::Duration::from_millis(100))
478 .await;
479
480 // Try to get hover documentation from LSP
481 let hover_position = location.range.start;
482
483 // Convert LSP position to a point
484 let hover_point = definition_buffer.update(cx, |buffer, _| {
485 let point_utf16 = point_from_lsp(hover_position);
486 let snapshot = buffer.snapshot();
487 let point = snapshot.clip_point_utf16(point_utf16, Bias::Left);
488 snapshot.anchor_after(point)
489 })?;
490
491 let hover_response = project
492 .update(cx, |project, cx| {
493 project.hover(&definition_buffer, hover_point, cx)
494 })?
495 .await;
496
497 if !hover_response.is_empty() {
498 // Get the first hover response
499 let hover = &hover_response[0];
500 if !hover.contents.is_empty() {
501 // Format the hover blocks as markdown
502 let mut formatted_docs = String::new();
503
504 // Add the type signature first
505 formatted_docs.push_str(&format!("```rust\n{}\n```\n\n", hint_value.trim()));
506
507 // Add all the hover content
508 for block in &hover.contents {
509 match &block.kind {
510 HoverBlockKind::Markdown => {
511 formatted_docs.push_str(&block.text);
512 formatted_docs.push_str("\n\n");
513 }
514 HoverBlockKind::Code { language } => {
515 formatted_docs.push_str(&format!("```{}\n{}\n```\n\n", language, block.text));
516 }
517 HoverBlockKind::PlainText => {
518 formatted_docs.push_str(&block.text);
519 formatted_docs.push_str("\n\n");
520 }
521 }
522 }
523
524 editor.update_in(cx, |editor, window, cx| {
525 hover_popover::hover_at_inlay(
526 editor,
527 InlayHover {
528 tooltip: HoverBlock {
529 text: formatted_docs.trim().to_string(),
530 kind: HoverBlockKind::Markdown,
531 },
532 range: highlight,
533 },
534 window,
535 cx,
536 );
537 }).log_err();
538
539 return Ok(());
540 }
541 }
542
543 // Fallback: Extract documentation directly from the source
544 let documentation = definition_buffer.update(cx, |buffer, _| {
545 let line_number = location.range.start.line as usize;
546
547 // Get the text of the buffer
548 let text = buffer.text();
549 let lines: Vec<&str> = text.lines().collect();
550
551 // Look backwards from the definition line to find doc comments
552 let mut doc_lines = Vec::new();
553 let mut current_line = line_number.saturating_sub(1);
554
555 // Skip any attributes like #[derive(...)]
556 while current_line > 0 && lines.get(current_line).map_or(false, |line| {
557 let trimmed = line.trim();
558 trimmed.starts_with("#[") || trimmed.is_empty()
559 }) {
560 current_line = current_line.saturating_sub(1);
561 }
562
563 // Collect doc comments
564 while current_line > 0 {
565 if let Some(line) = lines.get(current_line) {
566 let trimmed = line.trim();
567 if trimmed.starts_with("///") {
568 // Remove the /// and any leading space
569 let doc_text = trimmed.strip_prefix("///").unwrap_or("")
570 .strip_prefix(" ").unwrap_or_else(|| trimmed.strip_prefix("///").unwrap_or(""));
571 doc_lines.push(doc_text.to_string());
572 } else if !trimmed.is_empty() {
573 // Stop at the first non-doc, non-empty line
574 break;
575 }
576 }
577 current_line = current_line.saturating_sub(1);
578 }
579
580 // Reverse to get correct order
581 doc_lines.reverse();
582
583 // Also get the actual definition line
584 let definition = lines.get(line_number)
585 .map(|s| s.trim().to_string())
586 .unwrap_or_else(|| hint_value.clone());
587
588 if doc_lines.is_empty() {
589 None
590 } else {
591 let docs = doc_lines.join("\n");
592 Some((definition, docs))
593 }
594 })?;
595
596 if let Some((definition, docs)) = documentation {
597 // Format as markdown with the definition as a code block
598 let formatted_docs = format!("```rust\n{}\n```\n\n{}", definition, docs);
599
600 editor.update_in(cx, |editor, window, cx| {
601 hover_popover::hover_at_inlay(
602 editor,
603 InlayHover {
604 tooltip: HoverBlock {
605 text: formatted_docs,
606 kind: HoverBlockKind::Markdown,
607 },
608 range: highlight,
609 },
610 window,
611 cx,
612 );
613 }).log_err();
614 } else {
615 // Fallback to showing just the location info
616 let fallback_text = format!(
617 "{}\n\nDefined in {} at line {}",
618 hint_value.trim(),
619 filename,
620 location.range.start.line + 1
621 );
622 editor.update_in(cx, |editor, window, cx| {
623 hover_popover::hover_at_inlay(
624 editor,
625 InlayHover {
626 tooltip: HoverBlock {
627 text: fallback_text,
628 kind: HoverBlockKind::PlainText,
629 },
630 range: highlight,
631 },
632 window,
633 cx,
634 );
635 }).log_err();
636 }
637
638 anyhow::Ok(())
639 }).detach();
640 }
641
642 if let Some((language_server_id, location)) = &part.location {
643 if secondary_held
644 && !editor.has_pending_nonempty_selection()
645 {
646 go_to_definition_updated = true;
647 show_link_definition(
648 shift_held,
649 editor,
650 TriggerPoint::InlayHint(
651 highlight,
652 location.clone(),
653 *language_server_id,
654 ),
655 snapshot,
656 window,
657 cx,
658 );
659 }
660 }
661
662 // Found and processed the meaningful part
663 break;
664 }
665
666 part_offset += part_len;
667 }
668 }
669 };
670 }
671 }
672 }
673 }
674
675 if !go_to_definition_updated {
676 editor.hide_hovered_link(cx)
677 }
678 if !hover_updated {
679 hover_popover::hover_at(editor, None, window, cx);
680 }
681}
682
683pub fn show_link_definition(
684 shift_held: bool,
685 editor: &mut Editor,
686 trigger_point: TriggerPoint,
687 snapshot: &EditorSnapshot,
688 window: &mut Window,
689 cx: &mut Context<Editor>,
690) {
691 let preferred_kind = match trigger_point {
692 TriggerPoint::Text(_) if !shift_held => GotoDefinitionKind::Symbol,
693 _ => GotoDefinitionKind::Type,
694 };
695
696 let (mut hovered_link_state, is_cached) =
697 if let Some(existing) = editor.hovered_link_state.take() {
698 (existing, true)
699 } else {
700 (
701 HoveredLinkState {
702 last_trigger_point: trigger_point.clone(),
703 symbol_range: None,
704 preferred_kind,
705 links: vec![],
706 task: None,
707 },
708 false,
709 )
710 };
711
712 if editor.pending_rename.is_some() {
713 return;
714 }
715
716 let trigger_anchor = trigger_point.anchor();
717 let Some((buffer, buffer_position)) = editor
718 .buffer
719 .read(cx)
720 .text_anchor_for_position(*trigger_anchor, cx)
721 else {
722 return;
723 };
724
725 let Some((excerpt_id, _, _)) = editor
726 .buffer()
727 .read(cx)
728 .excerpt_containing(*trigger_anchor, cx)
729 else {
730 return;
731 };
732
733 let same_kind = hovered_link_state.preferred_kind == preferred_kind
734 || hovered_link_state
735 .links
736 .first()
737 .is_some_and(|d| matches!(d, HoverLink::Url(_)));
738
739 if same_kind {
740 if is_cached && (hovered_link_state.last_trigger_point == trigger_point)
741 || hovered_link_state
742 .symbol_range
743 .as_ref()
744 .is_some_and(|symbol_range| {
745 symbol_range.point_within_range(&trigger_point, snapshot)
746 })
747 {
748 editor.hovered_link_state = Some(hovered_link_state);
749 return;
750 }
751 } else {
752 editor.hide_hovered_link(cx)
753 }
754 let project = editor.project.clone();
755 let provider = editor.semantics_provider.clone();
756
757 let snapshot = snapshot.buffer_snapshot.clone();
758 hovered_link_state.task = Some(cx.spawn_in(window, async move |this, cx| {
759 async move {
760 let result = match &trigger_point {
761 TriggerPoint::Text(_) => {
762 if let Some((url_range, url)) = find_url(&buffer, buffer_position, cx.clone()) {
763 this.read_with(cx, |_, _| {
764 let range = maybe!({
765 let start =
766 snapshot.anchor_in_excerpt(excerpt_id, url_range.start)?;
767 let end = snapshot.anchor_in_excerpt(excerpt_id, url_range.end)?;
768 Some(RangeInEditor::Text(start..end))
769 });
770 (range, vec![HoverLink::Url(url)])
771 })
772 .ok()
773 } else if let Some((filename_range, filename)) =
774 find_file(&buffer, project.clone(), buffer_position, cx).await
775 {
776 let range = maybe!({
777 let start =
778 snapshot.anchor_in_excerpt(excerpt_id, filename_range.start)?;
779 let end = snapshot.anchor_in_excerpt(excerpt_id, filename_range.end)?;
780 Some(RangeInEditor::Text(start..end))
781 });
782
783 Some((range, vec![HoverLink::File(filename)]))
784 } else if let Some(provider) = provider {
785 let task = cx.update(|_, cx| {
786 provider.definitions(&buffer, buffer_position, preferred_kind, cx)
787 })?;
788 if let Some(task) = task {
789 task.await.ok().map(|definition_result| {
790 (
791 definition_result.iter().find_map(|link| {
792 link.origin.as_ref().and_then(|origin| {
793 let start = snapshot.anchor_in_excerpt(
794 excerpt_id,
795 origin.range.start,
796 )?;
797 let end = snapshot
798 .anchor_in_excerpt(excerpt_id, origin.range.end)?;
799 Some(RangeInEditor::Text(start..end))
800 })
801 }),
802 definition_result.into_iter().map(HoverLink::Text).collect(),
803 )
804 })
805 } else {
806 None
807 }
808 } else {
809 None
810 }
811 }
812 TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
813 Some(RangeInEditor::Inlay(highlight.clone())),
814 vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
815 )),
816 };
817
818 this.update(cx, |editor, cx| {
819 // Clear any existing highlights
820 editor.clear_highlights::<HoveredLinkState>(cx);
821 let Some(hovered_link_state) = editor.hovered_link_state.as_mut() else {
822 editor.hide_hovered_link(cx);
823 return;
824 };
825 hovered_link_state.preferred_kind = preferred_kind;
826 hovered_link_state.symbol_range = result
827 .as_ref()
828 .and_then(|(symbol_range, _)| symbol_range.clone());
829
830 if let Some((symbol_range, definitions)) = result {
831 hovered_link_state.links = definitions;
832
833 let underline_hovered_link = !hovered_link_state.links.is_empty()
834 || hovered_link_state.symbol_range.is_some();
835
836 if underline_hovered_link {
837 let style = gpui::HighlightStyle {
838 underline: Some(gpui::UnderlineStyle {
839 thickness: px(1.),
840 ..Default::default()
841 }),
842 color: Some(cx.theme().colors().link_text_hover),
843 ..Default::default()
844 };
845 let highlight_range =
846 symbol_range.unwrap_or_else(|| match &trigger_point {
847 TriggerPoint::Text(trigger_anchor) => {
848 // If no symbol range returned from language server, use the surrounding word.
849 let (offset_range, _) =
850 snapshot.surrounding_word(*trigger_anchor, false);
851 RangeInEditor::Text(
852 snapshot.anchor_before(offset_range.start)
853 ..snapshot.anchor_after(offset_range.end),
854 )
855 }
856 TriggerPoint::InlayHint(highlight, _, _) => {
857 RangeInEditor::Inlay(highlight.clone())
858 }
859 });
860
861 match highlight_range {
862 RangeInEditor::Text(text_range) => editor
863 .highlight_text::<HoveredLinkState>(vec![text_range], style, cx),
864 RangeInEditor::Inlay(highlight) => editor
865 .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
866 }
867 }
868 } else {
869 editor.hide_hovered_link(cx);
870 }
871 })?;
872
873 anyhow::Ok(())
874 }
875 .log_err()
876 .await
877 }));
878
879 editor.hovered_link_state = Some(hovered_link_state);
880}
881
882pub(crate) fn find_url(
883 buffer: &Entity<language::Buffer>,
884 position: text::Anchor,
885 mut cx: AsyncWindowContext,
886) -> Option<(Range<text::Anchor>, String)> {
887 const LIMIT: usize = 2048;
888
889 let Ok(snapshot) = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot()) else {
890 return None;
891 };
892
893 let offset = position.to_offset(&snapshot);
894 let mut token_start = offset;
895 let mut token_end = offset;
896 let mut found_start = false;
897 let mut found_end = false;
898
899 for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
900 if ch.is_whitespace() {
901 found_start = true;
902 break;
903 }
904 token_start -= ch.len_utf8();
905 }
906 // Check if we didn't find the starting whitespace or if we didn't reach the start of the buffer
907 if !found_start && token_start != 0 {
908 return None;
909 }
910
911 for ch in snapshot
912 .chars_at(offset)
913 .take(LIMIT - (offset - token_start))
914 {
915 if ch.is_whitespace() {
916 found_end = true;
917 break;
918 }
919 token_end += ch.len_utf8();
920 }
921 // Check if we didn't find the ending whitespace or if we read more or equal than LIMIT
922 // which at this point would happen only if we reached the end of buffer
923 if !found_end && (token_end - token_start >= LIMIT) {
924 return None;
925 }
926
927 let mut finder = LinkFinder::new();
928 finder.kinds(&[LinkKind::Url]);
929 let input = snapshot
930 .text_for_range(token_start..token_end)
931 .collect::<String>();
932
933 let relative_offset = offset - token_start;
934 for link in finder.links(&input) {
935 if link.start() <= relative_offset && link.end() >= relative_offset {
936 let range = snapshot.anchor_before(token_start + link.start())
937 ..snapshot.anchor_after(token_start + link.end());
938 return Some((range, link.as_str().to_string()));
939 }
940 }
941 None
942}
943
944pub(crate) fn find_url_from_range(
945 buffer: &Entity<language::Buffer>,
946 range: Range<text::Anchor>,
947 mut cx: AsyncWindowContext,
948) -> Option<String> {
949 const LIMIT: usize = 2048;
950
951 let Ok(snapshot) = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot()) else {
952 return None;
953 };
954
955 let start_offset = range.start.to_offset(&snapshot);
956 let end_offset = range.end.to_offset(&snapshot);
957
958 let mut token_start = start_offset.min(end_offset);
959 let mut token_end = start_offset.max(end_offset);
960
961 let range_len = token_end - token_start;
962
963 if range_len >= LIMIT {
964 return None;
965 }
966
967 // Skip leading whitespace
968 for ch in snapshot.chars_at(token_start).take(range_len) {
969 if !ch.is_whitespace() {
970 break;
971 }
972 token_start += ch.len_utf8();
973 }
974
975 // Skip trailing whitespace
976 for ch in snapshot.reversed_chars_at(token_end).take(range_len) {
977 if !ch.is_whitespace() {
978 break;
979 }
980 token_end -= ch.len_utf8();
981 }
982
983 if token_start >= token_end {
984 return None;
985 }
986
987 let text = snapshot
988 .text_for_range(token_start..token_end)
989 .collect::<String>();
990
991 let mut finder = LinkFinder::new();
992 finder.kinds(&[LinkKind::Url]);
993
994 if let Some(link) = finder.links(&text).next() {
995 if link.start() == 0 && link.end() == text.len() {
996 return Some(link.as_str().to_string());
997 }
998 }
999
1000 None
1001}
1002
1003pub(crate) async fn find_file(
1004 buffer: &Entity<language::Buffer>,
1005 project: Option<Entity<Project>>,
1006 position: text::Anchor,
1007 cx: &mut AsyncWindowContext,
1008) -> Option<(Range<text::Anchor>, ResolvedPath)> {
1009 let project = project?;
1010 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
1011 let scope = snapshot.language_scope_at(position);
1012 let (range, candidate_file_path) = surrounding_filename(snapshot, position)?;
1013
1014 async fn check_path(
1015 candidate_file_path: &str,
1016 project: &Entity<Project>,
1017 buffer: &Entity<language::Buffer>,
1018 cx: &mut AsyncWindowContext,
1019 ) -> Option<ResolvedPath> {
1020 project
1021 .update(cx, |project, cx| {
1022 project.resolve_path_in_buffer(&candidate_file_path, buffer, cx)
1023 })
1024 .ok()?
1025 .await
1026 .filter(|s| s.is_file())
1027 }
1028
1029 if let Some(existing_path) = check_path(&candidate_file_path, &project, buffer, cx).await {
1030 return Some((range, existing_path));
1031 }
1032
1033 if let Some(scope) = scope {
1034 for suffix in scope.path_suffixes() {
1035 if candidate_file_path.ends_with(format!(".{suffix}").as_str()) {
1036 continue;
1037 }
1038
1039 let suffixed_candidate = format!("{candidate_file_path}.{suffix}");
1040 if let Some(existing_path) = check_path(&suffixed_candidate, &project, buffer, cx).await
1041 {
1042 return Some((range, existing_path));
1043 }
1044 }
1045 }
1046
1047 None
1048}
1049
1050fn surrounding_filename(
1051 snapshot: language::BufferSnapshot,
1052 position: text::Anchor,
1053) -> Option<(Range<text::Anchor>, String)> {
1054 const LIMIT: usize = 2048;
1055
1056 let offset = position.to_offset(&snapshot);
1057 let mut token_start = offset;
1058 let mut token_end = offset;
1059 let mut found_start = false;
1060 let mut found_end = false;
1061 let mut inside_quotes = false;
1062
1063 let mut filename = String::new();
1064
1065 let mut backwards = snapshot.reversed_chars_at(offset).take(LIMIT).peekable();
1066 while let Some(ch) = backwards.next() {
1067 // Escaped whitespace
1068 if ch.is_whitespace() && backwards.peek() == Some(&'\\') {
1069 filename.push(ch);
1070 token_start -= ch.len_utf8();
1071 backwards.next();
1072 token_start -= '\\'.len_utf8();
1073 continue;
1074 }
1075 if ch.is_whitespace() {
1076 found_start = true;
1077 break;
1078 }
1079 if (ch == '"' || ch == '\'') && !inside_quotes {
1080 found_start = true;
1081 inside_quotes = true;
1082 break;
1083 }
1084
1085 filename.push(ch);
1086 token_start -= ch.len_utf8();
1087 }
1088 if !found_start && token_start != 0 {
1089 return None;
1090 }
1091
1092 filename = filename.chars().rev().collect();
1093
1094 let mut forwards = snapshot
1095 .chars_at(offset)
1096 .take(LIMIT - (offset - token_start))
1097 .peekable();
1098 while let Some(ch) = forwards.next() {
1099 // Skip escaped whitespace
1100 if ch == '\\' && forwards.peek().map_or(false, |ch| ch.is_whitespace()) {
1101 token_end += ch.len_utf8();
1102 let whitespace = forwards.next().unwrap();
1103 token_end += whitespace.len_utf8();
1104 filename.push(whitespace);
1105 continue;
1106 }
1107
1108 if ch.is_whitespace() {
1109 found_end = true;
1110 break;
1111 }
1112 if ch == '"' || ch == '\'' {
1113 // If we're inside quotes, we stop when we come across the next quote
1114 if inside_quotes {
1115 found_end = true;
1116 break;
1117 } else {
1118 // Otherwise, we skip the quote
1119 inside_quotes = true;
1120 continue;
1121 }
1122 }
1123 filename.push(ch);
1124 token_end += ch.len_utf8();
1125 }
1126
1127 if !found_end && (token_end - token_start >= LIMIT) {
1128 return None;
1129 }
1130
1131 if filename.is_empty() {
1132 return None;
1133 }
1134
1135 let range = snapshot.anchor_before(token_start)..snapshot.anchor_after(token_end);
1136
1137 Some((range, filename))
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142 use super::*;
1143 use crate::{
1144 DisplayPoint,
1145 display_map::ToDisplayPoint,
1146 editor_tests::init_test,
1147 inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
1148 test::editor_lsp_test_context::EditorLspTestContext,
1149 };
1150 use futures::StreamExt;
1151 use gpui::Modifiers;
1152 use indoc::indoc;
1153 use language::language_settings::InlayHintSettings;
1154 use lsp::request::{GotoDefinition, GotoTypeDefinition};
1155 use util::{assert_set_eq, path};
1156 use workspace::item::Item;
1157
1158 #[gpui::test]
1159 async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
1160 init_test(cx, |_| {});
1161
1162 let mut cx = EditorLspTestContext::new_rust(
1163 lsp::ServerCapabilities {
1164 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
1165 type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
1166 ..Default::default()
1167 },
1168 cx,
1169 )
1170 .await;
1171
1172 cx.set_state(indoc! {"
1173 struct A;
1174 let vˇariable = A;
1175 "});
1176 let screen_coord = cx.editor(|editor, _, cx| editor.pixel_position_of_cursor(cx));
1177
1178 // Basic hold cmd+shift, expect highlight in region if response contains type definition
1179 let symbol_range = cx.lsp_range(indoc! {"
1180 struct A;
1181 let «variable» = A;
1182 "});
1183 let target_range = cx.lsp_range(indoc! {"
1184 struct «A»;
1185 let variable = A;
1186 "});
1187
1188 cx.run_until_parked();
1189
1190 let mut requests =
1191 cx.set_request_handler::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
1192 Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
1193 lsp::LocationLink {
1194 origin_selection_range: Some(symbol_range),
1195 target_uri: url.clone(),
1196 target_range,
1197 target_selection_range: target_range,
1198 },
1199 ])))
1200 });
1201
1202 let modifiers = if cfg!(target_os = "macos") {
1203 Modifiers::command_shift()
1204 } else {
1205 Modifiers::control_shift()
1206 };
1207
1208 cx.simulate_mouse_move(screen_coord.unwrap(), None, modifiers);
1209
1210 requests.next().await;
1211 cx.run_until_parked();
1212 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1213 struct A;
1214 let «variable» = A;
1215 "});
1216
1217 cx.simulate_modifiers_change(Modifiers::secondary_key());
1218 cx.run_until_parked();
1219 // Assert no link highlights
1220 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1221 struct A;
1222 let variable = A;
1223 "});
1224
1225 cx.simulate_click(screen_coord.unwrap(), modifiers);
1226
1227 cx.assert_editor_state(indoc! {"
1228 struct «Aˇ»;
1229 let variable = A;
1230 "});
1231 }
1232
1233 #[gpui::test]
1234 async fn test_hover_links(cx: &mut gpui::TestAppContext) {
1235 init_test(cx, |_| {});
1236
1237 let mut cx = EditorLspTestContext::new_rust(
1238 lsp::ServerCapabilities {
1239 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
1240 definition_provider: Some(lsp::OneOf::Left(true)),
1241 ..Default::default()
1242 },
1243 cx,
1244 )
1245 .await;
1246
1247 cx.set_state(indoc! {"
1248 fn ˇtest() { do_work(); }
1249 fn do_work() { test(); }
1250 "});
1251
1252 // Basic hold cmd, expect highlight in region if response contains definition
1253 let hover_point = cx.pixel_position(indoc! {"
1254 fn test() { do_wˇork(); }
1255 fn do_work() { test(); }
1256 "});
1257 let symbol_range = cx.lsp_range(indoc! {"
1258 fn test() { «do_work»(); }
1259 fn do_work() { test(); }
1260 "});
1261 let target_range = cx.lsp_range(indoc! {"
1262 fn test() { do_work(); }
1263 fn «do_work»() { test(); }
1264 "});
1265
1266 let mut requests =
1267 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1268 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1269 lsp::LocationLink {
1270 origin_selection_range: Some(symbol_range),
1271 target_uri: url.clone(),
1272 target_range,
1273 target_selection_range: target_range,
1274 },
1275 ])))
1276 });
1277
1278 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1279 requests.next().await;
1280 cx.background_executor.run_until_parked();
1281 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1282 fn test() { «do_work»(); }
1283 fn do_work() { test(); }
1284 "});
1285
1286 // Unpress cmd causes highlight to go away
1287 cx.simulate_modifiers_change(Modifiers::none());
1288 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1289 fn test() { do_work(); }
1290 fn do_work() { test(); }
1291 "});
1292
1293 let mut requests =
1294 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1295 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1296 lsp::LocationLink {
1297 origin_selection_range: Some(symbol_range),
1298 target_uri: url.clone(),
1299 target_range,
1300 target_selection_range: target_range,
1301 },
1302 ])))
1303 });
1304
1305 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1306 requests.next().await;
1307 cx.background_executor.run_until_parked();
1308 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1309 fn test() { «do_work»(); }
1310 fn do_work() { test(); }
1311 "});
1312
1313 // Moving mouse to location with no response dismisses highlight
1314 let hover_point = cx.pixel_position(indoc! {"
1315 fˇn test() { do_work(); }
1316 fn do_work() { test(); }
1317 "});
1318 let mut requests =
1319 cx.lsp
1320 .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1321 // No definitions returned
1322 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1323 });
1324 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1325
1326 requests.next().await;
1327 cx.background_executor.run_until_parked();
1328
1329 // Assert no link highlights
1330 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1331 fn test() { do_work(); }
1332 fn do_work() { test(); }
1333 "});
1334
1335 // // Move mouse without cmd and then pressing cmd triggers highlight
1336 let hover_point = cx.pixel_position(indoc! {"
1337 fn test() { do_work(); }
1338 fn do_work() { teˇst(); }
1339 "});
1340 cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1341
1342 // Assert no link highlights
1343 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1344 fn test() { do_work(); }
1345 fn do_work() { test(); }
1346 "});
1347
1348 let symbol_range = cx.lsp_range(indoc! {"
1349 fn test() { do_work(); }
1350 fn do_work() { «test»(); }
1351 "});
1352 let target_range = cx.lsp_range(indoc! {"
1353 fn «test»() { do_work(); }
1354 fn do_work() { test(); }
1355 "});
1356
1357 let mut requests =
1358 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1359 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1360 lsp::LocationLink {
1361 origin_selection_range: Some(symbol_range),
1362 target_uri: url,
1363 target_range,
1364 target_selection_range: target_range,
1365 },
1366 ])))
1367 });
1368
1369 cx.simulate_modifiers_change(Modifiers::secondary_key());
1370
1371 requests.next().await;
1372 cx.background_executor.run_until_parked();
1373
1374 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1375 fn test() { do_work(); }
1376 fn do_work() { «test»(); }
1377 "});
1378
1379 cx.deactivate_window();
1380 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1381 fn test() { do_work(); }
1382 fn do_work() { test(); }
1383 "});
1384
1385 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1386 cx.background_executor.run_until_parked();
1387 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1388 fn test() { do_work(); }
1389 fn do_work() { «test»(); }
1390 "});
1391
1392 // Moving again within the same symbol range doesn't re-request
1393 let hover_point = cx.pixel_position(indoc! {"
1394 fn test() { do_work(); }
1395 fn do_work() { tesˇt(); }
1396 "});
1397 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1398 cx.background_executor.run_until_parked();
1399 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1400 fn test() { do_work(); }
1401 fn do_work() { «test»(); }
1402 "});
1403
1404 // Cmd click with existing definition doesn't re-request and dismisses highlight
1405 cx.simulate_click(hover_point, Modifiers::secondary_key());
1406 cx.lsp
1407 .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1408 // Empty definition response to make sure we aren't hitting the lsp and using
1409 // the cached location instead
1410 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1411 });
1412 cx.background_executor.run_until_parked();
1413 cx.assert_editor_state(indoc! {"
1414 fn «testˇ»() { do_work(); }
1415 fn do_work() { test(); }
1416 "});
1417
1418 // Assert no link highlights after jump
1419 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1420 fn test() { do_work(); }
1421 fn do_work() { test(); }
1422 "});
1423
1424 // Cmd click without existing definition requests and jumps
1425 let hover_point = cx.pixel_position(indoc! {"
1426 fn test() { do_wˇork(); }
1427 fn do_work() { test(); }
1428 "});
1429 let target_range = cx.lsp_range(indoc! {"
1430 fn test() { do_work(); }
1431 fn «do_work»() { test(); }
1432 "});
1433
1434 let mut requests =
1435 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1436 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1437 lsp::LocationLink {
1438 origin_selection_range: None,
1439 target_uri: url,
1440 target_range,
1441 target_selection_range: target_range,
1442 },
1443 ])))
1444 });
1445 cx.simulate_click(hover_point, Modifiers::secondary_key());
1446 requests.next().await;
1447 cx.background_executor.run_until_parked();
1448 cx.assert_editor_state(indoc! {"
1449 fn test() { do_work(); }
1450 fn «do_workˇ»() { test(); }
1451 "});
1452
1453 // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
1454 // 2. Selection is completed, hovering
1455 let hover_point = cx.pixel_position(indoc! {"
1456 fn test() { do_wˇork(); }
1457 fn do_work() { test(); }
1458 "});
1459 let target_range = cx.lsp_range(indoc! {"
1460 fn test() { do_work(); }
1461 fn «do_work»() { test(); }
1462 "});
1463 let mut requests =
1464 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1465 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1466 lsp::LocationLink {
1467 origin_selection_range: None,
1468 target_uri: url,
1469 target_range,
1470 target_selection_range: target_range,
1471 },
1472 ])))
1473 });
1474
1475 // create a pending selection
1476 let selection_range = cx.ranges(indoc! {"
1477 fn «test() { do_w»ork(); }
1478 fn do_work() { test(); }
1479 "})[0]
1480 .clone();
1481 cx.update_editor(|editor, window, cx| {
1482 let snapshot = editor.buffer().read(cx).snapshot(cx);
1483 let anchor_range = snapshot.anchor_before(selection_range.start)
1484 ..snapshot.anchor_after(selection_range.end);
1485 editor.change_selections(Default::default(), window, cx, |s| {
1486 s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
1487 });
1488 });
1489 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1490 cx.background_executor.run_until_parked();
1491 assert!(requests.try_next().is_err());
1492 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1493 fn test() { do_work(); }
1494 fn do_work() { test(); }
1495 "});
1496 cx.background_executor.run_until_parked();
1497 }
1498
1499 #[gpui::test]
1500 async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
1501 init_test(cx, |settings| {
1502 settings.defaults.inlay_hints = Some(InlayHintSettings {
1503 enabled: true,
1504 show_value_hints: false,
1505 edit_debounce_ms: 0,
1506 scroll_debounce_ms: 0,
1507 show_type_hints: true,
1508 show_parameter_hints: true,
1509 show_other_hints: true,
1510 show_background: false,
1511 toggle_on_modifiers_press: None,
1512 })
1513 });
1514
1515 let mut cx = EditorLspTestContext::new_rust(
1516 lsp::ServerCapabilities {
1517 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
1518 ..Default::default()
1519 },
1520 cx,
1521 )
1522 .await;
1523 cx.set_state(indoc! {"
1524 struct TestStruct;
1525
1526 fn main() {
1527 let variableˇ = TestStruct;
1528 }
1529 "});
1530 let hint_start_offset = cx.ranges(indoc! {"
1531 struct TestStruct;
1532
1533 fn main() {
1534 let variableˇ = TestStruct;
1535 }
1536 "})[0]
1537 .start;
1538 let hint_position = cx.to_lsp(hint_start_offset);
1539 let target_range = cx.lsp_range(indoc! {"
1540 struct «TestStruct»;
1541
1542 fn main() {
1543 let variable = TestStruct;
1544 }
1545 "});
1546
1547 let expected_uri = cx.buffer_lsp_url.clone();
1548 let hint_label = ": TestStruct";
1549 cx.lsp
1550 .set_request_handler::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1551 let expected_uri = expected_uri.clone();
1552 async move {
1553 assert_eq!(params.text_document.uri, expected_uri);
1554 Ok(Some(vec![lsp::InlayHint {
1555 position: hint_position,
1556 label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1557 value: hint_label.to_string(),
1558 location: Some(lsp::Location {
1559 uri: params.text_document.uri,
1560 range: target_range,
1561 }),
1562 ..Default::default()
1563 }]),
1564 kind: Some(lsp::InlayHintKind::TYPE),
1565 text_edits: None,
1566 tooltip: None,
1567 padding_left: Some(false),
1568 padding_right: Some(false),
1569 data: None,
1570 }]))
1571 }
1572 })
1573 .next()
1574 .await;
1575 cx.background_executor.run_until_parked();
1576 cx.update_editor(|editor, _window, cx| {
1577 let expected_layers = vec![hint_label.to_string()];
1578 assert_eq!(expected_layers, cached_hint_labels(editor));
1579 assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1580 });
1581
1582 let inlay_range = cx
1583 .ranges(indoc! {"
1584 struct TestStruct;
1585
1586 fn main() {
1587 let variable« »= TestStruct;
1588 }
1589 "})
1590 .first()
1591 .cloned()
1592 .unwrap();
1593 let midpoint = cx.update_editor(|editor, window, cx| {
1594 let snapshot = editor.snapshot(window, cx);
1595 let previous_valid = inlay_range.start.to_display_point(&snapshot);
1596 let next_valid = inlay_range.end.to_display_point(&snapshot);
1597 assert_eq!(previous_valid.row(), next_valid.row());
1598 assert!(previous_valid.column() < next_valid.column());
1599 DisplayPoint::new(
1600 previous_valid.row(),
1601 previous_valid.column() + (hint_label.len() / 2) as u32,
1602 )
1603 });
1604 // Press cmd to trigger highlight
1605 let hover_point = cx.pixel_position_for(midpoint);
1606 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1607 cx.background_executor.run_until_parked();
1608 cx.update_editor(|editor, window, cx| {
1609 let snapshot = editor.snapshot(window, cx);
1610 let actual_highlights = snapshot
1611 .inlay_highlights::<HoveredLinkState>()
1612 .into_iter()
1613 .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1614 .collect::<Vec<_>>();
1615
1616 let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1617 let expected_highlight = InlayHighlight {
1618 inlay: InlayId::Hint(0),
1619 inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1620 range: 0..hint_label.len(),
1621 };
1622 assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1623 });
1624
1625 cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1626 // Assert no link highlights
1627 cx.update_editor(|editor, window, cx| {
1628 let snapshot = editor.snapshot(window, cx);
1629 let actual_ranges = snapshot
1630 .text_highlight_ranges::<HoveredLinkState>()
1631 .map(|ranges| ranges.as_ref().clone().1)
1632 .unwrap_or_default();
1633
1634 assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1635 });
1636
1637 cx.simulate_modifiers_change(Modifiers::secondary_key());
1638 cx.background_executor.run_until_parked();
1639 cx.simulate_click(hover_point, Modifiers::secondary_key());
1640 cx.background_executor.run_until_parked();
1641 cx.assert_editor_state(indoc! {"
1642 struct «TestStructˇ»;
1643
1644 fn main() {
1645 let variable = TestStruct;
1646 }
1647 "});
1648 }
1649
1650 #[gpui::test]
1651 async fn test_urls(cx: &mut gpui::TestAppContext) {
1652 init_test(cx, |_| {});
1653 let mut cx = EditorLspTestContext::new_rust(
1654 lsp::ServerCapabilities {
1655 ..Default::default()
1656 },
1657 cx,
1658 )
1659 .await;
1660
1661 cx.set_state(indoc! {"
1662 Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1663 "});
1664
1665 let screen_coord = cx.pixel_position(indoc! {"
1666 Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1667 "});
1668
1669 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1670 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1671 Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1672 "});
1673
1674 cx.simulate_click(screen_coord, Modifiers::secondary_key());
1675 assert_eq!(
1676 cx.opened_url(),
1677 Some("https://zed.dev/channel/had-(oops)".into())
1678 );
1679 }
1680
1681 #[gpui::test]
1682 async fn test_urls_at_beginning_of_buffer(cx: &mut gpui::TestAppContext) {
1683 init_test(cx, |_| {});
1684 let mut cx = EditorLspTestContext::new_rust(
1685 lsp::ServerCapabilities {
1686 ..Default::default()
1687 },
1688 cx,
1689 )
1690 .await;
1691
1692 cx.set_state(indoc! {"https://zed.dev/releases is a cool ˇwebpage."});
1693
1694 let screen_coord =
1695 cx.pixel_position(indoc! {"https://zed.dev/relˇeases is a cool webpage."});
1696
1697 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1698 cx.assert_editor_text_highlights::<HoveredLinkState>(
1699 indoc! {"«https://zed.dev/releasesˇ» is a cool webpage."},
1700 );
1701
1702 cx.simulate_click(screen_coord, Modifiers::secondary_key());
1703 assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1704 }
1705
1706 #[gpui::test]
1707 async fn test_urls_at_end_of_buffer(cx: &mut gpui::TestAppContext) {
1708 init_test(cx, |_| {});
1709 let mut cx = EditorLspTestContext::new_rust(
1710 lsp::ServerCapabilities {
1711 ..Default::default()
1712 },
1713 cx,
1714 )
1715 .await;
1716
1717 cx.set_state(indoc! {"A cool ˇwebpage is https://zed.dev/releases"});
1718
1719 let screen_coord =
1720 cx.pixel_position(indoc! {"A cool webpage is https://zed.dev/releˇases"});
1721
1722 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1723 cx.assert_editor_text_highlights::<HoveredLinkState>(
1724 indoc! {"A cool webpage is «https://zed.dev/releasesˇ»"},
1725 );
1726
1727 cx.simulate_click(screen_coord, Modifiers::secondary_key());
1728 assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1729 }
1730
1731 #[gpui::test]
1732 async fn test_surrounding_filename(cx: &mut gpui::TestAppContext) {
1733 init_test(cx, |_| {});
1734 let mut cx = EditorLspTestContext::new_rust(
1735 lsp::ServerCapabilities {
1736 ..Default::default()
1737 },
1738 cx,
1739 )
1740 .await;
1741
1742 let test_cases = [
1743 ("file ˇ name", None),
1744 ("ˇfile name", Some("file")),
1745 ("file ˇname", Some("name")),
1746 ("fiˇle name", Some("file")),
1747 ("filenˇame", Some("filename")),
1748 // Absolute path
1749 ("foobar ˇ/home/user/f.txt", Some("/home/user/f.txt")),
1750 ("foobar /home/useˇr/f.txt", Some("/home/user/f.txt")),
1751 // Windows
1752 ("C:\\Useˇrs\\user\\f.txt", Some("C:\\Users\\user\\f.txt")),
1753 // Whitespace
1754 ("ˇfile\\ -\\ name.txt", Some("file - name.txt")),
1755 ("file\\ -\\ naˇme.txt", Some("file - name.txt")),
1756 // Tilde
1757 ("ˇ~/file.txt", Some("~/file.txt")),
1758 ("~/fiˇle.txt", Some("~/file.txt")),
1759 // Double quotes
1760 ("\"fˇile.txt\"", Some("file.txt")),
1761 ("ˇ\"file.txt\"", Some("file.txt")),
1762 ("ˇ\"fi\\ le.txt\"", Some("fi le.txt")),
1763 // Single quotes
1764 ("'fˇile.txt'", Some("file.txt")),
1765 ("ˇ'file.txt'", Some("file.txt")),
1766 ("ˇ'fi\\ le.txt'", Some("fi le.txt")),
1767 ];
1768
1769 for (input, expected) in test_cases {
1770 cx.set_state(input);
1771
1772 let (position, snapshot) = cx.editor(|editor, _, cx| {
1773 let positions = editor.selections.newest_anchor().head().text_anchor;
1774 let snapshot = editor
1775 .buffer()
1776 .clone()
1777 .read(cx)
1778 .as_singleton()
1779 .unwrap()
1780 .read(cx)
1781 .snapshot();
1782 (positions, snapshot)
1783 });
1784
1785 let result = surrounding_filename(snapshot, position);
1786
1787 if let Some(expected) = expected {
1788 assert!(result.is_some(), "Failed to find file path: {}", input);
1789 let (_, path) = result.unwrap();
1790 assert_eq!(&path, expected, "Incorrect file path for input: {}", input);
1791 } else {
1792 assert!(
1793 result.is_none(),
1794 "Expected no result, but got one: {:?}",
1795 result
1796 );
1797 }
1798 }
1799 }
1800
1801 #[gpui::test]
1802 async fn test_hover_filenames(cx: &mut gpui::TestAppContext) {
1803 init_test(cx, |_| {});
1804 let mut cx = EditorLspTestContext::new_rust(
1805 lsp::ServerCapabilities {
1806 ..Default::default()
1807 },
1808 cx,
1809 )
1810 .await;
1811
1812 // Insert a new file
1813 let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1814 fs.as_fake()
1815 .insert_file(
1816 path!("/root/dir/file2.rs"),
1817 "This is file2.rs".as_bytes().to_vec(),
1818 )
1819 .await;
1820
1821 #[cfg(not(target_os = "windows"))]
1822 cx.set_state(indoc! {"
1823 You can't go to a file that does_not_exist.txt.
1824 Go to file2.rs if you want.
1825 Or go to ../dir/file2.rs if you want.
1826 Or go to /root/dir/file2.rs if project is local.
1827 Or go to /root/dir/file2 if this is a Rust file.ˇ
1828 "});
1829 #[cfg(target_os = "windows")]
1830 cx.set_state(indoc! {"
1831 You can't go to a file that does_not_exist.txt.
1832 Go to file2.rs if you want.
1833 Or go to ../dir/file2.rs if you want.
1834 Or go to C:/root/dir/file2.rs if project is local.
1835 Or go to C:/root/dir/file2 if this is a Rust file.ˇ
1836 "});
1837
1838 // File does not exist
1839 #[cfg(not(target_os = "windows"))]
1840 let screen_coord = cx.pixel_position(indoc! {"
1841 You can't go to a file that dˇoes_not_exist.txt.
1842 Go to file2.rs if you want.
1843 Or go to ../dir/file2.rs if you want.
1844 Or go to /root/dir/file2.rs if project is local.
1845 Or go to /root/dir/file2 if this is a Rust file.
1846 "});
1847 #[cfg(target_os = "windows")]
1848 let screen_coord = cx.pixel_position(indoc! {"
1849 You can't go to a file that dˇoes_not_exist.txt.
1850 Go to file2.rs if you want.
1851 Or go to ../dir/file2.rs if you want.
1852 Or go to C:/root/dir/file2.rs if project is local.
1853 Or go to C:/root/dir/file2 if this is a Rust file.
1854 "});
1855 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1856 // No highlight
1857 cx.update_editor(|editor, window, cx| {
1858 assert!(
1859 editor
1860 .snapshot(window, cx)
1861 .text_highlight_ranges::<HoveredLinkState>()
1862 .unwrap_or_default()
1863 .1
1864 .is_empty()
1865 );
1866 });
1867
1868 // Moving the mouse over a file that does exist should highlight it.
1869 #[cfg(not(target_os = "windows"))]
1870 let screen_coord = cx.pixel_position(indoc! {"
1871 You can't go to a file that does_not_exist.txt.
1872 Go to fˇile2.rs if you want.
1873 Or go to ../dir/file2.rs if you want.
1874 Or go to /root/dir/file2.rs if project is local.
1875 Or go to /root/dir/file2 if this is a Rust file.
1876 "});
1877 #[cfg(target_os = "windows")]
1878 let screen_coord = cx.pixel_position(indoc! {"
1879 You can't go to a file that does_not_exist.txt.
1880 Go to fˇile2.rs if you want.
1881 Or go to ../dir/file2.rs if you want.
1882 Or go to C:/root/dir/file2.rs if project is local.
1883 Or go to C:/root/dir/file2 if this is a Rust file.
1884 "});
1885
1886 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1887 #[cfg(not(target_os = "windows"))]
1888 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1889 You can't go to a file that does_not_exist.txt.
1890 Go to «file2.rsˇ» if you want.
1891 Or go to ../dir/file2.rs if you want.
1892 Or go to /root/dir/file2.rs if project is local.
1893 Or go to /root/dir/file2 if this is a Rust file.
1894 "});
1895 #[cfg(target_os = "windows")]
1896 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1897 You can't go to a file that does_not_exist.txt.
1898 Go to «file2.rsˇ» if you want.
1899 Or go to ../dir/file2.rs if you want.
1900 Or go to C:/root/dir/file2.rs if project is local.
1901 Or go to C:/root/dir/file2 if this is a Rust file.
1902 "});
1903
1904 // Moving the mouse over a relative path that does exist should highlight it
1905 #[cfg(not(target_os = "windows"))]
1906 let screen_coord = cx.pixel_position(indoc! {"
1907 You can't go to a file that does_not_exist.txt.
1908 Go to file2.rs if you want.
1909 Or go to ../dir/fˇile2.rs if you want.
1910 Or go to /root/dir/file2.rs if project is local.
1911 Or go to /root/dir/file2 if this is a Rust file.
1912 "});
1913 #[cfg(target_os = "windows")]
1914 let screen_coord = cx.pixel_position(indoc! {"
1915 You can't go to a file that does_not_exist.txt.
1916 Go to file2.rs if you want.
1917 Or go to ../dir/fˇile2.rs if you want.
1918 Or go to C:/root/dir/file2.rs if project is local.
1919 Or go to C:/root/dir/file2 if this is a Rust file.
1920 "});
1921
1922 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1923 #[cfg(not(target_os = "windows"))]
1924 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1925 You can't go to a file that does_not_exist.txt.
1926 Go to file2.rs if you want.
1927 Or go to «../dir/file2.rsˇ» if you want.
1928 Or go to /root/dir/file2.rs if project is local.
1929 Or go to /root/dir/file2 if this is a Rust file.
1930 "});
1931 #[cfg(target_os = "windows")]
1932 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1933 You can't go to a file that does_not_exist.txt.
1934 Go to file2.rs if you want.
1935 Or go to «../dir/file2.rsˇ» if you want.
1936 Or go to C:/root/dir/file2.rs if project is local.
1937 Or go to C:/root/dir/file2 if this is a Rust file.
1938 "});
1939
1940 // Moving the mouse over an absolute path that does exist should highlight it
1941 #[cfg(not(target_os = "windows"))]
1942 let screen_coord = cx.pixel_position(indoc! {"
1943 You can't go to a file that does_not_exist.txt.
1944 Go to file2.rs if you want.
1945 Or go to ../dir/file2.rs if you want.
1946 Or go to /root/diˇr/file2.rs if project is local.
1947 Or go to /root/dir/file2 if this is a Rust file.
1948 "});
1949
1950 #[cfg(target_os = "windows")]
1951 let screen_coord = cx.pixel_position(indoc! {"
1952 You can't go to a file that does_not_exist.txt.
1953 Go to file2.rs if you want.
1954 Or go to ../dir/file2.rs if you want.
1955 Or go to C:/root/diˇr/file2.rs if project is local.
1956 Or go to C:/root/dir/file2 if this is a Rust file.
1957 "});
1958
1959 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1960 #[cfg(not(target_os = "windows"))]
1961 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1962 You can't go to a file that does_not_exist.txt.
1963 Go to file2.rs if you want.
1964 Or go to ../dir/file2.rs if you want.
1965 Or go to «/root/dir/file2.rsˇ» if project is local.
1966 Or go to /root/dir/file2 if this is a Rust file.
1967 "});
1968 #[cfg(target_os = "windows")]
1969 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1970 You can't go to a file that does_not_exist.txt.
1971 Go to file2.rs if you want.
1972 Or go to ../dir/file2.rs if you want.
1973 Or go to «C:/root/dir/file2.rsˇ» if project is local.
1974 Or go to C:/root/dir/file2 if this is a Rust file.
1975 "});
1976
1977 // Moving the mouse over a path that exists, if we add the language-specific suffix, it should highlight it
1978 #[cfg(not(target_os = "windows"))]
1979 let screen_coord = cx.pixel_position(indoc! {"
1980 You can't go to a file that does_not_exist.txt.
1981 Go to file2.rs if you want.
1982 Or go to ../dir/file2.rs if you want.
1983 Or go to /root/dir/file2.rs if project is local.
1984 Or go to /root/diˇr/file2 if this is a Rust file.
1985 "});
1986 #[cfg(target_os = "windows")]
1987 let screen_coord = cx.pixel_position(indoc! {"
1988 You can't go to a file that does_not_exist.txt.
1989 Go to file2.rs if you want.
1990 Or go to ../dir/file2.rs if you want.
1991 Or go to C:/root/dir/file2.rs if project is local.
1992 Or go to C:/root/diˇr/file2 if this is a Rust file.
1993 "});
1994
1995 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1996 #[cfg(not(target_os = "windows"))]
1997 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1998 You can't go to a file that does_not_exist.txt.
1999 Go to file2.rs if you want.
2000 Or go to ../dir/file2.rs if you want.
2001 Or go to /root/dir/file2.rs if project is local.
2002 Or go to «/root/dir/file2ˇ» if this is a Rust file.
2003 "});
2004 #[cfg(target_os = "windows")]
2005 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2006 You can't go to a file that does_not_exist.txt.
2007 Go to file2.rs if you want.
2008 Or go to ../dir/file2.rs if you want.
2009 Or go to C:/root/dir/file2.rs if project is local.
2010 Or go to «C:/root/dir/file2ˇ» if this is a Rust file.
2011 "});
2012
2013 cx.simulate_click(screen_coord, Modifiers::secondary_key());
2014
2015 cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2016 cx.update_workspace(|workspace, _, cx| {
2017 let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
2018
2019 let buffer = active_editor
2020 .read(cx)
2021 .buffer()
2022 .read(cx)
2023 .as_singleton()
2024 .unwrap();
2025
2026 let file = buffer.read(cx).file().unwrap();
2027 let file_path = file.as_local().unwrap().abs_path(cx);
2028
2029 assert_eq!(
2030 file_path,
2031 std::path::PathBuf::from(path!("/root/dir/file2.rs"))
2032 );
2033 });
2034 }
2035
2036 #[gpui::test]
2037 async fn test_hover_directories(cx: &mut gpui::TestAppContext) {
2038 init_test(cx, |_| {});
2039 let mut cx = EditorLspTestContext::new_rust(
2040 lsp::ServerCapabilities {
2041 ..Default::default()
2042 },
2043 cx,
2044 )
2045 .await;
2046
2047 // Insert a new file
2048 let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2049 fs.as_fake()
2050 .insert_file("/root/dir/file2.rs", "This is file2.rs".as_bytes().to_vec())
2051 .await;
2052
2053 cx.set_state(indoc! {"
2054 You can't open ../diˇr because it's a directory.
2055 "});
2056
2057 // File does not exist
2058 let screen_coord = cx.pixel_position(indoc! {"
2059 You can't open ../diˇr because it's a directory.
2060 "});
2061 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
2062
2063 // No highlight
2064 cx.update_editor(|editor, window, cx| {
2065 assert!(
2066 editor
2067 .snapshot(window, cx)
2068 .text_highlight_ranges::<HoveredLinkState>()
2069 .unwrap_or_default()
2070 .1
2071 .is_empty()
2072 );
2073 });
2074
2075 // Does not open the directory
2076 cx.simulate_click(screen_coord, Modifiers::secondary_key());
2077 cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
2078 }
2079}