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