hover_links.rs

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