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