gpui_base/input/editor/lsp/
completions.rs1use 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
14const DEFAULT_INLINE_COMPLETION_DEBOUNCE: Duration = Duration::from_millis(300);
16
17#[derive(Debug, Clone, Copy)]
22pub struct CompletionMenuOptions {
23 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
39pub trait CompletionProvider {
41 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 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 #[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 fn is_completion_trigger(&self, offset: usize, new_text: &str, cx: &mut App) -> bool;
103}
104
105pub(crate) struct InlineCompletion {
106 pub(crate) item: Option<InlineCompletionItem>,
108 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 self.schedule_inline_completion(window, cx);
140
141 let new_offset = self.cursor();
142 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 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 pub(crate) fn schedule_inline_completion(
284 &mut self,
285 window: &mut Window,
286 cx: &mut Context<Self>,
287 ) {
288 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 background_executor.timer(debounce).await;
303
304 let task = editor.update_in(cx, |editor, window, cx| {
306 if editor.cursor() != offset {
308 return None;
309 }
310
311 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 if editor.cursor() != offset {
333 return;
334 }
335
336 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 #[inline]
356 pub(crate) fn has_inline_completion(&self) -> bool {
357 self.extras.inline_completion.item.is_some()
358 }
359
360 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 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}