1use crate::{
2 display_map::{InlayOffset, ToDisplayPoint},
3 hover_links::{InlayHighlight, RangeInEditor},
4 Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSettings, EditorSnapshot, EditorStyle,
5 ExcerptId, Hover, RangeToAnchorExt,
6};
7use futures::FutureExt;
8use gpui::{
9 div, px, AnyElement, CursorStyle, Hsla, InteractiveElement, IntoElement, Model, MouseButton,
10 ParentElement, Pixels, SharedString, Size, StatefulInteractiveElement, Styled, Task,
11 ViewContext, WeakView,
12};
13use language::{markdown, Bias, DiagnosticEntry, Language, LanguageRegistry, ParsedMarkdown};
14
15use lsp::DiagnosticSeverity;
16use project::{HoverBlock, HoverBlockKind, InlayHintLabelPart, Project};
17use settings::Settings;
18use std::{ops::Range, sync::Arc, time::Duration};
19use ui::{prelude::*, Tooltip};
20use util::TryFutureExt;
21use workspace::Workspace;
22
23pub const HOVER_DELAY_MILLIS: u64 = 350;
24pub const HOVER_REQUEST_DELAY_MILLIS: u64 = 200;
25
26pub const MIN_POPOVER_CHARACTER_WIDTH: f32 = 20.;
27pub const MIN_POPOVER_LINE_HEIGHT: Pixels = px(4.);
28pub const HOVER_POPOVER_GAP: Pixels = px(10.);
29
30/// Bindable action which uses the most recent selection head to trigger a hover
31pub fn hover(editor: &mut Editor, _: &Hover, cx: &mut ViewContext<Editor>) {
32 let head = editor.selections.newest_display(cx).head();
33 show_hover(editor, head, true, cx);
34}
35
36/// The internal hover action dispatches between `show_hover` or `hide_hover`
37/// depending on whether a point to hover over is provided.
38pub fn hover_at(editor: &mut Editor, point: Option<DisplayPoint>, cx: &mut ViewContext<Editor>) {
39 if EditorSettings::get_global(cx).hover_popover_enabled {
40 if let Some(point) = point {
41 show_hover(editor, point, false, cx);
42 } else {
43 hide_hover(editor, cx);
44 }
45 }
46}
47
48pub struct InlayHover {
49 pub excerpt: ExcerptId,
50 pub range: InlayHighlight,
51 pub tooltip: HoverBlock,
52}
53
54pub fn find_hovered_hint_part(
55 label_parts: Vec<InlayHintLabelPart>,
56 hint_start: InlayOffset,
57 hovered_offset: InlayOffset,
58) -> Option<(InlayHintLabelPart, Range<InlayOffset>)> {
59 if hovered_offset >= hint_start {
60 let mut hovered_character = (hovered_offset - hint_start).0;
61 let mut part_start = hint_start;
62 for part in label_parts {
63 let part_len = part.value.chars().count();
64 if hovered_character > part_len {
65 hovered_character -= part_len;
66 part_start.0 += part_len;
67 } else {
68 let part_end = InlayOffset(part_start.0 + part_len);
69 return Some((part, part_start..part_end));
70 }
71 }
72 }
73 None
74}
75
76pub fn hover_at_inlay(editor: &mut Editor, inlay_hover: InlayHover, cx: &mut ViewContext<Editor>) {
77 if EditorSettings::get_global(cx).hover_popover_enabled {
78 if editor.pending_rename.is_some() {
79 return;
80 }
81
82 let Some(project) = editor.project.clone() else {
83 return;
84 };
85
86 if let Some(InfoPopover { symbol_range, .. }) = &editor.hover_state.info_popover {
87 if let RangeInEditor::Inlay(range) = symbol_range {
88 if range == &inlay_hover.range {
89 // Hover triggered from same location as last time. Don't show again.
90 return;
91 }
92 }
93 hide_hover(editor, cx);
94 }
95
96 let task = cx.spawn(|this, mut cx| {
97 async move {
98 cx.background_executor()
99 .timer(Duration::from_millis(HOVER_DELAY_MILLIS))
100 .await;
101 this.update(&mut cx, |this, _| {
102 this.hover_state.diagnostic_popover = None;
103 })?;
104
105 let language_registry = project.update(&mut cx, |p, _| p.languages().clone())?;
106 let blocks = vec![inlay_hover.tooltip];
107 let parsed_content = parse_blocks(&blocks, &language_registry, None).await;
108
109 let hover_popover = InfoPopover {
110 project: project.clone(),
111 symbol_range: RangeInEditor::Inlay(inlay_hover.range.clone()),
112 blocks,
113 parsed_content,
114 };
115
116 this.update(&mut cx, |this, cx| {
117 // Highlight the selected symbol using a background highlight
118 this.highlight_inlay_background::<HoverState>(
119 vec![inlay_hover.range],
120 |theme| theme.element_hover, // todo("use a proper background here")
121 cx,
122 );
123 this.hover_state.info_popover = Some(hover_popover);
124 cx.notify();
125 })?;
126
127 anyhow::Ok(())
128 }
129 .log_err()
130 });
131
132 editor.hover_state.info_task = Some(task);
133 }
134}
135
136/// Hides the type information popup.
137/// Triggered by the `Hover` action when the cursor is not over a symbol or when the
138/// selections changed.
139pub fn hide_hover(editor: &mut Editor, cx: &mut ViewContext<Editor>) -> bool {
140 let did_hide = editor.hover_state.info_popover.take().is_some()
141 | editor.hover_state.diagnostic_popover.take().is_some();
142
143 editor.hover_state.info_task = None;
144 editor.hover_state.triggered_from = None;
145
146 editor.clear_background_highlights::<HoverState>(cx);
147
148 if did_hide {
149 cx.notify();
150 }
151
152 did_hide
153}
154
155/// Queries the LSP and shows type info and documentation
156/// about the symbol the mouse is currently hovering over.
157/// Triggered by the `Hover` action when the cursor may be over a symbol.
158fn show_hover(
159 editor: &mut Editor,
160 point: DisplayPoint,
161 ignore_timeout: bool,
162 cx: &mut ViewContext<Editor>,
163) {
164 if editor.pending_rename.is_some() {
165 return;
166 }
167
168 let snapshot = editor.snapshot(cx);
169 let multibuffer_offset = point.to_offset(&snapshot.display_snapshot, Bias::Left);
170
171 let (buffer, buffer_position) = if let Some(output) = editor
172 .buffer
173 .read(cx)
174 .text_anchor_for_position(multibuffer_offset, cx)
175 {
176 output
177 } else {
178 return;
179 };
180
181 let excerpt_id = if let Some((excerpt_id, _, _)) = editor
182 .buffer()
183 .read(cx)
184 .excerpt_containing(multibuffer_offset, cx)
185 {
186 excerpt_id
187 } else {
188 return;
189 };
190
191 let project = if let Some(project) = editor.project.clone() {
192 project
193 } else {
194 return;
195 };
196
197 if !ignore_timeout {
198 if let Some(InfoPopover { symbol_range, .. }) = &editor.hover_state.info_popover {
199 if symbol_range
200 .as_text_range()
201 .map(|range| {
202 let hover_range = range.to_offset(&snapshot.buffer_snapshot);
203 // LSP returns a hover result for the end index of ranges that should be hovered, so we need to
204 // use an inclusive range here to check if we should dismiss the popover
205 (hover_range.start..=hover_range.end).contains(&multibuffer_offset)
206 })
207 .unwrap_or(false)
208 {
209 // Hover triggered from same location as last time. Don't show again.
210 return;
211 } else {
212 hide_hover(editor, cx);
213 }
214 }
215 }
216
217 // Get input anchor
218 let anchor = snapshot
219 .buffer_snapshot
220 .anchor_at(multibuffer_offset, Bias::Left);
221
222 // Don't request again if the location is the same as the previous request
223 if let Some(triggered_from) = &editor.hover_state.triggered_from {
224 if triggered_from
225 .cmp(&anchor, &snapshot.buffer_snapshot)
226 .is_eq()
227 {
228 return;
229 }
230 }
231
232 let task = cx.spawn(|this, mut cx| {
233 async move {
234 // If we need to delay, delay a set amount initially before making the lsp request
235 let delay = if !ignore_timeout {
236 // Construct delay task to wait for later
237 let total_delay = Some(
238 cx.background_executor()
239 .timer(Duration::from_millis(HOVER_DELAY_MILLIS)),
240 );
241
242 cx.background_executor()
243 .timer(Duration::from_millis(HOVER_REQUEST_DELAY_MILLIS))
244 .await;
245 total_delay
246 } else {
247 None
248 };
249
250 // query the LSP for hover info
251 let hover_request = cx.update(|cx| {
252 project.update(cx, |project, cx| {
253 project.hover(&buffer, buffer_position, cx)
254 })
255 })?;
256
257 if let Some(delay) = delay {
258 delay.await;
259 }
260
261 // If there's a diagnostic, assign it on the hover state and notify
262 let local_diagnostic = snapshot
263 .buffer_snapshot
264 .diagnostics_in_range::<_, usize>(multibuffer_offset..multibuffer_offset, false)
265 // Find the entry with the most specific range
266 .min_by_key(|entry| entry.range.end - entry.range.start)
267 .map(|entry| DiagnosticEntry {
268 diagnostic: entry.diagnostic,
269 range: entry.range.to_anchors(&snapshot.buffer_snapshot),
270 });
271
272 // Pull the primary diagnostic out so we can jump to it if the popover is clicked
273 let primary_diagnostic = local_diagnostic.as_ref().and_then(|local_diagnostic| {
274 snapshot
275 .buffer_snapshot
276 .diagnostic_group::<usize>(local_diagnostic.diagnostic.group_id)
277 .find(|diagnostic| diagnostic.diagnostic.is_primary)
278 .map(|entry| DiagnosticEntry {
279 diagnostic: entry.diagnostic,
280 range: entry.range.to_anchors(&snapshot.buffer_snapshot),
281 })
282 });
283
284 this.update(&mut cx, |this, _| {
285 this.hover_state.diagnostic_popover =
286 local_diagnostic.map(|local_diagnostic| DiagnosticPopover {
287 local_diagnostic,
288 primary_diagnostic,
289 });
290 })?;
291
292 let hover_result = hover_request.await.ok().flatten();
293 let snapshot = this.update(&mut cx, |this, cx| this.snapshot(cx))?;
294 let hover_popover = match hover_result {
295 Some(hover_result) if !hover_result.is_empty() => {
296 // Create symbol range of anchors for highlighting and filtering of future requests.
297 let range = if let Some(range) = hover_result.range {
298 let start = snapshot
299 .buffer_snapshot
300 .anchor_in_excerpt(excerpt_id, range.start);
301 let end = snapshot
302 .buffer_snapshot
303 .anchor_in_excerpt(excerpt_id, range.end);
304
305 start..end
306 } else {
307 anchor..anchor
308 };
309
310 let language_registry =
311 project.update(&mut cx, |p, _| p.languages().clone())?;
312 let blocks = hover_result.contents;
313 let language = hover_result.language;
314 let parsed_content = parse_blocks(&blocks, &language_registry, language).await;
315
316 Some(InfoPopover {
317 project: project.clone(),
318 symbol_range: RangeInEditor::Text(range),
319 blocks,
320 parsed_content,
321 })
322 }
323
324 _ => None,
325 };
326
327 this.update(&mut cx, |this, cx| {
328 if let Some(symbol_range) = hover_popover
329 .as_ref()
330 .and_then(|hover_popover| hover_popover.symbol_range.as_text_range())
331 {
332 // Highlight the selected symbol using a background highlight
333 this.highlight_background::<HoverState>(
334 vec![symbol_range],
335 |theme| theme.element_hover, // todo update theme
336 cx,
337 );
338 } else {
339 this.clear_background_highlights::<HoverState>(cx);
340 }
341
342 this.hover_state.info_popover = hover_popover;
343 cx.notify();
344 cx.refresh();
345 })?;
346
347 Ok::<_, anyhow::Error>(())
348 }
349 .log_err()
350 });
351
352 editor.hover_state.info_task = Some(task);
353}
354
355async fn parse_blocks(
356 blocks: &[HoverBlock],
357 language_registry: &Arc<LanguageRegistry>,
358 language: Option<Arc<Language>>,
359) -> markdown::ParsedMarkdown {
360 let mut text = String::new();
361 let mut highlights = Vec::new();
362 let mut region_ranges = Vec::new();
363 let mut regions = Vec::new();
364
365 for block in blocks {
366 match &block.kind {
367 HoverBlockKind::PlainText => {
368 markdown::new_paragraph(&mut text, &mut Vec::new());
369 text.push_str(&block.text);
370 }
371
372 HoverBlockKind::Markdown => {
373 markdown::parse_markdown_block(
374 &block.text,
375 language_registry,
376 language.clone(),
377 &mut text,
378 &mut highlights,
379 &mut region_ranges,
380 &mut regions,
381 )
382 .await
383 }
384
385 HoverBlockKind::Code { language } => {
386 if let Some(language) = language_registry
387 .language_for_name(language)
388 .now_or_never()
389 .and_then(Result::ok)
390 {
391 markdown::highlight_code(&mut text, &mut highlights, &block.text, &language);
392 } else {
393 text.push_str(&block.text);
394 }
395 }
396 }
397 }
398
399 let leading_space = text.chars().take_while(|c| c.is_whitespace()).count();
400 if leading_space > 0 {
401 highlights = highlights
402 .into_iter()
403 .map(|(range, style)| {
404 (
405 range.start.saturating_sub(leading_space)
406 ..range.end.saturating_sub(leading_space),
407 style,
408 )
409 })
410 .collect();
411 region_ranges = region_ranges
412 .into_iter()
413 .map(|range| {
414 range.start.saturating_sub(leading_space)..range.end.saturating_sub(leading_space)
415 })
416 .collect();
417 }
418
419 ParsedMarkdown {
420 text: text.trim().to_string(),
421 highlights,
422 region_ranges,
423 regions,
424 }
425}
426
427#[derive(Default)]
428pub struct HoverState {
429 pub info_popover: Option<InfoPopover>,
430 pub diagnostic_popover: Option<DiagnosticPopover>,
431 pub triggered_from: Option<Anchor>,
432 pub info_task: Option<Task<Option<()>>>,
433}
434
435impl HoverState {
436 pub fn visible(&self) -> bool {
437 self.info_popover.is_some() || self.diagnostic_popover.is_some()
438 }
439
440 pub fn render(
441 &mut self,
442 snapshot: &EditorSnapshot,
443 style: &EditorStyle,
444 visible_rows: Range<u32>,
445 max_size: Size<Pixels>,
446 workspace: Option<WeakView<Workspace>>,
447 cx: &mut ViewContext<Editor>,
448 ) -> Option<(DisplayPoint, Vec<AnyElement>)> {
449 // If there is a diagnostic, position the popovers based on that.
450 // Otherwise use the start of the hover range
451 let anchor = self
452 .diagnostic_popover
453 .as_ref()
454 .map(|diagnostic_popover| &diagnostic_popover.local_diagnostic.range.start)
455 .or_else(|| {
456 self.info_popover
457 .as_ref()
458 .map(|info_popover| match &info_popover.symbol_range {
459 RangeInEditor::Text(range) => &range.start,
460 RangeInEditor::Inlay(range) => &range.inlay_position,
461 })
462 })?;
463 let point = anchor.to_display_point(&snapshot.display_snapshot);
464
465 // Don't render if the relevant point isn't on screen
466 if !self.visible() || !visible_rows.contains(&point.row()) {
467 return None;
468 }
469
470 let mut elements = Vec::new();
471
472 if let Some(diagnostic_popover) = self.diagnostic_popover.as_ref() {
473 elements.push(diagnostic_popover.render(style, max_size, cx));
474 }
475 if let Some(info_popover) = self.info_popover.as_mut() {
476 elements.push(info_popover.render(style, max_size, workspace, cx));
477 }
478
479 Some((point, elements))
480 }
481}
482
483#[derive(Debug, Clone)]
484pub struct InfoPopover {
485 pub project: Model<Project>,
486 symbol_range: RangeInEditor,
487 pub blocks: Vec<HoverBlock>,
488 parsed_content: ParsedMarkdown,
489}
490
491impl InfoPopover {
492 pub fn render(
493 &mut self,
494 style: &EditorStyle,
495 max_size: Size<Pixels>,
496 workspace: Option<WeakView<Workspace>>,
497 cx: &mut ViewContext<Editor>,
498 ) -> AnyElement {
499 div()
500 .id("info_popover")
501 .elevation_2(cx)
502 .p_2()
503 .overflow_y_scroll()
504 .max_w(max_size.width)
505 .max_h(max_size.height)
506 // Prevent a mouse move on the popover from being propagated to the editor,
507 // because that would dismiss the popover.
508 .on_mouse_move(|_, cx| cx.stop_propagation())
509 .child(crate::render_parsed_markdown(
510 "content",
511 &self.parsed_content,
512 style,
513 workspace,
514 cx,
515 ))
516 .into_any_element()
517 }
518}
519
520#[derive(Debug, Clone)]
521pub struct DiagnosticPopover {
522 local_diagnostic: DiagnosticEntry<Anchor>,
523 primary_diagnostic: Option<DiagnosticEntry<Anchor>>,
524}
525
526impl DiagnosticPopover {
527 pub fn render(
528 &self,
529 style: &EditorStyle,
530 max_size: Size<Pixels>,
531 cx: &mut ViewContext<Editor>,
532 ) -> AnyElement {
533 let text = match &self.local_diagnostic.diagnostic.source {
534 Some(source) => format!("{source}: {}", self.local_diagnostic.diagnostic.message),
535 None => self.local_diagnostic.diagnostic.message.clone(),
536 };
537
538 let status_colors = cx.theme().status();
539
540 struct DiagnosticColors {
541 pub background: Hsla,
542 pub border: Hsla,
543 }
544
545 let diagnostic_colors = match self.local_diagnostic.diagnostic.severity {
546 DiagnosticSeverity::ERROR => DiagnosticColors {
547 background: status_colors.error_background,
548 border: status_colors.error_border,
549 },
550 DiagnosticSeverity::WARNING => DiagnosticColors {
551 background: status_colors.warning_background,
552 border: status_colors.warning_border,
553 },
554 DiagnosticSeverity::INFORMATION => DiagnosticColors {
555 background: status_colors.info_background,
556 border: status_colors.info_border,
557 },
558 DiagnosticSeverity::HINT => DiagnosticColors {
559 background: status_colors.hint_background,
560 border: status_colors.hint_border,
561 },
562 _ => DiagnosticColors {
563 background: status_colors.ignored_background,
564 border: status_colors.ignored_border,
565 },
566 };
567
568 div()
569 .id("diagnostic")
570 .elevation_2(cx)
571 .overflow_y_scroll()
572 .px_2()
573 .py_1()
574 .bg(diagnostic_colors.background)
575 .text_color(style.text.color)
576 .border_1()
577 .border_color(diagnostic_colors.border)
578 .rounded_md()
579 .max_w(max_size.width)
580 .max_h(max_size.height)
581 .cursor(CursorStyle::PointingHand)
582 .tooltip(move |cx| Tooltip::for_action("Go To Diagnostic", &crate::GoToDiagnostic, cx))
583 // Prevent a mouse move on the popover from being propagated to the editor,
584 // because that would dismiss the popover.
585 .on_mouse_move(|_, cx| cx.stop_propagation())
586 // Prevent a mouse down on the popover from being propagated to the editor,
587 // because that would move the cursor.
588 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
589 .on_click(cx.listener(|editor, _, cx| editor.go_to_diagnostic(&Default::default(), cx)))
590 .child(SharedString::from(text))
591 .into_any_element()
592 }
593
594 pub fn activation_info(&self) -> (usize, Anchor) {
595 let entry = self
596 .primary_diagnostic
597 .as_ref()
598 .unwrap_or(&self.local_diagnostic);
599
600 (entry.diagnostic.group_id, entry.range.start)
601 }
602}
603
604#[cfg(test)]
605mod tests {
606 use super::*;
607 use crate::{
608 editor_tests::init_test,
609 element::PointForPosition,
610 hover_links::update_inlay_link_and_hover_points,
611 inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
612 test::editor_lsp_test_context::EditorLspTestContext,
613 InlayId,
614 };
615 use collections::BTreeSet;
616 use gpui::{FontWeight, HighlightStyle, UnderlineStyle};
617 use indoc::indoc;
618 use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};
619 use lsp::LanguageServerId;
620 use project::{HoverBlock, HoverBlockKind};
621 use smol::stream::StreamExt;
622 use unindent::Unindent;
623 use util::test::marked_text_ranges;
624
625 #[gpui::test]
626 async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
627 init_test(cx, |_| {});
628
629 let mut cx = EditorLspTestContext::new_rust(
630 lsp::ServerCapabilities {
631 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
632 ..Default::default()
633 },
634 cx,
635 )
636 .await;
637
638 // Basic hover delays and then pops without moving the mouse
639 cx.set_state(indoc! {"
640 fn ˇtest() { println!(); }
641 "});
642 let hover_point = cx.display_point(indoc! {"
643 fn test() { printˇln!(); }
644 "});
645
646 cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
647 assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
648
649 // After delay, hover should be visible.
650 let symbol_range = cx.lsp_range(indoc! {"
651 fn test() { «println!»(); }
652 "});
653 let mut requests =
654 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
655 Ok(Some(lsp::Hover {
656 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
657 kind: lsp::MarkupKind::Markdown,
658 value: "some basic docs".to_string(),
659 }),
660 range: Some(symbol_range),
661 }))
662 });
663 cx.background_executor
664 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
665 requests.next().await;
666
667 cx.editor(|editor, _| {
668 assert!(editor.hover_state.visible());
669 assert_eq!(
670 editor.hover_state.info_popover.clone().unwrap().blocks,
671 vec![HoverBlock {
672 text: "some basic docs".to_string(),
673 kind: HoverBlockKind::Markdown,
674 },]
675 )
676 });
677
678 // Mouse moved with no hover response dismisses
679 let hover_point = cx.display_point(indoc! {"
680 fn teˇst() { println!(); }
681 "});
682 let mut request = cx
683 .lsp
684 .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
685 cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
686 cx.background_executor
687 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
688 request.next().await;
689 cx.editor(|editor, _| {
690 assert!(!editor.hover_state.visible());
691 });
692 }
693
694 #[gpui::test]
695 async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
696 init_test(cx, |_| {});
697
698 let mut cx = EditorLspTestContext::new_rust(
699 lsp::ServerCapabilities {
700 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
701 ..Default::default()
702 },
703 cx,
704 )
705 .await;
706
707 // Hover with keyboard has no delay
708 cx.set_state(indoc! {"
709 fˇn test() { println!(); }
710 "});
711 cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
712 let symbol_range = cx.lsp_range(indoc! {"
713 «fn» test() { println!(); }
714 "});
715 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
716 Ok(Some(lsp::Hover {
717 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
718 kind: lsp::MarkupKind::Markdown,
719 value: "some other basic docs".to_string(),
720 }),
721 range: Some(symbol_range),
722 }))
723 })
724 .next()
725 .await;
726
727 cx.condition(|editor, _| editor.hover_state.visible()).await;
728 cx.editor(|editor, _| {
729 assert_eq!(
730 editor.hover_state.info_popover.clone().unwrap().blocks,
731 vec![HoverBlock {
732 text: "some other basic docs".to_string(),
733 kind: HoverBlockKind::Markdown,
734 }]
735 )
736 });
737 }
738
739 #[gpui::test]
740 async fn test_empty_hovers_filtered(cx: &mut gpui::TestAppContext) {
741 init_test(cx, |_| {});
742
743 let mut cx = EditorLspTestContext::new_rust(
744 lsp::ServerCapabilities {
745 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
746 ..Default::default()
747 },
748 cx,
749 )
750 .await;
751
752 // Hover with keyboard has no delay
753 cx.set_state(indoc! {"
754 fˇn test() { println!(); }
755 "});
756 cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
757 let symbol_range = cx.lsp_range(indoc! {"
758 «fn» test() { println!(); }
759 "});
760 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
761 Ok(Some(lsp::Hover {
762 contents: lsp::HoverContents::Array(vec![
763 lsp::MarkedString::String("regular text for hover to show".to_string()),
764 lsp::MarkedString::String("".to_string()),
765 lsp::MarkedString::LanguageString(lsp::LanguageString {
766 language: "Rust".to_string(),
767 value: "".to_string(),
768 }),
769 ]),
770 range: Some(symbol_range),
771 }))
772 })
773 .next()
774 .await;
775
776 cx.condition(|editor, _| editor.hover_state.visible()).await;
777 cx.editor(|editor, _| {
778 assert_eq!(
779 editor.hover_state.info_popover.clone().unwrap().blocks,
780 vec![HoverBlock {
781 text: "regular text for hover to show".to_string(),
782 kind: HoverBlockKind::Markdown,
783 }],
784 "No empty string hovers should be shown"
785 );
786 });
787 }
788
789 #[gpui::test]
790 async fn test_line_ends_trimmed(cx: &mut gpui::TestAppContext) {
791 init_test(cx, |_| {});
792
793 let mut cx = EditorLspTestContext::new_rust(
794 lsp::ServerCapabilities {
795 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
796 ..Default::default()
797 },
798 cx,
799 )
800 .await;
801
802 // Hover with keyboard has no delay
803 cx.set_state(indoc! {"
804 fˇn test() { println!(); }
805 "});
806 cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
807 let symbol_range = cx.lsp_range(indoc! {"
808 «fn» test() { println!(); }
809 "});
810
811 let code_str = "\nlet hovered_point: Vector2F // size = 8, align = 0x4\n";
812 let markdown_string = format!("\n```rust\n{code_str}```");
813
814 let closure_markdown_string = markdown_string.clone();
815 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| {
816 let future_markdown_string = closure_markdown_string.clone();
817 async move {
818 Ok(Some(lsp::Hover {
819 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
820 kind: lsp::MarkupKind::Markdown,
821 value: future_markdown_string,
822 }),
823 range: Some(symbol_range),
824 }))
825 }
826 })
827 .next()
828 .await;
829
830 cx.condition(|editor, _| editor.hover_state.visible()).await;
831 cx.editor(|editor, _| {
832 let blocks = editor.hover_state.info_popover.clone().unwrap().blocks;
833 assert_eq!(
834 blocks,
835 vec![HoverBlock {
836 text: markdown_string,
837 kind: HoverBlockKind::Markdown,
838 }],
839 );
840
841 let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
842 assert_eq!(
843 rendered.text,
844 code_str.trim(),
845 "Should not have extra line breaks at end of rendered hover"
846 );
847 });
848 }
849
850 #[gpui::test]
851 async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
852 init_test(cx, |_| {});
853
854 let mut cx = EditorLspTestContext::new_rust(
855 lsp::ServerCapabilities {
856 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
857 ..Default::default()
858 },
859 cx,
860 )
861 .await;
862
863 // Hover with just diagnostic, pops DiagnosticPopover immediately and then
864 // info popover once request completes
865 cx.set_state(indoc! {"
866 fn teˇst() { println!(); }
867 "});
868
869 // Send diagnostic to client
870 let range = cx.text_anchor_range(indoc! {"
871 fn «test»() { println!(); }
872 "});
873 cx.update_buffer(|buffer, cx| {
874 let snapshot = buffer.text_snapshot();
875 let set = DiagnosticSet::from_sorted_entries(
876 vec![DiagnosticEntry {
877 range,
878 diagnostic: Diagnostic {
879 message: "A test diagnostic message.".to_string(),
880 ..Default::default()
881 },
882 }],
883 &snapshot,
884 );
885 buffer.update_diagnostics(LanguageServerId(0), set, cx);
886 });
887
888 // Hover pops diagnostic immediately
889 cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
890 cx.background_executor.run_until_parked();
891
892 cx.editor(|Editor { hover_state, .. }, _| {
893 assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
894 });
895
896 // Info Popover shows after request responded to
897 let range = cx.lsp_range(indoc! {"
898 fn «test»() { println!(); }
899 "});
900 cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
901 Ok(Some(lsp::Hover {
902 contents: lsp::HoverContents::Markup(lsp::MarkupContent {
903 kind: lsp::MarkupKind::Markdown,
904 value: "some new docs".to_string(),
905 }),
906 range: Some(range),
907 }))
908 });
909 cx.background_executor
910 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
911
912 cx.background_executor.run_until_parked();
913 cx.editor(|Editor { hover_state, .. }, _| {
914 hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
915 });
916 }
917
918 #[gpui::test]
919 fn test_render_blocks(cx: &mut gpui::TestAppContext) {
920 init_test(cx, |_| {});
921
922 let editor = cx.add_window(|cx| Editor::single_line(cx));
923 editor
924 .update(cx, |editor, _cx| {
925 let style = editor.style.clone().unwrap();
926
927 struct Row {
928 blocks: Vec<HoverBlock>,
929 expected_marked_text: String,
930 expected_styles: Vec<HighlightStyle>,
931 }
932
933 let rows = &[
934 // Strong emphasis
935 Row {
936 blocks: vec![HoverBlock {
937 text: "one **two** three".to_string(),
938 kind: HoverBlockKind::Markdown,
939 }],
940 expected_marked_text: "one «two» three".to_string(),
941 expected_styles: vec![HighlightStyle {
942 font_weight: Some(FontWeight::BOLD),
943 ..Default::default()
944 }],
945 },
946 // Links
947 Row {
948 blocks: vec three".to_string(),
950 kind: HoverBlockKind::Markdown,
951 }],
952 expected_marked_text: "one «two» three".to_string(),
953 expected_styles: vec![HighlightStyle {
954 underline: Some(UnderlineStyle {
955 thickness: 1.0.into(),
956 ..Default::default()
957 }),
958 ..Default::default()
959 }],
960 },
961 // Lists
962 Row {
963 blocks: vec
971 - d"
972 .unindent(),
973 kind: HoverBlockKind::Markdown,
974 }],
975 expected_marked_text: "
976 lists:
977 - one
978 - a
979 - b
980 - two
981 - «c»
982 - d"
983 .unindent(),
984 expected_styles: vec![HighlightStyle {
985 underline: Some(UnderlineStyle {
986 thickness: 1.0.into(),
987 ..Default::default()
988 }),
989 ..Default::default()
990 }],
991 },
992 // Multi-paragraph list items
993 Row {
994 blocks: vec![HoverBlock {
995 text: "
996 * one two
997 three
998
999 * four five
1000 * six seven
1001 eight
1002
1003 nine
1004 * ten
1005 * six"
1006 .unindent(),
1007 kind: HoverBlockKind::Markdown,
1008 }],
1009 expected_marked_text: "
1010 - one two three
1011 - four five
1012 - six seven eight
1013
1014 nine
1015 - ten
1016 - six"
1017 .unindent(),
1018 expected_styles: vec![HighlightStyle {
1019 underline: Some(UnderlineStyle {
1020 thickness: 1.0.into(),
1021 ..Default::default()
1022 }),
1023 ..Default::default()
1024 }],
1025 },
1026 ];
1027
1028 for Row {
1029 blocks,
1030 expected_marked_text,
1031 expected_styles,
1032 } in &rows[0..]
1033 {
1034 let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
1035
1036 let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);
1037 let expected_highlights = ranges
1038 .into_iter()
1039 .zip(expected_styles.iter().cloned())
1040 .collect::<Vec<_>>();
1041 assert_eq!(
1042 rendered.text, expected_text,
1043 "wrong text for input {blocks:?}"
1044 );
1045
1046 let rendered_highlights: Vec<_> = rendered
1047 .highlights
1048 .iter()
1049 .filter_map(|(range, highlight)| {
1050 let highlight = highlight.to_highlight_style(&style.syntax)?;
1051 Some((range.clone(), highlight))
1052 })
1053 .collect();
1054
1055 assert_eq!(
1056 rendered_highlights, expected_highlights,
1057 "wrong highlights for input {blocks:?}"
1058 );
1059 }
1060 })
1061 .unwrap();
1062 }
1063
1064 #[gpui::test]
1065 async fn test_hover_inlay_label_parts(cx: &mut gpui::TestAppContext) {
1066 init_test(cx, |settings| {
1067 settings.defaults.inlay_hints = Some(InlayHintSettings {
1068 enabled: true,
1069 edit_debounce_ms: 0,
1070 scroll_debounce_ms: 0,
1071 show_type_hints: true,
1072 show_parameter_hints: true,
1073 show_other_hints: true,
1074 })
1075 });
1076
1077 let mut cx = EditorLspTestContext::new_rust(
1078 lsp::ServerCapabilities {
1079 inlay_hint_provider: Some(lsp::OneOf::Right(
1080 lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
1081 resolve_provider: Some(true),
1082 ..Default::default()
1083 }),
1084 )),
1085 ..Default::default()
1086 },
1087 cx,
1088 )
1089 .await;
1090
1091 cx.set_state(indoc! {"
1092 struct TestStruct;
1093
1094 // ==================
1095
1096 struct TestNewType<T>(T);
1097
1098 fn main() {
1099 let variableˇ = TestNewType(TestStruct);
1100 }
1101 "});
1102
1103 let hint_start_offset = cx.ranges(indoc! {"
1104 struct TestStruct;
1105
1106 // ==================
1107
1108 struct TestNewType<T>(T);
1109
1110 fn main() {
1111 let variableˇ = TestNewType(TestStruct);
1112 }
1113 "})[0]
1114 .start;
1115 let hint_position = cx.to_lsp(hint_start_offset);
1116 let new_type_target_range = cx.lsp_range(indoc! {"
1117 struct TestStruct;
1118
1119 // ==================
1120
1121 struct «TestNewType»<T>(T);
1122
1123 fn main() {
1124 let variable = TestNewType(TestStruct);
1125 }
1126 "});
1127 let struct_target_range = cx.lsp_range(indoc! {"
1128 struct «TestStruct»;
1129
1130 // ==================
1131
1132 struct TestNewType<T>(T);
1133
1134 fn main() {
1135 let variable = TestNewType(TestStruct);
1136 }
1137 "});
1138
1139 let uri = cx.buffer_lsp_url.clone();
1140 let new_type_label = "TestNewType";
1141 let struct_label = "TestStruct";
1142 let entire_hint_label = ": TestNewType<TestStruct>";
1143 let closure_uri = uri.clone();
1144 cx.lsp
1145 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1146 let task_uri = closure_uri.clone();
1147 async move {
1148 assert_eq!(params.text_document.uri, task_uri);
1149 Ok(Some(vec![lsp::InlayHint {
1150 position: hint_position,
1151 label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1152 value: entire_hint_label.to_string(),
1153 ..Default::default()
1154 }]),
1155 kind: Some(lsp::InlayHintKind::TYPE),
1156 text_edits: None,
1157 tooltip: None,
1158 padding_left: Some(false),
1159 padding_right: Some(false),
1160 data: None,
1161 }]))
1162 }
1163 })
1164 .next()
1165 .await;
1166 cx.background_executor.run_until_parked();
1167 cx.update_editor(|editor, cx| {
1168 let expected_layers = vec![entire_hint_label.to_string()];
1169 assert_eq!(expected_layers, cached_hint_labels(editor));
1170 assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1171 });
1172
1173 let inlay_range = cx
1174 .ranges(indoc! {"
1175 struct TestStruct;
1176
1177 // ==================
1178
1179 struct TestNewType<T>(T);
1180
1181 fn main() {
1182 let variable« »= TestNewType(TestStruct);
1183 }
1184 "})
1185 .get(0)
1186 .cloned()
1187 .unwrap();
1188 let new_type_hint_part_hover_position = cx.update_editor(|editor, cx| {
1189 let snapshot = editor.snapshot(cx);
1190 let previous_valid = inlay_range.start.to_display_point(&snapshot);
1191 let next_valid = inlay_range.end.to_display_point(&snapshot);
1192 assert_eq!(previous_valid.row(), next_valid.row());
1193 assert!(previous_valid.column() < next_valid.column());
1194 let exact_unclipped = DisplayPoint::new(
1195 previous_valid.row(),
1196 previous_valid.column()
1197 + (entire_hint_label.find(new_type_label).unwrap() + new_type_label.len() / 2)
1198 as u32,
1199 );
1200 PointForPosition {
1201 previous_valid,
1202 next_valid,
1203 exact_unclipped,
1204 column_overshoot_after_line_end: 0,
1205 }
1206 });
1207 cx.update_editor(|editor, cx| {
1208 update_inlay_link_and_hover_points(
1209 &editor.snapshot(cx),
1210 new_type_hint_part_hover_position,
1211 editor,
1212 true,
1213 false,
1214 cx,
1215 );
1216 });
1217
1218 let resolve_closure_uri = uri.clone();
1219 cx.lsp
1220 .handle_request::<lsp::request::InlayHintResolveRequest, _, _>(
1221 move |mut hint_to_resolve, _| {
1222 let mut resolved_hint_positions = BTreeSet::new();
1223 let task_uri = resolve_closure_uri.clone();
1224 async move {
1225 let inserted = resolved_hint_positions.insert(hint_to_resolve.position);
1226 assert!(inserted, "Hint {hint_to_resolve:?} was resolved twice");
1227
1228 // `: TestNewType<TestStruct>`
1229 hint_to_resolve.label = lsp::InlayHintLabel::LabelParts(vec![
1230 lsp::InlayHintLabelPart {
1231 value: ": ".to_string(),
1232 ..Default::default()
1233 },
1234 lsp::InlayHintLabelPart {
1235 value: new_type_label.to_string(),
1236 location: Some(lsp::Location {
1237 uri: task_uri.clone(),
1238 range: new_type_target_range,
1239 }),
1240 tooltip: Some(lsp::InlayHintLabelPartTooltip::String(format!(
1241 "A tooltip for `{new_type_label}`"
1242 ))),
1243 ..Default::default()
1244 },
1245 lsp::InlayHintLabelPart {
1246 value: "<".to_string(),
1247 ..Default::default()
1248 },
1249 lsp::InlayHintLabelPart {
1250 value: struct_label.to_string(),
1251 location: Some(lsp::Location {
1252 uri: task_uri,
1253 range: struct_target_range,
1254 }),
1255 tooltip: Some(lsp::InlayHintLabelPartTooltip::MarkupContent(
1256 lsp::MarkupContent {
1257 kind: lsp::MarkupKind::Markdown,
1258 value: format!("A tooltip for `{struct_label}`"),
1259 },
1260 )),
1261 ..Default::default()
1262 },
1263 lsp::InlayHintLabelPart {
1264 value: ">".to_string(),
1265 ..Default::default()
1266 },
1267 ]);
1268
1269 Ok(hint_to_resolve)
1270 }
1271 },
1272 )
1273 .next()
1274 .await;
1275 cx.background_executor.run_until_parked();
1276
1277 cx.update_editor(|editor, cx| {
1278 update_inlay_link_and_hover_points(
1279 &editor.snapshot(cx),
1280 new_type_hint_part_hover_position,
1281 editor,
1282 true,
1283 false,
1284 cx,
1285 );
1286 });
1287 cx.background_executor
1288 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1289 cx.background_executor.run_until_parked();
1290 cx.update_editor(|editor, cx| {
1291 let hover_state = &editor.hover_state;
1292 assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1293 let popover = hover_state.info_popover.as_ref().unwrap();
1294 let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1295 assert_eq!(
1296 popover.symbol_range,
1297 RangeInEditor::Inlay(InlayHighlight {
1298 inlay: InlayId::Hint(0),
1299 inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1300 range: ": ".len()..": ".len() + new_type_label.len(),
1301 }),
1302 "Popover range should match the new type label part"
1303 );
1304 assert_eq!(
1305 popover.parsed_content.text,
1306 format!("A tooltip for `{new_type_label}`"),
1307 "Rendered text should not anyhow alter backticks"
1308 );
1309 });
1310
1311 let struct_hint_part_hover_position = cx.update_editor(|editor, cx| {
1312 let snapshot = editor.snapshot(cx);
1313 let previous_valid = inlay_range.start.to_display_point(&snapshot);
1314 let next_valid = inlay_range.end.to_display_point(&snapshot);
1315 assert_eq!(previous_valid.row(), next_valid.row());
1316 assert!(previous_valid.column() < next_valid.column());
1317 let exact_unclipped = DisplayPoint::new(
1318 previous_valid.row(),
1319 previous_valid.column()
1320 + (entire_hint_label.find(struct_label).unwrap() + struct_label.len() / 2)
1321 as u32,
1322 );
1323 PointForPosition {
1324 previous_valid,
1325 next_valid,
1326 exact_unclipped,
1327 column_overshoot_after_line_end: 0,
1328 }
1329 });
1330 cx.update_editor(|editor, cx| {
1331 update_inlay_link_and_hover_points(
1332 &editor.snapshot(cx),
1333 struct_hint_part_hover_position,
1334 editor,
1335 true,
1336 false,
1337 cx,
1338 );
1339 });
1340 cx.background_executor
1341 .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1342 cx.background_executor.run_until_parked();
1343 cx.update_editor(|editor, cx| {
1344 let hover_state = &editor.hover_state;
1345 assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1346 let popover = hover_state.info_popover.as_ref().unwrap();
1347 let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1348 assert_eq!(
1349 popover.symbol_range,
1350 RangeInEditor::Inlay(InlayHighlight {
1351 inlay: InlayId::Hint(0),
1352 inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1353 range: ": ".len() + new_type_label.len() + "<".len()
1354 ..": ".len() + new_type_label.len() + "<".len() + struct_label.len(),
1355 }),
1356 "Popover range should match the struct label part"
1357 );
1358 assert_eq!(
1359 popover.parsed_content.text,
1360 format!("A tooltip for {struct_label}"),
1361 "Rendered markdown element should remove backticks from text"
1362 );
1363 });
1364 }
1365}