1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use anyhow::Result;
use gpui::{Context, EntityInputHandler, Task, Window};
use lsp_types::{
CompletionContext, CompletionItem, CompletionResponse, InlineCompletionContext,
InlineCompletionItem, InlineCompletionResponse, InlineCompletionTriggerKind,
request::Completion,
};
use ropey::Rope;
use std::{cell::RefCell, ops::Range, rc::Rc, time::Duration};
use crate::input::{
InputState,
popovers::{CompletionMenu, ContextMenu},
};
/// Default debounce duration for inline completions.
const DEFAULT_INLINE_COMPLETION_DEBOUNCE: Duration = Duration::from_millis(300);
/// A trait for providing code completions based on the current input state and context.
pub trait CompletionProvider {
/// Fetches completions based on the given byte offset.
///
/// - The `offset` is in bytes of current cursor.
///
/// textDocument/completion
///
/// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion
fn completions(
&self,
text: &Rope,
offset: usize,
trigger: CompletionContext,
window: &mut Window,
cx: &mut Context<InputState>,
) -> Task<Result<CompletionResponse>>;
/// Fetches an inline completion suggestion for the given position.
///
/// This is called after a debounce period when the user stops typing.
/// The provider can analyze the text and cursor position to determine
/// what inline completion suggestion to show.
///
///
/// # Arguments
/// * `rope` - The current text content
/// * `offset` - The cursor position in bytes
///
/// textDocument/inlineCompletion
///
/// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.18/specification/#textDocument_inlineCompletion
fn inline_completion(
&self,
_rope: &Rope,
_offset: usize,
_trigger: InlineCompletionContext,
_window: &mut Window,
_cx: &mut Context<InputState>,
) -> Task<Result<InlineCompletionResponse>> {
Task::ready(Ok(InlineCompletionResponse::Array(vec![])))
}
/// Returns the debounce duration for inline completions.
///
/// Default: 300ms
#[inline]
fn inline_completion_debounce(&self) -> Duration {
DEFAULT_INLINE_COMPLETION_DEBOUNCE
}
fn resolve_completions(
&self,
_completion_indices: Vec<usize>,
_completions: Rc<RefCell<Box<[Completion]>>>,
_: &mut Context<InputState>,
) -> Task<Result<bool>> {
Task::ready(Ok(false))
}
/// Determines if the completion should be triggered based on the given byte offset.
///
/// This is called on the main thread.
fn is_completion_trigger(
&self,
offset: usize,
new_text: &str,
cx: &mut Context<InputState>,
) -> bool;
}
pub(crate) struct InlineCompletion {
/// Completion item to display as an inline completion suggestion
pub(crate) item: Option<InlineCompletionItem>,
/// Task for debouncing inline completion requests
pub(crate) task: Task<Result<InlineCompletionResponse>>,
}
impl Default for InlineCompletion {
fn default() -> Self {
Self {
item: None,
task: Task::ready(Ok(InlineCompletionResponse::Array(vec![]))),
}
}
}
impl InputState {
pub(crate) fn handle_completion_trigger(
&mut self,
range: &Range<usize>,
new_text: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.completion_inserting {
return;
}
let Some(provider) = self.lsp.completion_provider.clone() else {
return;
};
// Always schedule inline completion (debounced).
// It will check if menu is open before showing the suggestion.
self.schedule_inline_completion(window, cx);
let start = range.end;
let new_offset = self.cursor();
if !provider.is_completion_trigger(start, new_text, cx) {
return;
}
let menu = match self.context_menu.as_ref() {
Some(ContextMenu::Completion(menu)) => Some(menu),
_ => None,
};
// To create or get the existing completion menu.
let menu = match menu {
Some(menu) => menu.clone(),
None => {
let menu = CompletionMenu::new(cx.entity(), window, cx);
self.context_menu = Some(ContextMenu::Completion(menu.clone()));
menu
}
};
let start_offset = menu.read(cx).trigger_start_offset.unwrap_or(start);
if new_offset < start_offset {
return;
}
let query = self
.text_for_range(
self.range_to_utf16(&(start_offset..new_offset)),
&mut None,
window,
cx,
)
.map(|s| s.trim().to_string())
.unwrap_or_default();
_ = menu.update(cx, |menu, _| {
menu.update_query(start_offset, query.clone());
});
let completion_context = CompletionContext {
trigger_kind: lsp_types::CompletionTriggerKind::TRIGGER_CHARACTER,
trigger_character: Some(query),
};
let provider_responses =
provider.completions(&self.text, new_offset, completion_context, window, cx);
self._context_menu_task = cx.spawn_in(window, async move |editor, cx| {
let mut completions: Vec<CompletionItem> = vec![];
if let Some(provider_responses) = provider_responses.await.ok() {
match provider_responses {
CompletionResponse::Array(items) => completions.extend(items),
CompletionResponse::List(list) => completions.extend(list.items),
}
}
if completions.is_empty() {
_ = menu.update(cx, |menu, cx| {
menu.hide(cx);
cx.notify();
});
return Ok(());
}
editor
.update_in(cx, |editor, window, cx| {
if !editor.focus_handle.is_focused(window) {
return;
}
_ = menu.update(cx, |menu, cx| {
menu.show(new_offset, completions, window, cx);
});
cx.notify();
})
.ok();
Ok(())
});
}
/// Schedule an inline completion request after debouncing.
pub(crate) fn schedule_inline_completion(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
// Clear any existing inline completion on text change
self.clear_inline_completion(cx);
let Some(provider) = self.lsp.completion_provider.clone() else {
return;
};
let offset = self.cursor();
let text = self.text.clone();
let debounce = provider.inline_completion_debounce();
self.inline_completion.task = cx.spawn_in(window, async move |editor, cx| {
// Debounce: wait before fetching to avoid unnecessary requests while typing
smol::Timer::after(debounce).await;
// Now fetch the inline completion after the debounce period
let task = editor.update_in(cx, |editor, window, cx| {
// Check if cursor has moved during debounce
if editor.cursor() != offset {
return None;
}
// Don't fetch if completion menu is open
if editor.is_context_menu_open(cx) {
return None;
}
let trigger = InlineCompletionContext {
trigger_kind: InlineCompletionTriggerKind::Automatic,
selected_completion_info: None,
};
Some(provider.inline_completion(&text, offset, trigger, window, cx))
})?;
let Some(task) = task else {
return Ok(InlineCompletionResponse::Array(vec![]));
};
let response = task.await?;
editor.update_in(cx, |editor, _window, cx| {
// Only apply if cursor still hasn't moved
if editor.cursor() != offset {
return;
}
// Don't show if completion menu opened while we were fetching
if editor.is_context_menu_open(cx) {
return;
}
if let Some(item) = match response.clone() {
InlineCompletionResponse::Array(items) => items.into_iter().next(),
InlineCompletionResponse::List(comp_list) => comp_list.items.into_iter().next(),
} {
editor.inline_completion.item = Some(item);
cx.notify();
}
})?;
Ok(response)
});
}
/// Check if an inline completion suggestion is currently displayed.
#[inline]
pub(crate) fn has_inline_completion(&self) -> bool {
self.inline_completion.item.is_some()
}
/// Clear the inline completion suggestion.
pub(crate) fn clear_inline_completion(&mut self, cx: &mut Context<Self>) {
self.inline_completion = InlineCompletion::default();
cx.notify();
}
/// Accept the inline completion, inserting it at the cursor position.
/// Returns true if a completion was accepted, false if there was none.
pub(crate) fn accept_inline_completion(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
let Some(completion_item) = self.inline_completion.item.take() else {
return false;
};
let cursor = self.cursor();
let range_utf16 = self.range_to_utf16(&(cursor..cursor));
let completion_text = completion_item.insert_text;
self.replace_text_in_range_silent(Some(range_utf16), &completion_text, window, cx);
true
}
}