Skip to main content

gpui_base/input/editor/lsp/
completions.rs

1use crate::input::EditorMode;
2use anyhow::Result;
3use gpui::{App, Context, EntityInputHandler, Pixels, Task, Window, px};
4use lsp_types::{
5    CompletionContext, CompletionItem, CompletionResponse, InlineCompletionContext,
6    InlineCompletionItem, InlineCompletionResponse, InlineCompletionTriggerKind,
7    request::Completion,
8};
9use ropey::Rope;
10use std::{cell::RefCell, ops::Range, rc::Rc, time::Duration};
11
12use crate::input::InputBaseState;
13
14/// Default debounce duration for inline completions.
15const DEFAULT_INLINE_COMPLETION_DEBOUNCE: Duration = Duration::from_millis(300);
16
17/// Display options for the LSP completion popover.
18///
19/// Accessed through [`super::Lsp::completion_menu`] so embedders can tweak the
20/// popover without growing the [`InputBaseState`] API.
21#[derive(Debug, Clone, Copy)]
22pub struct CompletionMenuOptions {
23    /// Maximum width of the popover.
24    ///
25    /// Defaults to 320 px, which is fine for most identifiers but can
26    /// truncate longer labels. Widen this when hosting an editor that
27    /// surfaces long completion labels.
28    pub max_width: Pixels,
29}
30
31impl Default for CompletionMenuOptions {
32    fn default() -> Self {
33        Self {
34            max_width: px(320.),
35        }
36    }
37}
38
39/// A trait for providing code completions based on the current input state and context.
40pub trait CompletionProvider {
41    /// Fetches completions based on the given byte offset.
42    ///
43    /// - The `offset` is in bytes of current cursor.
44    ///
45    /// textDocument/completion
46    ///
47    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion
48    fn completions(
49        &self,
50        text: &Rope,
51        offset: usize,
52        trigger: CompletionContext,
53        window: &mut Window,
54        cx: &mut App,
55    ) -> Task<Result<CompletionResponse>>;
56
57    /// Fetches an inline completion suggestion for the given position.
58    ///
59    /// This is called after a debounce period when the user stops typing.
60    /// The provider can analyze the text and cursor position to determine
61    /// what inline completion suggestion to show.
62    ///
63    ///
64    /// # Arguments
65    /// * `rope` - The current text content
66    /// * `offset` - The cursor position in bytes
67    ///
68    /// textDocument/inlineCompletion
69    ///
70    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.18/specification/#textDocument_inlineCompletion
71    fn inline_completion(
72        &self,
73        _rope: &Rope,
74        _offset: usize,
75        _trigger: InlineCompletionContext,
76        _window: &mut Window,
77        _cx: &mut App,
78    ) -> Task<Result<InlineCompletionResponse>> {
79        Task::ready(Ok(InlineCompletionResponse::Array(vec![])))
80    }
81
82    /// Returns the debounce duration for inline completions.
83    ///
84    /// Default: 300ms
85    #[inline]
86    fn inline_completion_debounce(&self) -> Duration {
87        DEFAULT_INLINE_COMPLETION_DEBOUNCE
88    }
89
90    fn resolve_completions(
91        &self,
92        _completion_indices: Vec<usize>,
93        _completions: Rc<RefCell<Box<[Completion]>>>,
94        _: &mut App,
95    ) -> Task<Result<bool>> {
96        Task::ready(Ok(false))
97    }
98
99    /// Determines if the completion should be triggered based on the given byte offset.
100    ///
101    /// This is called on the main thread.
102    fn is_completion_trigger(&self, offset: usize, new_text: &str, cx: &mut App) -> bool;
103}
104
105pub(crate) struct InlineCompletion {
106    /// Completion item to display as an inline completion suggestion
107    pub(crate) item: Option<InlineCompletionItem>,
108    /// Task for debouncing inline completion requests
109    pub(crate) task: Task<Result<InlineCompletionResponse>>,
110}
111
112impl Default for InlineCompletion {
113    fn default() -> Self {
114        Self {
115            item: None,
116            task: Task::ready(Ok(InlineCompletionResponse::Array(vec![]))),
117        }
118    }
119}
120
121impl InputBaseState<EditorMode> {
122    pub(crate) fn handle_completion_trigger(
123        &mut self,
124        _range: &Range<usize>,
125        new_text: &str,
126        window: &mut Window,
127        cx: &mut Context<Self>,
128    ) {
129        if self.completion_inserting {
130            return;
131        }
132
133        let Some(provider) = self.extras.lsp.completion_provider.clone() else {
134            return;
135        };
136
137        // Always schedule inline completion (debounced).
138        // It will check if menu is open before showing the suggestion.
139        self.schedule_inline_completion(window, cx);
140
141        let new_offset = self.cursor();
142        // Measure the inserted text in the current document. The replaced range
143        // uses pre-edit coordinates, which preceding multi-cursor edits can
144        // shift. The active caret ends immediately after the normalized input,
145        // including selection replacements and IME commits.
146        let Some(start) = new_offset.checked_sub(new_text.len()) else {
147            return;
148        };
149
150        if !provider.is_completion_trigger(start, new_text, cx) {
151            return;
152        }
153
154        // `trigger_start_offset` latches where the word a menu was opened for
155        // begins, so later keystrokes refine the same query instead of starting
156        // over at each character. It only describes this edit while the edit
157        // continues that word: the document between the latch and the edit
158        // must still read as a prefix of the last query. Deleting back into
159        // the word keeps it; typing somewhere else, or into a document that
160        // has since been replaced, starts a new query at this edit instead of
161        // handing the provider text the user never typed as a prefix.
162        let completion = &self.extras.context_menu_content.completion;
163        let latched = completion.trigger_start_offset.filter(|&latched| {
164            latched <= start
165                && start <= latched + completion.query.len()
166                && self.text.is_char_boundary(latched)
167                && self.text.is_char_boundary(start)
168                && completion
169                    .query
170                    .starts_with(self.text.slice(latched..start).to_string().as_str())
171        });
172        let start_offset = latched.unwrap_or(start);
173        if new_offset < start_offset {
174            return;
175        }
176
177        let query = self
178            .text_for_range(
179                self.range_to_utf16(&(start_offset..new_offset)),
180                &mut None,
181                window,
182                cx,
183            )
184            .map(|s| s.trim().to_string())
185            .unwrap_or_default();
186        self.extras
187            .context_menu_content
188            .completion
189            .trigger_start_offset = Some(start_offset);
190        self.extras
191            .context_menu_content
192            .completion
193            .query
194            .clone_from(&query);
195
196        let completion_context = CompletionContext {
197            trigger_kind: lsp_types::CompletionTriggerKind::TRIGGER_CHARACTER,
198            trigger_character: Some(query),
199        };
200
201        let provider_responses =
202            provider.completions(&self.text, new_offset, completion_context, window, cx);
203        self.extras.context_menu_task = cx.spawn_in(window, async move |editor, cx| {
204            let mut completions: Vec<CompletionItem> = vec![];
205            if let Some(provider_responses) = provider_responses.await.ok() {
206                match provider_responses {
207                    CompletionResponse::Array(items) => completions.extend(items),
208                    CompletionResponse::List(list) => completions.extend(list.items),
209                }
210            }
211
212            if completions.is_empty() {
213                editor.update(cx, |editor, cx| {
214                    editor.extras.context_menu_content.completion.open = false;
215                    editor.extras.context_menu_content.completion.items.clear();
216                    editor.extras.context_menu_content.completion.bump();
217                    cx.notify();
218                })?;
219                return Ok(());
220            }
221
222            editor
223                .update_in(cx, |editor, window, cx| {
224                    if !editor.focus_handle.is_focused(window) {
225                        return;
226                    }
227
228                    editor.extras.context_menu_content.completion.items = completions;
229                    editor.extras.context_menu_content.completion.open = !editor
230                        .extras
231                        .context_menu_content
232                        .completion
233                        .items
234                        .is_empty();
235                    editor.extras.context_menu_content.completion.bump();
236
237                    cx.notify();
238                })
239                .ok();
240
241            Ok(())
242        });
243    }
244
245    pub(crate) fn hide_context_menu(&mut self, cx: &mut Context<Self>) {
246        self.extras.context_menu_content.completion.open = false;
247        self.extras.context_menu_content.code_action.open = false;
248        self.extras.context_menu_task = Task::ready(Ok(()));
249        cx.notify();
250    }
251
252    pub(crate) fn is_context_menu_open(&self, _cx: &gpui::App) -> bool {
253        self.extras.context_menu_content.completion.open
254            || self.extras.context_menu_content.code_action.open
255    }
256
257    pub(crate) fn handle_action_for_context_menu(
258        &mut self,
259        action: Box<dyn gpui::Action>,
260        window: &mut Window,
261        cx: &mut Context<Self>,
262    ) -> bool {
263        let closes_overlay =
264            crate::input::Enter::is_primary(&*action) || action.partial_eq(&crate::input::Escape);
265        let kind = if self.extras.context_menu_content.completion.open {
266            Some(super::InputOverlayKind::Completion)
267        } else if self.extras.context_menu_content.code_action.open {
268            Some(super::InputOverlayKind::CodeAction)
269        } else {
270            None
271        };
272        let Some((kind, handler)) = kind.zip(self.overlay_action_handler.clone()) else {
273            return false;
274        };
275        let handled = handler(kind, action, window, cx);
276        if handled && closes_overlay {
277            self.hide_context_menu(cx);
278        }
279        handled
280    }
281
282    /// Schedule an inline completion request after debouncing.
283    pub(crate) fn schedule_inline_completion(
284        &mut self,
285        window: &mut Window,
286        cx: &mut Context<Self>,
287    ) {
288        // Clear any existing inline completion on text change
289        self.clear_inline_completion(cx);
290
291        let Some(provider) = self.extras.lsp.completion_provider.clone() else {
292            return;
293        };
294
295        let offset = self.cursor();
296        let text = self.text.clone();
297        let debounce = provider.inline_completion_debounce();
298        let background_executor = cx.background_executor().clone();
299
300        self.extras.inline_completion.task = cx.spawn_in(window, async move |editor, cx| {
301            // Debounce: wait before fetching to avoid unnecessary requests while typing
302            background_executor.timer(debounce).await;
303
304            // Now fetch the inline completion after the debounce period
305            let task = editor.update_in(cx, |editor, window, cx| {
306                // Check if cursor has moved during debounce
307                if editor.cursor() != offset {
308                    return None;
309                }
310
311                // Don't fetch if completion menu is open
312                if editor.is_context_menu_open(cx) {
313                    return None;
314                }
315
316                let trigger = InlineCompletionContext {
317                    trigger_kind: InlineCompletionTriggerKind::Automatic,
318                    selected_completion_info: None,
319                };
320
321                Some(provider.inline_completion(&text, offset, trigger, window, cx))
322            })?;
323
324            let Some(task) = task else {
325                return Ok(InlineCompletionResponse::Array(vec![]));
326            };
327
328            let response = task.await?;
329
330            editor.update_in(cx, |editor, _window, cx| {
331                // Only apply if cursor still hasn't moved
332                if editor.cursor() != offset {
333                    return;
334                }
335
336                // Don't show if completion menu opened while we were fetching
337                if editor.is_context_menu_open(cx) {
338                    return;
339                }
340
341                if let Some(item) = match response.clone() {
342                    InlineCompletionResponse::Array(items) => items.into_iter().next(),
343                    InlineCompletionResponse::List(comp_list) => comp_list.items.into_iter().next(),
344                } {
345                    editor.extras.inline_completion.item = Some(item);
346                    cx.notify();
347                }
348            })?;
349
350            Ok(response)
351        });
352    }
353
354    /// Check if an inline completion suggestion is currently displayed.
355    #[inline]
356    pub(crate) fn has_inline_completion(&self) -> bool {
357        self.extras.inline_completion.item.is_some()
358    }
359
360    /// Clear the inline completion suggestion.
361    pub(crate) fn clear_inline_completion(&mut self, cx: &mut Context<Self>) {
362        self.extras.inline_completion = InlineCompletion::default();
363        cx.notify();
364    }
365
366    /// Accept the inline completion, inserting it at the cursor position.
367    /// Returns true if a completion was accepted, false if there was none.
368    pub(crate) fn accept_inline_completion(
369        &mut self,
370        window: &mut Window,
371        cx: &mut Context<Self>,
372    ) -> bool {
373        let Some(completion_item) = self.extras.inline_completion.item.take() else {
374            return false;
375        };
376
377        let cursor = self.cursor();
378        let range_utf16 = self.range_to_utf16(&(cursor..cursor));
379        let completion_text = completion_item.insert_text;
380        self.replace_text_in_range_silent(Some(range_utf16), &completion_text, window, cx);
381        true
382    }
383}