hover_links.rs

   1use crate::{
   2    Anchor, Editor, EditorSettings, EditorSnapshot, FindAllReferences, GoToDefinition,
   3    GoToTypeDefinition, GotoDefinitionKind, InlayId, Navigated, PointForPosition, SelectPhase,
   4    display_map::InlayOffset,
   5    editor_settings::GoToDefinitionFallback,
   6    hover_popover::{self, InlayHover},
   7    scroll::ScrollAmount,
   8};
   9use gpui::{App, AsyncWindowContext, Context, Entity, Modifiers, Task, Window, px};
  10use language::{Bias, ToOffset};
  11use linkify::{LinkFinder, LinkKind};
  12use lsp::LanguageServerId;
  13use project::{
  14    HoverBlock, HoverBlockKind, InlayHintLabelPartTooltip, InlayHintTooltip, LocationLink, Project,
  15    ResolveState, ResolvedPath,
  16};
  17use settings::Settings;
  18use std::ops::Range;
  19use text;
  20use theme::ActiveTheme as _;
  21use util::{ResultExt, TryFutureExt as _, maybe};
  22
  23#[derive(Debug)]
  24pub struct HoveredLinkState {
  25    pub last_trigger_point: TriggerPoint,
  26    pub preferred_kind: GotoDefinitionKind,
  27    pub symbol_range: Option<RangeInEditor>,
  28    pub links: Vec<HoverLink>,
  29    pub task: Option<Task<Option<()>>>,
  30}
  31
  32#[derive(Debug, Eq, PartialEq, Clone)]
  33pub enum RangeInEditor {
  34    Text(Range<Anchor>),
  35    Inlay(InlayHighlight),
  36}
  37
  38impl RangeInEditor {
  39    pub fn as_text_range(&self) -> Option<Range<Anchor>> {
  40        match self {
  41            Self::Text(range) => Some(range.clone()),
  42            Self::Inlay(_) => None,
  43        }
  44    }
  45
  46    pub fn point_within_range(
  47        &self,
  48        trigger_point: &TriggerPoint,
  49        snapshot: &EditorSnapshot,
  50    ) -> bool {
  51        match (self, trigger_point) {
  52            (Self::Text(range), TriggerPoint::Text(point)) => {
  53                let point_after_start = range.start.cmp(point, &snapshot.buffer_snapshot).is_le();
  54                point_after_start && range.end.cmp(point, &snapshot.buffer_snapshot).is_ge()
  55            }
  56            (Self::Inlay(highlight), TriggerPoint::InlayHint(point, _, _)) => {
  57                highlight.inlay == point.inlay
  58                    && highlight.range.contains(&point.range.start)
  59                    && highlight.range.contains(&point.range.end)
  60            }
  61            (Self::Inlay(_), TriggerPoint::Text(_))
  62            | (Self::Text(_), TriggerPoint::InlayHint(_, _, _)) => false,
  63        }
  64    }
  65}
  66
  67#[derive(Debug, Clone)]
  68pub enum HoverLink {
  69    Url(String),
  70    File(ResolvedPath),
  71    Text(LocationLink),
  72    InlayHint(lsp::Location, LanguageServerId),
  73}
  74
  75#[derive(Debug, Clone, PartialEq, Eq)]
  76pub struct InlayHighlight {
  77    pub inlay: InlayId,
  78    pub inlay_position: Anchor,
  79    pub range: Range<usize>,
  80}
  81
  82#[derive(Debug, Clone, PartialEq)]
  83pub enum TriggerPoint {
  84    Text(Anchor),
  85    InlayHint(InlayHighlight, lsp::Location, LanguageServerId),
  86}
  87
  88impl TriggerPoint {
  89    fn anchor(&self) -> &Anchor {
  90        match self {
  91            TriggerPoint::Text(anchor) => anchor,
  92            TriggerPoint::InlayHint(inlay_range, _, _) => &inlay_range.inlay_position,
  93        }
  94    }
  95}
  96
  97pub fn exclude_link_to_position(
  98    buffer: &Entity<language::Buffer>,
  99    current_position: &text::Anchor,
 100    location: &LocationLink,
 101    cx: &App,
 102) -> bool {
 103    // Exclude definition links that points back to cursor position.
 104    // (i.e., currently cursor upon definition).
 105    let snapshot = buffer.read(cx).snapshot();
 106    !(buffer == &location.target.buffer
 107        && current_position
 108            .bias_right(&snapshot)
 109            .cmp(&location.target.range.start, &snapshot)
 110            .is_ge()
 111        && current_position
 112            .cmp(&location.target.range.end, &snapshot)
 113            .is_le())
 114}
 115
 116impl Editor {
 117    pub(crate) fn update_hovered_link(
 118        &mut self,
 119        point_for_position: PointForPosition,
 120        snapshot: &EditorSnapshot,
 121        modifiers: Modifiers,
 122        window: &mut Window,
 123        cx: &mut Context<Self>,
 124    ) {
 125        let hovered_link_modifier = Editor::multi_cursor_modifier(false, &modifiers, cx);
 126
 127        match point_for_position.as_valid() {
 128            Some(point) => {
 129                if !hovered_link_modifier || self.has_pending_selection() {
 130                    self.hide_hovered_link(cx);
 131                    return;
 132                }
 133
 134                let trigger_point = TriggerPoint::Text(
 135                    snapshot
 136                        .buffer_snapshot
 137                        .anchor_before(point.to_offset(&snapshot.display_snapshot, Bias::Left)),
 138                );
 139
 140                show_link_definition(modifiers.shift, self, trigger_point, snapshot, window, cx);
 141            }
 142            None => {
 143                update_inlay_link_and_hover_points(
 144                    snapshot,
 145                    point_for_position,
 146                    self,
 147                    hovered_link_modifier,
 148                    modifiers.shift,
 149                    window,
 150                    cx,
 151                );
 152            }
 153        }
 154    }
 155
 156    pub(crate) fn hide_hovered_link(&mut self, cx: &mut Context<Self>) {
 157        self.hovered_link_state.take();
 158        self.clear_highlights::<HoveredLinkState>(cx);
 159    }
 160
 161    pub(crate) fn handle_click_hovered_link(
 162        &mut self,
 163        point: PointForPosition,
 164        modifiers: Modifiers,
 165        window: &mut Window,
 166        cx: &mut Context<Editor>,
 167    ) {
 168        let reveal_task = self.cmd_click_reveal_task(point, modifiers, window, cx);
 169        cx.spawn_in(window, async move |editor, cx| {
 170            let definition_revealed = reveal_task.await.log_err().unwrap_or(Navigated::No);
 171            let find_references = editor
 172                .update_in(cx, |editor, window, cx| {
 173                    if definition_revealed == Navigated::Yes {
 174                        return None;
 175                    }
 176                    match EditorSettings::get_global(cx).go_to_definition_fallback {
 177                        GoToDefinitionFallback::None => None,
 178                        GoToDefinitionFallback::FindAllReferences => {
 179                            editor.find_all_references(&FindAllReferences, window, cx)
 180                        }
 181                    }
 182                })
 183                .ok()
 184                .flatten();
 185            if let Some(find_references) = find_references {
 186                find_references.await.log_err();
 187            }
 188        })
 189        .detach();
 190    }
 191
 192    pub fn scroll_hover(
 193        &mut self,
 194        amount: &ScrollAmount,
 195        window: &mut Window,
 196        cx: &mut Context<Self>,
 197    ) -> bool {
 198        let selection = self.selections.newest_anchor().head();
 199        let snapshot = self.snapshot(window, cx);
 200
 201        let Some(popover) = self.hover_state.info_popovers.iter().find(|popover| {
 202            popover
 203                .symbol_range
 204                .point_within_range(&TriggerPoint::Text(selection), &snapshot)
 205        }) else {
 206            return false;
 207        };
 208        popover.scroll(amount, window, cx);
 209        true
 210    }
 211
 212    fn cmd_click_reveal_task(
 213        &mut self,
 214        point: PointForPosition,
 215        modifiers: Modifiers,
 216        window: &mut Window,
 217        cx: &mut Context<Editor>,
 218    ) -> Task<anyhow::Result<Navigated>> {
 219        if let Some(hovered_link_state) = self.hovered_link_state.take() {
 220            self.hide_hovered_link(cx);
 221            if !hovered_link_state.links.is_empty() {
 222                if !self.focus_handle.is_focused(window) {
 223                    window.focus(&self.focus_handle);
 224                }
 225
 226                // exclude links pointing back to the current anchor
 227                let current_position = point
 228                    .next_valid
 229                    .to_point(&self.snapshot(window, cx).display_snapshot);
 230                let Some((buffer, anchor)) = self
 231                    .buffer()
 232                    .read(cx)
 233                    .text_anchor_for_position(current_position, cx)
 234                else {
 235                    return Task::ready(Ok(Navigated::No));
 236                };
 237                let links = hovered_link_state
 238                    .links
 239                    .into_iter()
 240                    .filter(|link| {
 241                        if let HoverLink::Text(location) = link {
 242                            exclude_link_to_position(&buffer, &anchor, location, cx)
 243                        } else {
 244                            true
 245                        }
 246                    })
 247                    .collect();
 248                let navigate_task =
 249                    self.navigate_to_hover_links(None, links, modifiers.alt, window, cx);
 250                self.select(SelectPhase::End, window, cx);
 251                return navigate_task;
 252            }
 253        }
 254
 255        // We don't have the correct kind of link cached, set the selection on
 256        // click and immediately trigger GoToDefinition.
 257        self.select(
 258            SelectPhase::Begin {
 259                position: point.next_valid,
 260                add: false,
 261                click_count: 1,
 262            },
 263            window,
 264            cx,
 265        );
 266
 267        let navigate_task = if point.as_valid().is_some() {
 268            if modifiers.shift {
 269                self.go_to_type_definition(&GoToTypeDefinition, window, cx)
 270            } else {
 271                self.go_to_definition(&GoToDefinition, window, cx)
 272            }
 273        } else {
 274            Task::ready(Ok(Navigated::No))
 275        };
 276        self.select(SelectPhase::End, window, cx);
 277        return navigate_task;
 278    }
 279}
 280
 281pub fn update_inlay_link_and_hover_points(
 282    snapshot: &EditorSnapshot,
 283    point_for_position: PointForPosition,
 284    editor: &mut Editor,
 285    secondary_held: bool,
 286    shift_held: bool,
 287    window: &mut Window,
 288    cx: &mut Context<Editor>,
 289) {
 290    // For inlay hints, we need to use the exact position where the mouse is
 291    // But we must clip it to valid bounds to avoid panics
 292    let clipped_point = snapshot.clip_point(point_for_position.exact_unclipped, Bias::Left);
 293    let hovered_offset = snapshot.display_point_to_inlay_offset(clipped_point, Bias::Left);
 294
 295    let mut go_to_definition_updated = false;
 296    let mut hover_updated = false;
 297
 298    // Get all visible inlay hints
 299    let visible_hints = editor.visible_inlay_hints(cx);
 300
 301    // Find if we're hovering over an inlay hint
 302    if let Some(hovered_inlay) = visible_hints.into_iter().find(|inlay| {
 303        // Only process hint inlays
 304        if !matches!(inlay.id, InlayId::Hint(_)) {
 305            return false;
 306        }
 307
 308        // Check if the hovered position falls within this inlay's display range
 309        let inlay_start = snapshot.anchor_to_inlay_offset(inlay.position);
 310        let inlay_end = InlayOffset(inlay_start.0 + inlay.text.len());
 311
 312        hovered_offset >= inlay_start && hovered_offset < inlay_end
 313    }) {
 314        let inlay_hint_cache = editor.inlay_hint_cache();
 315        let excerpt_id = hovered_inlay.position.excerpt_id;
 316
 317        // Extract the hint ID from the inlay
 318        if let InlayId::Hint(_hint_id) = hovered_inlay.id {
 319            if let Some(cached_hint) = inlay_hint_cache.hint_by_id(excerpt_id, hovered_inlay.id) {
 320                // Check if we should process this hint for hover
 321                let should_process_hint = match cached_hint.resolve_state {
 322                    ResolveState::CanResolve(_, _) => {
 323                        // For unresolved hints, spawn resolution
 324                        if let Some(buffer_id) = hovered_inlay.position.buffer_id {
 325                            inlay_hint_cache.spawn_hint_resolve(
 326                                buffer_id,
 327                                excerpt_id,
 328                                hovered_inlay.id,
 329                                window,
 330                                cx,
 331                            );
 332                        }
 333                        false // Don't process unresolved hints
 334                    }
 335                    ResolveState::Resolved => true,
 336                    ResolveState::Resolving => false,
 337                };
 338
 339                if should_process_hint {
 340                    let mut extra_shift_left = 0;
 341                    let mut extra_shift_right = 0;
 342                    if cached_hint.padding_left {
 343                        extra_shift_left += 1;
 344                        extra_shift_right += 1;
 345                    }
 346                    if cached_hint.padding_right {
 347                        extra_shift_right += 1;
 348                    }
 349                    match cached_hint.label {
 350                        project::InlayHintLabel::String(_) => {
 351                            if let Some(tooltip) = cached_hint.tooltip {
 352                                hover_popover::hover_at_inlay(
 353                                    editor,
 354                                    InlayHover {
 355                                        tooltip: match tooltip {
 356                                            InlayHintTooltip::String(text) => HoverBlock {
 357                                                text,
 358                                                kind: HoverBlockKind::PlainText,
 359                                            },
 360                                            InlayHintTooltip::MarkupContent(content) => {
 361                                                HoverBlock {
 362                                                    text: content.value,
 363                                                    kind: content.kind,
 364                                                }
 365                                            }
 366                                        },
 367                                        range: InlayHighlight {
 368                                            inlay: hovered_inlay.id,
 369                                            inlay_position: hovered_inlay.position,
 370                                            range: extra_shift_left
 371                                                ..hovered_inlay.text.len() + extra_shift_right,
 372                                        },
 373                                    },
 374                                    window,
 375                                    cx,
 376                                );
 377                                hover_updated = true;
 378                            }
 379                        }
 380                        project::InlayHintLabel::LabelParts(label_parts) => {
 381                            // Find the first part with actual hover information (tooltip or location)
 382                            let _hint_start =
 383                                snapshot.anchor_to_inlay_offset(hovered_inlay.position);
 384                            let mut part_offset = 0;
 385
 386                            for part in label_parts {
 387                                let part_len = part.value.chars().count();
 388
 389                                if part.tooltip.is_some() || part.location.is_some() {
 390                                    // Found the meaningful part - show hover for it
 391                                    let highlight_start = part_offset + extra_shift_left;
 392                                    let highlight_end = part_offset + part_len + extra_shift_right;
 393
 394                                    let highlight = InlayHighlight {
 395                                        inlay: hovered_inlay.id,
 396                                        inlay_position: hovered_inlay.position,
 397                                        range: highlight_start..highlight_end,
 398                                    };
 399
 400                                    if let Some(tooltip) = part.tooltip {
 401                                        hover_popover::hover_at_inlay(
 402                                            editor,
 403                                            InlayHover {
 404                                                tooltip: match tooltip {
 405                                                    InlayHintLabelPartTooltip::String(text) => {
 406                                                        HoverBlock {
 407                                                            text,
 408                                                            kind: HoverBlockKind::PlainText,
 409                                                        }
 410                                                    }
 411                                                    InlayHintLabelPartTooltip::MarkupContent(
 412                                                        content,
 413                                                    ) => HoverBlock {
 414                                                        text: content.value,
 415                                                        kind: content.kind,
 416                                                    },
 417                                                },
 418                                                range: highlight.clone(),
 419                                            },
 420                                            window,
 421                                            cx,
 422                                        );
 423                                        hover_updated = true;
 424                                    } else if let Some((_language_server_id, location)) =
 425                                        part.location.clone()
 426                                    {
 427                                        // When there's no tooltip but we have a location, perform a "Go to Definition" style operation
 428                                        let filename = location
 429                                            .uri
 430                                            .path()
 431                                            .split('/')
 432                                            .next_back()
 433                                            .unwrap_or("unknown")
 434                                            .to_string();
 435
 436                                        hover_popover::hover_at_inlay(
 437                                            editor,
 438                                            InlayHover {
 439                                                tooltip: HoverBlock {
 440                                                    text: "Loading documentation...".to_string(),
 441                                                    kind: HoverBlockKind::PlainText,
 442                                                },
 443                                                range: highlight.clone(),
 444                                            },
 445                                            window,
 446                                            cx,
 447                                        );
 448                                        hover_updated = true;
 449
 450                                        // Now perform the "Go to Definition" flow to get hover documentation
 451                                        if let Some(project) = editor.project.clone() {
 452                                            let highlight = highlight.clone();
 453                                            let hint_value = part.value.clone();
 454                                            let location_uri = location.uri.clone();
 455
 456                                            cx.spawn_in(window, async move |editor, cx| {
 457                                                async move {
 458                                                    // Small delay to show the loading message first
 459                                                    cx.background_executor()
 460                                                        .timer(std::time::Duration::from_millis(50))
 461                                                        .await;
 462
 463                                                    // Convert LSP URL to file path
 464                                                    let file_path = location.uri.to_file_path()
 465                                                        .map_err(|_| anyhow::anyhow!("Invalid file URL"))?;
 466
 467                                                    // Open the definition file
 468                                                    let definition_buffer = project
 469                                                        .update(cx, |project, cx| {
 470                                                            project.open_local_buffer(file_path, cx)
 471                                                        })?
 472                                                        .await?;
 473
 474                                                    // Extract documentation directly from the source
 475                                                    let documentation = definition_buffer.update(cx, |buffer, _| {
 476                                                        let line_number = location.range.start.line as usize;
 477
 478                                                        // Get the text of the buffer
 479                                                        let text = buffer.text();
 480                                                        let lines: Vec<&str> = text.lines().collect();
 481
 482                                                        // Look backwards from the definition line to find doc comments
 483                                                        let mut doc_lines = Vec::new();
 484                                                        let mut current_line = line_number.saturating_sub(1);
 485
 486                                                        // Skip any attributes like #[derive(...)]
 487                                                        while current_line > 0 && lines.get(current_line).map_or(false, |line| {
 488                                                            let trimmed = line.trim();
 489                                                            trimmed.starts_with("#[") || trimmed.is_empty()
 490                                                        }) {
 491                                                            current_line = current_line.saturating_sub(1);
 492                                                        }
 493
 494                                                        // Collect doc comments
 495                                                        while current_line > 0 {
 496                                                            if let Some(line) = lines.get(current_line) {
 497                                                                let trimmed = line.trim();
 498                                                                if trimmed.starts_with("///") {
 499                                                                    // Remove the /// and any leading space
 500                                                                    let doc_text = trimmed.strip_prefix("///").unwrap_or("")
 501                                                                        .strip_prefix(" ").unwrap_or_else(|| trimmed.strip_prefix("///").unwrap_or(""));
 502                                                                    doc_lines.push(doc_text.to_string());
 503                                                                } else if !trimmed.is_empty() {
 504                                                                    // Stop at the first non-doc, non-empty line
 505                                                                    break;
 506                                                                }
 507                                                            }
 508                                                            current_line = current_line.saturating_sub(1);
 509                                                        }
 510
 511                                                        // Reverse to get correct order
 512                                                        doc_lines.reverse();
 513
 514                                                        // Also get the actual definition line
 515                                                        let definition = lines.get(line_number)
 516                                                            .map(|s| s.trim().to_string())
 517                                                            .unwrap_or_else(|| hint_value.clone());
 518
 519                                                        if doc_lines.is_empty() {
 520                                                            None
 521                                                        } else {
 522                                                            let docs = doc_lines.join("\n");
 523                                                            Some((definition, docs))
 524                                                        }
 525                                                    })?;
 526
 527                                                    if let Some((definition, docs)) = documentation {
 528                                                        // Format as markdown with the definition as a code block
 529                                                        let formatted_docs = format!("```rust\n{}\n```\n\n{}", definition, docs);
 530
 531                                                        editor.update_in(cx, |editor, window, cx| {
 532                                                            hover_popover::hover_at_inlay(
 533                                                                editor,
 534                                                                InlayHover {
 535                                                                    tooltip: HoverBlock {
 536                                                                        text: formatted_docs,
 537                                                                        kind: HoverBlockKind::Markdown,
 538                                                                    },
 539                                                                    range: highlight,
 540                                                                },
 541                                                                window,
 542                                                                cx,
 543                                                            );
 544                                                        }).log_err();
 545                                                    } else {
 546                                                        // Fallback to showing just the location info
 547                                                        let fallback_text = format!(
 548                                                            "{}\n\nDefined in {} at line {}",
 549                                                            hint_value.trim(),
 550                                                            filename,
 551                                                            location.range.start.line + 1
 552                                                        );
 553                                                        editor.update_in(cx, |editor, window, cx| {
 554                                                            hover_popover::hover_at_inlay(
 555                                                                editor,
 556                                                                InlayHover {
 557                                                                    tooltip: HoverBlock {
 558                                                                        text: fallback_text,
 559                                                                        kind: HoverBlockKind::PlainText,
 560                                                                    },
 561                                                                    range: highlight,
 562                                                                },
 563                                                                window,
 564                                                                cx,
 565                                                            );
 566                                                        }).log_err();
 567                                                    }
 568
 569                                                    anyhow::Ok(())
 570                                                }
 571                                                .log_err()
 572                                                .await
 573                                            }).detach();
 574                                        }
 575                                    }
 576
 577                                    if let Some((language_server_id, location)) = &part.location {
 578                                        if secondary_held
 579                                            && !editor.has_pending_nonempty_selection()
 580                                        {
 581                                            go_to_definition_updated = true;
 582                                            show_link_definition(
 583                                                shift_held,
 584                                                editor,
 585                                                TriggerPoint::InlayHint(
 586                                                    highlight,
 587                                                    location.clone(),
 588                                                    *language_server_id,
 589                                                ),
 590                                                snapshot,
 591                                                window,
 592                                                cx,
 593                                            );
 594                                        }
 595                                    }
 596
 597                                    break;
 598                                }
 599
 600                                part_offset += part_len;
 601                            }
 602                        }
 603                    };
 604                }
 605            }
 606        }
 607    }
 608
 609    if !go_to_definition_updated {
 610        editor.hide_hovered_link(cx)
 611    }
 612    if !hover_updated {
 613        hover_popover::hover_at(editor, None, window, cx);
 614    }
 615}
 616
 617pub fn show_link_definition(
 618    shift_held: bool,
 619    editor: &mut Editor,
 620    trigger_point: TriggerPoint,
 621    snapshot: &EditorSnapshot,
 622    window: &mut Window,
 623    cx: &mut Context<Editor>,
 624) {
 625    let preferred_kind = match trigger_point {
 626        TriggerPoint::Text(_) if !shift_held => GotoDefinitionKind::Symbol,
 627        _ => GotoDefinitionKind::Type,
 628    };
 629
 630    let (mut hovered_link_state, is_cached) =
 631        if let Some(existing) = editor.hovered_link_state.take() {
 632            (existing, true)
 633        } else {
 634            (
 635                HoveredLinkState {
 636                    last_trigger_point: trigger_point.clone(),
 637                    symbol_range: None,
 638                    preferred_kind,
 639                    links: vec![],
 640                    task: None,
 641                },
 642                false,
 643            )
 644        };
 645
 646    if editor.pending_rename.is_some() {
 647        return;
 648    }
 649
 650    let trigger_anchor = trigger_point.anchor();
 651    let Some((buffer, buffer_position)) = editor
 652        .buffer
 653        .read(cx)
 654        .text_anchor_for_position(*trigger_anchor, cx)
 655    else {
 656        return;
 657    };
 658
 659    let Some((excerpt_id, _, _)) = editor
 660        .buffer()
 661        .read(cx)
 662        .excerpt_containing(*trigger_anchor, cx)
 663    else {
 664        return;
 665    };
 666
 667    let same_kind = hovered_link_state.preferred_kind == preferred_kind
 668        || hovered_link_state
 669            .links
 670            .first()
 671            .is_some_and(|d| matches!(d, HoverLink::Url(_)));
 672
 673    if same_kind {
 674        if is_cached && (hovered_link_state.last_trigger_point == trigger_point)
 675            || hovered_link_state
 676                .symbol_range
 677                .as_ref()
 678                .is_some_and(|symbol_range| {
 679                    symbol_range.point_within_range(&trigger_point, snapshot)
 680                })
 681        {
 682            editor.hovered_link_state = Some(hovered_link_state);
 683            return;
 684        }
 685    } else {
 686        editor.hide_hovered_link(cx)
 687    }
 688    let project = editor.project.clone();
 689    let provider = editor.semantics_provider.clone();
 690
 691    let snapshot = snapshot.buffer_snapshot.clone();
 692    hovered_link_state.task = Some(cx.spawn_in(window, async move |this, cx| {
 693        async move {
 694            let result = match &trigger_point {
 695                TriggerPoint::Text(_) => {
 696                    if let Some((url_range, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 697                        this.read_with(cx, |_, _| {
 698                            let range = maybe!({
 699                                let start =
 700                                    snapshot.anchor_in_excerpt(excerpt_id, url_range.start)?;
 701                                let end = snapshot.anchor_in_excerpt(excerpt_id, url_range.end)?;
 702                                Some(RangeInEditor::Text(start..end))
 703                            });
 704                            (range, vec![HoverLink::Url(url)])
 705                        })
 706                        .ok()
 707                    } else if let Some((filename_range, filename)) =
 708                        find_file(&buffer, project.clone(), buffer_position, cx).await
 709                    {
 710                        let range = maybe!({
 711                            let start =
 712                                snapshot.anchor_in_excerpt(excerpt_id, filename_range.start)?;
 713                            let end = snapshot.anchor_in_excerpt(excerpt_id, filename_range.end)?;
 714                            Some(RangeInEditor::Text(start..end))
 715                        });
 716
 717                        Some((range, vec![HoverLink::File(filename)]))
 718                    } else if let Some(provider) = provider {
 719                        let task = cx.update(|_, cx| {
 720                            provider.definitions(&buffer, buffer_position, preferred_kind, cx)
 721                        })?;
 722                        if let Some(task) = task {
 723                            task.await.ok().map(|definition_result| {
 724                                (
 725                                    definition_result.iter().find_map(|link| {
 726                                        link.origin.as_ref().and_then(|origin| {
 727                                            let start = snapshot.anchor_in_excerpt(
 728                                                excerpt_id,
 729                                                origin.range.start,
 730                                            )?;
 731                                            let end = snapshot
 732                                                .anchor_in_excerpt(excerpt_id, origin.range.end)?;
 733                                            Some(RangeInEditor::Text(start..end))
 734                                        })
 735                                    }),
 736                                    definition_result.into_iter().map(HoverLink::Text).collect(),
 737                                )
 738                            })
 739                        } else {
 740                            None
 741                        }
 742                    } else {
 743                        None
 744                    }
 745                }
 746                TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
 747                    Some(RangeInEditor::Inlay(highlight.clone())),
 748                    vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
 749                )),
 750            };
 751
 752            this.update(cx, |editor, cx| {
 753                // Clear any existing highlights
 754                editor.clear_highlights::<HoveredLinkState>(cx);
 755                let Some(hovered_link_state) = editor.hovered_link_state.as_mut() else {
 756                    editor.hide_hovered_link(cx);
 757                    return;
 758                };
 759                hovered_link_state.preferred_kind = preferred_kind;
 760                hovered_link_state.symbol_range = result
 761                    .as_ref()
 762                    .and_then(|(symbol_range, _)| symbol_range.clone());
 763
 764                if let Some((symbol_range, definitions)) = result {
 765                    hovered_link_state.links = definitions;
 766
 767                    let underline_hovered_link = !hovered_link_state.links.is_empty()
 768                        || hovered_link_state.symbol_range.is_some();
 769
 770                    if underline_hovered_link {
 771                        let style = gpui::HighlightStyle {
 772                            underline: Some(gpui::UnderlineStyle {
 773                                thickness: px(1.),
 774                                ..Default::default()
 775                            }),
 776                            color: Some(cx.theme().colors().link_text_hover),
 777                            ..Default::default()
 778                        };
 779                        let highlight_range =
 780                            symbol_range.unwrap_or_else(|| match &trigger_point {
 781                                TriggerPoint::Text(trigger_anchor) => {
 782                                    // If no symbol range returned from language server, use the surrounding word.
 783                                    let (offset_range, _) =
 784                                        snapshot.surrounding_word(*trigger_anchor, false);
 785                                    RangeInEditor::Text(
 786                                        snapshot.anchor_before(offset_range.start)
 787                                            ..snapshot.anchor_after(offset_range.end),
 788                                    )
 789                                }
 790                                TriggerPoint::InlayHint(highlight, _, _) => {
 791                                    RangeInEditor::Inlay(highlight.clone())
 792                                }
 793                            });
 794
 795                        match highlight_range {
 796                            RangeInEditor::Text(text_range) => editor
 797                                .highlight_text::<HoveredLinkState>(vec![text_range], style, cx),
 798                            RangeInEditor::Inlay(highlight) => editor
 799                                .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
 800                        }
 801                    }
 802                } else {
 803                    editor.hide_hovered_link(cx);
 804                }
 805            })?;
 806
 807            anyhow::Ok(())
 808        }
 809        .log_err()
 810        .await
 811    }));
 812
 813    editor.hovered_link_state = Some(hovered_link_state);
 814}
 815
 816pub(crate) fn find_url(
 817    buffer: &Entity<language::Buffer>,
 818    position: text::Anchor,
 819    mut cx: AsyncWindowContext,
 820) -> Option<(Range<text::Anchor>, String)> {
 821    const LIMIT: usize = 2048;
 822
 823    let Ok(snapshot) = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot()) else {
 824        return None;
 825    };
 826
 827    let offset = position.to_offset(&snapshot);
 828    let mut token_start = offset;
 829    let mut token_end = offset;
 830    let mut found_start = false;
 831    let mut found_end = false;
 832
 833    for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
 834        if ch.is_whitespace() {
 835            found_start = true;
 836            break;
 837        }
 838        token_start -= ch.len_utf8();
 839    }
 840    // Check if we didn't find the starting whitespace or if we didn't reach the start of the buffer
 841    if !found_start && token_start != 0 {
 842        return None;
 843    }
 844
 845    for ch in snapshot
 846        .chars_at(offset)
 847        .take(LIMIT - (offset - token_start))
 848    {
 849        if ch.is_whitespace() {
 850            found_end = true;
 851            break;
 852        }
 853        token_end += ch.len_utf8();
 854    }
 855    // Check if we didn't find the ending whitespace or if we read more or equal than LIMIT
 856    // which at this point would happen only if we reached the end of buffer
 857    if !found_end && (token_end - token_start >= LIMIT) {
 858        return None;
 859    }
 860
 861    let mut finder = LinkFinder::new();
 862    finder.kinds(&[LinkKind::Url]);
 863    let input = snapshot
 864        .text_for_range(token_start..token_end)
 865        .collect::<String>();
 866
 867    let relative_offset = offset - token_start;
 868    for link in finder.links(&input) {
 869        if link.start() <= relative_offset && link.end() >= relative_offset {
 870            let range = snapshot.anchor_before(token_start + link.start())
 871                ..snapshot.anchor_after(token_start + link.end());
 872            return Some((range, link.as_str().to_string()));
 873        }
 874    }
 875    None
 876}
 877
 878pub(crate) fn find_url_from_range(
 879    buffer: &Entity<language::Buffer>,
 880    range: Range<text::Anchor>,
 881    mut cx: AsyncWindowContext,
 882) -> Option<String> {
 883    const LIMIT: usize = 2048;
 884
 885    let Ok(snapshot) = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot()) else {
 886        return None;
 887    };
 888
 889    let start_offset = range.start.to_offset(&snapshot);
 890    let end_offset = range.end.to_offset(&snapshot);
 891
 892    let mut token_start = start_offset.min(end_offset);
 893    let mut token_end = start_offset.max(end_offset);
 894
 895    let range_len = token_end - token_start;
 896
 897    if range_len >= LIMIT {
 898        return None;
 899    }
 900
 901    // Skip leading whitespace
 902    for ch in snapshot.chars_at(token_start).take(range_len) {
 903        if !ch.is_whitespace() {
 904            break;
 905        }
 906        token_start += ch.len_utf8();
 907    }
 908
 909    // Skip trailing whitespace
 910    for ch in snapshot.reversed_chars_at(token_end).take(range_len) {
 911        if !ch.is_whitespace() {
 912            break;
 913        }
 914        token_end -= ch.len_utf8();
 915    }
 916
 917    if token_start >= token_end {
 918        return None;
 919    }
 920
 921    let text = snapshot
 922        .text_for_range(token_start..token_end)
 923        .collect::<String>();
 924
 925    let mut finder = LinkFinder::new();
 926    finder.kinds(&[LinkKind::Url]);
 927
 928    if let Some(link) = finder.links(&text).next() {
 929        if link.start() == 0 && link.end() == text.len() {
 930            return Some(link.as_str().to_string());
 931        }
 932    }
 933
 934    None
 935}
 936
 937pub(crate) async fn find_file(
 938    buffer: &Entity<language::Buffer>,
 939    project: Option<Entity<Project>>,
 940    position: text::Anchor,
 941    cx: &mut AsyncWindowContext,
 942) -> Option<(Range<text::Anchor>, ResolvedPath)> {
 943    let project = project?;
 944    let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
 945    let scope = snapshot.language_scope_at(position);
 946    let (range, candidate_file_path) = surrounding_filename(snapshot, position)?;
 947
 948    async fn check_path(
 949        candidate_file_path: &str,
 950        project: &Entity<Project>,
 951        buffer: &Entity<language::Buffer>,
 952        cx: &mut AsyncWindowContext,
 953    ) -> Option<ResolvedPath> {
 954        project
 955            .update(cx, |project, cx| {
 956                project.resolve_path_in_buffer(&candidate_file_path, buffer, cx)
 957            })
 958            .ok()?
 959            .await
 960            .filter(|s| s.is_file())
 961    }
 962
 963    if let Some(existing_path) = check_path(&candidate_file_path, &project, buffer, cx).await {
 964        return Some((range, existing_path));
 965    }
 966
 967    if let Some(scope) = scope {
 968        for suffix in scope.path_suffixes() {
 969            if candidate_file_path.ends_with(format!(".{suffix}").as_str()) {
 970                continue;
 971            }
 972
 973            let suffixed_candidate = format!("{candidate_file_path}.{suffix}");
 974            if let Some(existing_path) = check_path(&suffixed_candidate, &project, buffer, cx).await
 975            {
 976                return Some((range, existing_path));
 977            }
 978        }
 979    }
 980
 981    None
 982}
 983
 984fn surrounding_filename(
 985    snapshot: language::BufferSnapshot,
 986    position: text::Anchor,
 987) -> Option<(Range<text::Anchor>, String)> {
 988    const LIMIT: usize = 2048;
 989
 990    let offset = position.to_offset(&snapshot);
 991    let mut token_start = offset;
 992    let mut token_end = offset;
 993    let mut found_start = false;
 994    let mut found_end = false;
 995    let mut inside_quotes = false;
 996
 997    let mut filename = String::new();
 998
 999    let mut backwards = snapshot.reversed_chars_at(offset).take(LIMIT).peekable();
1000    while let Some(ch) = backwards.next() {
1001        // Escaped whitespace
1002        if ch.is_whitespace() && backwards.peek() == Some(&'\\') {
1003            filename.push(ch);
1004            token_start -= ch.len_utf8();
1005            backwards.next();
1006            token_start -= '\\'.len_utf8();
1007            continue;
1008        }
1009        if ch.is_whitespace() {
1010            found_start = true;
1011            break;
1012        }
1013        if (ch == '"' || ch == '\'') && !inside_quotes {
1014            found_start = true;
1015            inside_quotes = true;
1016            break;
1017        }
1018
1019        filename.push(ch);
1020        token_start -= ch.len_utf8();
1021    }
1022    if !found_start && token_start != 0 {
1023        return None;
1024    }
1025
1026    filename = filename.chars().rev().collect();
1027
1028    let mut forwards = snapshot
1029        .chars_at(offset)
1030        .take(LIMIT - (offset - token_start))
1031        .peekable();
1032    while let Some(ch) = forwards.next() {
1033        // Skip escaped whitespace
1034        if ch == '\\' && forwards.peek().map_or(false, |ch| ch.is_whitespace()) {
1035            token_end += ch.len_utf8();
1036            let whitespace = forwards.next().unwrap();
1037            token_end += whitespace.len_utf8();
1038            filename.push(whitespace);
1039            continue;
1040        }
1041
1042        if ch.is_whitespace() {
1043            found_end = true;
1044            break;
1045        }
1046        if ch == '"' || ch == '\'' {
1047            // If we're inside quotes, we stop when we come across the next quote
1048            if inside_quotes {
1049                found_end = true;
1050                break;
1051            } else {
1052                // Otherwise, we skip the quote
1053                inside_quotes = true;
1054                continue;
1055            }
1056        }
1057        filename.push(ch);
1058        token_end += ch.len_utf8();
1059    }
1060
1061    if !found_end && (token_end - token_start >= LIMIT) {
1062        return None;
1063    }
1064
1065    if filename.is_empty() {
1066        return None;
1067    }
1068
1069    let range = snapshot.anchor_before(token_start)..snapshot.anchor_after(token_end);
1070
1071    Some((range, filename))
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076    use super::*;
1077    use crate::{
1078        DisplayPoint,
1079        display_map::ToDisplayPoint,
1080        editor_tests::init_test,
1081        inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
1082        test::editor_lsp_test_context::EditorLspTestContext,
1083    };
1084    use futures::StreamExt;
1085    use gpui::Modifiers;
1086    use indoc::indoc;
1087    use language::language_settings::InlayHintSettings;
1088    use lsp::request::{GotoDefinition, GotoTypeDefinition};
1089    use util::{assert_set_eq, path};
1090    use workspace::item::Item;
1091
1092    #[gpui::test]
1093    async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
1094        init_test(cx, |_| {});
1095
1096        let mut cx = EditorLspTestContext::new_rust(
1097            lsp::ServerCapabilities {
1098                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
1099                type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
1100                ..Default::default()
1101            },
1102            cx,
1103        )
1104        .await;
1105
1106        cx.set_state(indoc! {"
1107            struct A;
1108            let vˇariable = A;
1109        "});
1110        let screen_coord = cx.editor(|editor, _, cx| editor.pixel_position_of_cursor(cx));
1111
1112        // Basic hold cmd+shift, expect highlight in region if response contains type definition
1113        let symbol_range = cx.lsp_range(indoc! {"
1114            struct A;
1115            let «variable» = A;
1116        "});
1117        let target_range = cx.lsp_range(indoc! {"
1118            struct «A»;
1119            let variable = A;
1120        "});
1121
1122        cx.run_until_parked();
1123
1124        let mut requests =
1125            cx.set_request_handler::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
1126                Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
1127                    lsp::LocationLink {
1128                        origin_selection_range: Some(symbol_range),
1129                        target_uri: url.clone(),
1130                        target_range,
1131                        target_selection_range: target_range,
1132                    },
1133                ])))
1134            });
1135
1136        let modifiers = if cfg!(target_os = "macos") {
1137            Modifiers::command_shift()
1138        } else {
1139            Modifiers::control_shift()
1140        };
1141
1142        cx.simulate_mouse_move(screen_coord.unwrap(), None, modifiers);
1143
1144        requests.next().await;
1145        cx.run_until_parked();
1146        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1147            struct A;
1148            let «variable» = A;
1149        "});
1150
1151        cx.simulate_modifiers_change(Modifiers::secondary_key());
1152        cx.run_until_parked();
1153        // Assert no link highlights
1154        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1155            struct A;
1156            let variable = A;
1157        "});
1158
1159        cx.simulate_click(screen_coord.unwrap(), modifiers);
1160
1161        cx.assert_editor_state(indoc! {"
1162            struct «Aˇ»;
1163            let variable = A;
1164        "});
1165    }
1166
1167    #[gpui::test]
1168    async fn test_hover_links(cx: &mut gpui::TestAppContext) {
1169        init_test(cx, |_| {});
1170
1171        let mut cx = EditorLspTestContext::new_rust(
1172            lsp::ServerCapabilities {
1173                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
1174                definition_provider: Some(lsp::OneOf::Left(true)),
1175                ..Default::default()
1176            },
1177            cx,
1178        )
1179        .await;
1180
1181        cx.set_state(indoc! {"
1182                fn ˇtest() { do_work(); }
1183                fn do_work() { test(); }
1184            "});
1185
1186        // Basic hold cmd, expect highlight in region if response contains definition
1187        let hover_point = cx.pixel_position(indoc! {"
1188                fn test() { do_wˇork(); }
1189                fn do_work() { test(); }
1190            "});
1191        let symbol_range = cx.lsp_range(indoc! {"
1192                fn test() { «do_work»(); }
1193                fn do_work() { test(); }
1194            "});
1195        let target_range = cx.lsp_range(indoc! {"
1196                fn test() { do_work(); }
1197                fn «do_work»() { test(); }
1198            "});
1199
1200        let mut requests =
1201            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1202                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1203                    lsp::LocationLink {
1204                        origin_selection_range: Some(symbol_range),
1205                        target_uri: url.clone(),
1206                        target_range,
1207                        target_selection_range: target_range,
1208                    },
1209                ])))
1210            });
1211
1212        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1213        requests.next().await;
1214        cx.background_executor.run_until_parked();
1215        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1216                fn test() { «do_work»(); }
1217                fn do_work() { test(); }
1218            "});
1219
1220        // Unpress cmd causes highlight to go away
1221        cx.simulate_modifiers_change(Modifiers::none());
1222        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1223                fn test() { do_work(); }
1224                fn do_work() { test(); }
1225            "});
1226
1227        let mut requests =
1228            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1229                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1230                    lsp::LocationLink {
1231                        origin_selection_range: Some(symbol_range),
1232                        target_uri: url.clone(),
1233                        target_range,
1234                        target_selection_range: target_range,
1235                    },
1236                ])))
1237            });
1238
1239        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1240        requests.next().await;
1241        cx.background_executor.run_until_parked();
1242        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1243                fn test() { «do_work»(); }
1244                fn do_work() { test(); }
1245            "});
1246
1247        // Moving mouse to location with no response dismisses highlight
1248        let hover_point = cx.pixel_position(indoc! {"
1249                fˇn test() { do_work(); }
1250                fn do_work() { test(); }
1251            "});
1252        let mut requests =
1253            cx.lsp
1254                .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1255                    // No definitions returned
1256                    Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1257                });
1258        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1259
1260        requests.next().await;
1261        cx.background_executor.run_until_parked();
1262
1263        // Assert no link highlights
1264        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1265                fn test() { do_work(); }
1266                fn do_work() { test(); }
1267            "});
1268
1269        // // Move mouse without cmd and then pressing cmd triggers highlight
1270        let hover_point = cx.pixel_position(indoc! {"
1271                fn test() { do_work(); }
1272                fn do_work() { teˇst(); }
1273            "});
1274        cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1275
1276        // Assert no link highlights
1277        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1278                fn test() { do_work(); }
1279                fn do_work() { test(); }
1280            "});
1281
1282        let symbol_range = cx.lsp_range(indoc! {"
1283                fn test() { do_work(); }
1284                fn do_work() { «test»(); }
1285            "});
1286        let target_range = cx.lsp_range(indoc! {"
1287                fn «test»() { do_work(); }
1288                fn do_work() { test(); }
1289            "});
1290
1291        let mut requests =
1292            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1293                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1294                    lsp::LocationLink {
1295                        origin_selection_range: Some(symbol_range),
1296                        target_uri: url,
1297                        target_range,
1298                        target_selection_range: target_range,
1299                    },
1300                ])))
1301            });
1302
1303        cx.simulate_modifiers_change(Modifiers::secondary_key());
1304
1305        requests.next().await;
1306        cx.background_executor.run_until_parked();
1307
1308        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1309                fn test() { do_work(); }
1310                fn do_work() { «test»(); }
1311            "});
1312
1313        cx.deactivate_window();
1314        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1315                fn test() { do_work(); }
1316                fn do_work() { test(); }
1317            "});
1318
1319        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1320        cx.background_executor.run_until_parked();
1321        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1322                fn test() { do_work(); }
1323                fn do_work() { «test»(); }
1324            "});
1325
1326        // Moving again within the same symbol range doesn't re-request
1327        let hover_point = cx.pixel_position(indoc! {"
1328                fn test() { do_work(); }
1329                fn do_work() { tesˇt(); }
1330            "});
1331        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1332        cx.background_executor.run_until_parked();
1333        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1334                fn test() { do_work(); }
1335                fn do_work() { «test»(); }
1336            "});
1337
1338        // Cmd click with existing definition doesn't re-request and dismisses highlight
1339        cx.simulate_click(hover_point, Modifiers::secondary_key());
1340        cx.lsp
1341            .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1342                // Empty definition response to make sure we aren't hitting the lsp and using
1343                // the cached location instead
1344                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1345            });
1346        cx.background_executor.run_until_parked();
1347        cx.assert_editor_state(indoc! {"
1348                fn «testˇ»() { do_work(); }
1349                fn do_work() { test(); }
1350            "});
1351
1352        // Assert no link highlights after jump
1353        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1354                fn test() { do_work(); }
1355                fn do_work() { test(); }
1356            "});
1357
1358        // Cmd click without existing definition requests and jumps
1359        let hover_point = cx.pixel_position(indoc! {"
1360                fn test() { do_wˇork(); }
1361                fn do_work() { test(); }
1362            "});
1363        let target_range = cx.lsp_range(indoc! {"
1364                fn test() { do_work(); }
1365                fn «do_work»() { test(); }
1366            "});
1367
1368        let mut requests =
1369            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1370                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1371                    lsp::LocationLink {
1372                        origin_selection_range: None,
1373                        target_uri: url,
1374                        target_range,
1375                        target_selection_range: target_range,
1376                    },
1377                ])))
1378            });
1379        cx.simulate_click(hover_point, Modifiers::secondary_key());
1380        requests.next().await;
1381        cx.background_executor.run_until_parked();
1382        cx.assert_editor_state(indoc! {"
1383                fn test() { do_work(); }
1384                fn «do_workˇ»() { test(); }
1385            "});
1386
1387        // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
1388        // 2. Selection is completed, hovering
1389        let hover_point = cx.pixel_position(indoc! {"
1390                fn test() { do_wˇork(); }
1391                fn do_work() { test(); }
1392            "});
1393        let target_range = cx.lsp_range(indoc! {"
1394                fn test() { do_work(); }
1395                fn «do_work»() { test(); }
1396            "});
1397        let mut requests =
1398            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1399                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1400                    lsp::LocationLink {
1401                        origin_selection_range: None,
1402                        target_uri: url,
1403                        target_range,
1404                        target_selection_range: target_range,
1405                    },
1406                ])))
1407            });
1408
1409        // create a pending selection
1410        let selection_range = cx.ranges(indoc! {"
1411                fn «test() { do_w»ork(); }
1412                fn do_work() { test(); }
1413            "})[0]
1414            .clone();
1415        cx.update_editor(|editor, window, cx| {
1416            let snapshot = editor.buffer().read(cx).snapshot(cx);
1417            let anchor_range = snapshot.anchor_before(selection_range.start)
1418                ..snapshot.anchor_after(selection_range.end);
1419            editor.change_selections(Default::default(), window, cx, |s| {
1420                s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
1421            });
1422        });
1423        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1424        cx.background_executor.run_until_parked();
1425        assert!(requests.try_next().is_err());
1426        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1427                fn test() { do_work(); }
1428                fn do_work() { test(); }
1429            "});
1430        cx.background_executor.run_until_parked();
1431    }
1432
1433    #[gpui::test]
1434    async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
1435        init_test(cx, |settings| {
1436            settings.defaults.inlay_hints = Some(InlayHintSettings {
1437                enabled: true,
1438                show_value_hints: false,
1439                edit_debounce_ms: 0,
1440                scroll_debounce_ms: 0,
1441                show_type_hints: true,
1442                show_parameter_hints: true,
1443                show_other_hints: true,
1444                show_background: false,
1445                toggle_on_modifiers_press: None,
1446            })
1447        });
1448
1449        let mut cx = EditorLspTestContext::new_rust(
1450            lsp::ServerCapabilities {
1451                inlay_hint_provider: Some(lsp::OneOf::Left(true)),
1452                ..Default::default()
1453            },
1454            cx,
1455        )
1456        .await;
1457        cx.set_state(indoc! {"
1458                struct TestStruct;
1459
1460                fn main() {
1461                    let variableˇ = TestStruct;
1462                }
1463            "});
1464        let hint_start_offset = cx.ranges(indoc! {"
1465                struct TestStruct;
1466
1467                fn main() {
1468                    let variableˇ = TestStruct;
1469                }
1470            "})[0]
1471            .start;
1472        let hint_position = cx.to_lsp(hint_start_offset);
1473        let target_range = cx.lsp_range(indoc! {"
1474                struct «TestStruct»;
1475
1476                fn main() {
1477                    let variable = TestStruct;
1478                }
1479            "});
1480
1481        let expected_uri = cx.buffer_lsp_url.clone();
1482        let hint_label = ": TestStruct";
1483        cx.lsp
1484            .set_request_handler::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1485                let expected_uri = expected_uri.clone();
1486                async move {
1487                    assert_eq!(params.text_document.uri, expected_uri);
1488                    Ok(Some(vec![lsp::InlayHint {
1489                        position: hint_position,
1490                        label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1491                            value: hint_label.to_string(),
1492                            location: Some(lsp::Location {
1493                                uri: params.text_document.uri,
1494                                range: target_range,
1495                            }),
1496                            ..Default::default()
1497                        }]),
1498                        kind: Some(lsp::InlayHintKind::TYPE),
1499                        text_edits: None,
1500                        tooltip: None,
1501                        padding_left: Some(false),
1502                        padding_right: Some(false),
1503                        data: None,
1504                    }]))
1505                }
1506            })
1507            .next()
1508            .await;
1509        cx.background_executor.run_until_parked();
1510        cx.update_editor(|editor, _window, cx| {
1511            let expected_layers = vec![hint_label.to_string()];
1512            assert_eq!(expected_layers, cached_hint_labels(editor));
1513            assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1514        });
1515
1516        let inlay_range = cx
1517            .ranges(indoc! {"
1518                struct TestStruct;
1519
1520                fn main() {
1521                    let variable« »= TestStruct;
1522                }
1523            "})
1524            .first()
1525            .cloned()
1526            .unwrap();
1527        let midpoint = cx.update_editor(|editor, window, cx| {
1528            let snapshot = editor.snapshot(window, cx);
1529            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1530            let next_valid = inlay_range.end.to_display_point(&snapshot);
1531            assert_eq!(previous_valid.row(), next_valid.row());
1532            assert!(previous_valid.column() < next_valid.column());
1533            DisplayPoint::new(
1534                previous_valid.row(),
1535                previous_valid.column() + (hint_label.len() / 2) as u32,
1536            )
1537        });
1538        // Press cmd to trigger highlight
1539        let hover_point = cx.pixel_position_for(midpoint);
1540        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1541        cx.background_executor.run_until_parked();
1542        cx.update_editor(|editor, window, cx| {
1543            let snapshot = editor.snapshot(window, cx);
1544            let actual_highlights = snapshot
1545                .inlay_highlights::<HoveredLinkState>()
1546                .into_iter()
1547                .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1548                .collect::<Vec<_>>();
1549
1550            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1551            let expected_highlight = InlayHighlight {
1552                inlay: InlayId::Hint(0),
1553                inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1554                range: 0..hint_label.len(),
1555            };
1556            assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1557        });
1558
1559        cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1560        // Assert no link highlights
1561        cx.update_editor(|editor, window, cx| {
1562                let snapshot = editor.snapshot(window, cx);
1563                let actual_ranges = snapshot
1564                    .text_highlight_ranges::<HoveredLinkState>()
1565                    .map(|ranges| ranges.as_ref().clone().1)
1566                    .unwrap_or_default();
1567
1568                assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1569            });
1570
1571        cx.simulate_modifiers_change(Modifiers::secondary_key());
1572        cx.background_executor.run_until_parked();
1573        cx.simulate_click(hover_point, Modifiers::secondary_key());
1574        cx.background_executor.run_until_parked();
1575        cx.assert_editor_state(indoc! {"
1576                struct «TestStructˇ»;
1577
1578                fn main() {
1579                    let variable = TestStruct;
1580                }
1581            "});
1582    }
1583
1584    #[gpui::test]
1585    async fn test_urls(cx: &mut gpui::TestAppContext) {
1586        init_test(cx, |_| {});
1587        let mut cx = EditorLspTestContext::new_rust(
1588            lsp::ServerCapabilities {
1589                ..Default::default()
1590            },
1591            cx,
1592        )
1593        .await;
1594
1595        cx.set_state(indoc! {"
1596            Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1597        "});
1598
1599        let screen_coord = cx.pixel_position(indoc! {"
1600            Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1601            "});
1602
1603        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1604        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1605            Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1606        "});
1607
1608        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1609        assert_eq!(
1610            cx.opened_url(),
1611            Some("https://zed.dev/channel/had-(oops)".into())
1612        );
1613    }
1614
1615    #[gpui::test]
1616    async fn test_urls_at_beginning_of_buffer(cx: &mut gpui::TestAppContext) {
1617        init_test(cx, |_| {});
1618        let mut cx = EditorLspTestContext::new_rust(
1619            lsp::ServerCapabilities {
1620                ..Default::default()
1621            },
1622            cx,
1623        )
1624        .await;
1625
1626        cx.set_state(indoc! {"https://zed.dev/releases is a cool ˇwebpage."});
1627
1628        let screen_coord =
1629            cx.pixel_position(indoc! {"https://zed.dev/relˇeases is a cool webpage."});
1630
1631        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1632        cx.assert_editor_text_highlights::<HoveredLinkState>(
1633            indoc! {"«https://zed.dev/releasesˇ» is a cool webpage."},
1634        );
1635
1636        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1637        assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1638    }
1639
1640    #[gpui::test]
1641    async fn test_urls_at_end_of_buffer(cx: &mut gpui::TestAppContext) {
1642        init_test(cx, |_| {});
1643        let mut cx = EditorLspTestContext::new_rust(
1644            lsp::ServerCapabilities {
1645                ..Default::default()
1646            },
1647            cx,
1648        )
1649        .await;
1650
1651        cx.set_state(indoc! {"A cool ˇwebpage is https://zed.dev/releases"});
1652
1653        let screen_coord =
1654            cx.pixel_position(indoc! {"A cool webpage is https://zed.dev/releˇases"});
1655
1656        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1657        cx.assert_editor_text_highlights::<HoveredLinkState>(
1658            indoc! {"A cool webpage is «https://zed.dev/releasesˇ»"},
1659        );
1660
1661        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1662        assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1663    }
1664
1665    #[gpui::test]
1666    async fn test_surrounding_filename(cx: &mut gpui::TestAppContext) {
1667        init_test(cx, |_| {});
1668        let mut cx = EditorLspTestContext::new_rust(
1669            lsp::ServerCapabilities {
1670                ..Default::default()
1671            },
1672            cx,
1673        )
1674        .await;
1675
1676        let test_cases = [
1677            ("file ˇ name", None),
1678            ("ˇfile name", Some("file")),
1679            ("file ˇname", Some("name")),
1680            ("fiˇle name", Some("file")),
1681            ("filenˇame", Some("filename")),
1682            // Absolute path
1683            ("foobar ˇ/home/user/f.txt", Some("/home/user/f.txt")),
1684            ("foobar /home/useˇr/f.txt", Some("/home/user/f.txt")),
1685            // Windows
1686            ("C:\\Useˇrs\\user\\f.txt", Some("C:\\Users\\user\\f.txt")),
1687            // Whitespace
1688            ("ˇfile\\ -\\ name.txt", Some("file - name.txt")),
1689            ("file\\ -\\ naˇme.txt", Some("file - name.txt")),
1690            // Tilde
1691            ("ˇ~/file.txt", Some("~/file.txt")),
1692            ("~/fiˇle.txt", Some("~/file.txt")),
1693            // Double quotes
1694            ("\"fˇile.txt\"", Some("file.txt")),
1695            ("ˇ\"file.txt\"", Some("file.txt")),
1696            ("ˇ\"fi\\ le.txt\"", Some("fi le.txt")),
1697            // Single quotes
1698            ("'fˇile.txt'", Some("file.txt")),
1699            ("ˇ'file.txt'", Some("file.txt")),
1700            ("ˇ'fi\\ le.txt'", Some("fi le.txt")),
1701        ];
1702
1703        for (input, expected) in test_cases {
1704            cx.set_state(input);
1705
1706            let (position, snapshot) = cx.editor(|editor, _, cx| {
1707                let positions = editor.selections.newest_anchor().head().text_anchor;
1708                let snapshot = editor
1709                    .buffer()
1710                    .clone()
1711                    .read(cx)
1712                    .as_singleton()
1713                    .unwrap()
1714                    .read(cx)
1715                    .snapshot();
1716                (positions, snapshot)
1717            });
1718
1719            let result = surrounding_filename(snapshot, position);
1720
1721            if let Some(expected) = expected {
1722                assert!(result.is_some(), "Failed to find file path: {}", input);
1723                let (_, path) = result.unwrap();
1724                assert_eq!(&path, expected, "Incorrect file path for input: {}", input);
1725            } else {
1726                assert!(
1727                    result.is_none(),
1728                    "Expected no result, but got one: {:?}",
1729                    result
1730                );
1731            }
1732        }
1733    }
1734
1735    #[gpui::test]
1736    async fn test_hover_filenames(cx: &mut gpui::TestAppContext) {
1737        init_test(cx, |_| {});
1738        let mut cx = EditorLspTestContext::new_rust(
1739            lsp::ServerCapabilities {
1740                ..Default::default()
1741            },
1742            cx,
1743        )
1744        .await;
1745
1746        // Insert a new file
1747        let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1748        fs.as_fake()
1749            .insert_file(
1750                path!("/root/dir/file2.rs"),
1751                "This is file2.rs".as_bytes().to_vec(),
1752            )
1753            .await;
1754
1755        #[cfg(not(target_os = "windows"))]
1756        cx.set_state(indoc! {"
1757            You can't go to a file that does_not_exist.txt.
1758            Go to file2.rs if you want.
1759            Or go to ../dir/file2.rs if you want.
1760            Or go to /root/dir/file2.rs if project is local.
1761            Or go to /root/dir/file2 if this is a Rust file.ˇ
1762            "});
1763        #[cfg(target_os = "windows")]
1764        cx.set_state(indoc! {"
1765            You can't go to a file that does_not_exist.txt.
1766            Go to file2.rs if you want.
1767            Or go to ../dir/file2.rs if you want.
1768            Or go to C:/root/dir/file2.rs if project is local.
1769            Or go to C:/root/dir/file2 if this is a Rust file.ˇ
1770        "});
1771
1772        // File does not exist
1773        #[cfg(not(target_os = "windows"))]
1774        let screen_coord = cx.pixel_position(indoc! {"
1775            You can't go to a file that dˇoes_not_exist.txt.
1776            Go to file2.rs if you want.
1777            Or go to ../dir/file2.rs if you want.
1778            Or go to /root/dir/file2.rs if project is local.
1779            Or go to /root/dir/file2 if this is a Rust file.
1780        "});
1781        #[cfg(target_os = "windows")]
1782        let screen_coord = cx.pixel_position(indoc! {"
1783            You can't go to a file that dˇoes_not_exist.txt.
1784            Go to file2.rs if you want.
1785            Or go to ../dir/file2.rs if you want.
1786            Or go to C:/root/dir/file2.rs if project is local.
1787            Or go to C:/root/dir/file2 if this is a Rust file.
1788        "});
1789        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1790        // No highlight
1791        cx.update_editor(|editor, window, cx| {
1792            assert!(
1793                editor
1794                    .snapshot(window, cx)
1795                    .text_highlight_ranges::<HoveredLinkState>()
1796                    .unwrap_or_default()
1797                    .1
1798                    .is_empty()
1799            );
1800        });
1801
1802        // Moving the mouse over a file that does exist should highlight it.
1803        #[cfg(not(target_os = "windows"))]
1804        let screen_coord = cx.pixel_position(indoc! {"
1805            You can't go to a file that does_not_exist.txt.
1806            Go to fˇile2.rs if you want.
1807            Or go to ../dir/file2.rs if you want.
1808            Or go to /root/dir/file2.rs if project is local.
1809            Or go to /root/dir/file2 if this is a Rust file.
1810        "});
1811        #[cfg(target_os = "windows")]
1812        let screen_coord = cx.pixel_position(indoc! {"
1813            You can't go to a file that does_not_exist.txt.
1814            Go to fˇile2.rs if you want.
1815            Or go to ../dir/file2.rs if you want.
1816            Or go to C:/root/dir/file2.rs if project is local.
1817            Or go to C:/root/dir/file2 if this is a Rust file.
1818        "});
1819
1820        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1821        #[cfg(not(target_os = "windows"))]
1822        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1823            You can't go to a file that does_not_exist.txt.
1824            Go to «file2.rsˇ» if you want.
1825            Or go to ../dir/file2.rs if you want.
1826            Or go to /root/dir/file2.rs if project is local.
1827            Or go to /root/dir/file2 if this is a Rust file.
1828        "});
1829        #[cfg(target_os = "windows")]
1830        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1831            You can't go to a file that does_not_exist.txt.
1832            Go to «file2.rsˇ» if you want.
1833            Or go to ../dir/file2.rs if you want.
1834            Or go to C:/root/dir/file2.rs if project is local.
1835            Or go to C:/root/dir/file2 if this is a Rust file.
1836        "});
1837
1838        // Moving the mouse over a relative path that does exist should highlight it
1839        #[cfg(not(target_os = "windows"))]
1840        let screen_coord = cx.pixel_position(indoc! {"
1841            You can't go to a file that does_not_exist.txt.
1842            Go to file2.rs if you want.
1843            Or go to ../dir/fˇile2.rs if you want.
1844            Or go to /root/dir/file2.rs if project is local.
1845            Or go to /root/dir/file2 if this is a Rust file.
1846        "});
1847        #[cfg(target_os = "windows")]
1848        let screen_coord = cx.pixel_position(indoc! {"
1849            You can't go to a file that does_not_exist.txt.
1850            Go to file2.rs if you want.
1851            Or go to ../dir/fˇile2.rs if you want.
1852            Or go to C:/root/dir/file2.rs if project is local.
1853            Or go to C:/root/dir/file2 if this is a Rust file.
1854        "});
1855
1856        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1857        #[cfg(not(target_os = "windows"))]
1858        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1859            You can't go to a file that does_not_exist.txt.
1860            Go to file2.rs if you want.
1861            Or go to «../dir/file2.rsˇ» if you want.
1862            Or go to /root/dir/file2.rs if project is local.
1863            Or go to /root/dir/file2 if this is a Rust file.
1864        "});
1865        #[cfg(target_os = "windows")]
1866        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1867            You can't go to a file that does_not_exist.txt.
1868            Go to file2.rs if you want.
1869            Or go to «../dir/file2.rsˇ» if you want.
1870            Or go to C:/root/dir/file2.rs if project is local.
1871            Or go to C:/root/dir/file2 if this is a Rust file.
1872        "});
1873
1874        // Moving the mouse over an absolute path that does exist should highlight it
1875        #[cfg(not(target_os = "windows"))]
1876        let screen_coord = cx.pixel_position(indoc! {"
1877            You can't go to a file that does_not_exist.txt.
1878            Go to file2.rs if you want.
1879            Or go to ../dir/file2.rs if you want.
1880            Or go to /root/diˇr/file2.rs if project is local.
1881            Or go to /root/dir/file2 if this is a Rust file.
1882        "});
1883
1884        #[cfg(target_os = "windows")]
1885        let screen_coord = cx.pixel_position(indoc! {"
1886            You can't go to a file that does_not_exist.txt.
1887            Go to file2.rs if you want.
1888            Or go to ../dir/file2.rs if you want.
1889            Or go to C:/root/diˇr/file2.rs if project is local.
1890            Or go to C:/root/dir/file2 if this is a Rust file.
1891        "});
1892
1893        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1894        #[cfg(not(target_os = "windows"))]
1895        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1896            You can't go to a file that does_not_exist.txt.
1897            Go to file2.rs if you want.
1898            Or go to ../dir/file2.rs if you want.
1899            Or go to «/root/dir/file2.rsˇ» if project is local.
1900            Or go to /root/dir/file2 if this is a Rust file.
1901        "});
1902        #[cfg(target_os = "windows")]
1903        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1904            You can't go to a file that does_not_exist.txt.
1905            Go to file2.rs if you want.
1906            Or go to ../dir/file2.rs if you want.
1907            Or go to «C:/root/dir/file2.rsˇ» if project is local.
1908            Or go to C:/root/dir/file2 if this is a Rust file.
1909        "});
1910
1911        // Moving the mouse over a path that exists, if we add the language-specific suffix, it should highlight it
1912        #[cfg(not(target_os = "windows"))]
1913        let screen_coord = cx.pixel_position(indoc! {"
1914            You can't go to a file that does_not_exist.txt.
1915            Go to file2.rs if you want.
1916            Or go to ../dir/file2.rs if you want.
1917            Or go to /root/dir/file2.rs if project is local.
1918            Or go to /root/diˇr/file2 if this is a Rust file.
1919        "});
1920        #[cfg(target_os = "windows")]
1921        let screen_coord = cx.pixel_position(indoc! {"
1922            You can't go to a file that does_not_exist.txt.
1923            Go to file2.rs if you want.
1924            Or go to ../dir/file2.rs if you want.
1925            Or go to C:/root/dir/file2.rs if project is local.
1926            Or go to C:/root/diˇr/file2 if this is a Rust file.
1927        "});
1928
1929        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1930        #[cfg(not(target_os = "windows"))]
1931        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1932            You can't go to a file that does_not_exist.txt.
1933            Go to file2.rs if you want.
1934            Or go to ../dir/file2.rs if you want.
1935            Or go to /root/dir/file2.rs if project is local.
1936            Or go to «/root/dir/file2ˇ» if this is a Rust file.
1937        "});
1938        #[cfg(target_os = "windows")]
1939        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1940            You can't go to a file that does_not_exist.txt.
1941            Go to file2.rs if you want.
1942            Or go to ../dir/file2.rs if you want.
1943            Or go to C:/root/dir/file2.rs if project is local.
1944            Or go to «C:/root/dir/file2ˇ» if this is a Rust file.
1945        "});
1946
1947        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1948
1949        cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1950        cx.update_workspace(|workspace, _, cx| {
1951            let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
1952
1953            let buffer = active_editor
1954                .read(cx)
1955                .buffer()
1956                .read(cx)
1957                .as_singleton()
1958                .unwrap();
1959
1960            let file = buffer.read(cx).file().unwrap();
1961            let file_path = file.as_local().unwrap().abs_path(cx);
1962
1963            assert_eq!(
1964                file_path,
1965                std::path::PathBuf::from(path!("/root/dir/file2.rs"))
1966            );
1967        });
1968    }
1969
1970    #[gpui::test]
1971    async fn test_hover_directories(cx: &mut gpui::TestAppContext) {
1972        init_test(cx, |_| {});
1973        let mut cx = EditorLspTestContext::new_rust(
1974            lsp::ServerCapabilities {
1975                ..Default::default()
1976            },
1977            cx,
1978        )
1979        .await;
1980
1981        // Insert a new file
1982        let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1983        fs.as_fake()
1984            .insert_file("/root/dir/file2.rs", "This is file2.rs".as_bytes().to_vec())
1985            .await;
1986
1987        cx.set_state(indoc! {"
1988            You can't open ../diˇr because it's a directory.
1989        "});
1990
1991        // File does not exist
1992        let screen_coord = cx.pixel_position(indoc! {"
1993            You can't open ../diˇr because it's a directory.
1994        "});
1995        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1996
1997        // No highlight
1998        cx.update_editor(|editor, window, cx| {
1999            assert!(
2000                editor
2001                    .snapshot(window, cx)
2002                    .text_highlight_ranges::<HoveredLinkState>()
2003                    .unwrap_or_default()
2004                    .1
2005                    .is_empty()
2006            );
2007        });
2008
2009        // Does not open the directory
2010        cx.simulate_click(screen_coord, Modifiers::secondary_key());
2011        cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
2012    }
2013}