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    let mut go_to_definition_updated = false;
 291    let mut hover_updated = false;
 292
 293    // For inlay hints, we need to use the exact position where the mouse is
 294    // But we must clip it to valid bounds to avoid panics
 295    let clipped_point = snapshot.clip_point(point_for_position.exact_unclipped, Bias::Left);
 296    let hovered_offset = snapshot.display_point_to_inlay_offset(clipped_point, Bias::Left);
 297
 298    // Get all visible inlay hints
 299    let visible_hints = editor.visible_inlay_hints(cx);
 300
 301    if point_for_position.column_overshoot_after_line_end == 0 {
 302        let hovered_offset =
 303            snapshot.display_point_to_inlay_offset(point_for_position.exact_unclipped, Bias::Left);
 304        let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
 305        let previous_valid_anchor = buffer_snapshot.anchor_at(
 306            point_for_position.previous_valid.to_point(snapshot),
 307            Bias::Left,
 308        );
 309        let next_valid_anchor = buffer_snapshot.anchor_at(
 310            point_for_position.next_valid.to_point(snapshot),
 311            Bias::Right,
 312        );
 313        if let Some(hovered_hint) = editor
 314            .visible_inlay_hints(cx)
 315            .into_iter()
 316            .skip_while(|hint| {
 317                hint.position
 318                    .cmp(&previous_valid_anchor, &buffer_snapshot)
 319                    .is_lt()
 320            })
 321            .take_while(|hint| {
 322                hint.position
 323                    .cmp(&next_valid_anchor, &buffer_snapshot)
 324                    .is_le()
 325            })
 326            .max_by_key(|hint| hint.id)
 327        {
 328            let inlay_hint_cache = editor.inlay_hint_cache();
 329            let excerpt_id = previous_valid_anchor.excerpt_id;
 330            if let Some(cached_hint) = inlay_hint_cache.hint_by_id(excerpt_id, hovered_hint.id) {
 331                match cached_hint.resolve_state {
 332                    ResolveState::CanResolve(_, _) => {
 333                        if let Some(buffer_id) = previous_valid_anchor.buffer_id {
 334                            inlay_hint_cache.spawn_hint_resolve(
 335                                buffer_id,
 336                                excerpt_id,
 337                                hovered_hint.id,
 338                                window,
 339                                cx,
 340                            );
 341                        }
 342
 343                        if cached_hint.resolve_state.is_resolved() {
 344                            let mut extra_shift_left = 0;
 345                            let mut extra_shift_right = 0;
 346                            if cached_hint.padding_left {
 347                                extra_shift_left += 1;
 348                                extra_shift_right += 1;
 349                            }
 350                            if cached_hint.padding_right {
 351                                extra_shift_right += 1;
 352                            }
 353                            match cached_hint.label {
 354                                project::InlayHintLabel::String(_) => {
 355                                    if let Some(tooltip) = cached_hint.tooltip {
 356                                        hover_popover::hover_at_inlay(
 357                                            editor,
 358                                            InlayHover {
 359                                                tooltip: match tooltip {
 360                                                    InlayHintTooltip::String(text) => HoverBlock {
 361                                                        text,
 362                                                        kind: HoverBlockKind::PlainText,
 363                                                    },
 364                                                    InlayHintTooltip::MarkupContent(content) => {
 365                                                        HoverBlock {
 366                                                            text: content.value,
 367                                                            kind: content.kind,
 368                                                        }
 369                                                    }
 370                                                },
 371                                                range: InlayHighlight {
 372                                                    inlay: hovered_hint.id,
 373                                                    inlay_position: hovered_hint.position,
 374                                                    range: extra_shift_left
 375                                                        ..hovered_hint.text.len()
 376                                                            + extra_shift_right,
 377                                                },
 378                                            },
 379                                            window,
 380                                            cx,
 381                                        );
 382                                        hover_updated = true;
 383                                    }
 384                                }
 385                                project::InlayHintLabel::LabelParts(label_parts) => {
 386                                    // Find the first part with actual hover information (tooltip or location)
 387                                    let _hint_start =
 388                                        snapshot.anchor_to_inlay_offset(hovered_hint.position);
 389                                    let mut part_offset = 0;
 390
 391                                    for part in label_parts {
 392                                        let part_len = part.value.chars().count();
 393
 394                                        if part.tooltip.is_some() || part.location.is_some() {
 395                                            // Found the meaningful part - show hover for it
 396                                            let highlight_start = part_offset + extra_shift_left;
 397                                            let highlight_end =
 398                                                part_offset + part_len + extra_shift_right;
 399
 400                                            let highlight = InlayHighlight {
 401                                                inlay: hovered_hint.id,
 402                                                inlay_position: hovered_hint.position,
 403                                                range: highlight_start..highlight_end,
 404                                            };
 405
 406                                            if let Some(tooltip) = part.tooltip {
 407                                                hover_popover::hover_at_inlay(
 408                                                    editor,
 409                                                    InlayHover {
 410                                                        tooltip: match tooltip {
 411                                                            InlayHintLabelPartTooltip::String(text) => {
 412                                                                HoverBlock {
 413                                                                    text,
 414                                                                    kind: HoverBlockKind::PlainText,
 415                                                                }
 416                                                            }
 417                                                            InlayHintLabelPartTooltip::MarkupContent(
 418                                                                content,
 419                                                            ) => HoverBlock {
 420                                                                text: content.value,
 421                                                                kind: content.kind,
 422                                                            },
 423                                                        },
 424                                                        range: highlight.clone(),
 425                                                    },
 426                                                    window,
 427                                                    cx,
 428                                                );
 429                                                hover_updated = true;
 430                                            } else if let Some((_language_server_id, location)) =
 431                                                part.location.clone()
 432                                            {
 433                                                // When there's no tooltip but we have a location, perform a "Go to Definition" style operation
 434                                                let filename = location
 435                                                    .uri
 436                                                    .path()
 437                                                    .split('/')
 438                                                    .next_back()
 439                                                    .unwrap_or("unknown")
 440                                                    .to_string();
 441
 442                                                hover_popover::hover_at_inlay(
 443                                                    editor,
 444                                                    InlayHover {
 445                                                        tooltip: HoverBlock {
 446                                                            text: "Loading documentation..."
 447                                                                .to_string(),
 448                                                            kind: HoverBlockKind::PlainText,
 449                                                        },
 450                                                        range: highlight.clone(),
 451                                                    },
 452                                                    window,
 453                                                    cx,
 454                                                );
 455                                                hover_updated = true;
 456
 457                                                // Now perform the "Go to Definition" flow to get hover documentation
 458                                                if let Some(project) = editor.project.clone() {
 459                                                    let highlight = highlight.clone();
 460                                                    let hint_value = part.value.clone();
 461                                                    let location_uri = location.uri.clone();
 462
 463                                                    cx.spawn_in(window, async move |editor, cx| {
 464                                                        async move {
 465                                                            // Small delay to show the loading message first
 466                                                            cx.background_executor()
 467                                                                .timer(std::time::Duration::from_millis(50))
 468                                                                .await;
 469
 470                                                            // Convert LSP URL to file path
 471                                                            let file_path = location.uri.to_file_path()
 472                                                                .map_err(|_| anyhow::anyhow!("Invalid file URL"))?;
 473
 474                                                            // Open the definition file
 475                                                            let definition_buffer = project
 476                                                                .update(cx, |project, cx| {
 477                                                                    project.open_local_buffer(file_path, cx)
 478                                                                })?
 479                                                                .await?;
 480
 481                                                            // Extract documentation directly from the source
 482                                                            let documentation = definition_buffer.update(cx, |buffer, _| {
 483                                                                let line_number = location.range.start.line as usize;
 484
 485                                                                // Get the text of the buffer
 486                                                                let text = buffer.text();
 487                                                                let lines: Vec<&str> = text.lines().collect();
 488
 489                                                                // Look backwards from the definition line to find doc comments
 490                                                                let mut doc_lines = Vec::new();
 491                                                                let mut current_line = line_number.saturating_sub(1);
 492
 493                                                                // Skip any attributes like #[derive(...)]
 494                                                                while current_line > 0 && lines.get(current_line).map_or(false, |line| {
 495                                                                    let trimmed = line.trim();
 496                                                                    trimmed.starts_with("#[") || trimmed.is_empty()
 497                                                                }) {
 498                                                                    current_line = current_line.saturating_sub(1);
 499                                                                }
 500
 501                                                                // Collect doc comments
 502                                                                while current_line > 0 {
 503                                                                    if let Some(line) = lines.get(current_line) {
 504                                                                        let trimmed = line.trim();
 505                                                                        if trimmed.starts_with("///") {
 506                                                                            // Remove the /// and any leading space
 507                                                                            let doc_text = trimmed.strip_prefix("///").unwrap_or("")
 508                                                                                .strip_prefix(" ").unwrap_or_else(|| trimmed.strip_prefix("///").unwrap_or(""));
 509                                                                            doc_lines.push(doc_text.to_string());
 510                                                                        } else if !trimmed.is_empty() {
 511                                                                            // Stop at the first non-doc, non-empty line
 512                                                                            break;
 513                                                                        }
 514                                                                    }
 515                                                                    current_line = current_line.saturating_sub(1);
 516                                                                }
 517
 518                                                                // Reverse to get correct order
 519                                                                doc_lines.reverse();
 520
 521                                                                // Also get the actual definition line
 522                                                                let definition = lines.get(line_number)
 523                                                                    .map(|s| s.trim().to_string())
 524                                                                    .unwrap_or_else(|| hint_value.clone());
 525
 526                                                                if doc_lines.is_empty() {
 527                                                                    None
 528                                                                } else {
 529                                                                    let docs = doc_lines.join("\n");
 530                                                                    Some((definition, docs))
 531                                                                }
 532                                                            })?;
 533
 534                                                            if let Some((definition, docs)) = documentation {
 535                                                                // Format as markdown with the definition as a code block
 536                                                                let formatted_docs = format!("```rust\n{}\n```\n\n{}", definition, docs);
 537
 538                                                                editor.update_in(cx, |editor, window, cx| {
 539                                                                    hover_popover::hover_at_inlay(
 540                                                                        editor,
 541                                                                        InlayHover {
 542                                                                            tooltip: HoverBlock {
 543                                                                                text: formatted_docs,
 544                                                                                kind: HoverBlockKind::Markdown,
 545                                                                            },
 546                                                                            range: highlight,
 547                                                                        },
 548                                                                        window,
 549                                                                        cx,
 550                                                                    );
 551                                                                }).log_err();
 552                                                            } else {
 553                                                                // Fallback to showing just the location info
 554                                                                let fallback_text = format!(
 555                                                                    "{}\n\nDefined in {} at line {}",
 556                                                                    hint_value.trim(),
 557                                                                    filename,
 558                                                                    location.range.start.line + 1
 559                                                                );
 560                                                                editor.update_in(cx, |editor, window, cx| {
 561                                                                    hover_popover::hover_at_inlay(
 562                                                                        editor,
 563                                                                        InlayHover {
 564                                                                            tooltip: HoverBlock {
 565                                                                                text: fallback_text,
 566                                                                                kind: HoverBlockKind::PlainText,
 567                                                                            },
 568                                                                            range: highlight,
 569                                                                        },
 570                                                                        window,
 571                                                                        cx,
 572                                                                    );
 573                                                                }).log_err();
 574                                                            }
 575
 576                                                            anyhow::Ok(())
 577                                                        }
 578                                                        .log_err()
 579                                                        .await
 580                                                    }).detach();
 581                                                }
 582                                            }
 583
 584                                            if let Some((language_server_id, location)) =
 585                                                &part.location
 586                                            {
 587                                                if secondary_held
 588                                                    && !editor.has_pending_nonempty_selection()
 589                                                {
 590                                                    go_to_definition_updated = true;
 591                                                    show_link_definition(
 592                                                        shift_held,
 593                                                        editor,
 594                                                        TriggerPoint::InlayHint(
 595                                                            highlight,
 596                                                            location.clone(),
 597                                                            *language_server_id,
 598                                                        ),
 599                                                        snapshot,
 600                                                        window,
 601                                                        cx,
 602                                                    );
 603                                                }
 604                                            }
 605
 606                                            break;
 607                                        }
 608
 609                                        part_offset += part_len;
 610                                    }
 611                                }
 612                            };
 613                        }
 614                    }
 615                    ResolveState::Resolved => {
 616                        let mut extra_shift_left = 0;
 617                        let mut extra_shift_right = 0;
 618                        if cached_hint.padding_left {
 619                            extra_shift_left += 1;
 620                            extra_shift_right += 1;
 621                        }
 622                        if cached_hint.padding_right {
 623                            extra_shift_right += 1;
 624                        }
 625                        match cached_hint.label {
 626                            project::InlayHintLabel::String(_) => {
 627                                if let Some(tooltip) = cached_hint.tooltip {
 628                                    hover_popover::hover_at_inlay(
 629                                        editor,
 630                                        InlayHover {
 631                                            tooltip: match tooltip {
 632                                                InlayHintTooltip::String(text) => HoverBlock {
 633                                                    text,
 634                                                    kind: HoverBlockKind::PlainText,
 635                                                },
 636                                                InlayHintTooltip::MarkupContent(content) => {
 637                                                    HoverBlock {
 638                                                        text: content.value,
 639                                                        kind: content.kind,
 640                                                    }
 641                                                }
 642                                            },
 643                                            range: InlayHighlight {
 644                                                inlay: hovered_hint.id,
 645                                                inlay_position: hovered_hint.position,
 646                                                range: extra_shift_left
 647                                                    ..hovered_hint.text.len() + extra_shift_right,
 648                                            },
 649                                        },
 650                                        window,
 651                                        cx,
 652                                    );
 653                                    hover_updated = true;
 654                                }
 655                            }
 656                            project::InlayHintLabel::LabelParts(label_parts) => {
 657                                // VS Code shows hover for the meaningful part regardless of where you hover
 658                                // Find the first part with actual hover information (tooltip or location)
 659                                let _hint_start =
 660                                    snapshot.anchor_to_inlay_offset(hovered_hint.position);
 661                                let mut part_offset = 0;
 662
 663                                for part in label_parts {
 664                                    let part_len = part.value.chars().count();
 665
 666                                    if part.tooltip.is_some() || part.location.is_some() {
 667                                        // Found the meaningful part - show hover for it
 668                                        let highlight_start = part_offset + extra_shift_left;
 669                                        let highlight_end =
 670                                            part_offset + part_len + extra_shift_right;
 671
 672                                        let highlight = InlayHighlight {
 673                                            inlay: hovered_hint.id,
 674                                            inlay_position: hovered_hint.position,
 675                                            range: highlight_start..highlight_end,
 676                                        };
 677
 678                                        if let Some(tooltip) = part.tooltip {
 679                                            hover_popover::hover_at_inlay(
 680                                                editor,
 681                                                InlayHover {
 682                                                    tooltip: match tooltip {
 683                                                        InlayHintLabelPartTooltip::String(text) => {
 684                                                            HoverBlock {
 685                                                                text,
 686                                                                kind: HoverBlockKind::PlainText,
 687                                                            }
 688                                                        }
 689                                                        InlayHintLabelPartTooltip::MarkupContent(
 690                                                            content,
 691                                                        ) => HoverBlock {
 692                                                            text: content.value,
 693                                                            kind: content.kind,
 694                                                        },
 695                                                    },
 696                                                    range: highlight.clone(),
 697                                                },
 698                                                window,
 699                                                cx,
 700                                            );
 701                                            hover_updated = true;
 702                                        } else if let Some((_language_server_id, location)) =
 703                                            part.location.clone()
 704                                        {
 705                                            // When there's no tooltip but we have a location, perform a "Go to Definition" style operation
 706                                            let filename = location
 707                                                .uri
 708                                                .path()
 709                                                .split('/')
 710                                                .next_back()
 711                                                .unwrap_or("unknown")
 712                                                .to_string();
 713
 714                                            hover_popover::hover_at_inlay(
 715                                                editor,
 716                                                InlayHover {
 717                                                    tooltip: HoverBlock {
 718                                                        text: "Loading documentation..."
 719                                                            .to_string(),
 720                                                        kind: HoverBlockKind::PlainText,
 721                                                    },
 722                                                    range: highlight.clone(),
 723                                                },
 724                                                window,
 725                                                cx,
 726                                            );
 727                                            hover_updated = true;
 728
 729                                            // Now perform the "Go to Definition" flow to get hover documentation
 730                                            if let Some(project) = editor.project.clone() {
 731                                                let highlight = highlight.clone();
 732                                                let hint_value = part.value.clone();
 733                                                let location_uri = location.uri.clone();
 734
 735                                                cx.spawn_in(window, async move |editor, cx| {
 736                                                    async move {
 737                                                        // Small delay to show the loading message first
 738                                                        cx.background_executor()
 739                                                            .timer(std::time::Duration::from_millis(50))
 740                                                            .await;
 741
 742                                                        // Convert LSP URL to file path
 743                                                        let file_path = location.uri.to_file_path()
 744                                                            .map_err(|_| anyhow::anyhow!("Invalid file URL"))?;
 745
 746                                                        // Open the definition file
 747                                                        let definition_buffer = project
 748                                                            .update(cx, |project, cx| {
 749                                                                project.open_local_buffer(file_path, cx)
 750                                                            })?
 751                                                            .await?;
 752
 753                                                        // Extract documentation directly from the source
 754                                                        let documentation = definition_buffer.update(cx, |buffer, _| {
 755                                                            let line_number = location.range.start.line as usize;
 756
 757                                                            // Get the text of the buffer
 758                                                            let text = buffer.text();
 759                                                            let lines: Vec<&str> = text.lines().collect();
 760
 761                                                            // Look backwards from the definition line to find doc comments
 762                                                            let mut doc_lines = Vec::new();
 763                                                            let mut current_line = line_number.saturating_sub(1);
 764
 765                                                            // Skip any attributes like #[derive(...)]
 766                                                            while current_line > 0 && lines.get(current_line).map_or(false, |line| {
 767                                                                let trimmed = line.trim();
 768                                                                trimmed.starts_with("#[") || trimmed.is_empty()
 769                                                            }) {
 770                                                                current_line = current_line.saturating_sub(1);
 771                                                            }
 772
 773                                                            // Collect doc comments
 774                                                            while current_line > 0 {
 775                                                                if let Some(line) = lines.get(current_line) {
 776                                                                    let trimmed = line.trim();
 777                                                                    if trimmed.starts_with("///") {
 778                                                                        // Remove the /// and any leading space
 779                                                                        let doc_text = trimmed.strip_prefix("///").unwrap_or("")
 780                                                                            .strip_prefix(" ").unwrap_or_else(|| trimmed.strip_prefix("///").unwrap_or(""));
 781                                                                        doc_lines.push(doc_text.to_string());
 782                                                                    } else if !trimmed.is_empty() {
 783                                                                        // Stop at the first non-doc, non-empty line
 784                                                                        break;
 785                                                                    }
 786                                                                }
 787                                                                current_line = current_line.saturating_sub(1);
 788                                                            }
 789
 790                                                            // Reverse to get correct order
 791                                                            doc_lines.reverse();
 792
 793                                                            // Also get the actual definition line
 794                                                            let definition = lines.get(line_number)
 795                                                                .map(|s| s.trim().to_string())
 796                                                                .unwrap_or_else(|| hint_value.clone());
 797
 798                                                            if doc_lines.is_empty() {
 799                                                                None
 800                                                            } else {
 801                                                                let docs = doc_lines.join("\n");
 802                                                                Some((definition, docs))
 803                                                            }
 804                                                        })?;
 805
 806                                                        if let Some((definition, docs)) = documentation {
 807                                                            // Format as markdown with the definition as a code block
 808                                                            let formatted_docs = format!("```rust\n{}\n```\n\n{}", definition, docs);
 809
 810                                                            editor.update_in(cx, |editor, window, cx| {
 811                                                                hover_popover::hover_at_inlay(
 812                                                                    editor,
 813                                                                    InlayHover {
 814                                                                        tooltip: HoverBlock {
 815                                                                            text: formatted_docs,
 816                                                                            kind: HoverBlockKind::Markdown,
 817                                                                        },
 818                                                                        range: highlight,
 819                                                                    },
 820                                                                    window,
 821                                                                    cx,
 822                                                                );
 823                                                            }).log_err();
 824                                                        } else {
 825                                                            // Fallback to showing just the location info
 826                                                            let fallback_text = format!(
 827                                                                "{}\n\nDefined in {} at line {}",
 828                                                                hint_value.trim(),
 829                                                                filename,
 830                                                                location.range.start.line + 1
 831                                                            );
 832                                                            editor.update_in(cx, |editor, window, cx| {
 833                                                                hover_popover::hover_at_inlay(
 834                                                                    editor,
 835                                                                    InlayHover {
 836                                                                        tooltip: HoverBlock {
 837                                                                            text: fallback_text,
 838                                                                            kind: HoverBlockKind::PlainText,
 839                                                                        },
 840                                                                        range: highlight,
 841                                                                    },
 842                                                                    window,
 843                                                                    cx,
 844                                                                );
 845                                                            }).log_err();
 846                                                        }
 847
 848                                                        anyhow::Ok(())
 849                                                    }
 850                                                    .log_err()
 851                                                    .await
 852                                                }).detach();
 853                                            }
 854                                        }
 855
 856                                        if let Some((language_server_id, location)) = &part.location
 857                                        {
 858                                            if secondary_held
 859                                                && !editor.has_pending_nonempty_selection()
 860                                            {
 861                                                go_to_definition_updated = true;
 862                                                show_link_definition(
 863                                                    shift_held,
 864                                                    editor,
 865                                                    TriggerPoint::InlayHint(
 866                                                        highlight,
 867                                                        location.clone(),
 868                                                        *language_server_id,
 869                                                    ),
 870                                                    snapshot,
 871                                                    window,
 872                                                    cx,
 873                                                );
 874                                            }
 875                                        }
 876
 877                                        break;
 878                                    }
 879
 880                                    part_offset += part_len;
 881                                }
 882                            }
 883                        };
 884                    }
 885                }
 886            }
 887        }
 888    }
 889
 890    if !go_to_definition_updated {
 891        editor.hide_hovered_link(cx)
 892    }
 893    if !hover_updated {
 894        hover_popover::hover_at(editor, None, window, cx);
 895    }
 896}
 897
 898pub fn show_link_definition(
 899    shift_held: bool,
 900    editor: &mut Editor,
 901    trigger_point: TriggerPoint,
 902    snapshot: &EditorSnapshot,
 903    window: &mut Window,
 904    cx: &mut Context<Editor>,
 905) {
 906    let preferred_kind = match trigger_point {
 907        TriggerPoint::Text(_) if !shift_held => GotoDefinitionKind::Symbol,
 908        _ => GotoDefinitionKind::Type,
 909    };
 910
 911    let (mut hovered_link_state, is_cached) =
 912        if let Some(existing) = editor.hovered_link_state.take() {
 913            (existing, true)
 914        } else {
 915            (
 916                HoveredLinkState {
 917                    last_trigger_point: trigger_point.clone(),
 918                    symbol_range: None,
 919                    preferred_kind,
 920                    links: vec![],
 921                    task: None,
 922                },
 923                false,
 924            )
 925        };
 926
 927    if editor.pending_rename.is_some() {
 928        return;
 929    }
 930
 931    let trigger_anchor = trigger_point.anchor();
 932    let Some((buffer, buffer_position)) = editor
 933        .buffer
 934        .read(cx)
 935        .text_anchor_for_position(*trigger_anchor, cx)
 936    else {
 937        return;
 938    };
 939
 940    let Some((excerpt_id, _, _)) = editor
 941        .buffer()
 942        .read(cx)
 943        .excerpt_containing(*trigger_anchor, cx)
 944    else {
 945        return;
 946    };
 947
 948    let same_kind = hovered_link_state.preferred_kind == preferred_kind
 949        || hovered_link_state
 950            .links
 951            .first()
 952            .is_some_and(|d| matches!(d, HoverLink::Url(_)));
 953
 954    if same_kind {
 955        if is_cached && (hovered_link_state.last_trigger_point == trigger_point)
 956            || hovered_link_state
 957                .symbol_range
 958                .as_ref()
 959                .is_some_and(|symbol_range| {
 960                    symbol_range.point_within_range(&trigger_point, snapshot)
 961                })
 962        {
 963            editor.hovered_link_state = Some(hovered_link_state);
 964            return;
 965        }
 966    } else {
 967        editor.hide_hovered_link(cx)
 968    }
 969    let project = editor.project.clone();
 970    let provider = editor.semantics_provider.clone();
 971
 972    let snapshot = snapshot.buffer_snapshot.clone();
 973    hovered_link_state.task = Some(cx.spawn_in(window, async move |this, cx| {
 974        async move {
 975            let result = match &trigger_point {
 976                TriggerPoint::Text(_) => {
 977                    if let Some((url_range, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 978                        this.read_with(cx, |_, _| {
 979                            let range = maybe!({
 980                                let start =
 981                                    snapshot.anchor_in_excerpt(excerpt_id, url_range.start)?;
 982                                let end = snapshot.anchor_in_excerpt(excerpt_id, url_range.end)?;
 983                                Some(RangeInEditor::Text(start..end))
 984                            });
 985                            (range, vec![HoverLink::Url(url)])
 986                        })
 987                        .ok()
 988                    } else if let Some((filename_range, filename)) =
 989                        find_file(&buffer, project.clone(), buffer_position, cx).await
 990                    {
 991                        let range = maybe!({
 992                            let start =
 993                                snapshot.anchor_in_excerpt(excerpt_id, filename_range.start)?;
 994                            let end = snapshot.anchor_in_excerpt(excerpt_id, filename_range.end)?;
 995                            Some(RangeInEditor::Text(start..end))
 996                        });
 997
 998                        Some((range, vec![HoverLink::File(filename)]))
 999                    } else if let Some(provider) = provider {
1000                        let task = cx.update(|_, cx| {
1001                            provider.definitions(&buffer, buffer_position, preferred_kind, cx)
1002                        })?;
1003                        if let Some(task) = task {
1004                            task.await.ok().map(|definition_result| {
1005                                (
1006                                    definition_result.iter().find_map(|link| {
1007                                        link.origin.as_ref().and_then(|origin| {
1008                                            let start = snapshot.anchor_in_excerpt(
1009                                                excerpt_id,
1010                                                origin.range.start,
1011                                            )?;
1012                                            let end = snapshot
1013                                                .anchor_in_excerpt(excerpt_id, origin.range.end)?;
1014                                            Some(RangeInEditor::Text(start..end))
1015                                        })
1016                                    }),
1017                                    definition_result.into_iter().map(HoverLink::Text).collect(),
1018                                )
1019                            })
1020                        } else {
1021                            None
1022                        }
1023                    } else {
1024                        None
1025                    }
1026                }
1027                TriggerPoint::InlayHint(highlight, lsp_location, server_id) => Some((
1028                    Some(RangeInEditor::Inlay(highlight.clone())),
1029                    vec![HoverLink::InlayHint(lsp_location.clone(), *server_id)],
1030                )),
1031            };
1032
1033            this.update(cx, |editor, cx| {
1034                // Clear any existing highlights
1035                editor.clear_highlights::<HoveredLinkState>(cx);
1036                let Some(hovered_link_state) = editor.hovered_link_state.as_mut() else {
1037                    editor.hide_hovered_link(cx);
1038                    return;
1039                };
1040                hovered_link_state.preferred_kind = preferred_kind;
1041                hovered_link_state.symbol_range = result
1042                    .as_ref()
1043                    .and_then(|(symbol_range, _)| symbol_range.clone());
1044
1045                if let Some((symbol_range, definitions)) = result {
1046                    hovered_link_state.links = definitions;
1047
1048                    let underline_hovered_link = !hovered_link_state.links.is_empty()
1049                        || hovered_link_state.symbol_range.is_some();
1050
1051                    if underline_hovered_link {
1052                        let style = gpui::HighlightStyle {
1053                            underline: Some(gpui::UnderlineStyle {
1054                                thickness: px(1.),
1055                                ..Default::default()
1056                            }),
1057                            color: Some(cx.theme().colors().link_text_hover),
1058                            ..Default::default()
1059                        };
1060                        let highlight_range =
1061                            symbol_range.unwrap_or_else(|| match &trigger_point {
1062                                TriggerPoint::Text(trigger_anchor) => {
1063                                    // If no symbol range returned from language server, use the surrounding word.
1064                                    let (offset_range, _) =
1065                                        snapshot.surrounding_word(*trigger_anchor, false);
1066                                    RangeInEditor::Text(
1067                                        snapshot.anchor_before(offset_range.start)
1068                                            ..snapshot.anchor_after(offset_range.end),
1069                                    )
1070                                }
1071                                TriggerPoint::InlayHint(highlight, _, _) => {
1072                                    RangeInEditor::Inlay(highlight.clone())
1073                                }
1074                            });
1075
1076                        match highlight_range {
1077                            RangeInEditor::Text(text_range) => editor
1078                                .highlight_text::<HoveredLinkState>(vec![text_range], style, cx),
1079                            RangeInEditor::Inlay(highlight) => editor
1080                                .highlight_inlays::<HoveredLinkState>(vec![highlight], style, cx),
1081                        }
1082                    }
1083                } else {
1084                    editor.hide_hovered_link(cx);
1085                }
1086            })?;
1087
1088            anyhow::Ok(())
1089        }
1090        .log_err()
1091        .await
1092    }));
1093
1094    editor.hovered_link_state = Some(hovered_link_state);
1095}
1096
1097pub(crate) fn find_url(
1098    buffer: &Entity<language::Buffer>,
1099    position: text::Anchor,
1100    mut cx: AsyncWindowContext,
1101) -> Option<(Range<text::Anchor>, String)> {
1102    const LIMIT: usize = 2048;
1103
1104    let Ok(snapshot) = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot()) else {
1105        return None;
1106    };
1107
1108    let offset = position.to_offset(&snapshot);
1109    let mut token_start = offset;
1110    let mut token_end = offset;
1111    let mut found_start = false;
1112    let mut found_end = false;
1113
1114    for ch in snapshot.reversed_chars_at(offset).take(LIMIT) {
1115        if ch.is_whitespace() {
1116            found_start = true;
1117            break;
1118        }
1119        token_start -= ch.len_utf8();
1120    }
1121    // Check if we didn't find the starting whitespace or if we didn't reach the start of the buffer
1122    if !found_start && token_start != 0 {
1123        return None;
1124    }
1125
1126    for ch in snapshot
1127        .chars_at(offset)
1128        .take(LIMIT - (offset - token_start))
1129    {
1130        if ch.is_whitespace() {
1131            found_end = true;
1132            break;
1133        }
1134        token_end += ch.len_utf8();
1135    }
1136    // Check if we didn't find the ending whitespace or if we read more or equal than LIMIT
1137    // which at this point would happen only if we reached the end of buffer
1138    if !found_end && (token_end - token_start >= LIMIT) {
1139        return None;
1140    }
1141
1142    let mut finder = LinkFinder::new();
1143    finder.kinds(&[LinkKind::Url]);
1144    let input = snapshot
1145        .text_for_range(token_start..token_end)
1146        .collect::<String>();
1147
1148    let relative_offset = offset - token_start;
1149    for link in finder.links(&input) {
1150        if link.start() <= relative_offset && link.end() >= relative_offset {
1151            let range = snapshot.anchor_before(token_start + link.start())
1152                ..snapshot.anchor_after(token_start + link.end());
1153            return Some((range, link.as_str().to_string()));
1154        }
1155    }
1156    None
1157}
1158
1159pub(crate) fn find_url_from_range(
1160    buffer: &Entity<language::Buffer>,
1161    range: Range<text::Anchor>,
1162    mut cx: AsyncWindowContext,
1163) -> Option<String> {
1164    const LIMIT: usize = 2048;
1165
1166    let Ok(snapshot) = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot()) else {
1167        return None;
1168    };
1169
1170    let start_offset = range.start.to_offset(&snapshot);
1171    let end_offset = range.end.to_offset(&snapshot);
1172
1173    let mut token_start = start_offset.min(end_offset);
1174    let mut token_end = start_offset.max(end_offset);
1175
1176    let range_len = token_end - token_start;
1177
1178    if range_len >= LIMIT {
1179        return None;
1180    }
1181
1182    // Skip leading whitespace
1183    for ch in snapshot.chars_at(token_start).take(range_len) {
1184        if !ch.is_whitespace() {
1185            break;
1186        }
1187        token_start += ch.len_utf8();
1188    }
1189
1190    // Skip trailing whitespace
1191    for ch in snapshot.reversed_chars_at(token_end).take(range_len) {
1192        if !ch.is_whitespace() {
1193            break;
1194        }
1195        token_end -= ch.len_utf8();
1196    }
1197
1198    if token_start >= token_end {
1199        return None;
1200    }
1201
1202    let text = snapshot
1203        .text_for_range(token_start..token_end)
1204        .collect::<String>();
1205
1206    let mut finder = LinkFinder::new();
1207    finder.kinds(&[LinkKind::Url]);
1208
1209    if let Some(link) = finder.links(&text).next() {
1210        if link.start() == 0 && link.end() == text.len() {
1211            return Some(link.as_str().to_string());
1212        }
1213    }
1214
1215    None
1216}
1217
1218pub(crate) async fn find_file(
1219    buffer: &Entity<language::Buffer>,
1220    project: Option<Entity<Project>>,
1221    position: text::Anchor,
1222    cx: &mut AsyncWindowContext,
1223) -> Option<(Range<text::Anchor>, ResolvedPath)> {
1224    let project = project?;
1225    let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
1226    let scope = snapshot.language_scope_at(position);
1227    let (range, candidate_file_path) = surrounding_filename(snapshot, position)?;
1228
1229    async fn check_path(
1230        candidate_file_path: &str,
1231        project: &Entity<Project>,
1232        buffer: &Entity<language::Buffer>,
1233        cx: &mut AsyncWindowContext,
1234    ) -> Option<ResolvedPath> {
1235        project
1236            .update(cx, |project, cx| {
1237                project.resolve_path_in_buffer(&candidate_file_path, buffer, cx)
1238            })
1239            .ok()?
1240            .await
1241            .filter(|s| s.is_file())
1242    }
1243
1244    if let Some(existing_path) = check_path(&candidate_file_path, &project, buffer, cx).await {
1245        return Some((range, existing_path));
1246    }
1247
1248    if let Some(scope) = scope {
1249        for suffix in scope.path_suffixes() {
1250            if candidate_file_path.ends_with(format!(".{suffix}").as_str()) {
1251                continue;
1252            }
1253
1254            let suffixed_candidate = format!("{candidate_file_path}.{suffix}");
1255            if let Some(existing_path) = check_path(&suffixed_candidate, &project, buffer, cx).await
1256            {
1257                return Some((range, existing_path));
1258            }
1259        }
1260    }
1261
1262    None
1263}
1264
1265fn surrounding_filename(
1266    snapshot: language::BufferSnapshot,
1267    position: text::Anchor,
1268) -> Option<(Range<text::Anchor>, String)> {
1269    const LIMIT: usize = 2048;
1270
1271    let offset = position.to_offset(&snapshot);
1272    let mut token_start = offset;
1273    let mut token_end = offset;
1274    let mut found_start = false;
1275    let mut found_end = false;
1276    let mut inside_quotes = false;
1277
1278    let mut filename = String::new();
1279
1280    let mut backwards = snapshot.reversed_chars_at(offset).take(LIMIT).peekable();
1281    while let Some(ch) = backwards.next() {
1282        // Escaped whitespace
1283        if ch.is_whitespace() && backwards.peek() == Some(&'\\') {
1284            filename.push(ch);
1285            token_start -= ch.len_utf8();
1286            backwards.next();
1287            token_start -= '\\'.len_utf8();
1288            continue;
1289        }
1290        if ch.is_whitespace() {
1291            found_start = true;
1292            break;
1293        }
1294        if (ch == '"' || ch == '\'') && !inside_quotes {
1295            found_start = true;
1296            inside_quotes = true;
1297            break;
1298        }
1299
1300        filename.push(ch);
1301        token_start -= ch.len_utf8();
1302    }
1303    if !found_start && token_start != 0 {
1304        return None;
1305    }
1306
1307    filename = filename.chars().rev().collect();
1308
1309    let mut forwards = snapshot
1310        .chars_at(offset)
1311        .take(LIMIT - (offset - token_start))
1312        .peekable();
1313    while let Some(ch) = forwards.next() {
1314        // Skip escaped whitespace
1315        if ch == '\\' && forwards.peek().map_or(false, |ch| ch.is_whitespace()) {
1316            token_end += ch.len_utf8();
1317            let whitespace = forwards.next().unwrap();
1318            token_end += whitespace.len_utf8();
1319            filename.push(whitespace);
1320            continue;
1321        }
1322
1323        if ch.is_whitespace() {
1324            found_end = true;
1325            break;
1326        }
1327        if ch == '"' || ch == '\'' {
1328            // If we're inside quotes, we stop when we come across the next quote
1329            if inside_quotes {
1330                found_end = true;
1331                break;
1332            } else {
1333                // Otherwise, we skip the quote
1334                inside_quotes = true;
1335                continue;
1336            }
1337        }
1338        filename.push(ch);
1339        token_end += ch.len_utf8();
1340    }
1341
1342    if !found_end && (token_end - token_start >= LIMIT) {
1343        return None;
1344    }
1345
1346    if filename.is_empty() {
1347        return None;
1348    }
1349
1350    let range = snapshot.anchor_before(token_start)..snapshot.anchor_after(token_end);
1351
1352    Some((range, filename))
1353}
1354
1355#[cfg(test)]
1356mod tests {
1357    use super::*;
1358    use crate::{
1359        DisplayPoint,
1360        display_map::ToDisplayPoint,
1361        editor_tests::init_test,
1362        inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
1363        test::editor_lsp_test_context::EditorLspTestContext,
1364    };
1365    use futures::StreamExt;
1366    use gpui::Modifiers;
1367    use indoc::indoc;
1368    use language::language_settings::InlayHintSettings;
1369    use lsp::request::{GotoDefinition, GotoTypeDefinition};
1370    use util::{assert_set_eq, path};
1371    use workspace::item::Item;
1372
1373    #[gpui::test]
1374    async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
1375        init_test(cx, |_| {});
1376
1377        let mut cx = EditorLspTestContext::new_rust(
1378            lsp::ServerCapabilities {
1379                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
1380                type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
1381                ..Default::default()
1382            },
1383            cx,
1384        )
1385        .await;
1386
1387        cx.set_state(indoc! {"
1388            struct A;
1389            let vˇariable = A;
1390        "});
1391        let screen_coord = cx.editor(|editor, _, cx| editor.pixel_position_of_cursor(cx));
1392
1393        // Basic hold cmd+shift, expect highlight in region if response contains type definition
1394        let symbol_range = cx.lsp_range(indoc! {"
1395            struct A;
1396            let «variable» = A;
1397        "});
1398        let target_range = cx.lsp_range(indoc! {"
1399            struct «A»;
1400            let variable = A;
1401        "});
1402
1403        cx.run_until_parked();
1404
1405        let mut requests =
1406            cx.set_request_handler::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
1407                Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
1408                    lsp::LocationLink {
1409                        origin_selection_range: Some(symbol_range),
1410                        target_uri: url.clone(),
1411                        target_range,
1412                        target_selection_range: target_range,
1413                    },
1414                ])))
1415            });
1416
1417        let modifiers = if cfg!(target_os = "macos") {
1418            Modifiers::command_shift()
1419        } else {
1420            Modifiers::control_shift()
1421        };
1422
1423        cx.simulate_mouse_move(screen_coord.unwrap(), None, modifiers);
1424
1425        requests.next().await;
1426        cx.run_until_parked();
1427        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1428            struct A;
1429            let «variable» = A;
1430        "});
1431
1432        cx.simulate_modifiers_change(Modifiers::secondary_key());
1433        cx.run_until_parked();
1434        // Assert no link highlights
1435        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1436            struct A;
1437            let variable = A;
1438        "});
1439
1440        cx.simulate_click(screen_coord.unwrap(), modifiers);
1441
1442        cx.assert_editor_state(indoc! {"
1443            struct «Aˇ»;
1444            let variable = A;
1445        "});
1446    }
1447
1448    #[gpui::test]
1449    async fn test_hover_links(cx: &mut gpui::TestAppContext) {
1450        init_test(cx, |_| {});
1451
1452        let mut cx = EditorLspTestContext::new_rust(
1453            lsp::ServerCapabilities {
1454                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
1455                definition_provider: Some(lsp::OneOf::Left(true)),
1456                ..Default::default()
1457            },
1458            cx,
1459        )
1460        .await;
1461
1462        cx.set_state(indoc! {"
1463                fn ˇtest() { do_work(); }
1464                fn do_work() { test(); }
1465            "});
1466
1467        // Basic hold cmd, expect highlight in region if response contains definition
1468        let hover_point = cx.pixel_position(indoc! {"
1469                fn test() { do_wˇork(); }
1470                fn do_work() { test(); }
1471            "});
1472        let symbol_range = cx.lsp_range(indoc! {"
1473                fn test() { «do_work»(); }
1474                fn do_work() { test(); }
1475            "});
1476        let target_range = cx.lsp_range(indoc! {"
1477                fn test() { do_work(); }
1478                fn «do_work»() { test(); }
1479            "});
1480
1481        let mut requests =
1482            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1483                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1484                    lsp::LocationLink {
1485                        origin_selection_range: Some(symbol_range),
1486                        target_uri: url.clone(),
1487                        target_range,
1488                        target_selection_range: target_range,
1489                    },
1490                ])))
1491            });
1492
1493        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1494        requests.next().await;
1495        cx.background_executor.run_until_parked();
1496        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1497                fn test() { «do_work»(); }
1498                fn do_work() { test(); }
1499            "});
1500
1501        // Unpress cmd causes highlight to go away
1502        cx.simulate_modifiers_change(Modifiers::none());
1503        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1504                fn test() { do_work(); }
1505                fn do_work() { test(); }
1506            "});
1507
1508        let mut requests =
1509            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1510                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1511                    lsp::LocationLink {
1512                        origin_selection_range: Some(symbol_range),
1513                        target_uri: url.clone(),
1514                        target_range,
1515                        target_selection_range: target_range,
1516                    },
1517                ])))
1518            });
1519
1520        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1521        requests.next().await;
1522        cx.background_executor.run_until_parked();
1523        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1524                fn test() { «do_work»(); }
1525                fn do_work() { test(); }
1526            "});
1527
1528        // Moving mouse to location with no response dismisses highlight
1529        let hover_point = cx.pixel_position(indoc! {"
1530                fˇn test() { do_work(); }
1531                fn do_work() { test(); }
1532            "});
1533        let mut requests =
1534            cx.lsp
1535                .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1536                    // No definitions returned
1537                    Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1538                });
1539        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1540
1541        requests.next().await;
1542        cx.background_executor.run_until_parked();
1543
1544        // Assert no link highlights
1545        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1546                fn test() { do_work(); }
1547                fn do_work() { test(); }
1548            "});
1549
1550        // // Move mouse without cmd and then pressing cmd triggers highlight
1551        let hover_point = cx.pixel_position(indoc! {"
1552                fn test() { do_work(); }
1553                fn do_work() { teˇst(); }
1554            "});
1555        cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1556
1557        // Assert no link highlights
1558        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1559                fn test() { do_work(); }
1560                fn do_work() { test(); }
1561            "});
1562
1563        let symbol_range = cx.lsp_range(indoc! {"
1564                fn test() { do_work(); }
1565                fn do_work() { «test»(); }
1566            "});
1567        let target_range = cx.lsp_range(indoc! {"
1568                fn «test»() { do_work(); }
1569                fn do_work() { test(); }
1570            "});
1571
1572        let mut requests =
1573            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1574                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1575                    lsp::LocationLink {
1576                        origin_selection_range: Some(symbol_range),
1577                        target_uri: url,
1578                        target_range,
1579                        target_selection_range: target_range,
1580                    },
1581                ])))
1582            });
1583
1584        cx.simulate_modifiers_change(Modifiers::secondary_key());
1585
1586        requests.next().await;
1587        cx.background_executor.run_until_parked();
1588
1589        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1590                fn test() { do_work(); }
1591                fn do_work() { «test»(); }
1592            "});
1593
1594        cx.deactivate_window();
1595        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1596                fn test() { do_work(); }
1597                fn do_work() { test(); }
1598            "});
1599
1600        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1601        cx.background_executor.run_until_parked();
1602        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1603                fn test() { do_work(); }
1604                fn do_work() { «test»(); }
1605            "});
1606
1607        // Moving again within the same symbol range doesn't re-request
1608        let hover_point = cx.pixel_position(indoc! {"
1609                fn test() { do_work(); }
1610                fn do_work() { tesˇt(); }
1611            "});
1612        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1613        cx.background_executor.run_until_parked();
1614        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1615                fn test() { do_work(); }
1616                fn do_work() { «test»(); }
1617            "});
1618
1619        // Cmd click with existing definition doesn't re-request and dismisses highlight
1620        cx.simulate_click(hover_point, Modifiers::secondary_key());
1621        cx.lsp
1622            .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1623                // Empty definition response to make sure we aren't hitting the lsp and using
1624                // the cached location instead
1625                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1626            });
1627        cx.background_executor.run_until_parked();
1628        cx.assert_editor_state(indoc! {"
1629                fn «testˇ»() { do_work(); }
1630                fn do_work() { test(); }
1631            "});
1632
1633        // Assert no link highlights after jump
1634        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1635                fn test() { do_work(); }
1636                fn do_work() { test(); }
1637            "});
1638
1639        // Cmd click without existing definition requests and jumps
1640        let hover_point = cx.pixel_position(indoc! {"
1641                fn test() { do_wˇork(); }
1642                fn do_work() { test(); }
1643            "});
1644        let target_range = cx.lsp_range(indoc! {"
1645                fn test() { do_work(); }
1646                fn «do_work»() { test(); }
1647            "});
1648
1649        let mut requests =
1650            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1651                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1652                    lsp::LocationLink {
1653                        origin_selection_range: None,
1654                        target_uri: url,
1655                        target_range,
1656                        target_selection_range: target_range,
1657                    },
1658                ])))
1659            });
1660        cx.simulate_click(hover_point, Modifiers::secondary_key());
1661        requests.next().await;
1662        cx.background_executor.run_until_parked();
1663        cx.assert_editor_state(indoc! {"
1664                fn test() { do_work(); }
1665                fn «do_workˇ»() { test(); }
1666            "});
1667
1668        // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
1669        // 2. Selection is completed, hovering
1670        let hover_point = cx.pixel_position(indoc! {"
1671                fn test() { do_wˇork(); }
1672                fn do_work() { test(); }
1673            "});
1674        let target_range = cx.lsp_range(indoc! {"
1675                fn test() { do_work(); }
1676                fn «do_work»() { test(); }
1677            "});
1678        let mut requests =
1679            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1680                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1681                    lsp::LocationLink {
1682                        origin_selection_range: None,
1683                        target_uri: url,
1684                        target_range,
1685                        target_selection_range: target_range,
1686                    },
1687                ])))
1688            });
1689
1690        // create a pending selection
1691        let selection_range = cx.ranges(indoc! {"
1692                fn «test() { do_w»ork(); }
1693                fn do_work() { test(); }
1694            "})[0]
1695            .clone();
1696        cx.update_editor(|editor, window, cx| {
1697            let snapshot = editor.buffer().read(cx).snapshot(cx);
1698            let anchor_range = snapshot.anchor_before(selection_range.start)
1699                ..snapshot.anchor_after(selection_range.end);
1700            editor.change_selections(Default::default(), window, cx, |s| {
1701                s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
1702            });
1703        });
1704        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1705        cx.background_executor.run_until_parked();
1706        assert!(requests.try_next().is_err());
1707        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1708                fn test() { do_work(); }
1709                fn do_work() { test(); }
1710            "});
1711        cx.background_executor.run_until_parked();
1712    }
1713
1714    #[gpui::test]
1715    async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
1716        init_test(cx, |settings| {
1717            settings.defaults.inlay_hints = Some(InlayHintSettings {
1718                enabled: true,
1719                show_value_hints: false,
1720                edit_debounce_ms: 0,
1721                scroll_debounce_ms: 0,
1722                show_type_hints: true,
1723                show_parameter_hints: true,
1724                show_other_hints: true,
1725                show_background: false,
1726                toggle_on_modifiers_press: None,
1727            })
1728        });
1729
1730        let mut cx = EditorLspTestContext::new_rust(
1731            lsp::ServerCapabilities {
1732                inlay_hint_provider: Some(lsp::OneOf::Left(true)),
1733                ..Default::default()
1734            },
1735            cx,
1736        )
1737        .await;
1738        cx.set_state(indoc! {"
1739                struct TestStruct;
1740
1741                fn main() {
1742                    let variableˇ = TestStruct;
1743                }
1744            "});
1745        let hint_start_offset = cx.ranges(indoc! {"
1746                struct TestStruct;
1747
1748                fn main() {
1749                    let variableˇ = TestStruct;
1750                }
1751            "})[0]
1752            .start;
1753        let hint_position = cx.to_lsp(hint_start_offset);
1754        let target_range = cx.lsp_range(indoc! {"
1755                struct «TestStruct»;
1756
1757                fn main() {
1758                    let variable = TestStruct;
1759                }
1760            "});
1761
1762        let expected_uri = cx.buffer_lsp_url.clone();
1763        let hint_label = ": TestStruct";
1764        cx.lsp
1765            .set_request_handler::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1766                let expected_uri = expected_uri.clone();
1767                async move {
1768                    assert_eq!(params.text_document.uri, expected_uri);
1769                    Ok(Some(vec![lsp::InlayHint {
1770                        position: hint_position,
1771                        label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1772                            value: hint_label.to_string(),
1773                            location: Some(lsp::Location {
1774                                uri: params.text_document.uri,
1775                                range: target_range,
1776                            }),
1777                            ..Default::default()
1778                        }]),
1779                        kind: Some(lsp::InlayHintKind::TYPE),
1780                        text_edits: None,
1781                        tooltip: None,
1782                        padding_left: Some(false),
1783                        padding_right: Some(false),
1784                        data: None,
1785                    }]))
1786                }
1787            })
1788            .next()
1789            .await;
1790        cx.background_executor.run_until_parked();
1791        cx.update_editor(|editor, _window, cx| {
1792            let expected_layers = vec![hint_label.to_string()];
1793            assert_eq!(expected_layers, cached_hint_labels(editor));
1794            assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1795        });
1796
1797        let inlay_range = cx
1798            .ranges(indoc! {"
1799                struct TestStruct;
1800
1801                fn main() {
1802                    let variable« »= TestStruct;
1803                }
1804            "})
1805            .first()
1806            .cloned()
1807            .unwrap();
1808        let midpoint = cx.update_editor(|editor, window, cx| {
1809            let snapshot = editor.snapshot(window, cx);
1810            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1811            let next_valid = inlay_range.end.to_display_point(&snapshot);
1812            assert_eq!(previous_valid.row(), next_valid.row());
1813            assert!(previous_valid.column() < next_valid.column());
1814            DisplayPoint::new(
1815                previous_valid.row(),
1816                previous_valid.column() + (hint_label.len() / 2) as u32,
1817            )
1818        });
1819        // Press cmd to trigger highlight
1820        let hover_point = cx.pixel_position_for(midpoint);
1821        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1822        cx.background_executor.run_until_parked();
1823        cx.update_editor(|editor, window, cx| {
1824            let snapshot = editor.snapshot(window, cx);
1825            let actual_highlights = snapshot
1826                .inlay_highlights::<HoveredLinkState>()
1827                .into_iter()
1828                .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1829                .collect::<Vec<_>>();
1830
1831            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1832            let expected_highlight = InlayHighlight {
1833                inlay: InlayId::Hint(0),
1834                inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1835                range: 0..hint_label.len(),
1836            };
1837            assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1838        });
1839
1840        cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1841        // Assert no link highlights
1842        cx.update_editor(|editor, window, cx| {
1843                let snapshot = editor.snapshot(window, cx);
1844                let actual_ranges = snapshot
1845                    .text_highlight_ranges::<HoveredLinkState>()
1846                    .map(|ranges| ranges.as_ref().clone().1)
1847                    .unwrap_or_default();
1848
1849                assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1850            });
1851
1852        cx.simulate_modifiers_change(Modifiers::secondary_key());
1853        cx.background_executor.run_until_parked();
1854        cx.simulate_click(hover_point, Modifiers::secondary_key());
1855        cx.background_executor.run_until_parked();
1856        cx.assert_editor_state(indoc! {"
1857                struct «TestStructˇ»;
1858
1859                fn main() {
1860                    let variable = TestStruct;
1861                }
1862            "});
1863    }
1864
1865    #[gpui::test]
1866    async fn test_urls(cx: &mut gpui::TestAppContext) {
1867        init_test(cx, |_| {});
1868        let mut cx = EditorLspTestContext::new_rust(
1869            lsp::ServerCapabilities {
1870                ..Default::default()
1871            },
1872            cx,
1873        )
1874        .await;
1875
1876        cx.set_state(indoc! {"
1877            Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1878        "});
1879
1880        let screen_coord = cx.pixel_position(indoc! {"
1881            Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1882            "});
1883
1884        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1885        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1886            Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1887        "});
1888
1889        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1890        assert_eq!(
1891            cx.opened_url(),
1892            Some("https://zed.dev/channel/had-(oops)".into())
1893        );
1894    }
1895
1896    #[gpui::test]
1897    async fn test_urls_at_beginning_of_buffer(cx: &mut gpui::TestAppContext) {
1898        init_test(cx, |_| {});
1899        let mut cx = EditorLspTestContext::new_rust(
1900            lsp::ServerCapabilities {
1901                ..Default::default()
1902            },
1903            cx,
1904        )
1905        .await;
1906
1907        cx.set_state(indoc! {"https://zed.dev/releases is a cool ˇwebpage."});
1908
1909        let screen_coord =
1910            cx.pixel_position(indoc! {"https://zed.dev/relˇeases is a cool webpage."});
1911
1912        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1913        cx.assert_editor_text_highlights::<HoveredLinkState>(
1914            indoc! {"«https://zed.dev/releasesˇ» is a cool webpage."},
1915        );
1916
1917        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1918        assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1919    }
1920
1921    #[gpui::test]
1922    async fn test_urls_at_end_of_buffer(cx: &mut gpui::TestAppContext) {
1923        init_test(cx, |_| {});
1924        let mut cx = EditorLspTestContext::new_rust(
1925            lsp::ServerCapabilities {
1926                ..Default::default()
1927            },
1928            cx,
1929        )
1930        .await;
1931
1932        cx.set_state(indoc! {"A cool ˇwebpage is https://zed.dev/releases"});
1933
1934        let screen_coord =
1935            cx.pixel_position(indoc! {"A cool webpage is https://zed.dev/releˇases"});
1936
1937        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1938        cx.assert_editor_text_highlights::<HoveredLinkState>(
1939            indoc! {"A cool webpage is «https://zed.dev/releasesˇ»"},
1940        );
1941
1942        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1943        assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1944    }
1945
1946    #[gpui::test]
1947    async fn test_surrounding_filename(cx: &mut gpui::TestAppContext) {
1948        init_test(cx, |_| {});
1949        let mut cx = EditorLspTestContext::new_rust(
1950            lsp::ServerCapabilities {
1951                ..Default::default()
1952            },
1953            cx,
1954        )
1955        .await;
1956
1957        let test_cases = [
1958            ("file ˇ name", None),
1959            ("ˇfile name", Some("file")),
1960            ("file ˇname", Some("name")),
1961            ("fiˇle name", Some("file")),
1962            ("filenˇame", Some("filename")),
1963            // Absolute path
1964            ("foobar ˇ/home/user/f.txt", Some("/home/user/f.txt")),
1965            ("foobar /home/useˇr/f.txt", Some("/home/user/f.txt")),
1966            // Windows
1967            ("C:\\Useˇrs\\user\\f.txt", Some("C:\\Users\\user\\f.txt")),
1968            // Whitespace
1969            ("ˇfile\\ -\\ name.txt", Some("file - name.txt")),
1970            ("file\\ -\\ naˇme.txt", Some("file - name.txt")),
1971            // Tilde
1972            ("ˇ~/file.txt", Some("~/file.txt")),
1973            ("~/fiˇle.txt", Some("~/file.txt")),
1974            // Double quotes
1975            ("\"fˇile.txt\"", Some("file.txt")),
1976            ("ˇ\"file.txt\"", Some("file.txt")),
1977            ("ˇ\"fi\\ le.txt\"", Some("fi le.txt")),
1978            // Single quotes
1979            ("'fˇile.txt'", Some("file.txt")),
1980            ("ˇ'file.txt'", Some("file.txt")),
1981            ("ˇ'fi\\ le.txt'", Some("fi le.txt")),
1982        ];
1983
1984        for (input, expected) in test_cases {
1985            cx.set_state(input);
1986
1987            let (position, snapshot) = cx.editor(|editor, _, cx| {
1988                let positions = editor.selections.newest_anchor().head().text_anchor;
1989                let snapshot = editor
1990                    .buffer()
1991                    .clone()
1992                    .read(cx)
1993                    .as_singleton()
1994                    .unwrap()
1995                    .read(cx)
1996                    .snapshot();
1997                (positions, snapshot)
1998            });
1999
2000            let result = surrounding_filename(snapshot, position);
2001
2002            if let Some(expected) = expected {
2003                assert!(result.is_some(), "Failed to find file path: {}", input);
2004                let (_, path) = result.unwrap();
2005                assert_eq!(&path, expected, "Incorrect file path for input: {}", input);
2006            } else {
2007                assert!(
2008                    result.is_none(),
2009                    "Expected no result, but got one: {:?}",
2010                    result
2011                );
2012            }
2013        }
2014    }
2015
2016    #[gpui::test]
2017    async fn test_hover_filenames(cx: &mut gpui::TestAppContext) {
2018        init_test(cx, |_| {});
2019        let mut cx = EditorLspTestContext::new_rust(
2020            lsp::ServerCapabilities {
2021                ..Default::default()
2022            },
2023            cx,
2024        )
2025        .await;
2026
2027        // Insert a new file
2028        let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2029        fs.as_fake()
2030            .insert_file(
2031                path!("/root/dir/file2.rs"),
2032                "This is file2.rs".as_bytes().to_vec(),
2033            )
2034            .await;
2035
2036        #[cfg(not(target_os = "windows"))]
2037        cx.set_state(indoc! {"
2038            You can't go to a file that does_not_exist.txt.
2039            Go to file2.rs if you want.
2040            Or go to ../dir/file2.rs if you want.
2041            Or go to /root/dir/file2.rs if project is local.
2042            Or go to /root/dir/file2 if this is a Rust file.ˇ
2043            "});
2044        #[cfg(target_os = "windows")]
2045        cx.set_state(indoc! {"
2046            You can't go to a file that does_not_exist.txt.
2047            Go to file2.rs if you want.
2048            Or go to ../dir/file2.rs if you want.
2049            Or go to C:/root/dir/file2.rs if project is local.
2050            Or go to C:/root/dir/file2 if this is a Rust file.ˇ
2051        "});
2052
2053        // File does not exist
2054        #[cfg(not(target_os = "windows"))]
2055        let screen_coord = cx.pixel_position(indoc! {"
2056            You can't go to a file that dˇoes_not_exist.txt.
2057            Go to file2.rs if you want.
2058            Or go to ../dir/file2.rs if you want.
2059            Or go to /root/dir/file2.rs if project is local.
2060            Or go to /root/dir/file2 if this is a Rust file.
2061        "});
2062        #[cfg(target_os = "windows")]
2063        let screen_coord = cx.pixel_position(indoc! {"
2064            You can't go to a file that dˇoes_not_exist.txt.
2065            Go to file2.rs if you want.
2066            Or go to ../dir/file2.rs if you want.
2067            Or go to C:/root/dir/file2.rs if project is local.
2068            Or go to C:/root/dir/file2 if this is a Rust file.
2069        "});
2070        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
2071        // No highlight
2072        cx.update_editor(|editor, window, cx| {
2073            assert!(
2074                editor
2075                    .snapshot(window, cx)
2076                    .text_highlight_ranges::<HoveredLinkState>()
2077                    .unwrap_or_default()
2078                    .1
2079                    .is_empty()
2080            );
2081        });
2082
2083        // Moving the mouse over a file that does exist should highlight it.
2084        #[cfg(not(target_os = "windows"))]
2085        let screen_coord = cx.pixel_position(indoc! {"
2086            You can't go to a file that does_not_exist.txt.
2087            Go to fˇile2.rs if you want.
2088            Or go to ../dir/file2.rs if you want.
2089            Or go to /root/dir/file2.rs if project is local.
2090            Or go to /root/dir/file2 if this is a Rust file.
2091        "});
2092        #[cfg(target_os = "windows")]
2093        let screen_coord = cx.pixel_position(indoc! {"
2094            You can't go to a file that does_not_exist.txt.
2095            Go to fˇile2.rs if you want.
2096            Or go to ../dir/file2.rs if you want.
2097            Or go to C:/root/dir/file2.rs if project is local.
2098            Or go to C:/root/dir/file2 if this is a Rust file.
2099        "});
2100
2101        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
2102        #[cfg(not(target_os = "windows"))]
2103        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2104            You can't go to a file that does_not_exist.txt.
2105            Go to «file2.rsˇ» if you want.
2106            Or go to ../dir/file2.rs if you want.
2107            Or go to /root/dir/file2.rs if project is local.
2108            Or go to /root/dir/file2 if this is a Rust file.
2109        "});
2110        #[cfg(target_os = "windows")]
2111        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2112            You can't go to a file that does_not_exist.txt.
2113            Go to «file2.rsˇ» if you want.
2114            Or go to ../dir/file2.rs if you want.
2115            Or go to C:/root/dir/file2.rs if project is local.
2116            Or go to C:/root/dir/file2 if this is a Rust file.
2117        "});
2118
2119        // Moving the mouse over a relative path that does exist should highlight it
2120        #[cfg(not(target_os = "windows"))]
2121        let screen_coord = cx.pixel_position(indoc! {"
2122            You can't go to a file that does_not_exist.txt.
2123            Go to file2.rs if you want.
2124            Or go to ../dir/fˇile2.rs if you want.
2125            Or go to /root/dir/file2.rs if project is local.
2126            Or go to /root/dir/file2 if this is a Rust file.
2127        "});
2128        #[cfg(target_os = "windows")]
2129        let screen_coord = cx.pixel_position(indoc! {"
2130            You can't go to a file that does_not_exist.txt.
2131            Go to file2.rs if you want.
2132            Or go to ../dir/fˇile2.rs if you want.
2133            Or go to C:/root/dir/file2.rs if project is local.
2134            Or go to C:/root/dir/file2 if this is a Rust file.
2135        "});
2136
2137        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
2138        #[cfg(not(target_os = "windows"))]
2139        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2140            You can't go to a file that does_not_exist.txt.
2141            Go to file2.rs if you want.
2142            Or go to «../dir/file2.rsˇ» if you want.
2143            Or go to /root/dir/file2.rs if project is local.
2144            Or go to /root/dir/file2 if this is a Rust file.
2145        "});
2146        #[cfg(target_os = "windows")]
2147        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2148            You can't go to a file that does_not_exist.txt.
2149            Go to file2.rs if you want.
2150            Or go to «../dir/file2.rsˇ» if you want.
2151            Or go to C:/root/dir/file2.rs if project is local.
2152            Or go to C:/root/dir/file2 if this is a Rust file.
2153        "});
2154
2155        // Moving the mouse over an absolute path that does exist should highlight it
2156        #[cfg(not(target_os = "windows"))]
2157        let screen_coord = cx.pixel_position(indoc! {"
2158            You can't go to a file that does_not_exist.txt.
2159            Go to file2.rs if you want.
2160            Or go to ../dir/file2.rs if you want.
2161            Or go to /root/diˇr/file2.rs if project is local.
2162            Or go to /root/dir/file2 if this is a Rust file.
2163        "});
2164
2165        #[cfg(target_os = "windows")]
2166        let screen_coord = cx.pixel_position(indoc! {"
2167            You can't go to a file that does_not_exist.txt.
2168            Go to file2.rs if you want.
2169            Or go to ../dir/file2.rs if you want.
2170            Or go to C:/root/diˇr/file2.rs if project is local.
2171            Or go to C:/root/dir/file2 if this is a Rust file.
2172        "});
2173
2174        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
2175        #[cfg(not(target_os = "windows"))]
2176        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2177            You can't go to a file that does_not_exist.txt.
2178            Go to file2.rs if you want.
2179            Or go to ../dir/file2.rs if you want.
2180            Or go to «/root/dir/file2.rsˇ» if project is local.
2181            Or go to /root/dir/file2 if this is a Rust file.
2182        "});
2183        #[cfg(target_os = "windows")]
2184        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2185            You can't go to a file that does_not_exist.txt.
2186            Go to file2.rs if you want.
2187            Or go to ../dir/file2.rs if you want.
2188            Or go to «C:/root/dir/file2.rsˇ» if project is local.
2189            Or go to C:/root/dir/file2 if this is a Rust file.
2190        "});
2191
2192        // Moving the mouse over a path that exists, if we add the language-specific suffix, it should highlight it
2193        #[cfg(not(target_os = "windows"))]
2194        let screen_coord = cx.pixel_position(indoc! {"
2195            You can't go to a file that does_not_exist.txt.
2196            Go to file2.rs if you want.
2197            Or go to ../dir/file2.rs if you want.
2198            Or go to /root/dir/file2.rs if project is local.
2199            Or go to /root/diˇr/file2 if this is a Rust file.
2200        "});
2201        #[cfg(target_os = "windows")]
2202        let screen_coord = cx.pixel_position(indoc! {"
2203            You can't go to a file that does_not_exist.txt.
2204            Go to file2.rs if you want.
2205            Or go to ../dir/file2.rs if you want.
2206            Or go to C:/root/dir/file2.rs if project is local.
2207            Or go to C:/root/diˇr/file2 if this is a Rust file.
2208        "});
2209
2210        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
2211        #[cfg(not(target_os = "windows"))]
2212        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2213            You can't go to a file that does_not_exist.txt.
2214            Go to file2.rs if you want.
2215            Or go to ../dir/file2.rs if you want.
2216            Or go to /root/dir/file2.rs if project is local.
2217            Or go to «/root/dir/file2ˇ» if this is a Rust file.
2218        "});
2219        #[cfg(target_os = "windows")]
2220        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
2221            You can't go to a file that does_not_exist.txt.
2222            Go to file2.rs if you want.
2223            Or go to ../dir/file2.rs if you want.
2224            Or go to C:/root/dir/file2.rs if project is local.
2225            Or go to «C:/root/dir/file2ˇ» if this is a Rust file.
2226        "});
2227
2228        cx.simulate_click(screen_coord, Modifiers::secondary_key());
2229
2230        cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
2231        cx.update_workspace(|workspace, _, cx| {
2232            let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
2233
2234            let buffer = active_editor
2235                .read(cx)
2236                .buffer()
2237                .read(cx)
2238                .as_singleton()
2239                .unwrap();
2240
2241            let file = buffer.read(cx).file().unwrap();
2242            let file_path = file.as_local().unwrap().abs_path(cx);
2243
2244            assert_eq!(
2245                file_path,
2246                std::path::PathBuf::from(path!("/root/dir/file2.rs"))
2247            );
2248        });
2249    }
2250
2251    #[gpui::test]
2252    async fn test_hover_directories(cx: &mut gpui::TestAppContext) {
2253        init_test(cx, |_| {});
2254        let mut cx = EditorLspTestContext::new_rust(
2255            lsp::ServerCapabilities {
2256                ..Default::default()
2257            },
2258            cx,
2259        )
2260        .await;
2261
2262        // Insert a new file
2263        let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
2264        fs.as_fake()
2265            .insert_file("/root/dir/file2.rs", "This is file2.rs".as_bytes().to_vec())
2266            .await;
2267
2268        cx.set_state(indoc! {"
2269            You can't open ../diˇr because it's a directory.
2270        "});
2271
2272        // File does not exist
2273        let screen_coord = cx.pixel_position(indoc! {"
2274            You can't open ../diˇr because it's a directory.
2275        "});
2276        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
2277
2278        // No highlight
2279        cx.update_editor(|editor, window, cx| {
2280            assert!(
2281                editor
2282                    .snapshot(window, cx)
2283                    .text_highlight_ranges::<HoveredLinkState>()
2284                    .unwrap_or_default()
2285                    .1
2286                    .is_empty()
2287            );
2288        });
2289
2290        // Does not open the directory
2291        cx.simulate_click(screen_coord, Modifiers::secondary_key());
2292        cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
2293    }
2294}