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