Debian Codegraph @

helix-term/src/ui/completion.rs

raw symbols SCIP
1 use crate::handlers::completion::LspCompletionItem;
2 use crate::ui::{menu, Markdown, Menu, Popup, PromptEvent};
3 use crate::{
4 compositor::{Component, Context, Event, EventResult},
5 handlers::completion::{
6 trigger_auto_completion, CompletionItem, CompletionResponse, ResolveHandler,
7 },
8 };
9 use helix_core::snippets::{ActiveSnippet, RenderedSnippet, Snippet};
10 use helix_core::{self as core, chars, fuzzy::MATCHER, Change, Transaction};
11 use helix_lsp::{lsp, util, OffsetEncoding};
12 use helix_view::{
13 editor::CompleteAction,
14 handlers::lsp::SignatureHelpInvoked,
15 theme::{Color, Modifier, Style},
16 ViewId,
17 };
18 use helix_view::{graphics::Rect, Document, Editor};
19 use nucleo::{
20 pattern::{Atom, AtomKind, CaseMatching, Normalization},
21 Config, Utf32Str,
22 };
23 use tui::text::Spans;
24 use tui::{buffer::Buffer as Surface, text::Span};
25
26 use std::cmp::Reverse;
27
28 impl menu::Item for CompletionItem {
29 type Data = Style;
30
31 fn format(&self, dir_style: &Self::Data) -> menu::Row<'_> {
32 let deprecated = match self {
33 CompletionItem::Lsp(LspCompletionItem { item, .. }) => {
34 item.deprecated.unwrap_or_default()
35 || item
36 .tags
37 .as_ref()
38 .is_some_and(|tags| tags.contains(&lsp::CompletionItemTag::DEPRECATED))
39 }
40 CompletionItem::Other(_) => false,
41 };
42
43 let label = match self {
44 CompletionItem::Lsp(LspCompletionItem { item, .. }) => item.label.as_str(),
45 CompletionItem::Other(core::CompletionItem { label, .. }) => label,
46 };
47
48 let kind = match self {
49 CompletionItem::Lsp(LspCompletionItem { item, .. }) => match item.kind {
50 Some(lsp::CompletionItemKind::TEXT) => "text".into(),
51 Some(lsp::CompletionItemKind::METHOD) => "method".into(),
52 Some(lsp::CompletionItemKind::FUNCTION) => "function".into(),
53 Some(lsp::CompletionItemKind::CONSTRUCTOR) => "constructor".into(),
54 Some(lsp::CompletionItemKind::FIELD) => "field".into(),
55 Some(lsp::CompletionItemKind::VARIABLE) => "variable".into(),
56 Some(lsp::CompletionItemKind::CLASS) => "class".into(),
57 Some(lsp::CompletionItemKind::INTERFACE) => "interface".into(),
58 Some(lsp::CompletionItemKind::MODULE) => "module".into(),
59 Some(lsp::CompletionItemKind::PROPERTY) => "property".into(),
60 Some(lsp::CompletionItemKind::UNIT) => "unit".into(),
61 Some(lsp::CompletionItemKind::VALUE) => "value".into(),
62 Some(lsp::CompletionItemKind::ENUM) => "enum".into(),
63 Some(lsp::CompletionItemKind::KEYWORD) => "keyword".into(),
64 Some(lsp::CompletionItemKind::SNIPPET) => "snippet".into(),
65 Some(lsp::CompletionItemKind::COLOR) => item
66 .documentation
67 .as_ref()
68 .and_then(|docs| {
69 let text = match docs {
70 lsp::Documentation::String(text) => text,
71 lsp::Documentation::MarkupContent(lsp::MarkupContent {
72 value, ..
73 }) => value,
74 };
75 // Language servers which send Color completion items tend to include a 6
76 // digit hex code at the end for the color. The extra 1 digit is for the '#'
77 text.get(text.len().checked_sub(7)?..)
78 })
79 .and_then(|c| Color::from_hex(c).ok())
80 .map_or("color".into(), |color| {
81 Spans::from(vec![
82 Span::raw("color "),
83 Span::styled("■", Style::default().fg(color)),
84 ])
85 }),
86 Some(lsp::CompletionItemKind::FILE) => "file".into(),
87 Some(lsp::CompletionItemKind::REFERENCE) => "reference".into(),
88 Some(lsp::CompletionItemKind::FOLDER) => "folder".into(),
89 Some(lsp::CompletionItemKind::ENUM_MEMBER) => "enum_member".into(),
90 Some(lsp::CompletionItemKind::CONSTANT) => "constant".into(),
91 Some(lsp::CompletionItemKind::STRUCT) => "struct".into(),
92 Some(lsp::CompletionItemKind::EVENT) => "event".into(),
93 Some(lsp::CompletionItemKind::OPERATOR) => "operator".into(),
94 Some(lsp::CompletionItemKind::TYPE_PARAMETER) => "type_param".into(),
95 Some(kind) => {
96 log::error!("Received unknown completion item kind: {:?}", kind);
97 "".into()
98 }
99 None => "".into(),
100 },
101 CompletionItem::Other(core::CompletionItem { kind, .. }) => kind.as_ref().into(),
102 };
103
104 let label = Span::styled(
105 label,
106 if deprecated {
107 Style::default().add_modifier(Modifier::CROSSED_OUT)
108 } else if kind.0[0].content == "folder" {
109 *dir_style
110 } else {
111 Style::default()
112 },
113 );
114
115 menu::Row::new([menu::Cell::from(label), menu::Cell::from(kind)])
116 }
117 }
118
119 /// Wraps a Menu.
120 pub struct Completion {
121 popup: Popup<Menu<CompletionItem>>,
122 #[allow(dead_code)]
123 trigger_offset: usize,
124 filter: String,
125 // TODO: move to helix-view/central handler struct in the future
126 resolve_handler: ResolveHandler,
127 }
128
129 impl Completion {
130 pub const ID: &'static str = "completion";
131
132 pub fn new(editor: &Editor, items: Vec<CompletionItem>, trigger_offset: usize) -> Self {
133 let preview_completion_insert = editor.config().preview_completion_insert;
134 let replace_mode = editor.config().completion_replace;
135
136 let dir_style = editor.theme.get("ui.text.directory");
137
138 // Then create the menu
139 let menu = Menu::new(items, dir_style, move |editor: &mut Editor, item, event| {
140 let (view, doc) = current!(editor);
141
142 macro_rules! language_server {
143 ($item:expr) => {
144 match editor
145 .language_servers
146 .get_by_id($item.provider)
147 {
148 Some(ls) => ls,
149 None => {
150 editor.set_error("completions are outdated");
151 // TODO close the completion menu somehow,
152 // currently there is no trivial way to access the EditorView to close the completion menu
153 return;
154 }
155 }
156 };
157 }
158
159 match event {
160 PromptEvent::Abort => {}
161 PromptEvent::Update if preview_completion_insert => {
162 // Update creates "ghost" transactions which are not sent to the
163 // lsp server to avoid messing up re-requesting completions. Once a
164 // completion has been selected (with tab, c-n or c-p) it's always accepted whenever anything
165 // is typed. The only way to avoid that is to explicitly abort the completion
166 // with c-c. This will remove the "ghost" transaction.
167 //
168 // The ghost transaction is modeled with a transaction that is not sent to the LS.
169 // (apply_temporary) and a savepoint. It's extremely important this savepoint is restored
170 // (also without sending the transaction to the LS) *before any further transaction is applied*.
171 // Otherwise incremental sync breaks (since the state of the LS doesn't match the state the transaction
172 // is applied to).
173 if matches!(editor.last_completion, Some(CompleteAction::Triggered)) {
174 editor.last_completion = Some(CompleteAction::Selected {
175 savepoint: doc.savepoint(view),
176 })
177 }
178 let item = item.unwrap();
179 let context = &editor.handlers.completions.active_completions[&item.provider()];
180 // if more text was entered, remove it
181 doc.restore(view, &context.savepoint, false);
182 // always present here
183
184 match item {
185 CompletionItem::Lsp(item) => {
186 let (transaction, _) = lsp_item_to_transaction(
187 doc,
188 view.id,
189 &item.item,
190 language_server!(item).offset_encoding(),
191 trigger_offset,
192 replace_mode,
193 );
194 doc.apply_temporary(&transaction, view.id)
195 }
196 CompletionItem::Other(core::CompletionItem { transaction, .. }) => {
197 doc.apply_temporary(transaction, view.id)
198 }
199 };
200 }
201 PromptEvent::Update => {}
202 PromptEvent::Validate => {
203 if let Some(CompleteAction::Selected { savepoint }) =
204 editor.last_completion.take()
205 {
206 doc.restore(view, &savepoint, false);
207 }
208
209 let item = item.unwrap();
210 let context = &editor.handlers.completions.active_completions[&item.provider()];
211 // if more text was entered, remove it
212 doc.restore(view, &context.savepoint, true);
213 // save an undo checkpoint before the completion
214 doc.append_changes_to_history(view);
215
216 // item always present here
217 let (transaction, additional_edits, snippet) = match item.clone() {
218 CompletionItem::Lsp(mut item) => {
219 let language_server = language_server!(item);
220
221 // resolve item if not yet resolved
222 if !item.resolved {
223 if let Some(resolved_item) = Self::resolve_completion_item(
224 language_server,
225 item.item.clone(),
226 ) {
227 item.item = resolved_item;
228 }
229 };
230
231 let encoding = language_server.offset_encoding();
232 let (transaction, snippet) = lsp_item_to_transaction(
233 doc,
234 view.id,
235 &item.item,
236 encoding,
237 trigger_offset,
238 replace_mode,
239 );
240 let add_edits = item.item.additional_text_edits;
241
242 (
243 transaction,
244 add_edits.map(|edits| (edits, encoding)),
245 snippet,
246 )
247 }
248 CompletionItem::Other(core::CompletionItem { transaction, .. }) => {
249 (transaction, None, None)
250 }
251 };
252
253 doc.apply(&transaction, view.id);
254 let placeholder = snippet.is_some();
255 if let Some(snippet) = snippet {
256 doc.active_snippet = match doc.active_snippet.take() {
257 Some(active) => active.insert_subsnippet(snippet),
258 None => ActiveSnippet::new(snippet),
259 };
260 }
261
262 editor.last_completion = Some(CompleteAction::Applied {
263 trigger_offset,
264 changes: completion_changes(&transaction, trigger_offset),
265 placeholder,
266 });
267
268 // TODO: add additional _edits to completion_changes?
269 if let Some((additional_edits, offset_encoding)) = additional_edits {
270 if !additional_edits.is_empty() {
271 let transaction = util::generate_transaction_from_edits(
272 doc.text(),
273 additional_edits,
274 offset_encoding, // TODO: should probably transcode in Client
275 );
276 doc.apply(&transaction, view.id);
277 }
278 }
279 // we could have just inserted a trigger char (like a `crate::` completion for rust
280 // so we want to retrigger immediately when accepting a completion.
281 trigger_auto_completion(editor, true);
282 }
283 };
284
285 // In case the popup was deleted because of an intersection w/ the auto-complete menu.
286 if event != PromptEvent::Update {
287 editor
288 .handlers
289 .trigger_signature_help(SignatureHelpInvoked::Automatic, editor);
290 }
291 });
292
293 let popup = Popup::new(Self::ID, menu)
294 .with_scrollbar(false)
295 .ignore_escape_key(true);
296
297 let (view, doc) = current_ref!(editor);
298 let text = doc.text().slice(..);
299 let cursor = doc.selection(view.id).primary().cursor(text);
300 let offset = text
301 .chars_at(cursor)
302 .reversed()
303 .take_while(|ch| chars::char_is_word(*ch))
304 .count();
305 let start_offset = cursor.saturating_sub(offset);
306
307 let fragment = doc.text().slice(start_offset..cursor);
308 let mut completion = Self {
309 popup,
310 trigger_offset,
311 // TODO: expand nucleo api to allow moving straight to a Utf32String here
312 // and avoid allocation during matching
313 filter: String::from(fragment),
314 resolve_handler: ResolveHandler::new(),
315 };
316
317 // need to recompute immediately in case start_offset != trigger_offset
318 completion.score(false);
319
320 completion
321 }
322
323 fn score(&mut self, incremental: bool) {
324 let pattern = &self.filter;
325 let mut matcher = MATCHER.lock();
326 matcher.config = Config::DEFAULT;
327 // slight preference towards prefix matches
328 matcher.config.prefer_prefix = true;
329 let pattern = Atom::new(
330 pattern,
331 CaseMatching::Ignore,
332 Normalization::Smart,
333 AtomKind::Fuzzy,
334 false,
335 );
336 let mut buf = Vec::new();
337 let (matches, options) = self.popup.contents_mut().update_options();
338 if incremental {
339 matches.retain_mut(|(index, score)| {
340 let option = &options[*index as usize];
341 let text = option.filter_text();
342 let new_score = pattern.score(Utf32Str::new(text, &mut buf), &mut matcher);
343 match new_score {
344 Some(new_score) => {
345 *score = new_score as u32 / 2;
346 true
347 }
348 None => false,
349 }
350 })
351 } else {
352 matches.clear();
353 matches.extend(options.iter().enumerate().filter_map(|(i, option)| {
354 let text = option.filter_text();
355 pattern
356 .score(Utf32Str::new(text, &mut buf), &mut matcher)
357 .map(|score| (i as u32, score as u32 / 3))
358 }));
359 }
360 // Nucleo is meant as an FZF-like fuzzy matcher and only hides matches that are truly
361 // impossible - as in the sequence of characters just doesn't appear. That doesn't work
362 // well for completions with multiple language servers where all completions of the next
363 // server are below the current one (so you would get good suggestions from the second
364 // server below those of the first). Setting a reasonable cutoff below which to move bad
365 // completions out of the way helps with that.
366 //
367 // The score computation is a heuristic derived from Nucleo internal constants that may
368 // move upstream in the future. I want to test this out here to settle on a good number.
369 let min_score = (7 + pattern.needle_text().len() as u32 * 14) / 3;
370 matches.sort_unstable_by_key(|&(i, score)| {
371 let option = &options[i as usize];
372 (
373 score <= min_score,
374 Reverse(option.preselect()),
375 option.provider_priority(),
376 Reverse(score),
377 i,
378 )
379 });
380 }
381
382 /// Synchronously resolve the given completion item. This is used when
383 /// accepting a completion.
384 fn resolve_completion_item(
385 language_server: &helix_lsp::Client,
386 completion_item: lsp::CompletionItem,
387 ) -> Option<lsp::CompletionItem> {
388 if !matches!(
389 language_server.capabilities().completion_provider,
390 Some(lsp::CompletionOptions {
391 resolve_provider: Some(true),
392 ..
393 })
394 ) {
395 return None;
396 }
397 let future = language_server.resolve_completion_item(&completion_item);
398 let response = helix_lsp::block_on(future);
399 match response {
400 Ok(item) => Some(item),
401 Err(err) => {
402 log::error!("Failed to resolve completion item: {}", err);
403 None
404 }
405 }
406 }
407
408 /// Appends (`c: Some(c)`) or removes (`c: None`) a character to/from the filter
409 /// this should be called whenever the user types or deletes a character in insert mode.
410 pub fn update_filter(&mut self, c: Option<char>) {
411 // recompute menu based on matches
412 let menu = self.popup.contents_mut();
413 match c {
414 Some(c) => self.filter.push(c),
415 None => {
416 self.filter.pop();
417 if self.filter.is_empty() {
418 menu.clear();
419 return;
420 }
421 }
422 }
423 self.score(c.is_some());
424 self.popup.contents_mut().reset_cursor();
425 }
426
427 pub fn replace_provider_completions(
428 &mut self,
429 response: &mut CompletionResponse,
430 is_incomplete: bool,
431 ) {
432 let menu = self.popup.contents_mut();
433 let (_, options) = menu.update_options();
434 if is_incomplete {
435 options.retain(|item| item.provider() != response.provider)
436 }
437 response.take_items(options);
438 self.score(false);
439 let menu = self.popup.contents_mut();
440 menu.ensure_cursor_in_bounds();
441 }
442
443 pub fn is_empty(&self) -> bool {
444 self.popup.contents().is_empty()
445 }
446
447 pub fn replace_item(
448 &mut self,
449 old_item: &impl PartialEq<CompletionItem>,
450 new_item: CompletionItem,
451 ) {
452 self.popup.contents_mut().replace_option(old_item, new_item);
453 }
454
455 pub fn area(&mut self, viewport: Rect, editor: &Editor) -> Rect {
456 self.popup.area(viewport, editor)
457 }
458 }
459
460 impl Component for Completion {
461 fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
462 self.popup.handle_event(event, cx)
463 }
464
465 fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
466 self.popup.required_size(viewport)
467 }
468
469 fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
470 self.popup.render(area, surface, cx);
471
472 // if we have a selection, render a markdown popup on top/below with info
473 let option = match self.popup.contents_mut().selection_mut() {
474 Some(option) => option,
475 None => return,
476 };
477 if let CompletionItem::Lsp(option) = option {
478 self.resolve_handler.ensure_item_resolved(cx.editor, option);
479 }
480 // need to render:
481 // option.detail
482 // ---
483 // option.documentation
484
485 let Some(coords) = cx.editor.cursor().0 else {
486 return;
487 };
488 let cursor_pos = coords.row as u16;
489 let doc = doc!(cx.editor);
490 let language = doc.language_name().unwrap_or("");
491
492 let markdowned = |lang: &str, detail: Option<&str>, doc: Option<&str>| {
493 let md = match (detail, doc) {
494 (Some(detail), Some(doc)) => format!("```{lang}\n{detail}\n```\n{doc}"),
495 (Some(detail), None) => format!("```{lang}\n{detail}\n```"),
496 (None, Some(doc)) => doc.to_string(),
497 (None, None) => String::new(),
498 };
499 Markdown::new(md, cx.editor.syn_loader.clone())
500 };
501
502 let mut markdown_doc = match option {
503 CompletionItem::Lsp(option) => match &option.item.documentation {
504 Some(lsp::Documentation::String(contents))
505 | Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
506 kind: lsp::MarkupKind::PlainText,
507 value: contents,
508 })) => {
509 // TODO: convert to wrapped text
510 markdowned(language, option.item.detail.as_deref(), Some(contents))
511 }
512 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
513 kind: lsp::MarkupKind::Markdown,
514 value: contents,
515 })) => {
516 // TODO: set language based on doc scope
517 markdowned(language, option.item.detail.as_deref(), Some(contents))
518 }
519 None if option.item.detail.is_some() => {
520 // TODO: set language based on doc scope
521 markdowned(language, option.item.detail.as_deref(), None)
522 }
523 None => return,
524 },
525 CompletionItem::Other(option) => {
526 let Some(doc) = option.documentation.as_deref() else {
527 return;
528 };
529 markdowned(language, None, Some(doc))
530 }
531 };
532
533 let popup_area = self.popup.area(area, cx.editor);
534 let doc_width_available = area.width.saturating_sub(popup_area.right());
535 let doc_area = if doc_width_available > 30 {
536 let mut doc_width = doc_width_available;
537 let mut doc_height = area.height.saturating_sub(popup_area.top());
538 let x = popup_area.right();
539 let y = popup_area.top();
540
541 if let Some((rel_width, rel_height)) =
542 markdown_doc.required_size((doc_width, doc_height))
543 {
544 doc_width = rel_width.min(doc_width);
545 doc_height = rel_height.min(doc_height);
546 }
547 Rect::new(x, y, doc_width, doc_height)
548 } else {
549 // Documentation should not cover the cursor or the completion popup
550 // Completion popup could be above or below the current line
551 let avail_height_above = cursor_pos.min(popup_area.top()).saturating_sub(1);
552 let avail_height_below = area
553 .height
554 .saturating_sub(cursor_pos.max(popup_area.bottom()) + 1 /* padding */);
555 let (y, avail_height) = if avail_height_below >= avail_height_above {
556 (
557 area.height.saturating_sub(avail_height_below),
558 avail_height_below,
559 )
560 } else {
561 (0, avail_height_above)
562 };
563 if avail_height <= 1 {
564 return;
565 }
566
567 Rect::new(0, y, area.width, avail_height.min(15))
568 };
569
570 // clear area
571 let background = cx.editor.theme.get("ui.popup");
572 surface.clear_with(doc_area, background);
573
574 if cx.editor.popup_border() {
575 use tui::widgets::{Block, Widget};
576 Widget::render(Block::bordered(), doc_area, surface);
577 }
578
579 markdown_doc.render(doc_area, surface, cx);
580 }
581 }
582 fn lsp_item_to_transaction(
583 doc: &Document,
584 view_id: ViewId,
585 item: &lsp::CompletionItem,
586 offset_encoding: OffsetEncoding,
587 trigger_offset: usize,
588 replace_mode: bool,
589 ) -> (Transaction, Option<RenderedSnippet>) {
590 let selection = doc.selection(view_id);
591 let text = doc.text().slice(..);
592 let primary_cursor = selection.primary().cursor(text);
593
594 let (edit_offset, new_text) = if let Some(edit) = &item.text_edit {
595 let edit = match edit {
596 lsp::CompletionTextEdit::Edit(edit) => edit.clone(),
597 lsp::CompletionTextEdit::InsertAndReplace(item) => {
598 let range = if replace_mode {
599 item.replace
600 } else {
601 item.insert
602 };
603 lsp::TextEdit::new(range, item.new_text.clone())
604 }
605 };
606
607 let Some(range) = util::lsp_range_to_range(doc.text(), edit.range, offset_encoding) else {
608 return (Transaction::new(doc.text()), None);
609 };
610
611 let start_offset = range.anchor as i128 - primary_cursor as i128;
612 let end_offset = range.head as i128 - primary_cursor as i128;
613
614 (Some((start_offset, end_offset)), edit.new_text)
615 } else {
616 let new_text = item
617 .insert_text
618 .clone()
619 .unwrap_or_else(|| item.label.clone());
620 // check that we are still at the correct savepoint
621 // we can still generate a transaction regardless but if the
622 // document changed (and not just the selection) then we will
623 // likely delete the wrong text (same if we applied an edit sent by the LS)
624 debug_assert!(primary_cursor == trigger_offset);
625 (None, new_text)
626 };
627
628 if matches!(item.kind, Some(lsp::CompletionItemKind::SNIPPET))
629 || matches!(
630 item.insert_text_format,
631 Some(lsp::InsertTextFormat::SNIPPET)
632 )
633 {
634 let Ok(snippet) = Snippet::parse(&new_text) else {
635 log::error!("Failed to parse snippet: {new_text:?}",);
636 return (Transaction::new(doc.text()), None);
637 };
638 let (transaction, snippet) = util::generate_transaction_from_snippet(
639 doc.text(),
640 selection,
641 edit_offset,
642 replace_mode,
643 snippet,
644 &mut doc.snippet_ctx(),
645 );
646 (transaction, Some(snippet))
647 } else {
648 let transaction = util::generate_transaction_from_completion_edit(
649 doc.text(),
650 selection,
651 edit_offset,
652 replace_mode,
653 new_text,
654 );
655 (transaction, None)
656 }
657 }
658
659 fn completion_changes(transaction: &Transaction, trigger_offset: usize) -> Vec<Change> {
660 transaction
661 .changes_iter()
662 .filter(|(start, end, _)| (*start..=*end).contains(&trigger_offset))
663 .collect()
664 }