hover_popover.rs

   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 = hover_result
 298                        .range
 299                        .and_then(|range| {
 300                            let start = snapshot
 301                                .buffer_snapshot
 302                                .anchor_in_excerpt(excerpt_id, range.start)?;
 303                            let end = snapshot
 304                                .buffer_snapshot
 305                                .anchor_in_excerpt(excerpt_id, range.end)?;
 306
 307                            Some(start..end)
 308                        })
 309                        .unwrap_or_else(|| anchor..anchor);
 310
 311                    let language_registry =
 312                        project.update(&mut cx, |p, _| p.languages().clone())?;
 313                    let blocks = hover_result.contents;
 314                    let language = hover_result.language;
 315                    let parsed_content = parse_blocks(&blocks, &language_registry, language).await;
 316
 317                    Some(InfoPopover {
 318                        project: project.clone(),
 319                        symbol_range: RangeInEditor::Text(range),
 320                        blocks,
 321                        parsed_content,
 322                    })
 323                }
 324
 325                _ => None,
 326            };
 327
 328            this.update(&mut cx, |this, cx| {
 329                if let Some(symbol_range) = hover_popover
 330                    .as_ref()
 331                    .and_then(|hover_popover| hover_popover.symbol_range.as_text_range())
 332                {
 333                    // Highlight the selected symbol using a background highlight
 334                    this.highlight_background::<HoverState>(
 335                        vec![symbol_range],
 336                        |theme| theme.element_hover, // todo update theme
 337                        cx,
 338                    );
 339                } else {
 340                    this.clear_background_highlights::<HoverState>(cx);
 341                }
 342
 343                this.hover_state.info_popover = hover_popover;
 344                cx.notify();
 345                cx.refresh();
 346            })?;
 347
 348            Ok::<_, anyhow::Error>(())
 349        }
 350        .log_err()
 351    });
 352
 353    editor.hover_state.info_task = Some(task);
 354}
 355
 356async fn parse_blocks(
 357    blocks: &[HoverBlock],
 358    language_registry: &Arc<LanguageRegistry>,
 359    language: Option<Arc<Language>>,
 360) -> markdown::ParsedMarkdown {
 361    let mut text = String::new();
 362    let mut highlights = Vec::new();
 363    let mut region_ranges = Vec::new();
 364    let mut regions = Vec::new();
 365
 366    for block in blocks {
 367        match &block.kind {
 368            HoverBlockKind::PlainText => {
 369                markdown::new_paragraph(&mut text, &mut Vec::new());
 370                text.push_str(&block.text);
 371            }
 372
 373            HoverBlockKind::Markdown => {
 374                markdown::parse_markdown_block(
 375                    &block.text,
 376                    language_registry,
 377                    language.clone(),
 378                    &mut text,
 379                    &mut highlights,
 380                    &mut region_ranges,
 381                    &mut regions,
 382                )
 383                .await
 384            }
 385
 386            HoverBlockKind::Code { language } => {
 387                if let Some(language) = language_registry
 388                    .language_for_name(language)
 389                    .now_or_never()
 390                    .and_then(Result::ok)
 391                {
 392                    markdown::highlight_code(&mut text, &mut highlights, &block.text, &language);
 393                } else {
 394                    text.push_str(&block.text);
 395                }
 396            }
 397        }
 398    }
 399
 400    let leading_space = text.chars().take_while(|c| c.is_whitespace()).count();
 401    if leading_space > 0 {
 402        highlights = highlights
 403            .into_iter()
 404            .map(|(range, style)| {
 405                (
 406                    range.start.saturating_sub(leading_space)
 407                        ..range.end.saturating_sub(leading_space),
 408                    style,
 409                )
 410            })
 411            .collect();
 412        region_ranges = region_ranges
 413            .into_iter()
 414            .map(|range| {
 415                range.start.saturating_sub(leading_space)..range.end.saturating_sub(leading_space)
 416            })
 417            .collect();
 418    }
 419
 420    ParsedMarkdown {
 421        text: text.trim().to_string(),
 422        highlights,
 423        region_ranges,
 424        regions,
 425    }
 426}
 427
 428#[derive(Default)]
 429pub struct HoverState {
 430    pub info_popover: Option<InfoPopover>,
 431    pub diagnostic_popover: Option<DiagnosticPopover>,
 432    pub triggered_from: Option<Anchor>,
 433    pub info_task: Option<Task<Option<()>>>,
 434}
 435
 436impl HoverState {
 437    pub fn visible(&self) -> bool {
 438        self.info_popover.is_some() || self.diagnostic_popover.is_some()
 439    }
 440
 441    pub fn render(
 442        &mut self,
 443        snapshot: &EditorSnapshot,
 444        style: &EditorStyle,
 445        visible_rows: Range<u32>,
 446        max_size: Size<Pixels>,
 447        workspace: Option<WeakView<Workspace>>,
 448        cx: &mut ViewContext<Editor>,
 449    ) -> Option<(DisplayPoint, Vec<AnyElement>)> {
 450        // If there is a diagnostic, position the popovers based on that.
 451        // Otherwise use the start of the hover range
 452        let anchor = self
 453            .diagnostic_popover
 454            .as_ref()
 455            .map(|diagnostic_popover| &diagnostic_popover.local_diagnostic.range.start)
 456            .or_else(|| {
 457                self.info_popover
 458                    .as_ref()
 459                    .map(|info_popover| match &info_popover.symbol_range {
 460                        RangeInEditor::Text(range) => &range.start,
 461                        RangeInEditor::Inlay(range) => &range.inlay_position,
 462                    })
 463            })?;
 464        let point = anchor.to_display_point(&snapshot.display_snapshot);
 465
 466        // Don't render if the relevant point isn't on screen
 467        if !self.visible() || !visible_rows.contains(&point.row()) {
 468            return None;
 469        }
 470
 471        let mut elements = Vec::new();
 472
 473        if let Some(diagnostic_popover) = self.diagnostic_popover.as_ref() {
 474            elements.push(diagnostic_popover.render(style, max_size, cx));
 475        }
 476        if let Some(info_popover) = self.info_popover.as_mut() {
 477            elements.push(info_popover.render(style, max_size, workspace, cx));
 478        }
 479
 480        Some((point, elements))
 481    }
 482}
 483
 484#[derive(Debug, Clone)]
 485pub struct InfoPopover {
 486    pub project: Model<Project>,
 487    symbol_range: RangeInEditor,
 488    pub blocks: Vec<HoverBlock>,
 489    parsed_content: ParsedMarkdown,
 490}
 491
 492impl InfoPopover {
 493    pub fn render(
 494        &mut self,
 495        style: &EditorStyle,
 496        max_size: Size<Pixels>,
 497        workspace: Option<WeakView<Workspace>>,
 498        cx: &mut ViewContext<Editor>,
 499    ) -> AnyElement {
 500        div()
 501            .id("info_popover")
 502            .elevation_2(cx)
 503            .p_2()
 504            .overflow_y_scroll()
 505            .max_w(max_size.width)
 506            .max_h(max_size.height)
 507            // Prevent a mouse move on the popover from being propagated to the editor,
 508            // because that would dismiss the popover.
 509            .on_mouse_move(|_, cx| cx.stop_propagation())
 510            .child(crate::render_parsed_markdown(
 511                "content",
 512                &self.parsed_content,
 513                style,
 514                workspace,
 515                cx,
 516            ))
 517            .into_any_element()
 518    }
 519}
 520
 521#[derive(Debug, Clone)]
 522pub struct DiagnosticPopover {
 523    local_diagnostic: DiagnosticEntry<Anchor>,
 524    primary_diagnostic: Option<DiagnosticEntry<Anchor>>,
 525}
 526
 527impl DiagnosticPopover {
 528    pub fn render(
 529        &self,
 530        style: &EditorStyle,
 531        max_size: Size<Pixels>,
 532        cx: &mut ViewContext<Editor>,
 533    ) -> AnyElement {
 534        let text = match &self.local_diagnostic.diagnostic.source {
 535            Some(source) => format!("{source}: {}", self.local_diagnostic.diagnostic.message),
 536            None => self.local_diagnostic.diagnostic.message.clone(),
 537        };
 538
 539        let status_colors = cx.theme().status();
 540
 541        struct DiagnosticColors {
 542            pub background: Hsla,
 543            pub border: Hsla,
 544        }
 545
 546        let diagnostic_colors = match self.local_diagnostic.diagnostic.severity {
 547            DiagnosticSeverity::ERROR => DiagnosticColors {
 548                background: status_colors.error_background,
 549                border: status_colors.error_border,
 550            },
 551            DiagnosticSeverity::WARNING => DiagnosticColors {
 552                background: status_colors.warning_background,
 553                border: status_colors.warning_border,
 554            },
 555            DiagnosticSeverity::INFORMATION => DiagnosticColors {
 556                background: status_colors.info_background,
 557                border: status_colors.info_border,
 558            },
 559            DiagnosticSeverity::HINT => DiagnosticColors {
 560                background: status_colors.hint_background,
 561                border: status_colors.hint_border,
 562            },
 563            _ => DiagnosticColors {
 564                background: status_colors.ignored_background,
 565                border: status_colors.ignored_border,
 566            },
 567        };
 568
 569        div()
 570            .id("diagnostic")
 571            .elevation_2(cx)
 572            .overflow_y_scroll()
 573            .px_2()
 574            .py_1()
 575            .bg(diagnostic_colors.background)
 576            .text_color(style.text.color)
 577            .border_1()
 578            .border_color(diagnostic_colors.border)
 579            .rounded_md()
 580            .max_w(max_size.width)
 581            .max_h(max_size.height)
 582            .cursor(CursorStyle::PointingHand)
 583            .tooltip(move |cx| Tooltip::for_action("Go To Diagnostic", &crate::GoToDiagnostic, cx))
 584            // Prevent a mouse move on the popover from being propagated to the editor,
 585            // because that would dismiss the popover.
 586            .on_mouse_move(|_, cx| cx.stop_propagation())
 587            // Prevent a mouse down on the popover from being propagated to the editor,
 588            // because that would move the cursor.
 589            .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 590            .on_click(cx.listener(|editor, _, cx| editor.go_to_diagnostic(&Default::default(), cx)))
 591            .child(SharedString::from(text))
 592            .into_any_element()
 593    }
 594
 595    pub fn activation_info(&self) -> (usize, Anchor) {
 596        let entry = self
 597            .primary_diagnostic
 598            .as_ref()
 599            .unwrap_or(&self.local_diagnostic);
 600
 601        (entry.diagnostic.group_id, entry.range.start)
 602    }
 603}
 604
 605#[cfg(test)]
 606mod tests {
 607    use super::*;
 608    use crate::{
 609        editor_tests::init_test,
 610        element::PointForPosition,
 611        hover_links::update_inlay_link_and_hover_points,
 612        inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
 613        test::editor_lsp_test_context::EditorLspTestContext,
 614        InlayId,
 615    };
 616    use collections::BTreeSet;
 617    use gpui::{FontWeight, HighlightStyle, UnderlineStyle};
 618    use indoc::indoc;
 619    use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};
 620    use lsp::LanguageServerId;
 621    use project::{HoverBlock, HoverBlockKind};
 622    use smol::stream::StreamExt;
 623    use unindent::Unindent;
 624    use util::test::marked_text_ranges;
 625
 626    #[gpui::test]
 627    async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
 628        init_test(cx, |_| {});
 629
 630        let mut cx = EditorLspTestContext::new_rust(
 631            lsp::ServerCapabilities {
 632                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 633                ..Default::default()
 634            },
 635            cx,
 636        )
 637        .await;
 638
 639        // Basic hover delays and then pops without moving the mouse
 640        cx.set_state(indoc! {"
 641            fn ˇtest() { println!(); }
 642        "});
 643        let hover_point = cx.display_point(indoc! {"
 644            fn test() { printˇln!(); }
 645        "});
 646
 647        cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
 648        assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
 649
 650        // After delay, hover should be visible.
 651        let symbol_range = cx.lsp_range(indoc! {"
 652            fn test() { «println!»(); }
 653        "});
 654        let mut requests =
 655            cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
 656                Ok(Some(lsp::Hover {
 657                    contents: lsp::HoverContents::Markup(lsp::MarkupContent {
 658                        kind: lsp::MarkupKind::Markdown,
 659                        value: "some basic docs".to_string(),
 660                    }),
 661                    range: Some(symbol_range),
 662                }))
 663            });
 664        cx.background_executor
 665            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
 666        requests.next().await;
 667
 668        cx.editor(|editor, _| {
 669            assert!(editor.hover_state.visible());
 670            assert_eq!(
 671                editor.hover_state.info_popover.clone().unwrap().blocks,
 672                vec![HoverBlock {
 673                    text: "some basic docs".to_string(),
 674                    kind: HoverBlockKind::Markdown,
 675                },]
 676            )
 677        });
 678
 679        // Mouse moved with no hover response dismisses
 680        let hover_point = cx.display_point(indoc! {"
 681            fn teˇst() { println!(); }
 682        "});
 683        let mut request = cx
 684            .lsp
 685            .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
 686        cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
 687        cx.background_executor
 688            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
 689        request.next().await;
 690        cx.editor(|editor, _| {
 691            assert!(!editor.hover_state.visible());
 692        });
 693    }
 694
 695    #[gpui::test]
 696    async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
 697        init_test(cx, |_| {});
 698
 699        let mut cx = EditorLspTestContext::new_rust(
 700            lsp::ServerCapabilities {
 701                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 702                ..Default::default()
 703            },
 704            cx,
 705        )
 706        .await;
 707
 708        // Hover with keyboard has no delay
 709        cx.set_state(indoc! {"
 710            fˇn test() { println!(); }
 711        "});
 712        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
 713        let symbol_range = cx.lsp_range(indoc! {"
 714            «fn» test() { println!(); }
 715        "});
 716        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
 717            Ok(Some(lsp::Hover {
 718                contents: lsp::HoverContents::Markup(lsp::MarkupContent {
 719                    kind: lsp::MarkupKind::Markdown,
 720                    value: "some other basic docs".to_string(),
 721                }),
 722                range: Some(symbol_range),
 723            }))
 724        })
 725        .next()
 726        .await;
 727
 728        cx.condition(|editor, _| editor.hover_state.visible()).await;
 729        cx.editor(|editor, _| {
 730            assert_eq!(
 731                editor.hover_state.info_popover.clone().unwrap().blocks,
 732                vec![HoverBlock {
 733                    text: "some other basic docs".to_string(),
 734                    kind: HoverBlockKind::Markdown,
 735                }]
 736            )
 737        });
 738    }
 739
 740    #[gpui::test]
 741    async fn test_empty_hovers_filtered(cx: &mut gpui::TestAppContext) {
 742        init_test(cx, |_| {});
 743
 744        let mut cx = EditorLspTestContext::new_rust(
 745            lsp::ServerCapabilities {
 746                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 747                ..Default::default()
 748            },
 749            cx,
 750        )
 751        .await;
 752
 753        // Hover with keyboard has no delay
 754        cx.set_state(indoc! {"
 755            fˇn test() { println!(); }
 756        "});
 757        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
 758        let symbol_range = cx.lsp_range(indoc! {"
 759            «fn» test() { println!(); }
 760        "});
 761        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
 762            Ok(Some(lsp::Hover {
 763                contents: lsp::HoverContents::Array(vec![
 764                    lsp::MarkedString::String("regular text for hover to show".to_string()),
 765                    lsp::MarkedString::String("".to_string()),
 766                    lsp::MarkedString::LanguageString(lsp::LanguageString {
 767                        language: "Rust".to_string(),
 768                        value: "".to_string(),
 769                    }),
 770                ]),
 771                range: Some(symbol_range),
 772            }))
 773        })
 774        .next()
 775        .await;
 776
 777        cx.condition(|editor, _| editor.hover_state.visible()).await;
 778        cx.editor(|editor, _| {
 779            assert_eq!(
 780                editor.hover_state.info_popover.clone().unwrap().blocks,
 781                vec![HoverBlock {
 782                    text: "regular text for hover to show".to_string(),
 783                    kind: HoverBlockKind::Markdown,
 784                }],
 785                "No empty string hovers should be shown"
 786            );
 787        });
 788    }
 789
 790    #[gpui::test]
 791    async fn test_line_ends_trimmed(cx: &mut gpui::TestAppContext) {
 792        init_test(cx, |_| {});
 793
 794        let mut cx = EditorLspTestContext::new_rust(
 795            lsp::ServerCapabilities {
 796                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 797                ..Default::default()
 798            },
 799            cx,
 800        )
 801        .await;
 802
 803        // Hover with keyboard has no delay
 804        cx.set_state(indoc! {"
 805            fˇn test() { println!(); }
 806        "});
 807        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
 808        let symbol_range = cx.lsp_range(indoc! {"
 809            «fn» test() { println!(); }
 810        "});
 811
 812        let code_str = "\nlet hovered_point: Vector2F // size = 8, align = 0x4\n";
 813        let markdown_string = format!("\n```rust\n{code_str}```");
 814
 815        let closure_markdown_string = markdown_string.clone();
 816        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| {
 817            let future_markdown_string = closure_markdown_string.clone();
 818            async move {
 819                Ok(Some(lsp::Hover {
 820                    contents: lsp::HoverContents::Markup(lsp::MarkupContent {
 821                        kind: lsp::MarkupKind::Markdown,
 822                        value: future_markdown_string,
 823                    }),
 824                    range: Some(symbol_range),
 825                }))
 826            }
 827        })
 828        .next()
 829        .await;
 830
 831        cx.condition(|editor, _| editor.hover_state.visible()).await;
 832        cx.editor(|editor, _| {
 833            let blocks = editor.hover_state.info_popover.clone().unwrap().blocks;
 834            assert_eq!(
 835                blocks,
 836                vec![HoverBlock {
 837                    text: markdown_string,
 838                    kind: HoverBlockKind::Markdown,
 839                }],
 840            );
 841
 842            let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
 843            assert_eq!(
 844                rendered.text,
 845                code_str.trim(),
 846                "Should not have extra line breaks at end of rendered hover"
 847            );
 848        });
 849    }
 850
 851    #[gpui::test]
 852    async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
 853        init_test(cx, |_| {});
 854
 855        let mut cx = EditorLspTestContext::new_rust(
 856            lsp::ServerCapabilities {
 857                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 858                ..Default::default()
 859            },
 860            cx,
 861        )
 862        .await;
 863
 864        // Hover with just diagnostic, pops DiagnosticPopover immediately and then
 865        // info popover once request completes
 866        cx.set_state(indoc! {"
 867            fn teˇst() { println!(); }
 868        "});
 869
 870        // Send diagnostic to client
 871        let range = cx.text_anchor_range(indoc! {"
 872            fn «test»() { println!(); }
 873        "});
 874        cx.update_buffer(|buffer, cx| {
 875            let snapshot = buffer.text_snapshot();
 876            let set = DiagnosticSet::from_sorted_entries(
 877                vec![DiagnosticEntry {
 878                    range,
 879                    diagnostic: Diagnostic {
 880                        message: "A test diagnostic message.".to_string(),
 881                        ..Default::default()
 882                    },
 883                }],
 884                &snapshot,
 885            );
 886            buffer.update_diagnostics(LanguageServerId(0), set, cx);
 887        });
 888
 889        // Hover pops diagnostic immediately
 890        cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
 891        cx.background_executor.run_until_parked();
 892
 893        cx.editor(|Editor { hover_state, .. }, _| {
 894            assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
 895        });
 896
 897        // Info Popover shows after request responded to
 898        let range = cx.lsp_range(indoc! {"
 899            fn «test»() { println!(); }
 900        "});
 901        cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
 902            Ok(Some(lsp::Hover {
 903                contents: lsp::HoverContents::Markup(lsp::MarkupContent {
 904                    kind: lsp::MarkupKind::Markdown,
 905                    value: "some new docs".to_string(),
 906                }),
 907                range: Some(range),
 908            }))
 909        });
 910        cx.background_executor
 911            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
 912
 913        cx.background_executor.run_until_parked();
 914        cx.editor(|Editor { hover_state, .. }, _| {
 915            hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
 916        });
 917    }
 918
 919    #[gpui::test]
 920    fn test_render_blocks(cx: &mut gpui::TestAppContext) {
 921        init_test(cx, |_| {});
 922
 923        let editor = cx.add_window(|cx| Editor::single_line(cx));
 924        editor
 925            .update(cx, |editor, _cx| {
 926                let style = editor.style.clone().unwrap();
 927
 928                struct Row {
 929                    blocks: Vec<HoverBlock>,
 930                    expected_marked_text: String,
 931                    expected_styles: Vec<HighlightStyle>,
 932                }
 933
 934                let rows = &[
 935                    // Strong emphasis
 936                    Row {
 937                        blocks: vec![HoverBlock {
 938                            text: "one **two** three".to_string(),
 939                            kind: HoverBlockKind::Markdown,
 940                        }],
 941                        expected_marked_text: "one «two» three".to_string(),
 942                        expected_styles: vec![HighlightStyle {
 943                            font_weight: Some(FontWeight::BOLD),
 944                            ..Default::default()
 945                        }],
 946                    },
 947                    // Links
 948                    Row {
 949                        blocks: vec![HoverBlock {
 950                            text: "one [two](https://the-url) three".to_string(),
 951                            kind: HoverBlockKind::Markdown,
 952                        }],
 953                        expected_marked_text: "one «two» three".to_string(),
 954                        expected_styles: vec![HighlightStyle {
 955                            underline: Some(UnderlineStyle {
 956                                thickness: 1.0.into(),
 957                                ..Default::default()
 958                            }),
 959                            ..Default::default()
 960                        }],
 961                    },
 962                    // Lists
 963                    Row {
 964                        blocks: vec![HoverBlock {
 965                            text: "
 966                            lists:
 967                            * one
 968                                - a
 969                                - b
 970                            * two
 971                                - [c](https://the-url)
 972                                - d"
 973                            .unindent(),
 974                            kind: HoverBlockKind::Markdown,
 975                        }],
 976                        expected_marked_text: "
 977                        lists:
 978                        - one
 979                          - a
 980                          - b
 981                        - two
 982                          - «c»
 983                          - d"
 984                        .unindent(),
 985                        expected_styles: vec![HighlightStyle {
 986                            underline: Some(UnderlineStyle {
 987                                thickness: 1.0.into(),
 988                                ..Default::default()
 989                            }),
 990                            ..Default::default()
 991                        }],
 992                    },
 993                    // Multi-paragraph list items
 994                    Row {
 995                        blocks: vec![HoverBlock {
 996                            text: "
 997                            * one two
 998                              three
 999
1000                            * four five
1001                                * six seven
1002                                  eight
1003
1004                                  nine
1005                                * ten
1006                            * six"
1007                                .unindent(),
1008                            kind: HoverBlockKind::Markdown,
1009                        }],
1010                        expected_marked_text: "
1011                        - one two three
1012                        - four five
1013                          - six seven eight
1014
1015                            nine
1016                          - ten
1017                        - six"
1018                            .unindent(),
1019                        expected_styles: vec![HighlightStyle {
1020                            underline: Some(UnderlineStyle {
1021                                thickness: 1.0.into(),
1022                                ..Default::default()
1023                            }),
1024                            ..Default::default()
1025                        }],
1026                    },
1027                ];
1028
1029                for Row {
1030                    blocks,
1031                    expected_marked_text,
1032                    expected_styles,
1033                } in &rows[0..]
1034                {
1035                    let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
1036
1037                    let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);
1038                    let expected_highlights = ranges
1039                        .into_iter()
1040                        .zip(expected_styles.iter().cloned())
1041                        .collect::<Vec<_>>();
1042                    assert_eq!(
1043                        rendered.text, expected_text,
1044                        "wrong text for input {blocks:?}"
1045                    );
1046
1047                    let rendered_highlights: Vec<_> = rendered
1048                        .highlights
1049                        .iter()
1050                        .filter_map(|(range, highlight)| {
1051                            let highlight = highlight.to_highlight_style(&style.syntax)?;
1052                            Some((range.clone(), highlight))
1053                        })
1054                        .collect();
1055
1056                    assert_eq!(
1057                        rendered_highlights, expected_highlights,
1058                        "wrong highlights for input {blocks:?}"
1059                    );
1060                }
1061            })
1062            .unwrap();
1063    }
1064
1065    #[gpui::test]
1066    async fn test_hover_inlay_label_parts(cx: &mut gpui::TestAppContext) {
1067        init_test(cx, |settings| {
1068            settings.defaults.inlay_hints = Some(InlayHintSettings {
1069                enabled: true,
1070                edit_debounce_ms: 0,
1071                scroll_debounce_ms: 0,
1072                show_type_hints: true,
1073                show_parameter_hints: true,
1074                show_other_hints: true,
1075            })
1076        });
1077
1078        let mut cx = EditorLspTestContext::new_rust(
1079            lsp::ServerCapabilities {
1080                inlay_hint_provider: Some(lsp::OneOf::Right(
1081                    lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
1082                        resolve_provider: Some(true),
1083                        ..Default::default()
1084                    }),
1085                )),
1086                ..Default::default()
1087            },
1088            cx,
1089        )
1090        .await;
1091
1092        cx.set_state(indoc! {"
1093            struct TestStruct;
1094
1095            // ==================
1096
1097            struct TestNewType<T>(T);
1098
1099            fn main() {
1100                let variableˇ = TestNewType(TestStruct);
1101            }
1102        "});
1103
1104        let hint_start_offset = cx.ranges(indoc! {"
1105            struct TestStruct;
1106
1107            // ==================
1108
1109            struct TestNewType<T>(T);
1110
1111            fn main() {
1112                let variableˇ = TestNewType(TestStruct);
1113            }
1114        "})[0]
1115            .start;
1116        let hint_position = cx.to_lsp(hint_start_offset);
1117        let new_type_target_range = cx.lsp_range(indoc! {"
1118            struct TestStruct;
1119
1120            // ==================
1121
1122            struct «TestNewType»<T>(T);
1123
1124            fn main() {
1125                let variable = TestNewType(TestStruct);
1126            }
1127        "});
1128        let struct_target_range = cx.lsp_range(indoc! {"
1129            struct «TestStruct»;
1130
1131            // ==================
1132
1133            struct TestNewType<T>(T);
1134
1135            fn main() {
1136                let variable = TestNewType(TestStruct);
1137            }
1138        "});
1139
1140        let uri = cx.buffer_lsp_url.clone();
1141        let new_type_label = "TestNewType";
1142        let struct_label = "TestStruct";
1143        let entire_hint_label = ": TestNewType<TestStruct>";
1144        let closure_uri = uri.clone();
1145        cx.lsp
1146            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1147                let task_uri = closure_uri.clone();
1148                async move {
1149                    assert_eq!(params.text_document.uri, task_uri);
1150                    Ok(Some(vec![lsp::InlayHint {
1151                        position: hint_position,
1152                        label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1153                            value: entire_hint_label.to_string(),
1154                            ..Default::default()
1155                        }]),
1156                        kind: Some(lsp::InlayHintKind::TYPE),
1157                        text_edits: None,
1158                        tooltip: None,
1159                        padding_left: Some(false),
1160                        padding_right: Some(false),
1161                        data: None,
1162                    }]))
1163                }
1164            })
1165            .next()
1166            .await;
1167        cx.background_executor.run_until_parked();
1168        cx.update_editor(|editor, cx| {
1169            let expected_layers = vec![entire_hint_label.to_string()];
1170            assert_eq!(expected_layers, cached_hint_labels(editor));
1171            assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1172        });
1173
1174        let inlay_range = cx
1175            .ranges(indoc! {"
1176                struct TestStruct;
1177
1178                // ==================
1179
1180                struct TestNewType<T>(T);
1181
1182                fn main() {
1183                    let variable« »= TestNewType(TestStruct);
1184                }
1185        "})
1186            .get(0)
1187            .cloned()
1188            .unwrap();
1189        let new_type_hint_part_hover_position = cx.update_editor(|editor, cx| {
1190            let snapshot = editor.snapshot(cx);
1191            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1192            let next_valid = inlay_range.end.to_display_point(&snapshot);
1193            assert_eq!(previous_valid.row(), next_valid.row());
1194            assert!(previous_valid.column() < next_valid.column());
1195            let exact_unclipped = DisplayPoint::new(
1196                previous_valid.row(),
1197                previous_valid.column()
1198                    + (entire_hint_label.find(new_type_label).unwrap() + new_type_label.len() / 2)
1199                        as u32,
1200            );
1201            PointForPosition {
1202                previous_valid,
1203                next_valid,
1204                exact_unclipped,
1205                column_overshoot_after_line_end: 0,
1206            }
1207        });
1208        cx.update_editor(|editor, cx| {
1209            update_inlay_link_and_hover_points(
1210                &editor.snapshot(cx),
1211                new_type_hint_part_hover_position,
1212                editor,
1213                true,
1214                false,
1215                cx,
1216            );
1217        });
1218
1219        let resolve_closure_uri = uri.clone();
1220        cx.lsp
1221            .handle_request::<lsp::request::InlayHintResolveRequest, _, _>(
1222                move |mut hint_to_resolve, _| {
1223                    let mut resolved_hint_positions = BTreeSet::new();
1224                    let task_uri = resolve_closure_uri.clone();
1225                    async move {
1226                        let inserted = resolved_hint_positions.insert(hint_to_resolve.position);
1227                        assert!(inserted, "Hint {hint_to_resolve:?} was resolved twice");
1228
1229                        // `: TestNewType<TestStruct>`
1230                        hint_to_resolve.label = lsp::InlayHintLabel::LabelParts(vec![
1231                            lsp::InlayHintLabelPart {
1232                                value: ": ".to_string(),
1233                                ..Default::default()
1234                            },
1235                            lsp::InlayHintLabelPart {
1236                                value: new_type_label.to_string(),
1237                                location: Some(lsp::Location {
1238                                    uri: task_uri.clone(),
1239                                    range: new_type_target_range,
1240                                }),
1241                                tooltip: Some(lsp::InlayHintLabelPartTooltip::String(format!(
1242                                    "A tooltip for `{new_type_label}`"
1243                                ))),
1244                                ..Default::default()
1245                            },
1246                            lsp::InlayHintLabelPart {
1247                                value: "<".to_string(),
1248                                ..Default::default()
1249                            },
1250                            lsp::InlayHintLabelPart {
1251                                value: struct_label.to_string(),
1252                                location: Some(lsp::Location {
1253                                    uri: task_uri,
1254                                    range: struct_target_range,
1255                                }),
1256                                tooltip: Some(lsp::InlayHintLabelPartTooltip::MarkupContent(
1257                                    lsp::MarkupContent {
1258                                        kind: lsp::MarkupKind::Markdown,
1259                                        value: format!("A tooltip for `{struct_label}`"),
1260                                    },
1261                                )),
1262                                ..Default::default()
1263                            },
1264                            lsp::InlayHintLabelPart {
1265                                value: ">".to_string(),
1266                                ..Default::default()
1267                            },
1268                        ]);
1269
1270                        Ok(hint_to_resolve)
1271                    }
1272                },
1273            )
1274            .next()
1275            .await;
1276        cx.background_executor.run_until_parked();
1277
1278        cx.update_editor(|editor, cx| {
1279            update_inlay_link_and_hover_points(
1280                &editor.snapshot(cx),
1281                new_type_hint_part_hover_position,
1282                editor,
1283                true,
1284                false,
1285                cx,
1286            );
1287        });
1288        cx.background_executor
1289            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1290        cx.background_executor.run_until_parked();
1291        cx.update_editor(|editor, cx| {
1292            let hover_state = &editor.hover_state;
1293            assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1294            let popover = hover_state.info_popover.as_ref().unwrap();
1295            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1296            assert_eq!(
1297                popover.symbol_range,
1298                RangeInEditor::Inlay(InlayHighlight {
1299                    inlay: InlayId::Hint(0),
1300                    inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1301                    range: ": ".len()..": ".len() + new_type_label.len(),
1302                }),
1303                "Popover range should match the new type label part"
1304            );
1305            assert_eq!(
1306                popover.parsed_content.text,
1307                format!("A tooltip for `{new_type_label}`"),
1308                "Rendered text should not anyhow alter backticks"
1309            );
1310        });
1311
1312        let struct_hint_part_hover_position = cx.update_editor(|editor, cx| {
1313            let snapshot = editor.snapshot(cx);
1314            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1315            let next_valid = inlay_range.end.to_display_point(&snapshot);
1316            assert_eq!(previous_valid.row(), next_valid.row());
1317            assert!(previous_valid.column() < next_valid.column());
1318            let exact_unclipped = DisplayPoint::new(
1319                previous_valid.row(),
1320                previous_valid.column()
1321                    + (entire_hint_label.find(struct_label).unwrap() + struct_label.len() / 2)
1322                        as u32,
1323            );
1324            PointForPosition {
1325                previous_valid,
1326                next_valid,
1327                exact_unclipped,
1328                column_overshoot_after_line_end: 0,
1329            }
1330        });
1331        cx.update_editor(|editor, cx| {
1332            update_inlay_link_and_hover_points(
1333                &editor.snapshot(cx),
1334                struct_hint_part_hover_position,
1335                editor,
1336                true,
1337                false,
1338                cx,
1339            );
1340        });
1341        cx.background_executor
1342            .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1343        cx.background_executor.run_until_parked();
1344        cx.update_editor(|editor, cx| {
1345            let hover_state = &editor.hover_state;
1346            assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1347            let popover = hover_state.info_popover.as_ref().unwrap();
1348            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1349            assert_eq!(
1350                popover.symbol_range,
1351                RangeInEditor::Inlay(InlayHighlight {
1352                    inlay: InlayId::Hint(0),
1353                    inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1354                    range: ": ".len() + new_type_label.len() + "<".len()
1355                        ..": ".len() + new_type_label.len() + "<".len() + struct_label.len(),
1356                }),
1357                "Popover range should match the struct label part"
1358            );
1359            assert_eq!(
1360                popover.parsed_content.text,
1361                format!("A tooltip for {struct_label}"),
1362                "Rendered markdown element should remove backticks from text"
1363            );
1364        });
1365    }
1366}