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