hover_links.rs

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