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