hover_links.rs

   1use crate::{
   2    element::PointForPosition,
   3    hover_popover::{self, InlayHover},
   4    Anchor, Editor, EditorSnapshot, GoToDefinition, GoToTypeDefinition, InlayId, SelectPhase,
   5};
   6use gpui::{px, AsyncWindowContext, Model, Modifiers, Task, ViewContext};
   7use language::{Bias, ToOffset};
   8use linkify::{LinkFinder, LinkKind};
   9use lsp::LanguageServerId;
  10use project::{
  11    HoverBlock, HoverBlockKind, InlayHintLabelPartTooltip, InlayHintTooltip, LocationLink,
  12    ResolveState,
  13};
  14use std::ops::Range;
  15use theme::ActiveTheme as _;
  16use util::TryFutureExt;
  17
  18#[derive(Debug)]
  19pub struct HoveredLinkState {
  20    pub last_trigger_point: TriggerPoint,
  21    pub preferred_kind: LinkDefinitionKind,
  22    pub symbol_range: Option<RangeInEditor>,
  23    pub links: Vec<HoverLink>,
  24    pub task: Option<Task<Option<()>>>,
  25}
  26
  27#[derive(Debug, Eq, PartialEq, Clone)]
  28pub enum RangeInEditor {
  29    Text(Range<Anchor>),
  30    Inlay(InlayHighlight),
  31}
  32
  33impl RangeInEditor {
  34    pub fn as_text_range(&self) -> Option<Range<Anchor>> {
  35        match self {
  36            Self::Text(range) => Some(range.clone()),
  37            Self::Inlay(_) => None,
  38        }
  39    }
  40
  41    fn point_within_range(&self, trigger_point: &TriggerPoint, snapshot: &EditorSnapshot) -> bool {
  42        match (self, trigger_point) {
  43            (Self::Text(range), TriggerPoint::Text(point)) => {
  44                let point_after_start = range.start.cmp(point, &snapshot.buffer_snapshot).is_le();
  45                point_after_start && range.end.cmp(point, &snapshot.buffer_snapshot).is_ge()
  46            }
  47            (Self::Inlay(highlight), TriggerPoint::InlayHint(point, _, _)) => {
  48                highlight.inlay == point.inlay
  49                    && highlight.range.contains(&point.range.start)
  50                    && highlight.range.contains(&point.range.end)
  51            }
  52            (Self::Inlay(_), TriggerPoint::Text(_))
  53            | (Self::Text(_), TriggerPoint::InlayHint(_, _, _)) => false,
  54        }
  55    }
  56}
  57
  58#[derive(Debug, Clone)]
  59pub enum HoverLink {
  60    Url(String),
  61    Text(LocationLink),
  62    InlayHint(lsp::Location, LanguageServerId),
  63}
  64
  65#[derive(Debug, Clone, PartialEq, Eq)]
  66pub(crate) struct InlayHighlight {
  67    pub inlay: InlayId,
  68    pub inlay_position: Anchor,
  69    pub range: Range<usize>,
  70}
  71
  72#[derive(Debug, Clone, PartialEq)]
  73pub enum TriggerPoint {
  74    Text(Anchor),
  75    InlayHint(InlayHighlight, lsp::Location, LanguageServerId),
  76}
  77
  78impl TriggerPoint {
  79    fn anchor(&self) -> &Anchor {
  80        match self {
  81            TriggerPoint::Text(anchor) => anchor,
  82            TriggerPoint::InlayHint(inlay_range, _, _) => &inlay_range.inlay_position,
  83        }
  84    }
  85}
  86
  87impl Editor {
  88    pub(crate) fn update_hovered_link(
  89        &mut self,
  90        point_for_position: PointForPosition,
  91        snapshot: &EditorSnapshot,
  92        modifiers: Modifiers,
  93        cx: &mut ViewContext<Self>,
  94    ) {
  95        if !modifiers.command || self.has_pending_selection() {
  96            self.hide_hovered_link(cx);
  97            return;
  98        }
  99
 100        match point_for_position.as_valid() {
 101            Some(point) => {
 102                let trigger_point = TriggerPoint::Text(
 103                    snapshot
 104                        .buffer_snapshot
 105                        .anchor_before(point.to_offset(&snapshot.display_snapshot, Bias::Left)),
 106                );
 107
 108                show_link_definition(modifiers.shift, self, trigger_point, snapshot, cx);
 109            }
 110            None => {
 111                update_inlay_link_and_hover_points(
 112                    &snapshot,
 113                    point_for_position,
 114                    self,
 115                    modifiers.command,
 116                    modifiers.shift,
 117                    cx,
 118                );
 119            }
 120        }
 121    }
 122
 123    pub(crate) fn hide_hovered_link(&mut self, cx: &mut ViewContext<Self>) {
 124        self.hovered_link_state.take();
 125        self.clear_highlights::<HoveredLinkState>(cx);
 126    }
 127
 128    pub(crate) fn handle_click_hovered_link(
 129        &mut self,
 130        point: PointForPosition,
 131        modifiers: Modifiers,
 132        cx: &mut ViewContext<Editor>,
 133    ) {
 134        if let Some(hovered_link_state) = self.hovered_link_state.take() {
 135            self.hide_hovered_link(cx);
 136            if !hovered_link_state.links.is_empty() {
 137                if !self.focus_handle.is_focused(cx) {
 138                    cx.focus(&self.focus_handle);
 139                }
 140
 141                self.navigate_to_hover_links(None, hovered_link_state.links, modifiers.alt, cx);
 142                return;
 143            }
 144        }
 145
 146        // We don't have the correct kind of link cached, set the selection on
 147        // click and immediately trigger GoToDefinition.
 148        self.select(
 149            SelectPhase::Begin {
 150                position: point.next_valid,
 151                add: false,
 152                click_count: 1,
 153            },
 154            cx,
 155        );
 156
 157        if point.as_valid().is_some() {
 158            if modifiers.shift {
 159                self.go_to_type_definition(&GoToTypeDefinition, cx)
 160            } else {
 161                self.go_to_definition(&GoToDefinition, cx)
 162            }
 163        }
 164    }
 165}
 166
 167pub fn update_inlay_link_and_hover_points(
 168    snapshot: &EditorSnapshot,
 169    point_for_position: PointForPosition,
 170    editor: &mut Editor,
 171    cmd_held: bool,
 172    shift_held: bool,
 173    cx: &mut ViewContext<'_, Editor>,
 174) {
 175    let hovered_offset = if point_for_position.column_overshoot_after_line_end == 0 {
 176        Some(snapshot.display_point_to_inlay_offset(point_for_position.exact_unclipped, Bias::Left))
 177    } else {
 178        None
 179    };
 180    let mut go_to_definition_updated = false;
 181    let mut hover_updated = false;
 182    if let Some(hovered_offset) = hovered_offset {
 183        let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
 184        let previous_valid_anchor = buffer_snapshot.anchor_at(
 185            point_for_position.previous_valid.to_point(snapshot),
 186            Bias::Left,
 187        );
 188        let next_valid_anchor = buffer_snapshot.anchor_at(
 189            point_for_position.next_valid.to_point(snapshot),
 190            Bias::Right,
 191        );
 192        if let Some(hovered_hint) = editor
 193            .visible_inlay_hints(cx)
 194            .into_iter()
 195            .skip_while(|hint| {
 196                hint.position
 197                    .cmp(&previous_valid_anchor, &buffer_snapshot)
 198                    .is_lt()
 199            })
 200            .take_while(|hint| {
 201                hint.position
 202                    .cmp(&next_valid_anchor, &buffer_snapshot)
 203                    .is_le()
 204            })
 205            .max_by_key(|hint| hint.id)
 206        {
 207            let inlay_hint_cache = editor.inlay_hint_cache();
 208            let excerpt_id = previous_valid_anchor.excerpt_id;
 209            if let Some(cached_hint) = inlay_hint_cache.hint_by_id(excerpt_id, hovered_hint.id) {
 210                match cached_hint.resolve_state {
 211                    ResolveState::CanResolve(_, _) => {
 212                        if let Some(buffer_id) = previous_valid_anchor.buffer_id {
 213                            inlay_hint_cache.spawn_hint_resolve(
 214                                buffer_id,
 215                                excerpt_id,
 216                                hovered_hint.id,
 217                                cx,
 218                            );
 219                        }
 220                    }
 221                    ResolveState::Resolved => {
 222                        let mut extra_shift_left = 0;
 223                        let mut extra_shift_right = 0;
 224                        if cached_hint.padding_left {
 225                            extra_shift_left += 1;
 226                            extra_shift_right += 1;
 227                        }
 228                        if cached_hint.padding_right {
 229                            extra_shift_right += 1;
 230                        }
 231                        match cached_hint.label {
 232                            project::InlayHintLabel::String(_) => {
 233                                if let Some(tooltip) = cached_hint.tooltip {
 234                                    hover_popover::hover_at_inlay(
 235                                        editor,
 236                                        InlayHover {
 237                                            excerpt: excerpt_id,
 238                                            tooltip: match tooltip {
 239                                                InlayHintTooltip::String(text) => HoverBlock {
 240                                                    text,
 241                                                    kind: HoverBlockKind::PlainText,
 242                                                },
 243                                                InlayHintTooltip::MarkupContent(content) => {
 244                                                    HoverBlock {
 245                                                        text: content.value,
 246                                                        kind: content.kind,
 247                                                    }
 248                                                }
 249                                            },
 250                                            range: InlayHighlight {
 251                                                inlay: hovered_hint.id,
 252                                                inlay_position: hovered_hint.position,
 253                                                range: extra_shift_left
 254                                                    ..hovered_hint.text.len() + extra_shift_right,
 255                                            },
 256                                        },
 257                                        cx,
 258                                    );
 259                                    hover_updated = true;
 260                                }
 261                            }
 262                            project::InlayHintLabel::LabelParts(label_parts) => {
 263                                let hint_start =
 264                                    snapshot.anchor_to_inlay_offset(hovered_hint.position);
 265                                if let Some((hovered_hint_part, part_range)) =
 266                                    hover_popover::find_hovered_hint_part(
 267                                        label_parts,
 268                                        hint_start,
 269                                        hovered_offset,
 270                                    )
 271                                {
 272                                    let highlight_start =
 273                                        (part_range.start - hint_start).0 + extra_shift_left;
 274                                    let highlight_end =
 275                                        (part_range.end - hint_start).0 + extra_shift_right;
 276                                    let highlight = InlayHighlight {
 277                                        inlay: hovered_hint.id,
 278                                        inlay_position: hovered_hint.position,
 279                                        range: highlight_start..highlight_end,
 280                                    };
 281                                    if let Some(tooltip) = hovered_hint_part.tooltip {
 282                                        hover_popover::hover_at_inlay(
 283                                            editor,
 284                                            InlayHover {
 285                                                excerpt: excerpt_id,
 286                                                tooltip: match tooltip {
 287                                                    InlayHintLabelPartTooltip::String(text) => {
 288                                                        HoverBlock {
 289                                                            text,
 290                                                            kind: HoverBlockKind::PlainText,
 291                                                        }
 292                                                    }
 293                                                    InlayHintLabelPartTooltip::MarkupContent(
 294                                                        content,
 295                                                    ) => HoverBlock {
 296                                                        text: content.value,
 297                                                        kind: content.kind,
 298                                                    },
 299                                                },
 300                                                range: highlight.clone(),
 301                                            },
 302                                            cx,
 303                                        );
 304                                        hover_updated = true;
 305                                    }
 306                                    if let Some((language_server_id, location)) =
 307                                        hovered_hint_part.location
 308                                    {
 309                                        if cmd_held && !editor.has_pending_nonempty_selection() {
 310                                            go_to_definition_updated = true;
 311                                            show_link_definition(
 312                                                shift_held,
 313                                                editor,
 314                                                TriggerPoint::InlayHint(
 315                                                    highlight,
 316                                                    location,
 317                                                    language_server_id,
 318                                                ),
 319                                                snapshot,
 320                                                cx,
 321                                            );
 322                                        }
 323                                    }
 324                                }
 325                            }
 326                        };
 327                    }
 328                    ResolveState::Resolving => {}
 329                }
 330            }
 331        }
 332    }
 333
 334    if !go_to_definition_updated {
 335        editor.hide_hovered_link(cx)
 336    }
 337    if !hover_updated {
 338        hover_popover::hover_at(editor, None, cx);
 339    }
 340}
 341
 342#[derive(Debug, Clone, Copy, PartialEq)]
 343pub enum LinkDefinitionKind {
 344    Symbol,
 345    Type,
 346}
 347
 348pub fn show_link_definition(
 349    shift_held: bool,
 350    editor: &mut Editor,
 351    trigger_point: TriggerPoint,
 352    snapshot: &EditorSnapshot,
 353    cx: &mut ViewContext<Editor>,
 354) {
 355    let preferred_kind = match trigger_point {
 356        TriggerPoint::Text(_) if !shift_held => LinkDefinitionKind::Symbol,
 357        _ => LinkDefinitionKind::Type,
 358    };
 359
 360    let (mut hovered_link_state, is_cached) =
 361        if let Some(existing) = editor.hovered_link_state.take() {
 362            (existing, true)
 363        } else {
 364            (
 365                HoveredLinkState {
 366                    last_trigger_point: trigger_point.clone(),
 367                    symbol_range: None,
 368                    preferred_kind,
 369                    links: vec![],
 370                    task: None,
 371                },
 372                false,
 373            )
 374        };
 375
 376    if editor.pending_rename.is_some() {
 377        return;
 378    }
 379
 380    let trigger_anchor = trigger_point.anchor();
 381    let Some((buffer, buffer_position)) = editor
 382        .buffer
 383        .read(cx)
 384        .text_anchor_for_position(*trigger_anchor, cx)
 385    else {
 386        return;
 387    };
 388
 389    let Some((excerpt_id, _, _)) = editor
 390        .buffer()
 391        .read(cx)
 392        .excerpt_containing(*trigger_anchor, cx)
 393    else {
 394        return;
 395    };
 396
 397    let same_kind = hovered_link_state.preferred_kind == preferred_kind
 398        || hovered_link_state
 399            .links
 400            .first()
 401            .is_some_and(|d| matches!(d, HoverLink::Url(_)));
 402
 403    if same_kind {
 404        if is_cached && (&hovered_link_state.last_trigger_point == &trigger_point)
 405            || hovered_link_state
 406                .symbol_range
 407                .as_ref()
 408                .is_some_and(|symbol_range| {
 409                    symbol_range.point_within_range(&trigger_point, &snapshot)
 410                })
 411        {
 412            editor.hovered_link_state = Some(hovered_link_state);
 413            return;
 414        }
 415    } else {
 416        editor.hide_hovered_link(cx)
 417    }
 418    let project = editor.project.clone();
 419
 420    let snapshot = snapshot.buffer_snapshot.clone();
 421    hovered_link_state.task = Some(cx.spawn(|this, mut cx| {
 422        async move {
 423            let result = match &trigger_point {
 424                TriggerPoint::Text(_) => {
 425                    if let Some((url_range, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 426                        this.update(&mut cx, |_, _| {
 427                            let start = snapshot.anchor_in_excerpt(excerpt_id, url_range.start);
 428                            let end = snapshot.anchor_in_excerpt(excerpt_id, url_range.end);
 429                            (
 430                                Some(RangeInEditor::Text(start..end)),
 431                                vec![HoverLink::Url(url)],
 432                            )
 433                        })
 434                        .ok()
 435                    } else if let Some(project) = project {
 436                        // query the LSP for definition info
 437                        project
 438                            .update(&mut cx, |project, cx| match preferred_kind {
 439                                LinkDefinitionKind::Symbol => {
 440                                    project.definition(&buffer, buffer_position, cx)
 441                                }
 442
 443                                LinkDefinitionKind::Type => {
 444                                    project.type_definition(&buffer, buffer_position, cx)
 445                                }
 446                            })?
 447                            .await
 448                            .ok()
 449                            .map(|definition_result| {
 450                                (
 451                                    definition_result.iter().find_map(|link| {
 452                                        link.origin.as_ref().map(|origin| {
 453                                            let start = snapshot
 454                                                .anchor_in_excerpt(excerpt_id, origin.range.start);
 455                                            let end = snapshot
 456                                                .anchor_in_excerpt(excerpt_id, origin.range.end);
 457                                            RangeInEditor::Text(start..end)
 458                                        })
 459                                    }),
 460                                    definition_result.into_iter().map(HoverLink::Text).collect(),
 461                                )
 462                            })
 463                    } else {
 464                        None
 465                    }
 466                }
 467                TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
 468                    Some(RangeInEditor::Inlay(highlight.clone())),
 469                    vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
 470                )),
 471            };
 472
 473            this.update(&mut cx, |this, cx| {
 474                // Clear any existing highlights
 475                this.clear_highlights::<HoveredLinkState>(cx);
 476                let Some(hovered_link_state) = this.hovered_link_state.as_mut() else {
 477                    return;
 478                };
 479                hovered_link_state.preferred_kind = preferred_kind;
 480                hovered_link_state.symbol_range = result
 481                    .as_ref()
 482                    .and_then(|(symbol_range, _)| symbol_range.clone());
 483
 484                if let Some((symbol_range, definitions)) = result {
 485                    hovered_link_state.links = definitions.clone();
 486
 487                    let buffer_snapshot = buffer.read(cx).snapshot();
 488
 489                    // Only show highlight if there exists a definition to jump to that doesn't contain
 490                    // the current location.
 491                    let any_definition_does_not_contain_current_location =
 492                        definitions.iter().any(|definition| {
 493                            match &definition {
 494                                HoverLink::Text(link) => {
 495                                    if link.target.buffer == buffer {
 496                                        let range = &link.target.range;
 497                                        // Expand range by one character as lsp definition ranges include positions adjacent
 498                                        // but not contained by the symbol range
 499                                        let start = buffer_snapshot.clip_offset(
 500                                            range
 501                                                .start
 502                                                .to_offset(&buffer_snapshot)
 503                                                .saturating_sub(1),
 504                                            Bias::Left,
 505                                        );
 506                                        let end = buffer_snapshot.clip_offset(
 507                                            range.end.to_offset(&buffer_snapshot) + 1,
 508                                            Bias::Right,
 509                                        );
 510                                        let offset = buffer_position.to_offset(&buffer_snapshot);
 511                                        !(start <= offset && end >= offset)
 512                                    } else {
 513                                        true
 514                                    }
 515                                }
 516                                HoverLink::InlayHint(_, _) => true,
 517                                HoverLink::Url(_) => true,
 518                            }
 519                        });
 520
 521                    if any_definition_does_not_contain_current_location {
 522                        let style = gpui::HighlightStyle {
 523                            underline: Some(gpui::UnderlineStyle {
 524                                thickness: px(1.),
 525                                ..Default::default()
 526                            }),
 527                            color: Some(cx.theme().colors().link_text_hover),
 528                            ..Default::default()
 529                        };
 530                        let highlight_range =
 531                            symbol_range.unwrap_or_else(|| match &trigger_point {
 532                                TriggerPoint::Text(trigger_anchor) => {
 533                                    // If no symbol range returned from language server, use the surrounding word.
 534                                    let (offset_range, _) =
 535                                        snapshot.surrounding_word(*trigger_anchor);
 536                                    RangeInEditor::Text(
 537                                        snapshot.anchor_before(offset_range.start)
 538                                            ..snapshot.anchor_after(offset_range.end),
 539                                    )
 540                                }
 541                                TriggerPoint::InlayHint(highlight, _, _) => {
 542                                    RangeInEditor::Inlay(highlight.clone())
 543                                }
 544                            });
 545
 546                        match highlight_range {
 547                            RangeInEditor::Text(text_range) => {
 548                                this.highlight_text::<HoveredLinkState>(vec![text_range], style, cx)
 549                            }
 550                            RangeInEditor::Inlay(highlight) => this
 551                                .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
 552                        }
 553                    } else {
 554                        this.hide_hovered_link(cx);
 555                    }
 556                }
 557            })?;
 558
 559            Ok::<_, anyhow::Error>(())
 560        }
 561        .log_err()
 562    }));
 563
 564    editor.hovered_link_state = Some(hovered_link_state);
 565}
 566
 567pub(crate) fn find_url(
 568    buffer: &Model<language::Buffer>,
 569    position: text::Anchor,
 570    mut cx: AsyncWindowContext,
 571) -> Option<(Range<text::Anchor>, String)> {
 572    const LIMIT: usize = 2048;
 573
 574    let Ok(snapshot) = buffer.update(&mut cx, |buffer, _| buffer.snapshot()) else {
 575        return None;
 576    };
 577
 578    let offset = position.to_offset(&snapshot);
 579    let mut token_start = offset;
 580    let mut token_end = offset;
 581    let mut found_start = false;
 582    let mut found_end = false;
 583
 584    for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
 585        if ch.is_whitespace() {
 586            found_start = true;
 587            break;
 588        }
 589        token_start -= ch.len_utf8();
 590    }
 591    if !found_start {
 592        return None;
 593    }
 594
 595    for ch in snapshot
 596        .chars_at(offset)
 597        .take(LIMIT - (offset - token_start))
 598    {
 599        if ch.is_whitespace() {
 600            found_end = true;
 601            break;
 602        }
 603        token_end += ch.len_utf8();
 604    }
 605    if !found_end {
 606        return None;
 607    }
 608
 609    let mut finder = LinkFinder::new();
 610    finder.kinds(&[LinkKind::Url]);
 611    let input = snapshot
 612        .text_for_range(token_start..token_end)
 613        .collect::<String>();
 614
 615    let relative_offset = offset - token_start;
 616    for link in finder.links(&input) {
 617        if link.start() <= relative_offset && link.end() >= relative_offset {
 618            let range = snapshot.anchor_before(token_start + link.start())
 619                ..snapshot.anchor_after(token_start + link.end());
 620            return Some((range, link.as_str().to_string()));
 621        }
 622    }
 623    None
 624}
 625
 626#[cfg(test)]
 627mod tests {
 628    use super::*;
 629    use crate::{
 630        display_map::ToDisplayPoint,
 631        editor_tests::init_test,
 632        inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
 633        test::editor_lsp_test_context::EditorLspTestContext,
 634        DisplayPoint,
 635    };
 636    use futures::StreamExt;
 637    use gpui::Modifiers;
 638    use indoc::indoc;
 639    use language::language_settings::InlayHintSettings;
 640    use lsp::request::{GotoDefinition, GotoTypeDefinition};
 641    use util::assert_set_eq;
 642    use workspace::item::Item;
 643
 644    #[gpui::test]
 645    async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
 646        init_test(cx, |_| {});
 647
 648        let mut cx = EditorLspTestContext::new_rust(
 649            lsp::ServerCapabilities {
 650                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 651                type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
 652                ..Default::default()
 653            },
 654            cx,
 655        )
 656        .await;
 657
 658        cx.set_state(indoc! {"
 659            struct A;
 660            let vˇariable = A;
 661        "});
 662        let screen_coord = cx.editor(|editor, cx| editor.pixel_position_of_cursor(cx));
 663
 664        // Basic hold cmd+shift, expect highlight in region if response contains type definition
 665        let symbol_range = cx.lsp_range(indoc! {"
 666            struct A;
 667            let «variable» = A;
 668        "});
 669        let target_range = cx.lsp_range(indoc! {"
 670            struct «A»;
 671            let variable = A;
 672        "});
 673
 674        cx.run_until_parked();
 675
 676        let mut requests =
 677            cx.handle_request::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
 678                Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
 679                    lsp::LocationLink {
 680                        origin_selection_range: Some(symbol_range),
 681                        target_uri: url.clone(),
 682                        target_range,
 683                        target_selection_range: target_range,
 684                    },
 685                ])))
 686            });
 687
 688        cx.cx
 689            .cx
 690            .simulate_mouse_move(screen_coord.unwrap(), Modifiers::command_shift());
 691
 692        requests.next().await;
 693        cx.run_until_parked();
 694        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 695            struct A;
 696            let «variable» = A;
 697        "});
 698
 699        cx.simulate_modifiers_change(Modifiers::command());
 700        cx.run_until_parked();
 701        // Assert no link highlights
 702        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 703            struct A;
 704            let variable = A;
 705        "});
 706
 707        cx.cx
 708            .cx
 709            .simulate_click(screen_coord.unwrap(), Modifiers::command_shift());
 710
 711        cx.assert_editor_state(indoc! {"
 712            struct «Aˇ»;
 713            let variable = A;
 714        "});
 715    }
 716
 717    #[gpui::test]
 718    async fn test_hover_links(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        cx.set_state(indoc! {"
 731                fn ˇtest() { do_work(); }
 732                fn do_work() { test(); }
 733            "});
 734
 735        // Basic hold cmd, expect highlight in region if response contains definition
 736        let hover_point = cx.pixel_position(indoc! {"
 737                fn test() { do_wˇork(); }
 738                fn do_work() { test(); }
 739            "});
 740        let symbol_range = cx.lsp_range(indoc! {"
 741                fn test() { «do_work»(); }
 742                fn do_work() { test(); }
 743            "});
 744        let target_range = cx.lsp_range(indoc! {"
 745                fn test() { do_work(); }
 746                fn «do_work»() { test(); }
 747            "});
 748
 749        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 750            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 751                lsp::LocationLink {
 752                    origin_selection_range: Some(symbol_range),
 753                    target_uri: url.clone(),
 754                    target_range,
 755                    target_selection_range: target_range,
 756                },
 757            ])))
 758        });
 759
 760        cx.simulate_mouse_move(hover_point, Modifiers::command());
 761        requests.next().await;
 762        cx.background_executor.run_until_parked();
 763        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 764                fn test() { «do_work»(); }
 765                fn do_work() { test(); }
 766            "});
 767
 768        // Unpress cmd causes highlight to go away
 769        cx.simulate_modifiers_change(Modifiers::none());
 770        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 771                fn test() { do_work(); }
 772                fn do_work() { test(); }
 773            "});
 774
 775        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 776            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 777                lsp::LocationLink {
 778                    origin_selection_range: Some(symbol_range),
 779                    target_uri: url.clone(),
 780                    target_range,
 781                    target_selection_range: target_range,
 782                },
 783            ])))
 784        });
 785
 786        cx.simulate_mouse_move(hover_point, Modifiers::command());
 787        requests.next().await;
 788        cx.background_executor.run_until_parked();
 789        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 790                fn test() { «do_work»(); }
 791                fn do_work() { test(); }
 792            "});
 793
 794        // Moving mouse to location with no response dismisses highlight
 795        let hover_point = cx.pixel_position(indoc! {"
 796                fˇn test() { do_work(); }
 797                fn do_work() { test(); }
 798            "});
 799        let mut requests = cx
 800            .lsp
 801            .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
 802                // No definitions returned
 803                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
 804            });
 805        cx.simulate_mouse_move(hover_point, Modifiers::command());
 806
 807        requests.next().await;
 808        cx.background_executor.run_until_parked();
 809
 810        // Assert no link highlights
 811        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 812                fn test() { do_work(); }
 813                fn do_work() { test(); }
 814            "});
 815
 816        // // Move mouse without cmd and then pressing cmd triggers highlight
 817        let hover_point = cx.pixel_position(indoc! {"
 818                fn test() { do_work(); }
 819                fn do_work() { teˇst(); }
 820            "});
 821        cx.simulate_mouse_move(hover_point, Modifiers::none());
 822
 823        // Assert no link highlights
 824        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 825                fn test() { do_work(); }
 826                fn do_work() { test(); }
 827            "});
 828
 829        let symbol_range = cx.lsp_range(indoc! {"
 830                fn test() { do_work(); }
 831                fn do_work() { «test»(); }
 832            "});
 833        let target_range = cx.lsp_range(indoc! {"
 834                fn «test»() { do_work(); }
 835                fn do_work() { test(); }
 836            "});
 837
 838        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 839            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 840                lsp::LocationLink {
 841                    origin_selection_range: Some(symbol_range),
 842                    target_uri: url,
 843                    target_range,
 844                    target_selection_range: target_range,
 845                },
 846            ])))
 847        });
 848
 849        cx.simulate_modifiers_change(Modifiers::command());
 850
 851        requests.next().await;
 852        cx.background_executor.run_until_parked();
 853
 854        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 855                fn test() { do_work(); }
 856                fn do_work() { «test»(); }
 857            "});
 858
 859        cx.deactivate_window();
 860        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 861                fn test() { do_work(); }
 862                fn do_work() { test(); }
 863            "});
 864
 865        cx.simulate_mouse_move(hover_point, Modifiers::command());
 866        cx.background_executor.run_until_parked();
 867        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 868                fn test() { do_work(); }
 869                fn do_work() { «test»(); }
 870            "});
 871
 872        // Moving again within the same symbol range doesn't re-request
 873        let hover_point = cx.pixel_position(indoc! {"
 874                fn test() { do_work(); }
 875                fn do_work() { tesˇt(); }
 876            "});
 877        cx.simulate_mouse_move(hover_point, Modifiers::command());
 878        cx.background_executor.run_until_parked();
 879        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 880                fn test() { do_work(); }
 881                fn do_work() { «test»(); }
 882            "});
 883
 884        // Cmd click with existing definition doesn't re-request and dismisses highlight
 885        cx.simulate_click(hover_point, Modifiers::command());
 886        cx.lsp
 887            .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
 888                // Empty definition response to make sure we aren't hitting the lsp and using
 889                // the cached location instead
 890                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
 891            });
 892        cx.background_executor.run_until_parked();
 893        cx.assert_editor_state(indoc! {"
 894                fn «testˇ»() { do_work(); }
 895                fn do_work() { test(); }
 896            "});
 897
 898        // Assert no link highlights after jump
 899        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 900                fn test() { do_work(); }
 901                fn do_work() { test(); }
 902            "});
 903
 904        // Cmd click without existing definition requests and jumps
 905        let hover_point = cx.pixel_position(indoc! {"
 906                fn test() { do_wˇork(); }
 907                fn do_work() { test(); }
 908            "});
 909        let target_range = cx.lsp_range(indoc! {"
 910                fn test() { do_work(); }
 911                fn «do_work»() { test(); }
 912            "});
 913
 914        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 915            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 916                lsp::LocationLink {
 917                    origin_selection_range: None,
 918                    target_uri: url,
 919                    target_range,
 920                    target_selection_range: target_range,
 921                },
 922            ])))
 923        });
 924        cx.simulate_click(hover_point, Modifiers::command());
 925        requests.next().await;
 926        cx.background_executor.run_until_parked();
 927        cx.assert_editor_state(indoc! {"
 928                fn test() { do_work(); }
 929                fn «do_workˇ»() { test(); }
 930            "});
 931
 932        // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
 933        // 2. Selection is completed, hovering
 934        let hover_point = cx.pixel_position(indoc! {"
 935                fn test() { do_wˇork(); }
 936                fn do_work() { test(); }
 937            "});
 938        let target_range = cx.lsp_range(indoc! {"
 939                fn test() { do_work(); }
 940                fn «do_work»() { test(); }
 941            "});
 942        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 943            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 944                lsp::LocationLink {
 945                    origin_selection_range: None,
 946                    target_uri: url,
 947                    target_range,
 948                    target_selection_range: target_range,
 949                },
 950            ])))
 951        });
 952
 953        // create a pending selection
 954        let selection_range = cx.ranges(indoc! {"
 955                fn «test() { do_w»ork(); }
 956                fn do_work() { test(); }
 957            "})[0]
 958            .clone();
 959        cx.update_editor(|editor, cx| {
 960            let snapshot = editor.buffer().read(cx).snapshot(cx);
 961            let anchor_range = snapshot.anchor_before(selection_range.start)
 962                ..snapshot.anchor_after(selection_range.end);
 963            editor.change_selections(Some(crate::Autoscroll::fit()), cx, |s| {
 964                s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
 965            });
 966        });
 967        cx.simulate_mouse_move(hover_point, Modifiers::command());
 968        cx.background_executor.run_until_parked();
 969        assert!(requests.try_next().is_err());
 970        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 971                fn test() { do_work(); }
 972                fn do_work() { test(); }
 973            "});
 974        cx.background_executor.run_until_parked();
 975    }
 976
 977    #[gpui::test]
 978    async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
 979        init_test(cx, |settings| {
 980            settings.defaults.inlay_hints = Some(InlayHintSettings {
 981                enabled: true,
 982                edit_debounce_ms: 0,
 983                scroll_debounce_ms: 0,
 984                show_type_hints: true,
 985                show_parameter_hints: true,
 986                show_other_hints: true,
 987            })
 988        });
 989
 990        let mut cx = EditorLspTestContext::new_rust(
 991            lsp::ServerCapabilities {
 992                inlay_hint_provider: Some(lsp::OneOf::Left(true)),
 993                ..Default::default()
 994            },
 995            cx,
 996        )
 997        .await;
 998        cx.set_state(indoc! {"
 999                struct TestStruct;
1000
1001                fn main() {
1002                    let variableˇ = TestStruct;
1003                }
1004            "});
1005        let hint_start_offset = cx.ranges(indoc! {"
1006                struct TestStruct;
1007
1008                fn main() {
1009                    let variableˇ = TestStruct;
1010                }
1011            "})[0]
1012            .start;
1013        let hint_position = cx.to_lsp(hint_start_offset);
1014        let target_range = cx.lsp_range(indoc! {"
1015                struct «TestStruct»;
1016
1017                fn main() {
1018                    let variable = TestStruct;
1019                }
1020            "});
1021
1022        let expected_uri = cx.buffer_lsp_url.clone();
1023        let hint_label = ": TestStruct";
1024        cx.lsp
1025            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1026                let expected_uri = expected_uri.clone();
1027                async move {
1028                    assert_eq!(params.text_document.uri, expected_uri);
1029                    Ok(Some(vec![lsp::InlayHint {
1030                        position: hint_position,
1031                        label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1032                            value: hint_label.to_string(),
1033                            location: Some(lsp::Location {
1034                                uri: params.text_document.uri,
1035                                range: target_range,
1036                            }),
1037                            ..Default::default()
1038                        }]),
1039                        kind: Some(lsp::InlayHintKind::TYPE),
1040                        text_edits: None,
1041                        tooltip: None,
1042                        padding_left: Some(false),
1043                        padding_right: Some(false),
1044                        data: None,
1045                    }]))
1046                }
1047            })
1048            .next()
1049            .await;
1050        cx.background_executor.run_until_parked();
1051        cx.update_editor(|editor, cx| {
1052            let expected_layers = vec![hint_label.to_string()];
1053            assert_eq!(expected_layers, cached_hint_labels(editor));
1054            assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1055        });
1056
1057        let inlay_range = cx
1058            .ranges(indoc! {"
1059                struct TestStruct;
1060
1061                fn main() {
1062                    let variable« »= TestStruct;
1063                }
1064            "})
1065            .get(0)
1066            .cloned()
1067            .unwrap();
1068        let midpoint = cx.update_editor(|editor, cx| {
1069            let snapshot = editor.snapshot(cx);
1070            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1071            let next_valid = inlay_range.end.to_display_point(&snapshot);
1072            assert_eq!(previous_valid.row(), next_valid.row());
1073            assert!(previous_valid.column() < next_valid.column());
1074            DisplayPoint::new(
1075                previous_valid.row(),
1076                previous_valid.column() + (hint_label.len() / 2) as u32,
1077            )
1078        });
1079        // Press cmd to trigger highlight
1080        let hover_point = cx.pixel_position_for(midpoint);
1081        cx.simulate_mouse_move(hover_point, Modifiers::command());
1082        cx.background_executor.run_until_parked();
1083        cx.update_editor(|editor, cx| {
1084            let snapshot = editor.snapshot(cx);
1085            let actual_highlights = snapshot
1086                .inlay_highlights::<HoveredLinkState>()
1087                .into_iter()
1088                .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1089                .collect::<Vec<_>>();
1090
1091            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1092            let expected_highlight = InlayHighlight {
1093                inlay: InlayId::Hint(0),
1094                inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1095                range: 0..hint_label.len(),
1096            };
1097            assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1098        });
1099
1100        cx.simulate_mouse_move(hover_point, Modifiers::none());
1101        // Assert no link highlights
1102        cx.update_editor(|editor, cx| {
1103                let snapshot = editor.snapshot(cx);
1104                let actual_ranges = snapshot
1105                    .text_highlight_ranges::<HoveredLinkState>()
1106                    .map(|ranges| ranges.as_ref().clone().1)
1107                    .unwrap_or_default();
1108
1109                assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1110            });
1111
1112        cx.simulate_modifiers_change(Modifiers::command());
1113        cx.background_executor.run_until_parked();
1114        cx.simulate_click(hover_point, Modifiers::command());
1115        cx.background_executor.run_until_parked();
1116        cx.assert_editor_state(indoc! {"
1117                struct «TestStructˇ»;
1118
1119                fn main() {
1120                    let variable = TestStruct;
1121                }
1122            "});
1123    }
1124
1125    #[gpui::test]
1126    async fn test_urls(cx: &mut gpui::TestAppContext) {
1127        init_test(cx, |_| {});
1128        let mut cx = EditorLspTestContext::new_rust(
1129            lsp::ServerCapabilities {
1130                ..Default::default()
1131            },
1132            cx,
1133        )
1134        .await;
1135
1136        cx.set_state(indoc! {"
1137            Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1138        "});
1139
1140        let screen_coord = cx.pixel_position(indoc! {"
1141            Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1142            "});
1143
1144        cx.simulate_mouse_move(screen_coord, Modifiers::command());
1145        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1146            Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1147        "});
1148
1149        cx.simulate_click(screen_coord, Modifiers::command());
1150        assert_eq!(
1151            cx.opened_url(),
1152            Some("https://zed.dev/channel/had-(oops)".into())
1153        );
1154    }
1155}