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 return 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 {
422 if secondary_held
423 && !editor.has_pending_nonempty_selection()
424 {
425 go_to_definition_updated = true;
426 show_link_definition(
427 shift_held,
428 editor,
429 TriggerPoint::InlayHint(
430 highlight,
431 location,
432 language_server_id,
433 ),
434 snapshot,
435 window,
436 cx,
437 );
438 }
439 }
440 }
441 }
442 };
443 }
444 ResolveState::Resolving => {}
445 }
446 }
447 }
448 }
449
450 if !go_to_definition_updated {
451 editor.hide_hovered_link(cx)
452 }
453 if !hover_updated {
454 hover_popover::hover_at(editor, None, window, cx);
455 }
456}
457
458pub fn show_link_definition(
459 shift_held: bool,
460 editor: &mut Editor,
461 trigger_point: TriggerPoint,
462 snapshot: &EditorSnapshot,
463 window: &mut Window,
464 cx: &mut Context<Editor>,
465) {
466 let preferred_kind = match trigger_point {
467 TriggerPoint::Text(_) if !shift_held => GotoDefinitionKind::Symbol,
468 _ => GotoDefinitionKind::Type,
469 };
470
471 let (mut hovered_link_state, is_cached) =
472 if let Some(existing) = editor.hovered_link_state.take() {
473 (existing, true)
474 } else {
475 (
476 HoveredLinkState {
477 last_trigger_point: trigger_point.clone(),
478 symbol_range: None,
479 preferred_kind,
480 links: vec![],
481 task: None,
482 },
483 false,
484 )
485 };
486
487 if editor.pending_rename.is_some() {
488 return;
489 }
490
491 let trigger_anchor = trigger_point.anchor();
492 let Some((buffer, buffer_position)) = editor
493 .buffer
494 .read(cx)
495 .text_anchor_for_position(*trigger_anchor, cx)
496 else {
497 return;
498 };
499
500 let Some((excerpt_id, _, _)) = editor
501 .buffer()
502 .read(cx)
503 .excerpt_containing(*trigger_anchor, cx)
504 else {
505 return;
506 };
507
508 let same_kind = hovered_link_state.preferred_kind == preferred_kind
509 || hovered_link_state
510 .links
511 .first()
512 .is_some_and(|d| matches!(d, HoverLink::Url(_)));
513
514 if same_kind {
515 if is_cached && (hovered_link_state.last_trigger_point == trigger_point)
516 || hovered_link_state
517 .symbol_range
518 .as_ref()
519 .is_some_and(|symbol_range| {
520 symbol_range.point_within_range(&trigger_point, snapshot)
521 })
522 {
523 editor.hovered_link_state = Some(hovered_link_state);
524 return;
525 }
526 } else {
527 editor.hide_hovered_link(cx)
528 }
529 let project = editor.project.clone();
530 let provider = editor.semantics_provider.clone();
531
532 let snapshot = snapshot.buffer_snapshot.clone();
533 hovered_link_state.task = Some(cx.spawn_in(window, async move |this, cx| {
534 async move {
535 let result = match &trigger_point {
536 TriggerPoint::Text(_) => {
537 if let Some((url_range, url)) = find_url(&buffer, buffer_position, cx.clone()) {
538 this.read_with(cx, |_, _| {
539 let range = maybe!({
540 let start =
541 snapshot.anchor_in_excerpt(excerpt_id, url_range.start)?;
542 let end = snapshot.anchor_in_excerpt(excerpt_id, url_range.end)?;
543 Some(RangeInEditor::Text(start..end))
544 });
545 (range, vec![HoverLink::Url(url)])
546 })
547 .ok()
548 } else if let Some((filename_range, filename)) =
549 find_file(&buffer, project.clone(), buffer_position, cx).await
550 {
551 let range = maybe!({
552 let start =
553 snapshot.anchor_in_excerpt(excerpt_id, filename_range.start)?;
554 let end = snapshot.anchor_in_excerpt(excerpt_id, filename_range.end)?;
555 Some(RangeInEditor::Text(start..end))
556 });
557
558 Some((range, vec![HoverLink::File(filename)]))
559 } else if let Some(provider) = provider {
560 let task = cx.update(|_, cx| {
561 provider.definitions(&buffer, buffer_position, preferred_kind, cx)
562 })?;
563 if let Some(task) = task {
564 task.await.ok().map(|definition_result| {
565 (
566 definition_result.iter().find_map(|link| {
567 link.origin.as_ref().and_then(|origin| {
568 let start = snapshot.anchor_in_excerpt(
569 excerpt_id,
570 origin.range.start,
571 )?;
572 let end = snapshot
573 .anchor_in_excerpt(excerpt_id, origin.range.end)?;
574 Some(RangeInEditor::Text(start..end))
575 })
576 }),
577 definition_result.into_iter().map(HoverLink::Text).collect(),
578 )
579 })
580 } else {
581 None
582 }
583 } else {
584 None
585 }
586 }
587 TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
588 Some(RangeInEditor::Inlay(highlight.clone())),
589 vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
590 )),
591 };
592
593 this.update(cx, |editor, cx| {
594 // Clear any existing highlights
595 editor.clear_highlights::<HoveredLinkState>(cx);
596 let Some(hovered_link_state) = editor.hovered_link_state.as_mut() else {
597 editor.hide_hovered_link(cx);
598 return;
599 };
600 hovered_link_state.preferred_kind = preferred_kind;
601 hovered_link_state.symbol_range = result
602 .as_ref()
603 .and_then(|(symbol_range, _)| symbol_range.clone());
604
605 if let Some((symbol_range, definitions)) = result {
606 hovered_link_state.links = definitions;
607
608 let underline_hovered_link = !hovered_link_state.links.is_empty()
609 || hovered_link_state.symbol_range.is_some();
610
611 if underline_hovered_link {
612 let style = gpui::HighlightStyle {
613 underline: Some(gpui::UnderlineStyle {
614 thickness: px(1.),
615 ..Default::default()
616 }),
617 color: Some(cx.theme().colors().link_text_hover),
618 ..Default::default()
619 };
620 let highlight_range =
621 symbol_range.unwrap_or_else(|| match &trigger_point {
622 TriggerPoint::Text(trigger_anchor) => {
623 // If no symbol range returned from language server, use the surrounding word.
624 let (offset_range, _) =
625 snapshot.surrounding_word(*trigger_anchor, false);
626 RangeInEditor::Text(
627 snapshot.anchor_before(offset_range.start)
628 ..snapshot.anchor_after(offset_range.end),
629 )
630 }
631 TriggerPoint::InlayHint(highlight, _, _) => {
632 RangeInEditor::Inlay(highlight.clone())
633 }
634 });
635
636 match highlight_range {
637 RangeInEditor::Text(text_range) => editor
638 .highlight_text::<HoveredLinkState>(vec![(text_range, style)], cx),
639 RangeInEditor::Inlay(highlight) => editor
640 .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
641 }
642 }
643 } else {
644 editor.hide_hovered_link(cx);
645 }
646 })?;
647
648 anyhow::Ok(())
649 }
650 .log_err()
651 .await
652 }));
653
654 editor.hovered_link_state = Some(hovered_link_state);
655}
656
657pub(crate) fn find_url(
658 buffer: &Entity<language::Buffer>,
659 position: text::Anchor,
660 mut cx: AsyncWindowContext,
661) -> Option<(Range<text::Anchor>, String)> {
662 const LIMIT: usize = 2048;
663
664 let Ok(snapshot) = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot()) else {
665 return None;
666 };
667
668 let offset = position.to_offset(&snapshot);
669 let mut token_start = offset;
670 let mut token_end = offset;
671 let mut found_start = false;
672 let mut found_end = false;
673
674 for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
675 if ch.is_whitespace() {
676 found_start = true;
677 break;
678 }
679 token_start -= ch.len_utf8();
680 }
681 // Check if we didn't find the starting whitespace or if we didn't reach the start of the buffer
682 if !found_start && token_start != 0 {
683 return None;
684 }
685
686 for ch in snapshot
687 .chars_at(offset)
688 .take(LIMIT - (offset - token_start))
689 {
690 if ch.is_whitespace() {
691 found_end = true;
692 break;
693 }
694 token_end += ch.len_utf8();
695 }
696 // Check if we didn't find the ending whitespace or if we read more or equal than LIMIT
697 // which at this point would happen only if we reached the end of buffer
698 if !found_end && (token_end - token_start >= LIMIT) {
699 return None;
700 }
701
702 let mut finder = LinkFinder::new();
703 finder.kinds(&[LinkKind::Url]);
704 let input = snapshot
705 .text_for_range(token_start..token_end)
706 .collect::<String>();
707
708 let relative_offset = offset - token_start;
709 for link in finder.links(&input) {
710 if link.start() <= relative_offset && link.end() >= relative_offset {
711 let range = snapshot.anchor_before(token_start + link.start())
712 ..snapshot.anchor_after(token_start + link.end());
713 return Some((range, link.as_str().to_string()));
714 }
715 }
716 None
717}
718
719pub(crate) fn find_url_from_range(
720 buffer: &Entity<language::Buffer>,
721 range: Range<text::Anchor>,
722 mut cx: AsyncWindowContext,
723) -> Option<String> {
724 const LIMIT: usize = 2048;
725
726 let Ok(snapshot) = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot()) else {
727 return None;
728 };
729
730 let start_offset = range.start.to_offset(&snapshot);
731 let end_offset = range.end.to_offset(&snapshot);
732
733 let mut token_start = start_offset.min(end_offset);
734 let mut token_end = start_offset.max(end_offset);
735
736 let range_len = token_end - token_start;
737
738 if range_len >= LIMIT {
739 return None;
740 }
741
742 // Skip leading whitespace
743 for ch in snapshot.chars_at(token_start).take(range_len) {
744 if !ch.is_whitespace() {
745 break;
746 }
747 token_start += ch.len_utf8();
748 }
749
750 // Skip trailing whitespace
751 for ch in snapshot.reversed_chars_at(token_end).take(range_len) {
752 if !ch.is_whitespace() {
753 break;
754 }
755 token_end -= ch.len_utf8();
756 }
757
758 if token_start >= token_end {
759 return None;
760 }
761
762 let text = snapshot
763 .text_for_range(token_start..token_end)
764 .collect::<String>();
765
766 let mut finder = LinkFinder::new();
767 finder.kinds(&[LinkKind::Url]);
768
769 if let Some(link) = finder.links(&text).next() {
770 if link.start() == 0 && link.end() == text.len() {
771 return Some(link.as_str().to_string());
772 }
773 }
774
775 None
776}
777
778pub(crate) async fn find_file(
779 buffer: &Entity<language::Buffer>,
780 project: Option<Entity<Project>>,
781 position: text::Anchor,
782 cx: &mut AsyncWindowContext,
783) -> Option<(Range<text::Anchor>, ResolvedPath)> {
784 let project = project?;
785 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
786 let scope = snapshot.language_scope_at(position);
787 let (range, candidate_file_path) = surrounding_filename(snapshot, position)?;
788
789 async fn check_path(
790 candidate_file_path: &str,
791 project: &Entity<Project>,
792 buffer: &Entity<language::Buffer>,
793 cx: &mut AsyncWindowContext,
794 ) -> Option<ResolvedPath> {
795 project
796 .update(cx, |project, cx| {
797 project.resolve_path_in_buffer(&candidate_file_path, buffer, cx)
798 })
799 .ok()?
800 .await
801 .filter(|s| s.is_file())
802 }
803
804 if let Some(existing_path) = check_path(&candidate_file_path, &project, buffer, cx).await {
805 return Some((range, existing_path));
806 }
807
808 if let Some(scope) = scope {
809 for suffix in scope.path_suffixes() {
810 if candidate_file_path.ends_with(format!(".{suffix}").as_str()) {
811 continue;
812 }
813
814 let suffixed_candidate = format!("{candidate_file_path}.{suffix}");
815 if let Some(existing_path) = check_path(&suffixed_candidate, &project, buffer, cx).await
816 {
817 return Some((range, existing_path));
818 }
819 }
820 }
821
822 None
823}
824
825fn surrounding_filename(
826 snapshot: language::BufferSnapshot,
827 position: text::Anchor,
828) -> Option<(Range<text::Anchor>, String)> {
829 const LIMIT: usize = 2048;
830
831 let offset = position.to_offset(&snapshot);
832 let mut token_start = offset;
833 let mut token_end = offset;
834 let mut found_start = false;
835 let mut found_end = false;
836 let mut inside_quotes = false;
837
838 let mut filename = String::new();
839
840 let mut backwards = snapshot.reversed_chars_at(offset).take(LIMIT).peekable();
841 while let Some(ch) = backwards.next() {
842 // Escaped whitespace
843 if ch.is_whitespace() && backwards.peek() == Some(&'\\') {
844 filename.push(ch);
845 token_start -= ch.len_utf8();
846 backwards.next();
847 token_start -= '\\'.len_utf8();
848 continue;
849 }
850 if ch.is_whitespace() {
851 found_start = true;
852 break;
853 }
854 if (ch == '"' || ch == '\'') && !inside_quotes {
855 found_start = true;
856 inside_quotes = true;
857 break;
858 }
859
860 filename.push(ch);
861 token_start -= ch.len_utf8();
862 }
863 if !found_start && token_start != 0 {
864 return None;
865 }
866
867 filename = filename.chars().rev().collect();
868
869 let mut forwards = snapshot
870 .chars_at(offset)
871 .take(LIMIT - (offset - token_start))
872 .peekable();
873 while let Some(ch) = forwards.next() {
874 // Skip escaped whitespace
875 if ch == '\\' && forwards.peek().map_or(false, |ch| ch.is_whitespace()) {
876 token_end += ch.len_utf8();
877 let whitespace = forwards.next().unwrap();
878 token_end += whitespace.len_utf8();
879 filename.push(whitespace);
880 continue;
881 }
882
883 if ch.is_whitespace() {
884 found_end = true;
885 break;
886 }
887 if ch == '"' || ch == '\'' {
888 // If we're inside quotes, we stop when we come across the next quote
889 if inside_quotes {
890 found_end = true;
891 break;
892 } else {
893 // Otherwise, we skip the quote
894 inside_quotes = true;
895 continue;
896 }
897 }
898 filename.push(ch);
899 token_end += ch.len_utf8();
900 }
901
902 if !found_end && (token_end - token_start >= LIMIT) {
903 return None;
904 }
905
906 if filename.is_empty() {
907 return None;
908 }
909
910 let range = snapshot.anchor_before(token_start)..snapshot.anchor_after(token_end);
911
912 Some((range, filename))
913}
914
915#[cfg(test)]
916mod tests {
917 use super::*;
918 use crate::{
919 DisplayPoint,
920 display_map::ToDisplayPoint,
921 editor_tests::init_test,
922 inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
923 test::editor_lsp_test_context::EditorLspTestContext,
924 };
925 use futures::StreamExt;
926 use gpui::Modifiers;
927 use indoc::indoc;
928 use language::language_settings::InlayHintSettings;
929 use lsp::request::{GotoDefinition, GotoTypeDefinition};
930 use util::{assert_set_eq, path};
931 use workspace::item::Item;
932
933 #[gpui::test]
934 async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
935 init_test(cx, |_| {});
936
937 let mut cx = EditorLspTestContext::new_rust(
938 lsp::ServerCapabilities {
939 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
940 type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
941 ..Default::default()
942 },
943 cx,
944 )
945 .await;
946
947 cx.set_state(indoc! {"
948 struct A;
949 let vˇariable = A;
950 "});
951 let screen_coord = cx.editor(|editor, _, cx| editor.pixel_position_of_cursor(cx));
952
953 // Basic hold cmd+shift, expect highlight in region if response contains type definition
954 let symbol_range = cx.lsp_range(indoc! {"
955 struct A;
956 let «variable» = A;
957 "});
958 let target_range = cx.lsp_range(indoc! {"
959 struct «A»;
960 let variable = A;
961 "});
962
963 cx.run_until_parked();
964
965 let mut requests =
966 cx.set_request_handler::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
967 Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
968 lsp::LocationLink {
969 origin_selection_range: Some(symbol_range),
970 target_uri: url.clone(),
971 target_range,
972 target_selection_range: target_range,
973 },
974 ])))
975 });
976
977 let modifiers = if cfg!(target_os = "macos") {
978 Modifiers::command_shift()
979 } else {
980 Modifiers::control_shift()
981 };
982
983 cx.simulate_mouse_move(screen_coord.unwrap(), None, modifiers);
984
985 requests.next().await;
986 cx.run_until_parked();
987 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
988 struct A;
989 let «variable» = A;
990 "});
991
992 cx.simulate_modifiers_change(Modifiers::secondary_key());
993 cx.run_until_parked();
994 // Assert no link highlights
995 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
996 struct A;
997 let variable = A;
998 "});
999
1000 cx.simulate_click(screen_coord.unwrap(), modifiers);
1001
1002 cx.assert_editor_state(indoc! {"
1003 struct «Aˇ»;
1004 let variable = A;
1005 "});
1006 }
1007
1008 #[gpui::test]
1009 async fn test_hover_links(cx: &mut gpui::TestAppContext) {
1010 init_test(cx, |_| {});
1011
1012 let mut cx = EditorLspTestContext::new_rust(
1013 lsp::ServerCapabilities {
1014 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
1015 definition_provider: Some(lsp::OneOf::Left(true)),
1016 ..Default::default()
1017 },
1018 cx,
1019 )
1020 .await;
1021
1022 cx.set_state(indoc! {"
1023 fn ˇtest() { do_work(); }
1024 fn do_work() { test(); }
1025 "});
1026
1027 // Basic hold cmd, expect highlight in region if response contains definition
1028 let hover_point = cx.pixel_position(indoc! {"
1029 fn test() { do_wˇork(); }
1030 fn do_work() { test(); }
1031 "});
1032 let symbol_range = cx.lsp_range(indoc! {"
1033 fn test() { «do_work»(); }
1034 fn do_work() { test(); }
1035 "});
1036 let target_range = cx.lsp_range(indoc! {"
1037 fn test() { do_work(); }
1038 fn «do_work»() { test(); }
1039 "});
1040
1041 let mut requests =
1042 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1043 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1044 lsp::LocationLink {
1045 origin_selection_range: Some(symbol_range),
1046 target_uri: url.clone(),
1047 target_range,
1048 target_selection_range: target_range,
1049 },
1050 ])))
1051 });
1052
1053 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1054 requests.next().await;
1055 cx.background_executor.run_until_parked();
1056 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1057 fn test() { «do_work»(); }
1058 fn do_work() { test(); }
1059 "});
1060
1061 // Unpress cmd causes highlight to go away
1062 cx.simulate_modifiers_change(Modifiers::none());
1063 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1064 fn test() { do_work(); }
1065 fn do_work() { test(); }
1066 "});
1067
1068 let mut requests =
1069 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1070 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1071 lsp::LocationLink {
1072 origin_selection_range: Some(symbol_range),
1073 target_uri: url.clone(),
1074 target_range,
1075 target_selection_range: target_range,
1076 },
1077 ])))
1078 });
1079
1080 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1081 requests.next().await;
1082 cx.background_executor.run_until_parked();
1083 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1084 fn test() { «do_work»(); }
1085 fn do_work() { test(); }
1086 "});
1087
1088 // Moving mouse to location with no response dismisses highlight
1089 let hover_point = cx.pixel_position(indoc! {"
1090 fˇn test() { do_work(); }
1091 fn do_work() { test(); }
1092 "});
1093 let mut requests =
1094 cx.lsp
1095 .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1096 // No definitions returned
1097 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1098 });
1099 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1100
1101 requests.next().await;
1102 cx.background_executor.run_until_parked();
1103
1104 // Assert no link highlights
1105 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1106 fn test() { do_work(); }
1107 fn do_work() { test(); }
1108 "});
1109
1110 // // Move mouse without cmd and then pressing cmd triggers highlight
1111 let hover_point = cx.pixel_position(indoc! {"
1112 fn test() { do_work(); }
1113 fn do_work() { teˇst(); }
1114 "});
1115 cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1116
1117 // Assert no link highlights
1118 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1119 fn test() { do_work(); }
1120 fn do_work() { test(); }
1121 "});
1122
1123 let symbol_range = cx.lsp_range(indoc! {"
1124 fn test() { do_work(); }
1125 fn do_work() { «test»(); }
1126 "});
1127 let target_range = cx.lsp_range(indoc! {"
1128 fn «test»() { do_work(); }
1129 fn do_work() { test(); }
1130 "});
1131
1132 let mut requests =
1133 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1134 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1135 lsp::LocationLink {
1136 origin_selection_range: Some(symbol_range),
1137 target_uri: url,
1138 target_range,
1139 target_selection_range: target_range,
1140 },
1141 ])))
1142 });
1143
1144 cx.simulate_modifiers_change(Modifiers::secondary_key());
1145
1146 requests.next().await;
1147 cx.background_executor.run_until_parked();
1148
1149 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1150 fn test() { do_work(); }
1151 fn do_work() { «test»(); }
1152 "});
1153
1154 cx.deactivate_window();
1155 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1156 fn test() { do_work(); }
1157 fn do_work() { test(); }
1158 "});
1159
1160 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1161 cx.background_executor.run_until_parked();
1162 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1163 fn test() { do_work(); }
1164 fn do_work() { «test»(); }
1165 "});
1166
1167 // Moving again within the same symbol range doesn't re-request
1168 let hover_point = cx.pixel_position(indoc! {"
1169 fn test() { do_work(); }
1170 fn do_work() { tesˇt(); }
1171 "});
1172 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1173 cx.background_executor.run_until_parked();
1174 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1175 fn test() { do_work(); }
1176 fn do_work() { «test»(); }
1177 "});
1178
1179 // Cmd click with existing definition doesn't re-request and dismisses highlight
1180 cx.simulate_click(hover_point, Modifiers::secondary_key());
1181 cx.lsp
1182 .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1183 // Empty definition response to make sure we aren't hitting the lsp and using
1184 // the cached location instead
1185 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1186 });
1187 cx.background_executor.run_until_parked();
1188 cx.assert_editor_state(indoc! {"
1189 fn «testˇ»() { do_work(); }
1190 fn do_work() { test(); }
1191 "});
1192
1193 // Assert no link highlights after jump
1194 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1195 fn test() { do_work(); }
1196 fn do_work() { test(); }
1197 "});
1198
1199 // Cmd click without existing definition requests and jumps
1200 let hover_point = cx.pixel_position(indoc! {"
1201 fn test() { do_wˇork(); }
1202 fn do_work() { test(); }
1203 "});
1204 let target_range = cx.lsp_range(indoc! {"
1205 fn test() { do_work(); }
1206 fn «do_work»() { test(); }
1207 "});
1208
1209 let mut requests =
1210 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1211 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1212 lsp::LocationLink {
1213 origin_selection_range: None,
1214 target_uri: url,
1215 target_range,
1216 target_selection_range: target_range,
1217 },
1218 ])))
1219 });
1220 cx.simulate_click(hover_point, Modifiers::secondary_key());
1221 requests.next().await;
1222 cx.background_executor.run_until_parked();
1223 cx.assert_editor_state(indoc! {"
1224 fn test() { do_work(); }
1225 fn «do_workˇ»() { test(); }
1226 "});
1227
1228 // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
1229 // 2. Selection is completed, hovering
1230 let hover_point = cx.pixel_position(indoc! {"
1231 fn test() { do_wˇork(); }
1232 fn do_work() { test(); }
1233 "});
1234 let target_range = cx.lsp_range(indoc! {"
1235 fn test() { do_work(); }
1236 fn «do_work»() { test(); }
1237 "});
1238 let mut requests =
1239 cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1240 Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1241 lsp::LocationLink {
1242 origin_selection_range: None,
1243 target_uri: url,
1244 target_range,
1245 target_selection_range: target_range,
1246 },
1247 ])))
1248 });
1249
1250 // create a pending selection
1251 let selection_range = cx.ranges(indoc! {"
1252 fn «test() { do_w»ork(); }
1253 fn do_work() { test(); }
1254 "})[0]
1255 .clone();
1256 cx.update_editor(|editor, window, cx| {
1257 let snapshot = editor.buffer().read(cx).snapshot(cx);
1258 let anchor_range = snapshot.anchor_before(selection_range.start)
1259 ..snapshot.anchor_after(selection_range.end);
1260 editor.change_selections(Some(crate::Autoscroll::fit()), window, cx, |s| {
1261 s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
1262 });
1263 });
1264 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1265 cx.background_executor.run_until_parked();
1266 assert!(requests.try_next().is_err());
1267 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1268 fn test() { do_work(); }
1269 fn do_work() { test(); }
1270 "});
1271 cx.background_executor.run_until_parked();
1272 }
1273
1274 #[gpui::test]
1275 async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
1276 init_test(cx, |settings| {
1277 settings.defaults.inlay_hints = Some(InlayHintSettings {
1278 enabled: true,
1279 show_value_hints: false,
1280 edit_debounce_ms: 0,
1281 scroll_debounce_ms: 0,
1282 show_type_hints: true,
1283 show_parameter_hints: true,
1284 show_other_hints: true,
1285 show_background: false,
1286 toggle_on_modifiers_press: None,
1287 })
1288 });
1289
1290 let mut cx = EditorLspTestContext::new_rust(
1291 lsp::ServerCapabilities {
1292 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
1293 ..Default::default()
1294 },
1295 cx,
1296 )
1297 .await;
1298 cx.set_state(indoc! {"
1299 struct TestStruct;
1300
1301 fn main() {
1302 let variableˇ = TestStruct;
1303 }
1304 "});
1305 let hint_start_offset = cx.ranges(indoc! {"
1306 struct TestStruct;
1307
1308 fn main() {
1309 let variableˇ = TestStruct;
1310 }
1311 "})[0]
1312 .start;
1313 let hint_position = cx.to_lsp(hint_start_offset);
1314 let target_range = cx.lsp_range(indoc! {"
1315 struct «TestStruct»;
1316
1317 fn main() {
1318 let variable = TestStruct;
1319 }
1320 "});
1321
1322 let expected_uri = cx.buffer_lsp_url.clone();
1323 let hint_label = ": TestStruct";
1324 cx.lsp
1325 .set_request_handler::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1326 let expected_uri = expected_uri.clone();
1327 async move {
1328 assert_eq!(params.text_document.uri, expected_uri);
1329 Ok(Some(vec![lsp::InlayHint {
1330 position: hint_position,
1331 label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1332 value: hint_label.to_string(),
1333 location: Some(lsp::Location {
1334 uri: params.text_document.uri,
1335 range: target_range,
1336 }),
1337 ..Default::default()
1338 }]),
1339 kind: Some(lsp::InlayHintKind::TYPE),
1340 text_edits: None,
1341 tooltip: None,
1342 padding_left: Some(false),
1343 padding_right: Some(false),
1344 data: None,
1345 }]))
1346 }
1347 })
1348 .next()
1349 .await;
1350 cx.background_executor.run_until_parked();
1351 cx.update_editor(|editor, _window, cx| {
1352 let expected_layers = vec![hint_label.to_string()];
1353 assert_eq!(expected_layers, cached_hint_labels(editor));
1354 assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1355 });
1356
1357 let inlay_range = cx
1358 .ranges(indoc! {"
1359 struct TestStruct;
1360
1361 fn main() {
1362 let variable« »= TestStruct;
1363 }
1364 "})
1365 .first()
1366 .cloned()
1367 .unwrap();
1368 let midpoint = cx.update_editor(|editor, window, cx| {
1369 let snapshot = editor.snapshot(window, cx);
1370 let previous_valid = inlay_range.start.to_display_point(&snapshot);
1371 let next_valid = inlay_range.end.to_display_point(&snapshot);
1372 assert_eq!(previous_valid.row(), next_valid.row());
1373 assert!(previous_valid.column() < next_valid.column());
1374 DisplayPoint::new(
1375 previous_valid.row(),
1376 previous_valid.column() + (hint_label.len() / 2) as u32,
1377 )
1378 });
1379 // Press cmd to trigger highlight
1380 let hover_point = cx.pixel_position_for(midpoint);
1381 cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1382 cx.background_executor.run_until_parked();
1383 cx.update_editor(|editor, window, cx| {
1384 let snapshot = editor.snapshot(window, cx);
1385 let actual_highlights = snapshot
1386 .inlay_highlights::<HoveredLinkState>()
1387 .into_iter()
1388 .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1389 .collect::<Vec<_>>();
1390
1391 let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1392 let expected_highlight = InlayHighlight {
1393 inlay: InlayId::Hint(0),
1394 inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1395 range: 0..hint_label.len(),
1396 };
1397 assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1398 });
1399
1400 cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1401 // Assert no link highlights
1402 cx.update_editor(|editor, window, cx| {
1403 let snapshot = editor.snapshot(window, cx);
1404 let actual_ranges = snapshot
1405 .text_highlight_ranges::<HoveredLinkState>()
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 .is_empty()
1638 );
1639 });
1640
1641 // Moving the mouse over a file that does exist should highlight it.
1642 #[cfg(not(target_os = "windows"))]
1643 let screen_coord = cx.pixel_position(indoc! {"
1644 You can't go to a file that does_not_exist.txt.
1645 Go to fˇile2.rs if you want.
1646 Or go to ../dir/file2.rs if you want.
1647 Or go to /root/dir/file2.rs if project is local.
1648 Or go to /root/dir/file2 if this is a Rust file.
1649 "});
1650 #[cfg(target_os = "windows")]
1651 let screen_coord = cx.pixel_position(indoc! {"
1652 You can't go to a file that does_not_exist.txt.
1653 Go to fˇile2.rs if you want.
1654 Or go to ../dir/file2.rs if you want.
1655 Or go to C:/root/dir/file2.rs if project is local.
1656 Or go to C:/root/dir/file2 if this is a Rust file.
1657 "});
1658
1659 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1660 #[cfg(not(target_os = "windows"))]
1661 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1662 You can't go to a file that does_not_exist.txt.
1663 Go to «file2.rsˇ» if you want.
1664 Or go to ../dir/file2.rs if you want.
1665 Or go to /root/dir/file2.rs if project is local.
1666 Or go to /root/dir/file2 if this is a Rust file.
1667 "});
1668 #[cfg(target_os = "windows")]
1669 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1670 You can't go to a file that does_not_exist.txt.
1671 Go to «file2.rsˇ» if you want.
1672 Or go to ../dir/file2.rs if you want.
1673 Or go to C:/root/dir/file2.rs if project is local.
1674 Or go to C:/root/dir/file2 if this is a Rust file.
1675 "});
1676
1677 // Moving the mouse over a relative path that does exist should highlight it
1678 #[cfg(not(target_os = "windows"))]
1679 let screen_coord = cx.pixel_position(indoc! {"
1680 You can't go to a file that does_not_exist.txt.
1681 Go to file2.rs if you want.
1682 Or go to ../dir/fˇile2.rs if you want.
1683 Or go to /root/dir/file2.rs if project is local.
1684 Or go to /root/dir/file2 if this is a Rust file.
1685 "});
1686 #[cfg(target_os = "windows")]
1687 let screen_coord = cx.pixel_position(indoc! {"
1688 You can't go to a file that does_not_exist.txt.
1689 Go to file2.rs if you want.
1690 Or go to ../dir/fˇile2.rs if you want.
1691 Or go to C:/root/dir/file2.rs if project is local.
1692 Or go to C:/root/dir/file2 if this is a Rust file.
1693 "});
1694
1695 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1696 #[cfg(not(target_os = "windows"))]
1697 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1698 You can't go to a file that does_not_exist.txt.
1699 Go to file2.rs if you want.
1700 Or go to «../dir/file2.rsˇ» if you want.
1701 Or go to /root/dir/file2.rs if project is local.
1702 Or go to /root/dir/file2 if this is a Rust file.
1703 "});
1704 #[cfg(target_os = "windows")]
1705 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1706 You can't go to a file that does_not_exist.txt.
1707 Go to file2.rs if you want.
1708 Or go to «../dir/file2.rsˇ» if you want.
1709 Or go to C:/root/dir/file2.rs if project is local.
1710 Or go to C:/root/dir/file2 if this is a Rust file.
1711 "});
1712
1713 // Moving the mouse over an absolute path that does exist should highlight it
1714 #[cfg(not(target_os = "windows"))]
1715 let screen_coord = cx.pixel_position(indoc! {"
1716 You can't go to a file that does_not_exist.txt.
1717 Go to file2.rs if you want.
1718 Or go to ../dir/file2.rs if you want.
1719 Or go to /root/diˇr/file2.rs if project is local.
1720 Or go to /root/dir/file2 if this is a Rust file.
1721 "});
1722
1723 #[cfg(target_os = "windows")]
1724 let screen_coord = cx.pixel_position(indoc! {"
1725 You can't go to a file that does_not_exist.txt.
1726 Go to file2.rs if you want.
1727 Or go to ../dir/file2.rs if you want.
1728 Or go to C:/root/diˇr/file2.rs if project is local.
1729 Or go to C:/root/dir/file2 if this is a Rust file.
1730 "});
1731
1732 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1733 #[cfg(not(target_os = "windows"))]
1734 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1735 You can't go to a file that does_not_exist.txt.
1736 Go to file2.rs if you want.
1737 Or go to ../dir/file2.rs if you want.
1738 Or go to «/root/dir/file2.rsˇ» if project is local.
1739 Or go to /root/dir/file2 if this is a Rust file.
1740 "});
1741 #[cfg(target_os = "windows")]
1742 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1743 You can't go to a file that does_not_exist.txt.
1744 Go to file2.rs if you want.
1745 Or go to ../dir/file2.rs if you want.
1746 Or go to «C:/root/dir/file2.rsˇ» if project is local.
1747 Or go to C:/root/dir/file2 if this is a Rust file.
1748 "});
1749
1750 // Moving the mouse over a path that exists, if we add the language-specific suffix, it should highlight it
1751 #[cfg(not(target_os = "windows"))]
1752 let screen_coord = cx.pixel_position(indoc! {"
1753 You can't go to a file that does_not_exist.txt.
1754 Go to file2.rs if you want.
1755 Or go to ../dir/file2.rs if you want.
1756 Or go to /root/dir/file2.rs if project is local.
1757 Or go to /root/diˇr/file2 if this is a Rust file.
1758 "});
1759 #[cfg(target_os = "windows")]
1760 let screen_coord = cx.pixel_position(indoc! {"
1761 You can't go to a file that does_not_exist.txt.
1762 Go to file2.rs if you want.
1763 Or go to ../dir/file2.rs if you want.
1764 Or go to C:/root/dir/file2.rs if project is local.
1765 Or go to C:/root/diˇr/file2 if this is a Rust file.
1766 "});
1767
1768 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1769 #[cfg(not(target_os = "windows"))]
1770 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1771 You can't go to a file that does_not_exist.txt.
1772 Go to file2.rs if you want.
1773 Or go to ../dir/file2.rs if you want.
1774 Or go to /root/dir/file2.rs if project is local.
1775 Or go to «/root/dir/file2ˇ» if this is a Rust file.
1776 "});
1777 #[cfg(target_os = "windows")]
1778 cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1779 You can't go to a file that does_not_exist.txt.
1780 Go to file2.rs if you want.
1781 Or go to ../dir/file2.rs if you want.
1782 Or go to C:/root/dir/file2.rs if project is local.
1783 Or go to «C:/root/dir/file2ˇ» if this is a Rust file.
1784 "});
1785
1786 cx.simulate_click(screen_coord, Modifiers::secondary_key());
1787
1788 cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1789 cx.update_workspace(|workspace, _, cx| {
1790 let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
1791
1792 let buffer = active_editor
1793 .read(cx)
1794 .buffer()
1795 .read(cx)
1796 .as_singleton()
1797 .unwrap();
1798
1799 let file = buffer.read(cx).file().unwrap();
1800 let file_path = file.as_local().unwrap().abs_path(cx);
1801
1802 assert_eq!(
1803 file_path,
1804 std::path::PathBuf::from(path!("/root/dir/file2.rs"))
1805 );
1806 });
1807 }
1808
1809 #[gpui::test]
1810 async fn test_hover_directories(cx: &mut gpui::TestAppContext) {
1811 init_test(cx, |_| {});
1812 let mut cx = EditorLspTestContext::new_rust(
1813 lsp::ServerCapabilities {
1814 ..Default::default()
1815 },
1816 cx,
1817 )
1818 .await;
1819
1820 // Insert a new file
1821 let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1822 fs.as_fake()
1823 .insert_file("/root/dir/file2.rs", "This is file2.rs".as_bytes().to_vec())
1824 .await;
1825
1826 cx.set_state(indoc! {"
1827 You can't open ../diˇr because it's a directory.
1828 "});
1829
1830 // File does not exist
1831 let screen_coord = cx.pixel_position(indoc! {"
1832 You can't open ../diˇr because it's a directory.
1833 "});
1834 cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1835
1836 // No highlight
1837 cx.update_editor(|editor, window, cx| {
1838 assert!(
1839 editor
1840 .snapshot(window, cx)
1841 .text_highlight_ranges::<HoveredLinkState>()
1842 .unwrap_or_default()
1843 .is_empty()
1844 );
1845 });
1846
1847 // Does not open the directory
1848 cx.simulate_click(screen_coord, Modifiers::secondary_key());
1849 cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
1850 }
1851}