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 text::{self, Point};
19use theme::ActiveTheme as _;
20use util::{ResultExt, TryFutureExt as _, maybe};
21
22#[derive(Debug)]
23pub struct HoveredLinkState {
24 pub last_trigger_point: TriggerPoint,
25 pub preferred_kind: GotoDefinitionKind,
26 pub symbol_range: Option<RangeInEditor>,
27 pub links: Vec<HoverLink>,
28 pub task: Option<Task<Option<()>>>,
29}
30
31#[derive(Debug, Eq, PartialEq, Clone)]
32pub enum RangeInEditor {
33 Text(Range<Anchor>),
34 Inlay(InlayHighlight),
35}
36
37impl RangeInEditor {
38 pub fn as_text_range(&self) -> Option<Range<Anchor>> {
39 match self {
40 Self::Text(range) => Some(range.clone()),
41 Self::Inlay(_) => None,
42 }
43 }
44
45 pub fn point_within_range(
46 &self,
47 trigger_point: &TriggerPoint,
48 snapshot: &EditorSnapshot,
49 ) -> bool {
50 match (self, trigger_point) {
51 (Self::Text(range), TriggerPoint::Text(point)) => {
52 let point_after_start = range.start.cmp(point, &snapshot.buffer_snapshot).is_le();
53 point_after_start && range.end.cmp(point, &snapshot.buffer_snapshot).is_ge()
54 }
55 (Self::Inlay(highlight), TriggerPoint::InlayHint(point, _, _)) => {
56 highlight.inlay == point.inlay
57 && highlight.range.contains(&point.range.start)
58 && highlight.range.contains(&point.range.end)
59 }
60 (Self::Inlay(_), TriggerPoint::Text(_))
61 | (Self::Text(_), TriggerPoint::InlayHint(_, _, _)) => false,
62 }
63 }
64}
65
66#[derive(Debug, Clone)]
67pub enum HoverLink {
68 Url(String),
69 File(ResolvedPath),
70 Text(LocationLink),
71 InlayHint(lsp::Location, LanguageServerId),
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct InlayHighlight {
76 pub inlay: InlayId,
77 pub inlay_position: Anchor,
78 pub range: Range<usize>,
79}
80
81#[derive(Debug, Clone, PartialEq)]
82pub enum TriggerPoint {
83 Text(Anchor),
84 InlayHint(InlayHighlight, lsp::Location, LanguageServerId),
85}
86
87impl TriggerPoint {
88 fn anchor(&self) -> &Anchor {
89 match self {
90 TriggerPoint::Text(anchor) => anchor,
91 TriggerPoint::InlayHint(inlay_range, _, _) => &inlay_range.inlay_position,
92 }
93 }
94}
95
96pub fn exclude_link_to_position(
97 buffer: &Entity<language::Buffer>,
98 current_position: &text::Anchor,
99 location: &LocationLink,
100 cx: &App,
101) -> bool {
102 // Exclude definition links that points back to cursor position.
103 // (i.e., currently cursor upon definition).
104 let snapshot = buffer.read(cx).snapshot();
105 !(buffer == &location.target.buffer
106 && current_position
107 .bias_right(&snapshot)
108 .cmp(&location.target.range.start, &snapshot)
109 .is_ge()
110 && current_position
111 .cmp(&location.target.range.end, &snapshot)
112 .is_le())
113}
114
115impl Editor {
116 pub(crate) fn update_hovered_link(
117 &mut self,
118 point_for_position: PointForPosition,
119 snapshot: &EditorSnapshot,
120 modifiers: Modifiers,
121 window: &mut Window,
122 cx: &mut Context<Self>,
123 ) {
124 let hovered_link_modifier = Editor::multi_cursor_modifier(false, &modifiers, cx);
125
126 // When you're dragging to select, and you release the drag to create the selection,
127 // if you happened to end over something hoverable (including an inlay hint), don't
128 // have the hovered link appear. That would be annoying, because all you're trying
129 // to do is to create a selection, not hover to see a hovered link.
130 if self.has_pending_selection() {
131 self.hide_hovered_link(cx);
132 return;
133 }
134
135 match point_for_position.as_valid() {
136 Some(point) => {
137 // Hide the underline unless you're holding the modifier key on the keyboard
138 // which will perform a goto definition.
139 if !hovered_link_modifier {
140 self.hide_hovered_link(cx);
141 return;
142 }
143
144 let trigger_point = TriggerPoint::Text(
145 snapshot
146 .buffer_snapshot
147 .anchor_before(point.to_offset(&snapshot.display_snapshot, Bias::Left)),
148 );
149
150 show_link_definition(modifiers.shift, self, trigger_point, snapshot, window, cx);
151 }
152 None => {
153 update_inlay_link_and_hover_points(
154 snapshot,
155 point_for_position,
156 self,
157 hovered_link_modifier,
158 modifiers.shift,
159 window,
160 cx,
161 );
162 }
163 }
164 }
165
166 pub(crate) fn hide_hovered_link(&mut self, cx: &mut Context<Self>) {
167 self.hovered_link_state.take();
168 self.clear_highlights::<HoveredLinkState>(cx);
169 }
170
171 pub(crate) fn handle_click_hovered_link(
172 &mut self,
173 point: PointForPosition,
174 modifiers: Modifiers,
175 window: &mut Window,
176 cx: &mut Context<Editor>,
177 ) {
178 let reveal_task = self.cmd_click_reveal_task(point, modifiers, window, cx);
179 cx.spawn_in(window, async move |editor, cx| {
180 let definition_revealed = reveal_task.await.log_err().unwrap_or(Navigated::No);
181 let find_references = editor
182 .update_in(cx, |editor, window, cx| {
183 if definition_revealed == Navigated::Yes {
184 return None;
185 }
186 match EditorSettings::get_global(cx).go_to_definition_fallback {
187 GoToDefinitionFallback::None => None,
188 GoToDefinitionFallback::FindAllReferences => {
189 editor.find_all_references(&FindAllReferences, window, cx)
190 }
191 }
192 })
193 .ok()
194 .flatten();
195 if let Some(find_references) = find_references {
196 find_references.await.log_err();
197 }
198 })
199 .detach();
200 }
201
202 pub fn scroll_hover(
203 &mut self,
204 amount: &ScrollAmount,
205 window: &mut Window,
206 cx: &mut Context<Self>,
207 ) -> bool {
208 let selection = self.selections.newest_anchor().head();
209 let snapshot = self.snapshot(window, cx);
210
211 let Some(popover) = self.hover_state.info_popovers.iter().find(|popover| {
212 popover
213 .symbol_range
214 .point_within_range(&TriggerPoint::Text(selection), &snapshot)
215 }) else {
216 return false;
217 };
218 popover.scroll(amount, window, cx);
219 true
220 }
221
222 fn cmd_click_reveal_task(
223 &mut self,
224 point: PointForPosition,
225 modifiers: Modifiers,
226 window: &mut Window,
227 cx: &mut Context<Editor>,
228 ) -> Task<anyhow::Result<Navigated>> {
229 if let Some(hovered_link_state) = self.hovered_link_state.take() {
230 self.hide_hovered_link(cx);
231 if !hovered_link_state.links.is_empty() {
232 if !self.focus_handle.is_focused(window) {
233 window.focus(&self.focus_handle);
234 }
235
236 // exclude links pointing back to the current anchor
237 let current_position = point
238 .next_valid
239 .to_point(&self.snapshot(window, cx).display_snapshot);
240 let Some((buffer, anchor)) = self
241 .buffer()
242 .read(cx)
243 .text_anchor_for_position(current_position, cx)
244 else {
245 return Task::ready(Ok(Navigated::No));
246 };
247 let links = hovered_link_state
248 .links
249 .into_iter()
250 .filter(|link| {
251 if let HoverLink::Text(location) = link {
252 exclude_link_to_position(&buffer, &anchor, location, cx)
253 } else {
254 true
255 }
256 })
257 .collect();
258 let navigate_task =
259 self.navigate_to_hover_links(None, links, modifiers.alt, window, cx);
260 self.select(SelectPhase::End, window, cx);
261 return navigate_task;
262 }
263 }
264
265 // We don't have the correct kind of link cached, set the selection on
266 // click and immediately trigger GoToDefinition.
267 self.select(
268 SelectPhase::Begin {
269 position: point.next_valid,
270 add: false,
271 click_count: 1,
272 },
273 window,
274 cx,
275 );
276
277 let navigate_task = if point.as_valid().is_some() {
278 if modifiers.shift {
279 self.go_to_type_definition(&GoToTypeDefinition, window, cx)
280 } else {
281 self.go_to_definition(&GoToDefinition, window, cx)
282 }
283 } else {
284 Task::ready(Ok(Navigated::No))
285 };
286 self.select(SelectPhase::End, window, cx);
287 navigate_task
288 }
289}
290
291pub fn update_inlay_link_and_hover_points(
292 snapshot: &EditorSnapshot,
293 point_for_position: PointForPosition,
294 editor: &mut Editor,
295 secondary_held: bool,
296 shift_held: bool,
297 window: &mut Window,
298 cx: &mut Context<Editor>,
299) {
300 let hovered_offset = if point_for_position.column_overshoot_after_line_end == 0 {
301 Some(snapshot.display_point_to_inlay_offset(point_for_position.exact_unclipped, Bias::Left))
302 } else {
303 None
304 };
305 let mut go_to_definition_updated = false;
306 let mut hover_updated = false;
307 if let Some(hovered_offset) = hovered_offset {
308 let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
309 let previous_valid_anchor = buffer_snapshot.anchor_at(
310 point_for_position.previous_valid.to_point(snapshot),
311 Bias::Left,
312 );
313 let next_valid_anchor = buffer_snapshot.anchor_at(
314 point_for_position.next_valid.to_point(snapshot),
315 Bias::Right,
316 );
317 if let Some(hovered_hint) = editor
318 .visible_inlay_hints(cx)
319 .into_iter()
320 .skip_while(|hint| {
321 hint.position
322 .cmp(&previous_valid_anchor, &buffer_snapshot)
323 .is_lt()
324 })
325 .take_while(|hint| {
326 hint.position
327 .cmp(&next_valid_anchor, &buffer_snapshot)
328 .is_le()
329 })
330 .max_by_key(|hint| hint.id)
331 {
332 let inlay_hint_cache = editor.inlay_hint_cache();
333 let excerpt_id = previous_valid_anchor.excerpt_id;
334 if let Some(cached_hint) = inlay_hint_cache.hint_by_id(excerpt_id, hovered_hint.id) {
335 // Check if we should process this hint for hover
336 match cached_hint.resolve_state {
337 ResolveState::CanResolve(_, _) => {
338 if let Some(buffer_id) = snapshot
339 .buffer_snapshot
340 .buffer_id_for_anchor(previous_valid_anchor)
341 {
342 inlay_hint_cache.spawn_hint_resolve(
343 buffer_id,
344 excerpt_id,
345 hovered_hint.id,
346 window,
347 cx,
348 );
349 }
350 }
351 ResolveState::Resolved => {
352 let mut extra_shift_left = 0;
353 let mut extra_shift_right = 0;
354 if cached_hint.padding_left {
355 extra_shift_left += 1;
356 extra_shift_right += 1;
357 }
358 if cached_hint.padding_right {
359 extra_shift_right += 1;
360 }
361 match cached_hint.label {
362 project::InlayHintLabel::String(_) => {
363 if let Some(tooltip) = cached_hint.tooltip {
364 hover_popover::hover_at_inlay(
365 editor,
366 InlayHover {
367 tooltip: match tooltip {
368 InlayHintTooltip::String(text) => HoverBlock {
369 text,
370 kind: HoverBlockKind::PlainText,
371 },
372 InlayHintTooltip::MarkupContent(content) => {
373 HoverBlock {
374 text: content.value,
375 kind: content.kind,
376 }
377 }
378 },
379 range: InlayHighlight {
380 inlay: hovered_hint.id,
381 inlay_position: hovered_hint.position,
382 range: extra_shift_left
383 ..hovered_hint.text.len() + extra_shift_right,
384 },
385 },
386 window,
387 cx,
388 );
389 hover_updated = true;
390 }
391 }
392 project::InlayHintLabel::LabelParts(label_parts) => {
393 let hint_start =
394 snapshot.anchor_to_inlay_offset(hovered_hint.position);
395 if let Some((hovered_hint_part, part_range)) =
396 hover_popover::find_hovered_hint_part(
397 label_parts,
398 hint_start,
399 hovered_offset,
400 )
401 {
402 let highlight_start =
403 (part_range.start - hint_start).0 + extra_shift_left;
404 let highlight_end =
405 (part_range.end - hint_start).0 + extra_shift_right;
406 let highlight = InlayHighlight {
407 inlay: hovered_hint.id,
408 inlay_position: hovered_hint.position,
409 range: highlight_start..highlight_end,
410 };
411 if let Some(tooltip) = hovered_hint_part.tooltip {
412 hover_popover::hover_at_inlay(
413 editor,
414 InlayHover {
415 tooltip: match tooltip {
416 InlayHintLabelPartTooltip::String(text) => {
417 HoverBlock {
418 text,
419 kind: HoverBlockKind::PlainText,
420 }
421 }
422 InlayHintLabelPartTooltip::MarkupContent(
423 content,
424 ) => HoverBlock {
425 text: content.value,
426 kind: content.kind,
427 },
428 },
429 range: highlight.clone(),
430 },
431 window,
432 cx,
433 );
434 hover_updated = true;
435 }
436
437 if let Some((language_server_id, location)) =
438 hovered_hint_part.location
439 {
440 // Now perform the "Go to Definition" flow to get hover documentation
441 if let Some(project) = editor.project.clone() {
442 let highlight = highlight.clone();
443 let hint_value = hovered_hint_part.value.clone();
444 let location = location.clone();
445
446 get_docs_then_show_hover(
447 editor, window, cx, highlight, hint_value,
448 location, project,
449 );
450 }
451
452 if secondary_held
453 && !editor.has_pending_nonempty_selection()
454 {
455 go_to_definition_updated = true;
456 show_link_definition(
457 shift_held,
458 editor,
459 TriggerPoint::InlayHint(
460 highlight,
461 location,
462 language_server_id,
463 ),
464 snapshot,
465 window,
466 cx,
467 );
468 }
469 }
470 }
471 }
472 }
473 }
474 ResolveState::Resolving => {}
475 };
476 }
477 }
478 }
479
480 if !go_to_definition_updated {
481 editor.hide_hovered_link(cx)
482 }
483 if !hover_updated {
484 hover_popover::hover_at(editor, None, window, cx);
485 }
486}
487
488/// todo dvdsk: This extracts doc comments and shows them, a fine fallback
489/// though maybe we should instead alsk the LSP for info on the type?. Lets figure
490/// out what normal hoverdocs do.
491///
492/// issue with Entity<Markdown>. Needs one more (expensive) step before rendering
493/// which we need to cache.
494///
495/// --- PLAN ---
496/// - use location to call hover_popover and extract the text
497/// - then use claude written 'existing' hover method to see if that works
498/// - try use or adapt InfoPopover to get scrollbar/nice rendering (note issue above)
499/// - get the unwraps and as_refs out of here
500fn get_docs_then_show_hover(
501 editor: &mut Editor,
502 window: &mut Window,
503 cx: &mut Context<'_, Editor>,
504 highlight: InlayHighlight,
505 hint_value: String,
506 location: lsp::Location,
507 project: Entity<Project>,
508) {
509 let provider = editor.semantics_provider.clone().unwrap();
510 cx.spawn_in(window, async move |editor, cx| {
511 async move {
512 // Convert LSP URL to file path
513 let file_path = location
514 .uri
515 .to_file_path()
516 .map_err(|_| anyhow::anyhow!("Invalid file URL"))?;
517 // Open the definition file
518 let definition_buffer = project
519 .update(cx, |project, cx| project.open_local_buffer(file_path, cx))?
520 .await?;
521 let location = Point::new(location.range.start.line, location.range.start.character);
522 let buffer_position = definition_buffer
523 .update(cx, |buffer, _| buffer.snapshot().anchor_after(location))
524 .unwrap();
525
526 // debounce the lsp request
527 cx.background_executor()
528 .timer(std::time::Duration::from_millis(50))
529 .await;
530 let hover_request =
531 cx.update(|_, cx| provider.hover(&definition_buffer, buffer_position, cx))?;
532 let hovers_response = if let Some(hover_request) = hover_request {
533 hover_request.await.unwrap_or_default()
534 } else {
535 Vec::new()
536 };
537
538 let text = hovers_response
539 .first()
540 .as_ref()
541 .unwrap()
542 .contents
543 .first()
544 .as_ref()
545 .unwrap()
546 .text
547 .clone();
548
549 editor
550 .update_in(cx, |editor, window, cx| {
551 hover_popover::hover_at_inlay(
552 editor,
553 InlayHover {
554 tooltip: HoverBlock {
555 text,
556 kind: HoverBlockKind::Markdown,
557 },
558 range: highlight,
559 },
560 window,
561 cx,
562 );
563 })
564 .log_err();
565
566 anyhow::Ok(())
567 }
568 .log_err()
569 .await
570 })
571 .detach();
572}
573
574pub fn show_link_definition(
575 shift_held: bool,
576 editor: &mut Editor,
577 trigger_point: TriggerPoint,
578 snapshot: &EditorSnapshot,
579 window: &mut Window,
580 cx: &mut Context<Editor>,
581) {
582 let preferred_kind = match trigger_point {
583 TriggerPoint::Text(_) if !shift_held => GotoDefinitionKind::Symbol,
584 _ => GotoDefinitionKind::Type,
585 };
586
587 let (mut hovered_link_state, is_cached) =
588 if let Some(existing) = editor.hovered_link_state.take() {
589 (existing, true)
590 } else {
591 (
592 HoveredLinkState {
593 last_trigger_point: trigger_point.clone(),
594 symbol_range: None,
595 preferred_kind,
596 links: vec![],
597 task: None,
598 },
599 false,
600 )
601 };
602
603 if editor.pending_rename.is_some() {
604 return;
605 }
606
607 let trigger_anchor = trigger_point.anchor();
608 let Some((buffer, buffer_position)) = editor
609 .buffer
610 .read(cx)
611 .text_anchor_for_position(*trigger_anchor, cx)
612 else {
613 return;
614 };
615
616 let Some((excerpt_id, _, _)) = editor
617 .buffer()
618 .read(cx)
619 .excerpt_containing(*trigger_anchor, cx)
620 else {
621 return;
622 };
623
624 let same_kind = hovered_link_state.preferred_kind == preferred_kind
625 || hovered_link_state
626 .links
627 .first()
628 .is_some_and(|d| matches!(d, HoverLink::Url(_)));
629
630 if same_kind {
631 if is_cached && (hovered_link_state.last_trigger_point == trigger_point)
632 || hovered_link_state
633 .symbol_range
634 .as_ref()
635 .is_some_and(|symbol_range| {
636 symbol_range.point_within_range(&trigger_point, snapshot)
637 })
638 {
639 editor.hovered_link_state = Some(hovered_link_state);
640 return;
641 }
642 } else {
643 editor.hide_hovered_link(cx)
644 }
645 let project = editor.project.clone();
646 let provider = editor.semantics_provider.clone();
647
648 let snapshot = snapshot.buffer_snapshot.clone();
649 hovered_link_state.task = Some(cx.spawn_in(window, async move |this, cx| {
650 async move {
651 let result = match &trigger_point {
652 TriggerPoint::Text(_) => {
653 if let Some((url_range, url)) = find_url(&buffer, buffer_position, cx.clone()) {
654 this.read_with(cx, |_, _| {
655 let range = maybe!({
656 let start =
657 snapshot.anchor_in_excerpt(excerpt_id, url_range.start)?;
658 let end = snapshot.anchor_in_excerpt(excerpt_id, url_range.end)?;
659 Some(RangeInEditor::Text(start..end))
660 });
661 (range, vec![HoverLink::Url(url)])
662 })
663 .ok()
664 } else if let Some((filename_range, filename)) =
665 find_file(&buffer, project.clone(), buffer_position, cx).await
666 {
667 let range = maybe!({
668 let start =
669 snapshot.anchor_in_excerpt(excerpt_id, filename_range.start)?;
670 let end = snapshot.anchor_in_excerpt(excerpt_id, filename_range.end)?;
671 Some(RangeInEditor::Text(start..end))
672 });
673
674 Some((range, vec![HoverLink::File(filename)]))
675 } else if let Some(provider) = provider {
676 let task = cx.update(|_, cx| {
677 provider.definitions(&buffer, buffer_position, preferred_kind, cx)
678 })?;
679 if let Some(task) = task {
680 task.await.ok().flatten().map(|definition_result| {
681 (
682 definition_result.iter().find_map(|link| {
683 link.origin.as_ref().and_then(|origin| {
684 let start = snapshot.anchor_in_excerpt(
685 excerpt_id,
686 origin.range.start,
687 )?;
688 let end = snapshot
689 .anchor_in_excerpt(excerpt_id, origin.range.end)?;
690 Some(RangeInEditor::Text(start..end))
691 })
692 }),
693 definition_result.into_iter().map(HoverLink::Text).collect(),
694 )
695 })
696 } else {
697 None
698 }
699 } else {
700 None
701 }
702 }
703 TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
704 Some(RangeInEditor::Inlay(highlight.clone())),
705 vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
706 )),
707 };
708
709 this.update(cx, |editor, cx| {
710 // Clear any existing highlights
711 editor.clear_highlights::<HoveredLinkState>(cx);
712 let Some(hovered_link_state) = editor.hovered_link_state.as_mut() else {
713 editor.hide_hovered_link(cx);
714 return;
715 };
716 hovered_link_state.preferred_kind = preferred_kind;
717 hovered_link_state.symbol_range = result
718 .as_ref()
719 .and_then(|(symbol_range, _)| symbol_range.clone());
720
721 if let Some((symbol_range, definitions)) = result {
722 hovered_link_state.links = definitions;
723
724 let underline_hovered_link = !hovered_link_state.links.is_empty()
725 || hovered_link_state.symbol_range.is_some();
726
727 if underline_hovered_link {
728 let style = gpui::HighlightStyle {
729 underline: Some(gpui::UnderlineStyle {
730 thickness: px(1.),
731 ..Default::default()
732 }),
733 color: Some(cx.theme().colors().link_text_hover),
734 ..Default::default()
735 };
736 let highlight_range =
737 symbol_range.unwrap_or_else(|| match &trigger_point {
738 TriggerPoint::Text(trigger_anchor) => {
739 // If no symbol range returned from language server, use the surrounding word.
740 let (offset_range, _) =
741 snapshot.surrounding_word(*trigger_anchor, false);
742 RangeInEditor::Text(
743 snapshot.anchor_before(offset_range.start)
744 ..snapshot.anchor_after(offset_range.end),
745 )
746 }
747 TriggerPoint::InlayHint(highlight, _, _) => {
748 RangeInEditor::Inlay(highlight.clone())
749 }
750 });
751
752 match highlight_range {
753 RangeInEditor::Text(text_range) => editor
754 .highlight_text::<HoveredLinkState>(vec![text_range], style, cx),
755 RangeInEditor::Inlay(highlight) => editor
756 .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
757 }
758 }
759 } else {
760 editor.hide_hovered_link(cx);
761 }
762 })?;
763
764 anyhow::Ok(())
765 }
766 .log_err()
767 .await
768 }));
769
770 editor.hovered_link_state = Some(hovered_link_state);
771}
772
773pub(crate) fn find_url(
774 buffer: &Entity<language::Buffer>,
775 position: text::Anchor,
776 cx: AsyncWindowContext,
777) -> Option<(Range<text::Anchor>, String)> {
778 const LIMIT: usize = 2048;
779
780 let Ok(snapshot) = buffer.read_with(&cx, |buffer, _| buffer.snapshot()) else {
781 return None;
782 };
783
784 let offset = position.to_offset(&snapshot);
785 let mut token_start = offset;
786 let mut token_end = offset;
787 let mut found_start = false;
788 let mut found_end = false;
789
790 for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
791 if ch.is_whitespace() {
792 found_start = true;
793 break;
794 }
795 token_start -= ch.len_utf8();
796 }
797 // Check if we didn't find the starting whitespace or if we didn't reach the start of the buffer
798 if !found_start && token_start != 0 {
799 return None;
800 }
801
802 for ch in snapshot
803 .chars_at(offset)
804 .take(LIMIT - (offset - token_start))
805 {
806 if ch.is_whitespace() {
807 found_end = true;
808 break;
809 }
810 token_end += ch.len_utf8();
811 }
812 // Check if we didn't find the ending whitespace or if we read more or equal than LIMIT
813 // which at this point would happen only if we reached the end of buffer
814 if !found_end && (token_end - token_start >= LIMIT) {
815 return None;
816 }
817
818 let mut finder = LinkFinder::new();
819 finder.kinds(&[LinkKind::Url]);
820 let input = snapshot
821 .text_for_range(token_start..token_end)
822 .collect::<String>();
823
824 let relative_offset = offset - token_start;
825 for link in finder.links(&input) {
826 if link.start() <= relative_offset && link.end() >= relative_offset {
827 let range = snapshot.anchor_before(token_start + link.start())
828 ..snapshot.anchor_after(token_start + link.end());
829 return Some((range, link.as_str().to_string()));
830 }
831 }
832 None
833}
834
835pub(crate) fn find_url_from_range(
836 buffer: &Entity<language::Buffer>,
837 range: Range<text::Anchor>,
838 cx: AsyncWindowContext,
839) -> Option<String> {
840 const LIMIT: usize = 2048;
841
842 let Ok(snapshot) = buffer.read_with(&cx, |buffer, _| buffer.snapshot()) else {
843 return None;
844 };
845
846 let start_offset = range.start.to_offset(&snapshot);
847 let end_offset = range.end.to_offset(&snapshot);
848
849 let mut token_start = start_offset.min(end_offset);
850 let mut token_end = start_offset.max(end_offset);
851
852 let range_len = token_end - token_start;
853
854 if range_len >= LIMIT {
855 return None;
856 }
857
858 // Skip leading whitespace
859 for ch in snapshot.chars_at(token_start).take(range_len) {
860 if !ch.is_whitespace() {
861 break;
862 }
863 token_start += ch.len_utf8();
864 }
865
866 // Skip trailing whitespace
867 for ch in snapshot.reversed_chars_at(token_end).take(range_len) {
868 if !ch.is_whitespace() {
869 break;
870 }
871 token_end -= ch.len_utf8();
872 }
873
874 if token_start >= token_end {
875 return None;
876 }
877
878 let text = snapshot
879 .text_for_range(token_start..token_end)
880 .collect::<String>();
881
882 let mut finder = LinkFinder::new();
883 finder.kinds(&[LinkKind::Url]);
884
885 if let Some(link) = finder.links(&text).next()
886 && link.start() == 0
887 && link.end() == text.len()
888 {
889 return Some(link.as_str().to_string());
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().is_some_and(|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}