1use 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
15const DEFAULT_INLINE_COMPLETION_DEBOUNCE: Duration = Duration::from_millis(300);
17
18pub type CompletionHighlighter = dyn Fn(&str, &CompletionItem) -> Vec<Range<usize>>;
23
24pub 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
40pub 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
71pub 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#[derive(Debug, Clone, Copy)]
129pub struct CompletionMenuOptions {
130 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
146pub trait CompletionProvider {
148 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 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 #[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 fn is_completion_trigger(&self, offset: usize, new_text: &str, cx: &mut App) -> bool;
210}
211
212pub(crate) struct InlineCompletion {
213 pub(crate) item: Option<InlineCompletionItem>,
215 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 self.schedule_inline_completion(window, cx);
247
248 let new_offset = self.cursor();
249 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 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 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 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 pub(crate) fn schedule_inline_completion(
463 &mut self,
464 window: &mut Window,
465 cx: &mut Context<Self>,
466 ) {
467 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 background_executor.timer(debounce).await;
482
483 let task = editor.update_in(cx, |editor, window, cx| {
485 if editor.cursor() != offset {
487 return None;
488 }
489
490 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 if editor.cursor() != offset {
512 return;
513 }
514
515 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 #[inline]
535 pub(crate) fn has_inline_completion(&self) -> bool {
536 self.extras.inline_completion.item.is_some()
537 }
538
539 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 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 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}