hover_links.rs

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