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