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, None);
 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                token_end += ch.len_utf8();
 902                continue;
 903            }
 904        }
 905        filename.push(ch);
 906        token_end += ch.len_utf8();
 907    }
 908
 909    if !found_end && (token_end - token_start >= LIMIT) {
 910        return None;
 911    }
 912
 913    if filename.is_empty() {
 914        return None;
 915    }
 916
 917    let range = snapshot.anchor_before(token_start)..snapshot.anchor_after(token_end);
 918
 919    Some((range, filename))
 920}
 921
 922#[cfg(test)]
 923mod tests {
 924    use super::*;
 925    use crate::{
 926        DisplayPoint,
 927        display_map::ToDisplayPoint,
 928        editor_tests::init_test,
 929        inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
 930        test::editor_lsp_test_context::EditorLspTestContext,
 931    };
 932    use futures::StreamExt;
 933    use gpui::Modifiers;
 934    use indoc::indoc;
 935    use lsp::request::{GotoDefinition, GotoTypeDefinition};
 936    use settings::InlayHintSettingsContent;
 937    use util::{assert_set_eq, path};
 938    use workspace::item::Item;
 939
 940    #[gpui::test]
 941    async fn test_hover_type_links(cx: &mut gpui::TestAppContext) {
 942        init_test(cx, |_| {});
 943
 944        let mut cx = EditorLspTestContext::new_rust(
 945            lsp::ServerCapabilities {
 946                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
 947                type_definition_provider: Some(lsp::TypeDefinitionProviderCapability::Simple(true)),
 948                ..Default::default()
 949            },
 950            cx,
 951        )
 952        .await;
 953
 954        cx.set_state(indoc! {"
 955            struct A;
 956            let vˇariable = A;
 957        "});
 958        let screen_coord = cx.editor(|editor, _, cx| editor.pixel_position_of_cursor(cx));
 959
 960        // Basic hold cmd+shift, expect highlight in region if response contains type definition
 961        let symbol_range = cx.lsp_range(indoc! {"
 962            struct A;
 963            let «variable» = A;
 964        "});
 965        let target_range = cx.lsp_range(indoc! {"
 966            struct «A»;
 967            let variable = A;
 968        "});
 969
 970        cx.run_until_parked();
 971
 972        let mut requests =
 973            cx.set_request_handler::<GotoTypeDefinition, _, _>(move |url, _, _| async move {
 974                Ok(Some(lsp::GotoTypeDefinitionResponse::Link(vec![
 975                    lsp::LocationLink {
 976                        origin_selection_range: Some(symbol_range),
 977                        target_uri: url.clone(),
 978                        target_range,
 979                        target_selection_range: target_range,
 980                    },
 981                ])))
 982            });
 983
 984        let modifiers = if cfg!(target_os = "macos") {
 985            Modifiers::command_shift()
 986        } else {
 987            Modifiers::control_shift()
 988        };
 989
 990        cx.simulate_mouse_move(screen_coord.unwrap(), None, modifiers);
 991
 992        requests.next().await;
 993        cx.run_until_parked();
 994        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
 995            struct A;
 996            let «variable» = A;
 997        "});
 998
 999        cx.simulate_modifiers_change(Modifiers::secondary_key());
1000        cx.run_until_parked();
1001        // Assert no link highlights
1002        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1003            struct A;
1004            let variable = A;
1005        "});
1006
1007        cx.simulate_click(screen_coord.unwrap(), modifiers);
1008
1009        cx.assert_editor_state(indoc! {"
1010            struct «Aˇ»;
1011            let variable = A;
1012        "});
1013    }
1014
1015    #[gpui::test]
1016    async fn test_hover_links(cx: &mut gpui::TestAppContext) {
1017        init_test(cx, |_| {});
1018
1019        let mut cx = EditorLspTestContext::new_rust(
1020            lsp::ServerCapabilities {
1021                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
1022                definition_provider: Some(lsp::OneOf::Left(true)),
1023                ..Default::default()
1024            },
1025            cx,
1026        )
1027        .await;
1028
1029        cx.set_state(indoc! {"
1030                fn ˇtest() { do_work(); }
1031                fn do_work() { test(); }
1032            "});
1033
1034        // Basic hold cmd, expect highlight in region if response contains definition
1035        let hover_point = cx.pixel_position(indoc! {"
1036                fn test() { do_wˇork(); }
1037                fn do_work() { test(); }
1038            "});
1039        let symbol_range = cx.lsp_range(indoc! {"
1040                fn test() { «do_work»(); }
1041                fn do_work() { test(); }
1042            "});
1043        let target_range = cx.lsp_range(indoc! {"
1044                fn test() { do_work(); }
1045                fn «do_work»() { test(); }
1046            "});
1047
1048        let mut requests =
1049            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1050                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1051                    lsp::LocationLink {
1052                        origin_selection_range: Some(symbol_range),
1053                        target_uri: url.clone(),
1054                        target_range,
1055                        target_selection_range: target_range,
1056                    },
1057                ])))
1058            });
1059
1060        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1061        requests.next().await;
1062        cx.background_executor.run_until_parked();
1063        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1064                fn test() { «do_work»(); }
1065                fn do_work() { test(); }
1066            "});
1067
1068        // Unpress cmd causes highlight to go away
1069        cx.simulate_modifiers_change(Modifiers::none());
1070        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1071                fn test() { do_work(); }
1072                fn do_work() { test(); }
1073            "});
1074
1075        let mut requests =
1076            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1077                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1078                    lsp::LocationLink {
1079                        origin_selection_range: Some(symbol_range),
1080                        target_uri: url.clone(),
1081                        target_range,
1082                        target_selection_range: target_range,
1083                    },
1084                ])))
1085            });
1086
1087        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1088        requests.next().await;
1089        cx.background_executor.run_until_parked();
1090        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1091                fn test() { «do_work»(); }
1092                fn do_work() { test(); }
1093            "});
1094
1095        // Moving mouse to location with no response dismisses highlight
1096        let hover_point = cx.pixel_position(indoc! {"
1097                fˇn test() { do_work(); }
1098                fn do_work() { test(); }
1099            "});
1100        let mut requests =
1101            cx.lsp
1102                .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1103                    // No definitions returned
1104                    Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1105                });
1106        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1107
1108        requests.next().await;
1109        cx.background_executor.run_until_parked();
1110
1111        // Assert no link highlights
1112        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1113                fn test() { do_work(); }
1114                fn do_work() { test(); }
1115            "});
1116
1117        // // Move mouse without cmd and then pressing cmd triggers highlight
1118        let hover_point = cx.pixel_position(indoc! {"
1119                fn test() { do_work(); }
1120                fn do_work() { teˇst(); }
1121            "});
1122        cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1123
1124        // Assert no link highlights
1125        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1126                fn test() { do_work(); }
1127                fn do_work() { test(); }
1128            "});
1129
1130        let symbol_range = cx.lsp_range(indoc! {"
1131                fn test() { do_work(); }
1132                fn do_work() { «test»(); }
1133            "});
1134        let target_range = cx.lsp_range(indoc! {"
1135                fn «test»() { do_work(); }
1136                fn do_work() { test(); }
1137            "});
1138
1139        let mut requests =
1140            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1141                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1142                    lsp::LocationLink {
1143                        origin_selection_range: Some(symbol_range),
1144                        target_uri: url,
1145                        target_range,
1146                        target_selection_range: target_range,
1147                    },
1148                ])))
1149            });
1150
1151        cx.simulate_modifiers_change(Modifiers::secondary_key());
1152
1153        requests.next().await;
1154        cx.background_executor.run_until_parked();
1155
1156        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1157                fn test() { do_work(); }
1158                fn do_work() { «test»(); }
1159            "});
1160
1161        cx.deactivate_window();
1162        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1163                fn test() { do_work(); }
1164                fn do_work() { test(); }
1165            "});
1166
1167        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1168        cx.background_executor.run_until_parked();
1169        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1170                fn test() { do_work(); }
1171                fn do_work() { «test»(); }
1172            "});
1173
1174        // Moving again within the same symbol range doesn't re-request
1175        let hover_point = cx.pixel_position(indoc! {"
1176                fn test() { do_work(); }
1177                fn do_work() { tesˇt(); }
1178            "});
1179        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1180        cx.background_executor.run_until_parked();
1181        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1182                fn test() { do_work(); }
1183                fn do_work() { «test»(); }
1184            "});
1185
1186        // Cmd click with existing definition doesn't re-request and dismisses highlight
1187        cx.simulate_click(hover_point, Modifiers::secondary_key());
1188        cx.lsp
1189            .set_request_handler::<GotoDefinition, _, _>(move |_, _| async move {
1190                // Empty definition response to make sure we aren't hitting the lsp and using
1191                // the cached location instead
1192                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![])))
1193            });
1194        cx.background_executor.run_until_parked();
1195        cx.assert_editor_state(indoc! {"
1196                fn «testˇ»() { do_work(); }
1197                fn do_work() { test(); }
1198            "});
1199
1200        // Assert no link highlights after jump
1201        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1202                fn test() { do_work(); }
1203                fn do_work() { test(); }
1204            "});
1205
1206        // Cmd click without existing definition requests and jumps
1207        let hover_point = cx.pixel_position(indoc! {"
1208                fn test() { do_wˇork(); }
1209                fn do_work() { test(); }
1210            "});
1211        let target_range = cx.lsp_range(indoc! {"
1212                fn test() { do_work(); }
1213                fn «do_work»() { test(); }
1214            "});
1215
1216        let mut requests =
1217            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1218                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1219                    lsp::LocationLink {
1220                        origin_selection_range: None,
1221                        target_uri: url,
1222                        target_range,
1223                        target_selection_range: target_range,
1224                    },
1225                ])))
1226            });
1227        cx.simulate_click(hover_point, Modifiers::secondary_key());
1228        requests.next().await;
1229        cx.background_executor.run_until_parked();
1230        cx.assert_editor_state(indoc! {"
1231                fn test() { do_work(); }
1232                fn «do_workˇ»() { test(); }
1233            "});
1234
1235        // 1. We have a pending selection, mouse point is over a symbol that we have a response for, hitting cmd and nothing happens
1236        // 2. Selection is completed, hovering
1237        let hover_point = cx.pixel_position(indoc! {"
1238                fn test() { do_wˇork(); }
1239                fn do_work() { test(); }
1240            "});
1241        let target_range = cx.lsp_range(indoc! {"
1242                fn test() { do_work(); }
1243                fn «do_work»() { test(); }
1244            "});
1245        let mut requests =
1246            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
1247                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
1248                    lsp::LocationLink {
1249                        origin_selection_range: None,
1250                        target_uri: url,
1251                        target_range,
1252                        target_selection_range: target_range,
1253                    },
1254                ])))
1255            });
1256
1257        // create a pending selection
1258        let selection_range = cx.ranges(indoc! {"
1259                fn «test() { do_w»ork(); }
1260                fn do_work() { test(); }
1261            "})[0]
1262            .clone();
1263        cx.update_editor(|editor, window, cx| {
1264            let snapshot = editor.buffer().read(cx).snapshot(cx);
1265            let anchor_range = snapshot.anchor_before(selection_range.start)
1266                ..snapshot.anchor_after(selection_range.end);
1267            editor.change_selections(Default::default(), window, cx, |s| {
1268                s.set_pending_anchor_range(anchor_range, crate::SelectMode::Character)
1269            });
1270        });
1271        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1272        cx.background_executor.run_until_parked();
1273        assert!(requests.try_next().is_err());
1274        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1275                fn test() { do_work(); }
1276                fn do_work() { test(); }
1277            "});
1278        cx.background_executor.run_until_parked();
1279    }
1280
1281    #[gpui::test]
1282    async fn test_inlay_hover_links(cx: &mut gpui::TestAppContext) {
1283        init_test(cx, |settings| {
1284            settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
1285                enabled: Some(true),
1286                show_value_hints: Some(false),
1287                edit_debounce_ms: Some(0),
1288                scroll_debounce_ms: Some(0),
1289                show_type_hints: Some(true),
1290                show_parameter_hints: Some(true),
1291                show_other_hints: Some(true),
1292                show_background: Some(false),
1293                toggle_on_modifiers_press: None,
1294            })
1295        });
1296
1297        let mut cx = EditorLspTestContext::new_rust(
1298            lsp::ServerCapabilities {
1299                inlay_hint_provider: Some(lsp::OneOf::Left(true)),
1300                ..Default::default()
1301            },
1302            cx,
1303        )
1304        .await;
1305        cx.set_state(indoc! {"
1306                struct TestStruct;
1307
1308                fn main() {
1309                    let variableˇ = TestStruct;
1310                }
1311            "});
1312        let hint_start_offset = cx.ranges(indoc! {"
1313                struct TestStruct;
1314
1315                fn main() {
1316                    let variableˇ = TestStruct;
1317                }
1318            "})[0]
1319            .start;
1320        let hint_position = cx.to_lsp(hint_start_offset);
1321        let target_range = cx.lsp_range(indoc! {"
1322                struct «TestStruct»;
1323
1324                fn main() {
1325                    let variable = TestStruct;
1326                }
1327            "});
1328
1329        let expected_uri = cx.buffer_lsp_url.clone();
1330        let hint_label = ": TestStruct";
1331        cx.lsp
1332            .set_request_handler::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1333                let expected_uri = expected_uri.clone();
1334                async move {
1335                    assert_eq!(params.text_document.uri, expected_uri);
1336                    Ok(Some(vec![lsp::InlayHint {
1337                        position: hint_position,
1338                        label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1339                            value: hint_label.to_string(),
1340                            location: Some(lsp::Location {
1341                                uri: params.text_document.uri,
1342                                range: target_range,
1343                            }),
1344                            ..Default::default()
1345                        }]),
1346                        kind: Some(lsp::InlayHintKind::TYPE),
1347                        text_edits: None,
1348                        tooltip: None,
1349                        padding_left: Some(false),
1350                        padding_right: Some(false),
1351                        data: None,
1352                    }]))
1353                }
1354            })
1355            .next()
1356            .await;
1357        cx.background_executor.run_until_parked();
1358        cx.update_editor(|editor, _window, cx| {
1359            let expected_layers = vec![hint_label.to_string()];
1360            assert_eq!(expected_layers, cached_hint_labels(editor));
1361            assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1362        });
1363
1364        let inlay_range = cx
1365            .ranges(indoc! {"
1366                struct TestStruct;
1367
1368                fn main() {
1369                    let variable« »= TestStruct;
1370                }
1371            "})
1372            .first()
1373            .cloned()
1374            .unwrap();
1375        let midpoint = cx.update_editor(|editor, window, cx| {
1376            let snapshot = editor.snapshot(window, cx);
1377            let previous_valid = inlay_range.start.to_display_point(&snapshot);
1378            let next_valid = inlay_range.end.to_display_point(&snapshot);
1379            assert_eq!(previous_valid.row(), next_valid.row());
1380            assert!(previous_valid.column() < next_valid.column());
1381            DisplayPoint::new(
1382                previous_valid.row(),
1383                previous_valid.column() + (hint_label.len() / 2) as u32,
1384            )
1385        });
1386        // Press cmd to trigger highlight
1387        let hover_point = cx.pixel_position_for(midpoint);
1388        cx.simulate_mouse_move(hover_point, None, Modifiers::secondary_key());
1389        cx.background_executor.run_until_parked();
1390        cx.update_editor(|editor, window, cx| {
1391            let snapshot = editor.snapshot(window, cx);
1392            let actual_highlights = snapshot
1393                .inlay_highlights::<HoveredLinkState>()
1394                .into_iter()
1395                .flat_map(|highlights| highlights.values().map(|(_, highlight)| highlight))
1396                .collect::<Vec<_>>();
1397
1398            let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1399            let expected_highlight = InlayHighlight {
1400                inlay: InlayId::Hint(0),
1401                inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1402                range: 0..hint_label.len(),
1403            };
1404            assert_set_eq!(actual_highlights, vec![&expected_highlight]);
1405        });
1406
1407        cx.simulate_mouse_move(hover_point, None, Modifiers::none());
1408        // Assert no link highlights
1409        cx.update_editor(|editor, window, cx| {
1410                let snapshot = editor.snapshot(window, cx);
1411                let actual_ranges = snapshot
1412                    .text_highlight_ranges::<HoveredLinkState>()
1413                    .map(|ranges| ranges.as_ref().clone().1)
1414                    .unwrap_or_default();
1415
1416                assert!(actual_ranges.is_empty(), "When no cmd is pressed, should have no hint label selected, but got: {actual_ranges:?}");
1417            });
1418
1419        cx.simulate_modifiers_change(Modifiers::secondary_key());
1420        cx.background_executor.run_until_parked();
1421        cx.simulate_click(hover_point, Modifiers::secondary_key());
1422        cx.background_executor.run_until_parked();
1423        cx.assert_editor_state(indoc! {"
1424                struct «TestStructˇ»;
1425
1426                fn main() {
1427                    let variable = TestStruct;
1428                }
1429            "});
1430    }
1431
1432    #[gpui::test]
1433    async fn test_urls(cx: &mut gpui::TestAppContext) {
1434        init_test(cx, |_| {});
1435        let mut cx = EditorLspTestContext::new_rust(
1436            lsp::ServerCapabilities {
1437                ..Default::default()
1438            },
1439            cx,
1440        )
1441        .await;
1442
1443        cx.set_state(indoc! {"
1444            Let's test a [complex](https://zed.dev/channel/had-(oops)) caseˇ.
1445        "});
1446
1447        let screen_coord = cx.pixel_position(indoc! {"
1448            Let's test a [complex](https://zed.dev/channel/had-(ˇoops)) case.
1449            "});
1450
1451        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1452        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1453            Let's test a [complex](«https://zed.dev/channel/had-(oops)ˇ») case.
1454        "});
1455
1456        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1457        assert_eq!(
1458            cx.opened_url(),
1459            Some("https://zed.dev/channel/had-(oops)".into())
1460        );
1461    }
1462
1463    #[gpui::test]
1464    async fn test_urls_at_beginning_of_buffer(cx: &mut gpui::TestAppContext) {
1465        init_test(cx, |_| {});
1466        let mut cx = EditorLspTestContext::new_rust(
1467            lsp::ServerCapabilities {
1468                ..Default::default()
1469            },
1470            cx,
1471        )
1472        .await;
1473
1474        cx.set_state(indoc! {"https://zed.dev/releases is a cool ˇwebpage."});
1475
1476        let screen_coord =
1477            cx.pixel_position(indoc! {"https://zed.dev/relˇeases is a cool webpage."});
1478
1479        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1480        cx.assert_editor_text_highlights::<HoveredLinkState>(
1481            indoc! {"«https://zed.dev/releasesˇ» is a cool webpage."},
1482        );
1483
1484        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1485        assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1486    }
1487
1488    #[gpui::test]
1489    async fn test_urls_at_end_of_buffer(cx: &mut gpui::TestAppContext) {
1490        init_test(cx, |_| {});
1491        let mut cx = EditorLspTestContext::new_rust(
1492            lsp::ServerCapabilities {
1493                ..Default::default()
1494            },
1495            cx,
1496        )
1497        .await;
1498
1499        cx.set_state(indoc! {"A cool ˇwebpage is https://zed.dev/releases"});
1500
1501        let screen_coord =
1502            cx.pixel_position(indoc! {"A cool webpage is https://zed.dev/releˇases"});
1503
1504        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1505        cx.assert_editor_text_highlights::<HoveredLinkState>(
1506            indoc! {"A cool webpage is «https://zed.dev/releasesˇ»"},
1507        );
1508
1509        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1510        assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
1511    }
1512
1513    #[gpui::test]
1514    async fn test_surrounding_filename(cx: &mut gpui::TestAppContext) {
1515        init_test(cx, |_| {});
1516        let mut cx = EditorLspTestContext::new_rust(
1517            lsp::ServerCapabilities {
1518                ..Default::default()
1519            },
1520            cx,
1521        )
1522        .await;
1523
1524        let test_cases = [
1525            ("file ˇ name", None),
1526            ("ˇfile name", Some("file")),
1527            ("file ˇname", Some("name")),
1528            ("fiˇle name", Some("file")),
1529            ("filenˇame", Some("filename")),
1530            // Absolute path
1531            ("foobar ˇ/home/user/f.txt", Some("/home/user/f.txt")),
1532            ("foobar /home/useˇr/f.txt", Some("/home/user/f.txt")),
1533            // Windows
1534            ("C:\\Useˇrs\\user\\f.txt", Some("C:\\Users\\user\\f.txt")),
1535            // Whitespace
1536            ("ˇfile\\ -\\ name.txt", Some("file - name.txt")),
1537            ("file\\ -\\ naˇme.txt", Some("file - name.txt")),
1538            // Tilde
1539            ("ˇ~/file.txt", Some("~/file.txt")),
1540            ("~/fiˇle.txt", Some("~/file.txt")),
1541            // Double quotes
1542            ("\"fˇile.txt\"", Some("file.txt")),
1543            ("ˇ\"file.txt\"", Some("file.txt")),
1544            ("ˇ\"fi\\ le.txt\"", Some("fi le.txt")),
1545            // Single quotes
1546            ("'fˇile.txt'", Some("file.txt")),
1547            ("ˇ'file.txt'", Some("file.txt")),
1548            ("ˇ'fi\\ le.txt'", Some("fi le.txt")),
1549            // Quoted multibyte characters
1550            (" ˇ\"\"", Some("")),
1551            (" \"ˇ常\"", Some("")),
1552            ("ˇ\"\"", Some("")),
1553        ];
1554
1555        for (input, expected) in test_cases {
1556            cx.set_state(input);
1557
1558            let (position, snapshot) = cx.editor(|editor, _, cx| {
1559                let positions = editor.selections.newest_anchor().head().text_anchor;
1560                let snapshot = editor
1561                    .buffer()
1562                    .clone()
1563                    .read(cx)
1564                    .as_singleton()
1565                    .unwrap()
1566                    .read(cx)
1567                    .snapshot();
1568                (positions, snapshot)
1569            });
1570
1571            let result = surrounding_filename(snapshot, position);
1572
1573            if let Some(expected) = expected {
1574                assert!(result.is_some(), "Failed to find file path: {}", input);
1575                let (_, path) = result.unwrap();
1576                assert_eq!(&path, expected, "Incorrect file path for input: {}", input);
1577            } else {
1578                assert!(
1579                    result.is_none(),
1580                    "Expected no result, but got one: {:?}",
1581                    result
1582                );
1583            }
1584        }
1585    }
1586
1587    #[gpui::test]
1588    async fn test_hover_filenames(cx: &mut gpui::TestAppContext) {
1589        init_test(cx, |_| {});
1590        let mut cx = EditorLspTestContext::new_rust(
1591            lsp::ServerCapabilities {
1592                ..Default::default()
1593            },
1594            cx,
1595        )
1596        .await;
1597
1598        // Insert a new file
1599        let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1600        fs.as_fake()
1601            .insert_file(
1602                path!("/root/dir/file2.rs"),
1603                "This is file2.rs".as_bytes().to_vec(),
1604            )
1605            .await;
1606
1607        #[cfg(not(target_os = "windows"))]
1608        cx.set_state(indoc! {"
1609            You can't go to a file that does_not_exist.txt.
1610            Go to file2.rs if you want.
1611            Or go to ../dir/file2.rs if you want.
1612            Or go to /root/dir/file2.rs if project is local.
1613            Or go to /root/dir/file2 if this is a Rust file.ˇ
1614            "});
1615        #[cfg(target_os = "windows")]
1616        cx.set_state(indoc! {"
1617            You can't go to a file that does_not_exist.txt.
1618            Go to file2.rs if you want.
1619            Or go to ../dir/file2.rs if you want.
1620            Or go to C:/root/dir/file2.rs if project is local.
1621            Or go to C:/root/dir/file2 if this is a Rust file.ˇ
1622        "});
1623
1624        // File does not exist
1625        #[cfg(not(target_os = "windows"))]
1626        let screen_coord = cx.pixel_position(indoc! {"
1627            You can't go to a file that dˇoes_not_exist.txt.
1628            Go to file2.rs if you want.
1629            Or go to ../dir/file2.rs if you want.
1630            Or go to /root/dir/file2.rs if project is local.
1631            Or go to /root/dir/file2 if this is a Rust file.
1632        "});
1633        #[cfg(target_os = "windows")]
1634        let screen_coord = cx.pixel_position(indoc! {"
1635            You can't go to a file that dˇoes_not_exist.txt.
1636            Go to file2.rs if you want.
1637            Or go to ../dir/file2.rs if you want.
1638            Or go to C:/root/dir/file2.rs if project is local.
1639            Or go to C:/root/dir/file2 if this is a Rust file.
1640        "});
1641        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1642        // No highlight
1643        cx.update_editor(|editor, window, cx| {
1644            assert!(
1645                editor
1646                    .snapshot(window, cx)
1647                    .text_highlight_ranges::<HoveredLinkState>()
1648                    .unwrap_or_default()
1649                    .1
1650                    .is_empty()
1651            );
1652        });
1653
1654        // Moving the mouse over a file that does exist should highlight it.
1655        #[cfg(not(target_os = "windows"))]
1656        let screen_coord = cx.pixel_position(indoc! {"
1657            You can't go to a file that does_not_exist.txt.
1658            Go to fˇile2.rs if you want.
1659            Or go to ../dir/file2.rs if you want.
1660            Or go to /root/dir/file2.rs if project is local.
1661            Or go to /root/dir/file2 if this is a Rust file.
1662        "});
1663        #[cfg(target_os = "windows")]
1664        let screen_coord = cx.pixel_position(indoc! {"
1665            You can't go to a file that does_not_exist.txt.
1666            Go to fˇile2.rs if you want.
1667            Or go to ../dir/file2.rs if you want.
1668            Or go to C:/root/dir/file2.rs if project is local.
1669            Or go to C:/root/dir/file2 if this is a Rust file.
1670        "});
1671
1672        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1673        #[cfg(not(target_os = "windows"))]
1674        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1675            You can't go to a file that does_not_exist.txt.
1676            Go to «file2.rsˇ» if you want.
1677            Or go to ../dir/file2.rs if you want.
1678            Or go to /root/dir/file2.rs if project is local.
1679            Or go to /root/dir/file2 if this is a Rust file.
1680        "});
1681        #[cfg(target_os = "windows")]
1682        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1683            You can't go to a file that does_not_exist.txt.
1684            Go to «file2.rsˇ» if you want.
1685            Or go to ../dir/file2.rs if you want.
1686            Or go to C:/root/dir/file2.rs if project is local.
1687            Or go to C:/root/dir/file2 if this is a Rust file.
1688        "});
1689
1690        // Moving the mouse over a relative path that does exist should highlight it
1691        #[cfg(not(target_os = "windows"))]
1692        let screen_coord = cx.pixel_position(indoc! {"
1693            You can't go to a file that does_not_exist.txt.
1694            Go to file2.rs if you want.
1695            Or go to ../dir/fˇile2.rs if you want.
1696            Or go to /root/dir/file2.rs if project is local.
1697            Or go to /root/dir/file2 if this is a Rust file.
1698        "});
1699        #[cfg(target_os = "windows")]
1700        let screen_coord = cx.pixel_position(indoc! {"
1701            You can't go to a file that does_not_exist.txt.
1702            Go to file2.rs if you want.
1703            Or go to ../dir/fˇile2.rs if you want.
1704            Or go to C:/root/dir/file2.rs if project is local.
1705            Or go to C:/root/dir/file2 if this is a Rust file.
1706        "});
1707
1708        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1709        #[cfg(not(target_os = "windows"))]
1710        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1711            You can't go to a file that does_not_exist.txt.
1712            Go to file2.rs if you want.
1713            Or go to «../dir/file2.rsˇ» if you want.
1714            Or go to /root/dir/file2.rs if project is local.
1715            Or go to /root/dir/file2 if this is a Rust file.
1716        "});
1717        #[cfg(target_os = "windows")]
1718        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1719            You can't go to a file that does_not_exist.txt.
1720            Go to file2.rs if you want.
1721            Or go to «../dir/file2.rsˇ» if you want.
1722            Or go to C:/root/dir/file2.rs if project is local.
1723            Or go to C:/root/dir/file2 if this is a Rust file.
1724        "});
1725
1726        // Moving the mouse over an absolute path that does exist should highlight it
1727        #[cfg(not(target_os = "windows"))]
1728        let screen_coord = cx.pixel_position(indoc! {"
1729            You can't go to a file that does_not_exist.txt.
1730            Go to file2.rs if you want.
1731            Or go to ../dir/file2.rs if you want.
1732            Or go to /root/diˇr/file2.rs if project is local.
1733            Or go to /root/dir/file2 if this is a Rust file.
1734        "});
1735
1736        #[cfg(target_os = "windows")]
1737        let screen_coord = cx.pixel_position(indoc! {"
1738            You can't go to a file that does_not_exist.txt.
1739            Go to file2.rs if you want.
1740            Or go to ../dir/file2.rs if you want.
1741            Or go to C:/root/diˇr/file2.rs if project is local.
1742            Or go to C:/root/dir/file2 if this is a Rust file.
1743        "});
1744
1745        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1746        #[cfg(not(target_os = "windows"))]
1747        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1748            You can't go to a file that does_not_exist.txt.
1749            Go to file2.rs if you want.
1750            Or go to ../dir/file2.rs if you want.
1751            Or go to «/root/dir/file2.rsˇ» if project is local.
1752            Or go to /root/dir/file2 if this is a Rust file.
1753        "});
1754        #[cfg(target_os = "windows")]
1755        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1756            You can't go to a file that does_not_exist.txt.
1757            Go to file2.rs if you want.
1758            Or go to ../dir/file2.rs if you want.
1759            Or go to «C:/root/dir/file2.rsˇ» if project is local.
1760            Or go to C:/root/dir/file2 if this is a Rust file.
1761        "});
1762
1763        // Moving the mouse over a path that exists, if we add the language-specific suffix, it should highlight it
1764        #[cfg(not(target_os = "windows"))]
1765        let screen_coord = cx.pixel_position(indoc! {"
1766            You can't go to a file that does_not_exist.txt.
1767            Go to file2.rs if you want.
1768            Or go to ../dir/file2.rs if you want.
1769            Or go to /root/dir/file2.rs if project is local.
1770            Or go to /root/diˇr/file2 if this is a Rust file.
1771        "});
1772        #[cfg(target_os = "windows")]
1773        let screen_coord = cx.pixel_position(indoc! {"
1774            You can't go to a file that does_not_exist.txt.
1775            Go to file2.rs if you want.
1776            Or go to ../dir/file2.rs if you want.
1777            Or go to C:/root/dir/file2.rs if project is local.
1778            Or go to C:/root/diˇr/file2 if this is a Rust file.
1779        "});
1780
1781        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1782        #[cfg(not(target_os = "windows"))]
1783        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1784            You can't go to a file that does_not_exist.txt.
1785            Go to file2.rs if you want.
1786            Or go to ../dir/file2.rs if you want.
1787            Or go to /root/dir/file2.rs if project is local.
1788            Or go to «/root/dir/file2ˇ» if this is a Rust file.
1789        "});
1790        #[cfg(target_os = "windows")]
1791        cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
1792            You can't go to a file that does_not_exist.txt.
1793            Go to file2.rs if you want.
1794            Or go to ../dir/file2.rs if you want.
1795            Or go to C:/root/dir/file2.rs if project is local.
1796            Or go to «C:/root/dir/file2ˇ» if this is a Rust file.
1797        "});
1798
1799        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1800
1801        cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 2));
1802        cx.update_workspace(|workspace, _, cx| {
1803            let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
1804
1805            let buffer = active_editor
1806                .read(cx)
1807                .buffer()
1808                .read(cx)
1809                .as_singleton()
1810                .unwrap();
1811
1812            let file = buffer.read(cx).file().unwrap();
1813            let file_path = file.as_local().unwrap().abs_path(cx);
1814
1815            assert_eq!(
1816                file_path,
1817                std::path::PathBuf::from(path!("/root/dir/file2.rs"))
1818            );
1819        });
1820    }
1821
1822    #[gpui::test]
1823    async fn test_hover_directories(cx: &mut gpui::TestAppContext) {
1824        init_test(cx, |_| {});
1825        let mut cx = EditorLspTestContext::new_rust(
1826            lsp::ServerCapabilities {
1827                ..Default::default()
1828            },
1829            cx,
1830        )
1831        .await;
1832
1833        // Insert a new file
1834        let fs = cx.update_workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
1835        fs.as_fake()
1836            .insert_file("/root/dir/file2.rs", "This is file2.rs".as_bytes().to_vec())
1837            .await;
1838
1839        cx.set_state(indoc! {"
1840            You can't open ../diˇr because it's a directory.
1841        "});
1842
1843        // File does not exist
1844        let screen_coord = cx.pixel_position(indoc! {"
1845            You can't open ../diˇr because it's a directory.
1846        "});
1847        cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
1848
1849        // No highlight
1850        cx.update_editor(|editor, window, cx| {
1851            assert!(
1852                editor
1853                    .snapshot(window, cx)
1854                    .text_highlight_ranges::<HoveredLinkState>()
1855                    .unwrap_or_default()
1856                    .1
1857                    .is_empty()
1858            );
1859        });
1860
1861        // Does not open the directory
1862        cx.simulate_click(screen_coord, Modifiers::secondary_key());
1863        cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
1864    }
1865}