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