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