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