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::{maybe, 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 range = maybe!({
 428                                let start =
 429                                    snapshot.anchor_in_excerpt(excerpt_id, url_range.start)?;
 430                                let end = snapshot.anchor_in_excerpt(excerpt_id, url_range.end)?;
 431                                Some(RangeInEditor::Text(start..end))
 432                            });
 433                            (range, vec![HoverLink::Url(url)])
 434                        })
 435                        .ok()
 436                    } else if let Some(project) = project {
 437                        // query the LSP for definition info
 438                        project
 439                            .update(&mut cx, |project, cx| match preferred_kind {
 440                                LinkDefinitionKind::Symbol => {
 441                                    project.definition(&buffer, buffer_position, cx)
 442                                }
 443
 444                                LinkDefinitionKind::Type => {
 445                                    project.type_definition(&buffer, buffer_position, cx)
 446                                }
 447                            })?
 448                            .await
 449                            .ok()
 450                            .map(|definition_result| {
 451                                (
 452                                    definition_result.iter().find_map(|link| {
 453                                        link.origin.as_ref().and_then(|origin| {
 454                                            let start = snapshot.anchor_in_excerpt(
 455                                                excerpt_id,
 456                                                origin.range.start,
 457                                            )?;
 458                                            let end = snapshot
 459                                                .anchor_in_excerpt(excerpt_id, origin.range.end)?;
 460                                            Some(RangeInEditor::Text(start..end))
 461                                        })
 462                                    }),
 463                                    definition_result.into_iter().map(HoverLink::Text).collect(),
 464                                )
 465                            })
 466                    } else {
 467                        None
 468                    }
 469                }
 470                TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
 471                    Some(RangeInEditor::Inlay(highlight.clone())),
 472                    vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
 473                )),
 474            };
 475
 476            this.update(&mut cx, |this, cx| {
 477                // Clear any existing highlights
 478                this.clear_highlights::<HoveredLinkState>(cx);
 479                let Some(hovered_link_state) = this.hovered_link_state.as_mut() else {
 480                    return;
 481                };
 482                hovered_link_state.preferred_kind = preferred_kind;
 483                hovered_link_state.symbol_range = result
 484                    .as_ref()
 485                    .and_then(|(symbol_range, _)| symbol_range.clone());
 486
 487                if let Some((symbol_range, definitions)) = result {
 488                    hovered_link_state.links = definitions.clone();
 489
 490                    let buffer_snapshot = buffer.read(cx).snapshot();
 491
 492                    // Only show highlight if there exists a definition to jump to that doesn't contain
 493                    // the current location.
 494                    let any_definition_does_not_contain_current_location =
 495                        definitions.iter().any(|definition| {
 496                            match &definition {
 497                                HoverLink::Text(link) => {
 498                                    if link.target.buffer == buffer {
 499                                        let range = &link.target.range;
 500                                        // Expand range by one character as lsp definition ranges include positions adjacent
 501                                        // but not contained by the symbol range
 502                                        let start = buffer_snapshot.clip_offset(
 503                                            range
 504                                                .start
 505                                                .to_offset(&buffer_snapshot)
 506                                                .saturating_sub(1),
 507                                            Bias::Left,
 508                                        );
 509                                        let end = buffer_snapshot.clip_offset(
 510                                            range.end.to_offset(&buffer_snapshot) + 1,
 511                                            Bias::Right,
 512                                        );
 513                                        let offset = buffer_position.to_offset(&buffer_snapshot);
 514                                        !(start <= offset && end >= offset)
 515                                    } else {
 516                                        true
 517                                    }
 518                                }
 519                                HoverLink::InlayHint(_, _) => true,
 520                                HoverLink::Url(_) => true,
 521                            }
 522                        });
 523
 524                    if any_definition_does_not_contain_current_location {
 525                        let style = gpui::HighlightStyle {
 526                            underline: Some(gpui::UnderlineStyle {
 527                                thickness: px(1.),
 528                                ..Default::default()
 529                            }),
 530                            color: Some(cx.theme().colors().link_text_hover),
 531                            ..Default::default()
 532                        };
 533                        let highlight_range =
 534                            symbol_range.unwrap_or_else(|| match &trigger_point {
 535                                TriggerPoint::Text(trigger_anchor) => {
 536                                    // If no symbol range returned from language server, use the surrounding word.
 537                                    let (offset_range, _) =
 538                                        snapshot.surrounding_word(*trigger_anchor);
 539                                    RangeInEditor::Text(
 540                                        snapshot.anchor_before(offset_range.start)
 541                                            ..snapshot.anchor_after(offset_range.end),
 542                                    )
 543                                }
 544                                TriggerPoint::InlayHint(highlight, _, _) => {
 545                                    RangeInEditor::Inlay(highlight.clone())
 546                                }
 547                            });
 548
 549                        match highlight_range {
 550                            RangeInEditor::Text(text_range) => {
 551                                this.highlight_text::<HoveredLinkState>(vec![text_range], style, cx)
 552                            }
 553                            RangeInEditor::Inlay(highlight) => this
 554                                .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
 555                        }
 556                    } else {
 557                        this.hide_hovered_link(cx);
 558                    }
 559                }
 560            })?;
 561
 562            Ok::<_, anyhow::Error>(())
 563        }
 564        .log_err()
 565    }));
 566
 567    editor.hovered_link_state = Some(hovered_link_state);
 568}
 569
 570pub(crate) fn find_url(
 571    buffer: &Model<language::Buffer>,
 572    position: text::Anchor,
 573    mut cx: AsyncWindowContext,
 574) -> Option<(Range<text::Anchor>, String)> {
 575    const LIMIT: usize = 2048;
 576
 577    let Ok(snapshot) = buffer.update(&mut cx, |buffer, _| buffer.snapshot()) else {
 578        return None;
 579    };
 580
 581    let offset = position.to_offset(&snapshot);
 582    let mut token_start = offset;
 583    let mut token_end = offset;
 584    let mut found_start = false;
 585    let mut found_end = false;
 586
 587    for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
 588        if ch.is_whitespace() {
 589            found_start = true;
 590            break;
 591        }
 592        token_start -= ch.len_utf8();
 593    }
 594    if !found_start {
 595        return None;
 596    }
 597
 598    for ch in snapshot
 599        .chars_at(offset)
 600        .take(LIMIT - (offset - token_start))
 601    {
 602        if ch.is_whitespace() {
 603            found_end = true;
 604            break;
 605        }
 606        token_end += ch.len_utf8();
 607    }
 608    if !found_end {
 609        return None;
 610    }
 611
 612    let mut finder = LinkFinder::new();
 613    finder.kinds(&[LinkKind::Url]);
 614    let input = snapshot
 615        .text_for_range(token_start..token_end)
 616        .collect::<String>();
 617
 618    let relative_offset = offset - token_start;
 619    for link in finder.links(&input) {
 620        if link.start() <= relative_offset && link.end() >= relative_offset {
 621            let range = snapshot.anchor_before(token_start + link.start())
 622                ..snapshot.anchor_after(token_start + link.end());
 623            return Some((range, link.as_str().to_string()));
 624        }
 625    }
 626    None
 627}
 628
 629#[cfg(test)]
 630mod tests {
 631    use super::*;
 632    use crate::{
 633        display_map::ToDisplayPoint,
 634        editor_tests::init_test,
 635        inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
 636        test::editor_lsp_test_context::EditorLspTestContext,
 637        DisplayPoint,
 638    };
 639    use futures::StreamExt;
 640    use gpui::Modifiers;
 641    use indoc::indoc;
 642    use language::language_settings::InlayHintSettings;
 643    use lsp::request::{GotoDefinition, GotoTypeDefinition};
 644    use util::assert_set_eq;
 645    use workspace::item::Item;
 646
 647    #[gpui::test]
 648    async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
 649        init_test(cx, |_| {});
 650
 651        let mut cx = EditorLspTestContext::new_rust(
 652            lsp::ServerCapabilities {
 653                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 654                type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
 655                ..Default::default()
 656            },
 657            cx,
 658        )
 659        .await;
 660
 661        cx.set_state(indoc! {"
 662            struct A;
 663            let vˇariable = A;
 664        "});
 665        let screen_coord = cx.editor(|editor, cx| editor.pixel_position_of_cursor(cx));
 666
 667        // Basic hold cmd+shift, expect highlight in region if response contains type definition
 668        let symbol_range = cx.lsp_range(indoc! {"
 669            struct A;
 670            let «variable» = A;
 671        "});
 672        let target_range = cx.lsp_range(indoc! {"
 673            struct «A»;
 674            let variable = A;
 675        "});
 676
 677        cx.run_until_parked();
 678
 679        let mut requests =
 680            cx.handle_request::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
 681                Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
 682                    lsp::LocationLink {
 683                        origin_selection_range: Some(symbol_range),
 684                        target_uri: url.clone(),
 685                        target_range,
 686                        target_selection_range: target_range,
 687                    },
 688                ])))
 689            });
 690
 691        cx.cx
 692            .cx
 693            .simulate_mouse_move(screen_coord.unwrap(), Modifiers::command_shift());
 694
 695        requests.next().await;
 696        cx.run_until_parked();
 697        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 698            struct A;
 699            let «variable» = A;
 700        "});
 701
 702        cx.simulate_modifiers_change(Modifiers::command());
 703        cx.run_until_parked();
 704        // Assert no link highlights
 705        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 706            struct A;
 707            let variable = A;
 708        "});
 709
 710        cx.cx
 711            .cx
 712            .simulate_click(screen_coord.unwrap(), Modifiers::command_shift());
 713
 714        cx.assert_editor_state(indoc! {"
 715            struct «Aˇ»;
 716            let variable = A;
 717        "});
 718    }
 719
 720    #[gpui::test]
 721    async fn test_hover_links(cx: &mut gpui::TestAppContext) {
 722        init_test(cx, |_| {});
 723
 724        let mut cx = EditorLspTestContext::new_rust(
 725            lsp::ServerCapabilities {
 726                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 727                ..Default::default()
 728            },
 729            cx,
 730        )
 731        .await;
 732
 733        cx.set_state(indoc! {"
 734                fn ˇtest() { do_work(); }
 735                fn do_work() { test(); }
 736            "});
 737
 738        // Basic hold cmd, expect highlight in region if response contains definition
 739        let hover_point = cx.pixel_position(indoc! {"
 740                fn test() { do_wˇork(); }
 741                fn do_work() { test(); }
 742            "});
 743        let symbol_range = cx.lsp_range(indoc! {"
 744                fn test() { «do_work»(); }
 745                fn do_work() { test(); }
 746            "});
 747        let target_range = cx.lsp_range(indoc! {"
 748                fn test() { do_work(); }
 749                fn «do_work»() { test(); }
 750            "});
 751
 752        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 753            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 754                lsp::LocationLink {
 755                    origin_selection_range: Some(symbol_range),
 756                    target_uri: url.clone(),
 757                    target_range,
 758                    target_selection_range: target_range,
 759                },
 760            ])))
 761        });
 762
 763        cx.simulate_mouse_move(hover_point, Modifiers::command());
 764        requests.next().await;
 765        cx.background_executor.run_until_parked();
 766        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 767                fn test() { «do_work»(); }
 768                fn do_work() { test(); }
 769            "});
 770
 771        // Unpress cmd causes highlight to go away
 772        cx.simulate_modifiers_change(Modifiers::none());
 773        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 774                fn test() { do_work(); }
 775                fn do_work() { test(); }
 776            "});
 777
 778        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 779            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 780                lsp::LocationLink {
 781                    origin_selection_range: Some(symbol_range),
 782                    target_uri: url.clone(),
 783                    target_range,
 784                    target_selection_range: target_range,
 785                },
 786            ])))
 787        });
 788
 789        cx.simulate_mouse_move(hover_point, Modifiers::command());
 790        requests.next().await;
 791        cx.background_executor.run_until_parked();
 792        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 793                fn test() { «do_work»(); }
 794                fn do_work() { test(); }
 795            "});
 796
 797        // Moving mouse to location with no response dismisses highlight
 798        let hover_point = cx.pixel_position(indoc! {"
 799                fˇn test() { do_work(); }
 800                fn do_work() { test(); }
 801            "});
 802        let mut requests = cx
 803            .lsp
 804            .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
 805                // No definitions returned
 806                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
 807            });
 808        cx.simulate_mouse_move(hover_point, Modifiers::command());
 809
 810        requests.next().await;
 811        cx.background_executor.run_until_parked();
 812
 813        // Assert no link highlights
 814        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 815                fn test() { do_work(); }
 816                fn do_work() { test(); }
 817            "});
 818
 819        // // Move mouse without cmd and then pressing cmd triggers highlight
 820        let hover_point = cx.pixel_position(indoc! {"
 821                fn test() { do_work(); }
 822                fn do_work() { teˇst(); }
 823            "});
 824        cx.simulate_mouse_move(hover_point, Modifiers::none());
 825
 826        // Assert no link highlights
 827        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 828                fn test() { do_work(); }
 829                fn do_work() { test(); }
 830            "});
 831
 832        let symbol_range = cx.lsp_range(indoc! {"
 833                fn test() { do_work(); }
 834                fn do_work() { «test»(); }
 835            "});
 836        let target_range = cx.lsp_range(indoc! {"
 837                fn «test»() { do_work(); }
 838                fn do_work() { test(); }
 839            "});
 840
 841        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 842            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 843                lsp::LocationLink {
 844                    origin_selection_range: Some(symbol_range),
 845                    target_uri: url,
 846                    target_range,
 847                    target_selection_range: target_range,
 848                },
 849            ])))
 850        });
 851
 852        cx.simulate_modifiers_change(Modifiers::command());
 853
 854        requests.next().await;
 855        cx.background_executor.run_until_parked();
 856
 857        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 858                fn test() { do_work(); }
 859                fn do_work() { «test»(); }
 860            "});
 861
 862        cx.deactivate_window();
 863        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 864                fn test() { do_work(); }
 865                fn do_work() { test(); }
 866            "});
 867
 868        cx.simulate_mouse_move(hover_point, Modifiers::command());
 869        cx.background_executor.run_until_parked();
 870        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 871                fn test() { do_work(); }
 872                fn do_work() { «test»(); }
 873            "});
 874
 875        // Moving again within the same symbol range doesn't re-request
 876        let hover_point = cx.pixel_position(indoc! {"
 877                fn test() { do_work(); }
 878                fn do_work() { tesˇt(); }
 879            "});
 880        cx.simulate_mouse_move(hover_point, Modifiers::command());
 881        cx.background_executor.run_until_parked();
 882        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 883                fn test() { do_work(); }
 884                fn do_work() { «test»(); }
 885            "});
 886
 887        // Cmd click with existing definition doesn't re-request and dismisses highlight
 888        cx.simulate_click(hover_point, Modifiers::command());
 889        cx.lsp
 890            .handle_request::<GotoDefinition, _, _>(move |_, _| async move {
 891                // Empty definition response to make sure we aren't hitting the lsp and using
 892                // the cached location instead
 893                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
 894            });
 895        cx.background_executor.run_until_parked();
 896        cx.assert_editor_state(indoc! {"
 897                fn «testˇ»() { do_work(); }
 898                fn do_work() { test(); }
 899            "});
 900
 901        // Assert no link highlights after jump
 902        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 903                fn test() { do_work(); }
 904                fn do_work() { test(); }
 905            "});
 906
 907        // Cmd click without existing definition requests and jumps
 908        let hover_point = cx.pixel_position(indoc! {"
 909                fn test() { do_wˇork(); }
 910                fn do_work() { test(); }
 911            "});
 912        let target_range = cx.lsp_range(indoc! {"
 913                fn test() { do_work(); }
 914                fn «do_work»() { test(); }
 915            "});
 916
 917        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 918            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 919                lsp::LocationLink {
 920                    origin_selection_range: None,
 921                    target_uri: url,
 922                    target_range,
 923                    target_selection_range: target_range,
 924                },
 925            ])))
 926        });
 927        cx.simulate_click(hover_point, Modifiers::command());
 928        requests.next().await;
 929        cx.background_executor.run_until_parked();
 930        cx.assert_editor_state(indoc! {"
 931                fn test() { do_work(); }
 932                fn «do_workˇ»() { test(); }
 933            "});
 934
 935        // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
 936        // 2. Selection is completed, hovering
 937        let hover_point = cx.pixel_position(indoc! {"
 938                fn test() { do_wˇork(); }
 939                fn do_work() { test(); }
 940            "});
 941        let target_range = cx.lsp_range(indoc! {"
 942                fn test() { do_work(); }
 943                fn «do_work»() { test(); }
 944            "});
 945        let mut requests = cx.handle_request::<GotoDefinition, _, _>(move |url, _, _| async move {
 946            Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
 947                lsp::LocationLink {
 948                    origin_selection_range: None,
 949                    target_uri: url,
 950                    target_range,
 951                    target_selection_range: target_range,
 952                },
 953            ])))
 954        });
 955
 956        // create a pending selection
 957        let selection_range = cx.ranges(indoc! {"
 958                fn «test() { do_w»ork(); }
 959                fn do_work() { test(); }
 960            "})[0]
 961            .clone();
 962        cx.update_editor(|editor, cx| {
 963            let snapshot = editor.buffer().read(cx).snapshot(cx);
 964            let anchor_range = snapshot.anchor_before(selection_range.start)
 965                ..snapshot.anchor_after(selection_range.end);
 966            editor.change_selections(Some(crate::Autoscroll::fit()), cx, |s| {
 967                s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
 968            });
 969        });
 970        cx.simulate_mouse_move(hover_point, Modifiers::command());
 971        cx.background_executor.run_until_parked();
 972        assert!(requests.try_next().is_err());
 973        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 974                fn test() { do_work(); }
 975                fn do_work() { test(); }
 976            "});
 977        cx.background_executor.run_until_parked();
 978    }
 979
 980    #[gpui::test]
 981    async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
 982        init_test(cx, |settings| {
 983            settings.defaults.inlay_hints = Some(InlayHintSettings {
 984                enabled: true,
 985                edit_debounce_ms: 0,
 986                scroll_debounce_ms: 0,
 987                show_type_hints: true,
 988                show_parameter_hints: true,
 989                show_other_hints: true,
 990            })
 991        });
 992
 993        let mut cx = EditorLspTestContext::new_rust(
 994            lsp::ServerCapabilities {
 995                inlay_hint_provider: Some(lsp::OneOf::Left(true)),
 996                ..Default::default()
 997            },
 998            cx,
 999        )
1000        .await;
1001        cx.set_state(indoc! {"
1002                struct TestStruct;
1003
1004                fn main() {
1005                    let variableˇ = TestStruct;
1006                }
1007            "});
1008        let hint_start_offset = cx.ranges(indoc! {"
1009                struct TestStruct;
1010
1011                fn main() {
1012                    let variableˇ = TestStruct;
1013                }
1014            "})[0]
1015            .start;
1016        let hint_position = cx.to_lsp(hint_start_offset);
1017        let target_range = cx.lsp_range(indoc! {"
1018                struct «TestStruct»;
1019
1020                fn main() {
1021                    let variable = TestStruct;
1022                }
1023            "});
1024
1025        let expected_uri = cx.buffer_lsp_url.clone();
1026        let hint_label = ": TestStruct";
1027        cx.lsp
1028            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1029                let expected_uri = expected_uri.clone();
1030                async move {
1031                    assert_eq!(params.text_document.uri, expected_uri);
1032                    Ok(Some(vec![lsp::InlayHint {
1033                        position: hint_position,
1034                        label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1035                            value: hint_label.to_string(),
1036                            location: Some(lsp::Location {
1037                                uri: params.text_document.uri,
1038                                range: target_range,
1039                            }),
1040                            ..Default::default()
1041                        }]),
1042                        kind: Some(lsp::InlayHintKind::TYPE),
1043                        text_edits: None,
1044                        tooltip: None,
1045                        padding_left: Some(false),
1046                        padding_right: Some(false),
1047                        data: None,
1048                    }]))
1049                }
1050            })
1051            .next()
1052            .await;
1053        cx.background_executor.run_until_parked();
1054        cx.update_editor(|editor, cx| {
1055            let expected_layers = vec![hint_label.to_string()];
1056            assert_eq!(expected_layers, cached_hint_labels(editor));
1057            assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1058        });
1059
1060        let inlay_range = cx
1061            .ranges(indoc! {"
1062                struct TestStruct;
1063
1064                fn main() {
1065                    let variable« »= TestStruct;
1066                }
1067            "})
1068            .get(0)
1069            .cloned()
1070            .unwrap();
1071        let midpoint = cx.update_editor(|editor, cx| {
1072            let snapshot = editor.snapshot(cx);
1073            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1074            let next_valid = inlay_range.end.to_display_point(&snapshot);
1075            assert_eq!(previous_valid.row(), next_valid.row());
1076            assert!(previous_valid.column() < next_valid.column());
1077            DisplayPoint::new(
1078                previous_valid.row(),
1079                previous_valid.column() + (hint_label.len() / 2) as u32,
1080            )
1081        });
1082        // Press cmd to trigger highlight
1083        let hover_point = cx.pixel_position_for(midpoint);
1084        cx.simulate_mouse_move(hover_point, Modifiers::command());
1085        cx.background_executor.run_until_parked();
1086        cx.update_editor(|editor, cx| {
1087            let snapshot = editor.snapshot(cx);
1088            let actual_highlights = snapshot
1089                .inlay_highlights::<HoveredLinkState>()
1090                .into_iter()
1091                .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1092                .collect::<Vec<_>>();
1093
1094            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1095            let expected_highlight = InlayHighlight {
1096                inlay: InlayId::Hint(0),
1097                inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1098                range: 0..hint_label.len(),
1099            };
1100            assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1101        });
1102
1103        cx.simulate_mouse_move(hover_point, Modifiers::none());
1104        // Assert no link highlights
1105        cx.update_editor(|editor, cx| {
1106                let snapshot = editor.snapshot(cx);
1107                let actual_ranges = snapshot
1108                    .text_highlight_ranges::<HoveredLinkState>()
1109                    .map(|ranges| ranges.as_ref().clone().1)
1110                    .unwrap_or_default();
1111
1112                assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1113            });
1114
1115        cx.simulate_modifiers_change(Modifiers::command());
1116        cx.background_executor.run_until_parked();
1117        cx.simulate_click(hover_point, Modifiers::command());
1118        cx.background_executor.run_until_parked();
1119        cx.assert_editor_state(indoc! {"
1120                struct «TestStructˇ»;
1121
1122                fn main() {
1123                    let variable = TestStruct;
1124                }
1125            "});
1126    }
1127
1128    #[gpui::test]
1129    async fn test_urls(cx: &mut gpui::TestAppContext) {
1130        init_test(cx, |_| {});
1131        let mut cx = EditorLspTestContext::new_rust(
1132            lsp::ServerCapabilities {
1133                ..Default::default()
1134            },
1135            cx,
1136        )
1137        .await;
1138
1139        cx.set_state(indoc! {"
1140            Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1141        "});
1142
1143        let screen_coord = cx.pixel_position(indoc! {"
1144            Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1145            "});
1146
1147        cx.simulate_mouse_move(screen_coord, Modifiers::command());
1148        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1149            Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1150        "});
1151
1152        cx.simulate_click(screen_coord, Modifiers::command());
1153        assert_eq!(
1154            cx.opened_url(),
1155            Some("https://zed.dev/channel/had-(oops)".into())
1156        );
1157    }
1158}