hover_links.rs

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