hover_links.rs

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