hover_links.rs

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