Skip to main content

gpui_base/input/editor/lsp/
hover.rs

1use anyhow::Result;
2use gpui::{App, Context, MouseMoveEvent, Task, Window};
3use instant::Duration;
4use ropey::Rope;
5
6use crate::input::{EditorMode, HoverPopoverState, InputBaseState, RopeExt, ShowHover};
7
8/// Hover provider
9///
10/// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_hover
11pub trait HoverProvider {
12    /// textDocument/hover
13    ///
14    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_hover
15    fn hover(
16        &self,
17        _text: &Rope,
18        _offset: usize,
19        _window: &mut Window,
20        _cx: &mut App,
21    ) -> Task<Result<Option<lsp_types::Hover>>>;
22}
23
24impl InputBaseState<EditorMode> {
25    /// Handle hover trigger LSP request.
26    pub(super) fn handle_hover_popover(
27        &mut self,
28        offset: usize,
29        window: &mut Window,
30        cx: &mut Context<InputBaseState<EditorMode>>,
31    ) {
32        if self.selecting {
33            return;
34        }
35
36        let Some(provider) = self.extras.lsp.hover_provider.clone() else {
37            return;
38        };
39
40        if let Some(hover_popover) = self.extras.hover_popover.as_ref() {
41            if hover_popover.symbol_range.contains(&offset) {
42                return;
43            }
44        }
45
46        let text = self.text.clone();
47        let symbol_range = self.text.word_range(offset).unwrap_or(offset..offset);
48        let editor = cx.entity();
49        let should_delay = self.extras.hover_popover.is_none();
50        // Ask the provider only after the delay: every mouse move replaces this
51        // task, so positions the pointer merely passes over never reach it.
52        self.extras.lsp._hover_task = cx.spawn_in(window, async move |this, cx| {
53            if should_delay {
54                cx.background_executor()
55                    .timer(Duration::from_millis(150))
56                    .await;
57            }
58
59            let task = this.update_in(cx, |_, window, cx| {
60                provider.hover(&text, offset, window, cx)
61            })?;
62            let result = task.await?;
63
64            _ = editor.update(cx, |editor, cx| {
65                editor.apply_hover_result(result, symbol_range, cx);
66            });
67
68            Ok(())
69        });
70    }
71
72    /// Show the provider's answer anchored to `symbol_range`, or close the
73    /// popover when there is none. The answer's own range takes precedence.
74    fn apply_hover_result(
75        &mut self,
76        result: Option<lsp_types::Hover>,
77        mut symbol_range: std::ops::Range<usize>,
78        cx: &mut Context<Self>,
79    ) {
80        match result {
81            Some(hover) => {
82                if let Some(range) = hover.range {
83                    let start = self.text.position_to_offset(&range.start);
84                    let end = self.text.position_to_offset(&range.end);
85                    symbol_range = start..end;
86                }
87                self.extras.hover_popover = Some(HoverPopoverState {
88                    symbol_range,
89                    hover,
90                });
91            }
92            None => {
93                self.extras.hover_popover = None;
94            }
95        }
96        cx.notify();
97    }
98
99    pub(crate) fn on_action_show_hover(
100        &mut self,
101        _: &ShowHover,
102        window: &mut Window,
103        cx: &mut Context<Self>,
104    ) {
105        self.show_hover(window, cx);
106    }
107
108    /// Ask the [`HoverProvider`] about the caret and open the hover popover
109    /// there, as resting the mouse on the text does. Focuses the editor.
110    ///
111    /// There is no default keybinding; applications can dispatch [`ShowHover`]
112    /// in the `Input && mode == editor` context or call this method from a
113    /// command.
114    ///
115    /// The popover is shown without the mouse delay. Escape, editing, moving
116    /// the caret and losing focus close it, and a late answer is dropped once
117    /// any of those happened. Disabled editors, editors without a provider and
118    /// IME preedit issue no request; a popover already open for the symbol
119    /// under the caret is left as it is.
120    pub fn show_hover(&mut self, window: &mut Window, cx: &mut Context<Self>) {
121        if self.disabled || self.ime_marked_range.is_some() {
122            return;
123        }
124        let Some(provider) = self.extras.lsp.hover_provider.clone() else {
125            return;
126        };
127
128        let offset = self.cursor();
129        self.focus(window, cx);
130        if let Some(hover_popover) = self.extras.hover_popover.as_ref() {
131            if hover_popover.symbol_range.contains(&offset) {
132                return;
133            }
134        }
135
136        let symbol_range = self.text.word_range(offset).unwrap_or(offset..offset);
137        let revision = self.document_revision;
138        let task = provider.hover(&self.text, offset, window, cx);
139        self.extras.lsp._show_hover_task = cx.spawn_in(window, async move |editor, cx| {
140            let result = task.await?;
141            editor.update_in(cx, |editor, window, cx| {
142                if !editor.focus_handle.is_focused(window)
143                    || editor.document_revision != revision
144                    || editor.cursor() != offset
145                    || editor.ime_marked_range.is_some()
146                {
147                    return;
148                }
149                editor.apply_hover_result(result, symbol_range, cx);
150            })?;
151            Ok(())
152        });
153    }
154
155    /// Close the hover popover and cancel a pending [`ShowHover`] request.
156    ///
157    /// Unlike [`Self::clear_hover_state`], this leaves the go-to-definition
158    /// underline and its pending lookup alone, so a caret move made by the same
159    /// click does not cancel them.
160    pub(crate) fn dismiss_hover_popover(&mut self, cx: &mut Context<Self>) {
161        self.extras.lsp._show_hover_task = Task::ready(Ok(()));
162        if self.extras.hover_popover.take().is_some() {
163            cx.notify();
164        }
165    }
166
167    pub(crate) fn handle_mouse_move(
168        &mut self,
169        offset: usize,
170        event: &MouseMoveEvent,
171        window: &mut Window,
172        cx: &mut Context<Self>,
173    ) {
174        if event.modifiers.alt {
175            self.clear_hover_state(cx);
176            return;
177        }
178        if event.modifiers.secondary(cx) {
179            self.handle_hover_definition(offset, window, cx);
180        } else {
181            // Repaint only when the definition underline goes away; the hover
182            // and definition results notify when they arrive.
183            if !self.extras.hover_definition.is_empty() {
184                self.extras.hover_definition.clear();
185                cx.notify();
186            }
187            self.handle_hover_popover(offset, window, cx);
188        }
189    }
190
191    pub fn clear_hover_state(&mut self, cx: &mut Context<Self>) {
192        let changed =
193            !self.extras.hover_definition.is_empty() || self.extras.hover_popover.is_some();
194        self.extras.hover_definition.clear();
195        self.extras.hover_popover = None;
196        self.extras.lsp._hover_task = Task::ready(Ok(()));
197        self.extras.lsp._show_hover_task = Task::ready(Ok(()));
198        if changed {
199            cx.notify();
200        }
201    }
202}