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