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