Skip to main content

gpui_deck/input/editor/lsp/
completions.rs

1// Modified for GPUI Deck: update references to the extracted crate.
2use crate::input::EditorMode;
3use anyhow::Result;
4use gpui::{App, Context, EntityInputHandler, Pixels, Task, Window, px};
5use lsp_types::{
6    CompletionContext, CompletionItem, CompletionResponse, InlineCompletionContext,
7    InlineCompletionItem, InlineCompletionResponse, InlineCompletionTriggerKind,
8    request::Completion,
9};
10use ropey::Rope;
11use std::{cell::RefCell, ops::Range, rc::Rc, time::Duration};
12
13use crate::input::{InputBaseState, ShowCompletions};
14
15/// Default debounce duration for inline completions.
16const DEFAULT_INLINE_COMPLETION_DEBOUNCE: Duration = Duration::from_millis(300);
17
18/// Decides which bytes of a completion label the menu paints as the match.
19///
20/// `query` is the word typed since the menu opened. Returned ranges are byte
21/// offsets into [`CompletionItem::label`].
22pub type CompletionHighlighter = dyn Fn(&str, &CompletionItem) -> Vec<Range<usize>>;
23
24/// Highlight a prefix of the completion label, matching today's menu.
25///
26/// The painted length is [`CompletionItem::filter_text`] when the item sets
27/// one, otherwise the query. It is shortened so the range never splits a
28/// character. An empty length paints nothing.
29pub fn highlight_prefix(query: &str, item: &CompletionItem) -> Vec<Range<usize>> {
30    let matched_len = item
31        .filter_text
32        .as_ref()
33        .map(|text| text.len())
34        .unwrap_or(query.len())
35        .min(item.label.len());
36    let end = item.label.floor_char_boundary(matched_len);
37    if end == 0 { Vec::new() } else { vec![0..end] }
38}
39
40/// Highlight the first case-insensitive occurrence of `query` in the label.
41///
42/// An empty query, or a query that does not occur as a contiguous span,
43/// paints nothing.
44pub fn highlight_contains(query: &str, item: &CompletionItem) -> Vec<Range<usize>> {
45    let query: Vec<char> = query.chars().collect();
46    if query.is_empty() {
47        return Vec::new();
48    }
49
50    let label: Vec<(usize, char)> = item.label.char_indices().collect();
51    let Some(last_start) = label.len().checked_sub(query.len()) else {
52        return Vec::new();
53    };
54
55    for start in 0..=last_start {
56        let matched = query
57            .iter()
58            .zip(label[start..].iter())
59            .all(|(query_char, (_, label_char))| chars_eq_ignore_case(*query_char, *label_char));
60        if !matched {
61            continue;
62        }
63
64        let byte_start = label[start].0;
65        let (last_index, last_char) = label[start + query.len() - 1];
66        return vec![byte_start..last_index + last_char.len_utf8()];
67    }
68    Vec::new()
69}
70
71/// Highlight each character of `query` in order, skipping characters in between.
72///
73/// Matching is case-insensitive. Adjacent hits merge into one range, so a
74/// contiguous match still paints as a single span. A query that cannot be
75/// matched in full paints nothing.
76pub fn highlight_characters(query: &str, item: &CompletionItem) -> Vec<Range<usize>> {
77    if query.is_empty() {
78        return Vec::new();
79    }
80
81    let mut ranges: Vec<Range<usize>> = Vec::new();
82    let mut rest = item.label.as_str();
83    let mut base = 0usize;
84    for query_char in query.chars() {
85        let Some((index, matched)) = rest
86            .char_indices()
87            .find(|(_, label_char)| chars_eq_ignore_case(query_char, *label_char))
88        else {
89            return Vec::new();
90        };
91
92        let start = base + index;
93        let end = start + matched.len_utf8();
94        let next = index + matched.len_utf8();
95        base += next;
96        rest = &rest[next..];
97        if let Some(last) = ranges.last_mut() {
98            if last.end == start {
99                last.end = end;
100                continue;
101            }
102        }
103        ranges.push(start..end);
104    }
105    ranges
106}
107
108fn chars_eq_ignore_case(left: char, right: char) -> bool {
109    left == right
110        || left.eq_ignore_ascii_case(&right)
111        || left.to_lowercase().eq(right.to_lowercase())
112}
113
114/// Display options for the LSP completion popover.
115///
116/// Accessed through [`super::Lsp::completion_menu`] so embedders can tweak the
117/// popover without growing the [`InputBaseState`] API. Label highlighting is
118/// configured separately, on [`super::Lsp::completion_highlighter`].
119///
120/// ```
121/// use gpui_deck::input::CompletionMenuOptions;
122/// let options = CompletionMenuOptions {
123///     max_width: gpui::px(480.),
124/// };
125/// let _copied = options;
126/// let _again = options;
127/// ```
128#[derive(Debug, Clone, Copy)]
129pub struct CompletionMenuOptions {
130    /// Maximum width of the popover.
131    ///
132    /// Defaults to 320 px, which is fine for most identifiers but can
133    /// truncate longer labels. Widen this when hosting an editor that
134    /// surfaces long completion labels.
135    pub max_width: Pixels,
136}
137
138impl Default for CompletionMenuOptions {
139    fn default() -> Self {
140        Self {
141            max_width: px(320.),
142        }
143    }
144}
145
146/// A trait for providing code completions based on the current input state and context.
147pub trait CompletionProvider {
148    /// Fetches completions based on the given byte offset.
149    ///
150    /// - The `offset` is in bytes of current cursor.
151    ///
152    /// textDocument/completion
153    ///
154    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion
155    fn completions(
156        &self,
157        text: &Rope,
158        offset: usize,
159        trigger: CompletionContext,
160        window: &mut Window,
161        cx: &mut App,
162    ) -> Task<Result<CompletionResponse>>;
163
164    /// Fetches an inline completion suggestion for the given position.
165    ///
166    /// This is called after a debounce period when the user stops typing.
167    /// The provider can analyze the text and cursor position to determine
168    /// what inline completion suggestion to show.
169    ///
170    ///
171    /// # Arguments
172    /// * `rope` - The current text content
173    /// * `offset` - The cursor position in bytes
174    ///
175    /// textDocument/inlineCompletion
176    ///
177    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.18/specification/#textDocument_inlineCompletion
178    fn inline_completion(
179        &self,
180        _rope: &Rope,
181        _offset: usize,
182        _trigger: InlineCompletionContext,
183        _window: &mut Window,
184        _cx: &mut App,
185    ) -> Task<Result<InlineCompletionResponse>> {
186        Task::ready(Ok(InlineCompletionResponse::Array(vec![])))
187    }
188
189    /// Returns the debounce duration for inline completions.
190    ///
191    /// Default: 300ms
192    #[inline]
193    fn inline_completion_debounce(&self) -> Duration {
194        DEFAULT_INLINE_COMPLETION_DEBOUNCE
195    }
196
197    fn resolve_completions(
198        &self,
199        _completion_indices: Vec<usize>,
200        _completions: Rc<RefCell<Box<[Completion]>>>,
201        _: &mut App,
202    ) -> Task<Result<bool>> {
203        Task::ready(Ok(false))
204    }
205
206    /// Determines if the completion should be triggered based on the given byte offset.
207    ///
208    /// This is called on the main thread.
209    fn is_completion_trigger(&self, offset: usize, new_text: &str, cx: &mut App) -> bool;
210}
211
212pub(crate) struct InlineCompletion {
213    /// Completion item to display as an inline completion suggestion
214    pub(crate) item: Option<InlineCompletionItem>,
215    /// Task for debouncing inline completion requests
216    pub(crate) task: Task<Result<InlineCompletionResponse>>,
217}
218
219impl Default for InlineCompletion {
220    fn default() -> Self {
221        Self {
222            item: None,
223            task: Task::ready(Ok(InlineCompletionResponse::Array(vec![]))),
224        }
225    }
226}
227
228impl InputBaseState<EditorMode> {
229    pub(crate) fn handle_completion_trigger(
230        &mut self,
231        _range: &Range<usize>,
232        new_text: &str,
233        window: &mut Window,
234        cx: &mut Context<Self>,
235    ) {
236        if self.completion_inserting {
237            return;
238        }
239
240        let Some(provider) = self.extras.lsp.completion_provider.clone() else {
241            return;
242        };
243
244        // Always schedule inline completion (debounced).
245        // It will check if menu is open before showing the suggestion.
246        self.schedule_inline_completion(window, cx);
247
248        let new_offset = self.cursor();
249        // Measure the inserted text in the current document. The replaced range
250        // uses pre-edit coordinates, which preceding multi-cursor edits can
251        // shift. The active caret ends immediately after the normalized input,
252        // including selection replacements and IME commits.
253        let Some(start) = new_offset.checked_sub(new_text.len()) else {
254            return;
255        };
256
257        if !provider.is_completion_trigger(start, new_text, cx) {
258            return;
259        }
260
261        // `trigger_start_offset` latches where the word a menu was opened for
262        // begins, so later keystrokes refine the same query instead of starting
263        // over at each character. It only describes this edit while the edit
264        // continues that word: the document between the latch and the edit
265        // must still read as a prefix of the last query. Deleting back into
266        // the word keeps it; typing somewhere else, or into a document that
267        // has since been replaced, starts a new query at this edit instead of
268        // handing the provider text the user never typed as a prefix.
269        let completion = &self.extras.context_menu_content.completion;
270        let latched = completion.trigger_start_offset.filter(|&latched| {
271            latched <= start
272                && start <= latched + completion.query.len()
273                && self.text.is_char_boundary(latched)
274                && self.text.is_char_boundary(start)
275                && completion
276                    .query
277                    .starts_with(self.text.slice(latched..start).to_string().as_str())
278        });
279        let start_offset = latched.unwrap_or(start);
280        if new_offset < start_offset {
281            return;
282        }
283
284        let query = self
285            .text_for_range(
286                self.range_to_utf16(&(start_offset..new_offset)),
287                &mut None,
288                window,
289                cx,
290            )
291            .map(|s| s.trim().to_string())
292            .unwrap_or_default();
293        self.request_completions(
294            provider,
295            start_offset,
296            query.clone(),
297            CompletionContext {
298                trigger_kind: lsp_types::CompletionTriggerKind::TRIGGER_CHARACTER,
299                trigger_character: Some(query),
300            },
301            window,
302            cx,
303        );
304    }
305
306    pub(crate) fn on_action_show_completions(
307        &mut self,
308        _: &ShowCompletions,
309        window: &mut Window,
310        cx: &mut Context<Self>,
311    ) {
312        self.show_completions(window, cx);
313    }
314
315    /// Request completions at the caret and focus the editor, without editing text.
316    ///
317    /// The current identifier prefix is used to refine the menu. An empty
318    /// prefix still asks the provider for suggestions. There is no default
319    /// keybinding; applications can dispatch [`ShowCompletions`] in the
320    /// `Input && mode == editor` context or call this method from a command.
321    ///
322    /// Disabled/readonly editors, IME preedit, and an already-open completion
323    /// menu are left alone. A new request cancels the previous overlay request
324    /// and inline suggestion, and closes the code-action menu.
325    pub fn show_completions(&mut self, window: &mut Window, cx: &mut Context<Self>) {
326        if self.disabled
327            || self.readonly
328            || self.completion_inserting
329            || self.ime_marked_range.is_some()
330            || self.extras.context_menu_content.completion.open
331        {
332            return;
333        }
334        let Some(provider) = self.extras.lsp.completion_provider.clone() else {
335            return;
336        };
337
338        let offset = self.cursor();
339        let word_len: usize = self
340            .text
341            .chars_at(offset)
342            .reversed()
343            .take_while(|ch| ch.is_alphanumeric() || *ch == '_')
344            .map(char::len_utf8)
345            .sum();
346        let start_offset = offset - word_len;
347        let query = self.text.slice(start_offset..offset).to_string();
348
349        self.hide_context_menu(cx);
350        self.clear_inline_completion(cx);
351        self.focus(window, cx);
352
353        self.request_completions(
354            provider,
355            start_offset,
356            query,
357            CompletionContext {
358                trigger_kind: lsp_types::CompletionTriggerKind::INVOKED,
359                trigger_character: None,
360            },
361            window,
362            cx,
363        );
364    }
365
366    /// Record the word a menu is for and ask `provider` about the caret.
367    fn request_completions(
368        &mut self,
369        provider: Rc<dyn CompletionProvider>,
370        start_offset: usize,
371        query: String,
372        completion_context: CompletionContext,
373        window: &mut Window,
374        cx: &mut Context<Self>,
375    ) {
376        let new_offset = self.cursor();
377        let revision = self.document_revision;
378        self.extras.context_menu_task = Task::ready(Ok(()));
379        self.extras.context_menu_content.code_action.open = false;
380        self.extras
381            .context_menu_content
382            .completion
383            .trigger_start_offset = Some(start_offset);
384        self.extras
385            .context_menu_content
386            .completion
387            .query
388            .clone_from(&query);
389
390        let provider_responses =
391            provider.completions(&self.text, new_offset, completion_context, window, cx);
392        self.extras.context_menu_task = cx.spawn_in(window, async move |editor, cx| {
393            let mut completions: Vec<CompletionItem> = vec![];
394            if let Some(provider_responses) = provider_responses.await.ok() {
395                match provider_responses {
396                    CompletionResponse::Array(items) => completions.extend(items),
397                    CompletionResponse::List(list) => completions.extend(list.items),
398                }
399            }
400
401            editor
402                .update_in(cx, |editor, window, cx| {
403                    if !editor.focus_handle.is_focused(window)
404                        || editor.document_revision != revision
405                        || editor.cursor() != new_offset
406                        || editor.ime_marked_range.is_some()
407                        || editor.disabled
408                        || editor.readonly
409                    {
410                        return;
411                    }
412
413                    editor.extras.context_menu_content.completion.open = !completions.is_empty();
414                    editor.extras.context_menu_content.completion.items = completions;
415                    editor.extras.context_menu_content.completion.bump();
416                    cx.notify();
417                })
418                .ok();
419
420            Ok(())
421        });
422    }
423
424    pub(crate) fn hide_context_menu(&mut self, cx: &mut Context<Self>) {
425        self.extras.context_menu_content.completion.open = false;
426        self.extras.context_menu_content.code_action.open = false;
427        self.extras.context_menu_task = Task::ready(Ok(()));
428        cx.notify();
429    }
430
431    pub(crate) fn is_context_menu_open(&self, _cx: &gpui::App) -> bool {
432        self.extras.context_menu_content.completion.open
433            || self.extras.context_menu_content.code_action.open
434    }
435
436    pub(crate) fn handle_action_for_context_menu(
437        &mut self,
438        action: Box<dyn gpui::Action>,
439        window: &mut Window,
440        cx: &mut Context<Self>,
441    ) -> bool {
442        let closes_overlay =
443            crate::input::Enter::is_primary(&*action) || action.partial_eq(&crate::input::Escape);
444        let kind = if self.extras.context_menu_content.completion.open {
445            Some(super::InputOverlayKind::Completion)
446        } else if self.extras.context_menu_content.code_action.open {
447            Some(super::InputOverlayKind::CodeAction)
448        } else {
449            None
450        };
451        let Some((kind, handler)) = kind.zip(self.overlay_action_handler.clone()) else {
452            return false;
453        };
454        let handled = handler(kind, action, window, cx);
455        if handled && closes_overlay {
456            self.hide_context_menu(cx);
457        }
458        handled
459    }
460
461    /// Schedule an inline completion request after debouncing.
462    pub(crate) fn schedule_inline_completion(
463        &mut self,
464        window: &mut Window,
465        cx: &mut Context<Self>,
466    ) {
467        // Clear any existing inline completion on text change
468        self.clear_inline_completion(cx);
469
470        let Some(provider) = self.extras.lsp.completion_provider.clone() else {
471            return;
472        };
473
474        let offset = self.cursor();
475        let text = self.text.clone();
476        let debounce = provider.inline_completion_debounce();
477        let background_executor = cx.background_executor().clone();
478
479        self.extras.inline_completion.task = cx.spawn_in(window, async move |editor, cx| {
480            // Debounce: wait before fetching to avoid unnecessary requests while typing
481            background_executor.timer(debounce).await;
482
483            // Now fetch the inline completion after the debounce period
484            let task = editor.update_in(cx, |editor, window, cx| {
485                // Check if cursor has moved during debounce
486                if editor.cursor() != offset {
487                    return None;
488                }
489
490                // Don't fetch if completion menu is open
491                if editor.is_context_menu_open(cx) {
492                    return None;
493                }
494
495                let trigger = InlineCompletionContext {
496                    trigger_kind: InlineCompletionTriggerKind::Automatic,
497                    selected_completion_info: None,
498                };
499
500                Some(provider.inline_completion(&text, offset, trigger, window, cx))
501            })?;
502
503            let Some(task) = task else {
504                return Ok(InlineCompletionResponse::Array(vec![]));
505            };
506
507            let response = task.await?;
508
509            editor.update_in(cx, |editor, _window, cx| {
510                // Only apply if cursor still hasn't moved
511                if editor.cursor() != offset {
512                    return;
513                }
514
515                // Don't show if completion menu opened while we were fetching
516                if editor.is_context_menu_open(cx) {
517                    return;
518                }
519
520                if let Some(item) = match response.clone() {
521                    InlineCompletionResponse::Array(items) => items.into_iter().next(),
522                    InlineCompletionResponse::List(comp_list) => comp_list.items.into_iter().next(),
523                } {
524                    editor.extras.inline_completion.item = Some(item);
525                    cx.notify();
526                }
527            })?;
528
529            Ok(response)
530        });
531    }
532
533    /// Check if an inline completion suggestion is currently displayed.
534    #[inline]
535    pub(crate) fn has_inline_completion(&self) -> bool {
536        self.extras.inline_completion.item.is_some()
537    }
538
539    /// Clear the inline completion suggestion.
540    pub(crate) fn clear_inline_completion(&mut self, cx: &mut Context<Self>) {
541        self.extras.inline_completion = InlineCompletion::default();
542        cx.notify();
543    }
544
545    /// Accept the inline completion, inserting it at the cursor position.
546    /// Returns true if a completion was accepted, false if there was none.
547    pub(crate) fn accept_inline_completion(
548        &mut self,
549        window: &mut Window,
550        cx: &mut Context<Self>,
551    ) -> bool {
552        let Some(completion_item) = self.extras.inline_completion.item.take() else {
553            return false;
554        };
555
556        let cursor = self.cursor();
557        let range_utf16 = self.range_to_utf16(&(cursor..cursor));
558        let completion_text = completion_item.insert_text;
559        self.replace_text_in_range_silent(Some(range_utf16), &completion_text, window, cx);
560        true
561    }
562}
563
564#[cfg(test)]
565mod tests {
566    use super::*;
567
568    fn item(label: &str, filter_text: Option<&str>) -> CompletionItem {
569        CompletionItem {
570            label: label.to_string(),
571            filter_text: filter_text.map(str::to_string),
572            ..Default::default()
573        }
574    }
575
576    #[test]
577    fn prefix_uses_the_query_length_unless_filter_text_is_set() {
578        assert_eq!(highlight_prefix("fl", &item("flag", None)), vec![0..2]);
579        assert_eq!(highlight_prefix("fl", &item("flag", Some("f"))), vec![0..1]);
580        assert_eq!(
581            highlight_prefix("flagpole", &item("flag", None)),
582            vec![0..4]
583        );
584        assert!(highlight_prefix("", &item("flag", None)).is_empty());
585    }
586
587    #[test]
588    fn prefix_does_not_split_a_character() {
589        assert_eq!(highlight_prefix("你", &item("你好", None)), vec![0..3]);
590        assert!(highlight_prefix("a", &item("你", None)).is_empty());
591    }
592
593    #[test]
594    fn contains_highlights_the_first_contiguous_match() {
595        // "dialog" itself ends in "log", so that hit comes before the suffix.
596        assert_eq!(
597            highlight_contains("log", &item("dialog_log", None)),
598            vec![3..6]
599        );
600        assert_eq!(
601            highlight_contains("LOG", &item("dialog_log", None)),
602            vec![3..6]
603        );
604        assert_eq!(
605            highlight_contains("log", &item("catalog", None)),
606            vec![4..7]
607        );
608        assert_eq!(
609            highlight_contains("好世", &item("你好世界", None)),
610            vec![3..9]
611        );
612        assert!(highlight_contains("log", &item("flag", None)).is_empty());
613        assert!(highlight_contains("", &item("flag", None)).is_empty());
614    }
615
616    #[test]
617    fn characters_highlight_gaps_and_merge_adjacent_hits() {
618        assert_eq!(highlight_characters("fl", &item("flag", None)), vec![0..2]);
619        assert_eq!(
620            highlight_characters("fl", &item("file_loader", None)),
621            vec![0..1, 2..3]
622        );
623        assert_eq!(
624            highlight_characters("你世", &item("你好世界", None)),
625            vec![0..3, 6..9]
626        );
627        assert!(highlight_characters("fx", &item("flag", None)).is_empty());
628        assert!(highlight_characters("", &item("flag", None)).is_empty());
629    }
630}