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