1use fuzzy::{StringMatch, StringMatchCandidate};
2use gpui::{
3 AnyElement, Entity, Focusable, FontWeight, ListSizingBehavior, ScrollStrategy, SharedString,
4 Size, StrikethroughStyle, StyledText, Task, UniformListScrollHandle, div, px, uniform_list,
5};
6use itertools::Itertools;
7use language::CodeLabel;
8use language::{Buffer, LanguageName, LanguageRegistry};
9use markdown::{Markdown, MarkdownElement};
10use multi_buffer::{Anchor, ExcerptId};
11use ordered_float::OrderedFloat;
12use project::CompletionSource;
13use project::lsp_store::CompletionDocumentation;
14use project::{CodeAction, Completion, TaskSourceKind};
15use task::DebugScenario;
16use task::TaskContext;
17
18use std::collections::VecDeque;
19use std::sync::Arc;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::{
22 cell::RefCell,
23 cmp::{Reverse, min},
24 iter,
25 ops::Range,
26 rc::Rc,
27};
28use task::ResolvedTask;
29use ui::{Color, IntoElement, ListItem, Pixels, Popover, Styled, prelude::*};
30use util::ResultExt;
31
32use crate::CodeActionSource;
33use crate::editor_settings::SnippetSortOrder;
34use crate::hover_popover::{hover_markdown_style, open_markdown_url};
35use crate::{
36 CodeActionProvider, CompletionId, CompletionItemKind, CompletionProvider, DisplayRow, Editor,
37 EditorStyle, ResolvedTasks,
38 actions::{ConfirmCodeAction, ConfirmCompletion},
39 split_words, styled_runs_for_code_label,
40};
41
42pub const MENU_GAP: Pixels = px(4.);
43pub const MENU_ASIDE_X_PADDING: Pixels = px(16.);
44pub const MENU_ASIDE_MIN_WIDTH: Pixels = px(260.);
45pub const MENU_ASIDE_MAX_WIDTH: Pixels = px(500.);
46
47// Constants for the markdown cache. The purpose of this cache is to reduce flickering due to
48// documentation not yet being parsed.
49//
50// The size of the cache is set to 16, which is roughly 3 times more than the number of items
51// fetched around the current selection. This way documentation is more often ready for render when
52// revisiting previous entries, such as when pressing backspace.
53const MARKDOWN_CACHE_MAX_SIZE: usize = 16;
54const MARKDOWN_CACHE_BEFORE_ITEMS: usize = 2;
55const MARKDOWN_CACHE_AFTER_ITEMS: usize = 2;
56
57// Number of items beyond the visible items to resolve documentation.
58const RESOLVE_BEFORE_ITEMS: usize = 4;
59const RESOLVE_AFTER_ITEMS: usize = 4;
60
61pub enum CodeContextMenu {
62 Completions(CompletionsMenu),
63 CodeActions(CodeActionsMenu),
64}
65
66impl CodeContextMenu {
67 pub fn select_first(
68 &mut self,
69 provider: Option<&dyn CompletionProvider>,
70 window: &mut Window,
71 cx: &mut Context<Editor>,
72 ) -> bool {
73 if self.visible() {
74 match self {
75 CodeContextMenu::Completions(menu) => menu.select_first(provider, window, cx),
76 CodeContextMenu::CodeActions(menu) => menu.select_first(cx),
77 }
78 true
79 } else {
80 false
81 }
82 }
83
84 pub fn select_prev(
85 &mut self,
86 provider: Option<&dyn CompletionProvider>,
87 window: &mut Window,
88 cx: &mut Context<Editor>,
89 ) -> bool {
90 if self.visible() {
91 match self {
92 CodeContextMenu::Completions(menu) => menu.select_prev(provider, window, cx),
93 CodeContextMenu::CodeActions(menu) => menu.select_prev(cx),
94 }
95 true
96 } else {
97 false
98 }
99 }
100
101 pub fn select_next(
102 &mut self,
103 provider: Option<&dyn CompletionProvider>,
104 window: &mut Window,
105 cx: &mut Context<Editor>,
106 ) -> bool {
107 if self.visible() {
108 match self {
109 CodeContextMenu::Completions(menu) => menu.select_next(provider, window, cx),
110 CodeContextMenu::CodeActions(menu) => menu.select_next(cx),
111 }
112 true
113 } else {
114 false
115 }
116 }
117
118 pub fn select_last(
119 &mut self,
120 provider: Option<&dyn CompletionProvider>,
121 window: &mut Window,
122 cx: &mut Context<Editor>,
123 ) -> bool {
124 if self.visible() {
125 match self {
126 CodeContextMenu::Completions(menu) => menu.select_last(provider, window, cx),
127 CodeContextMenu::CodeActions(menu) => menu.select_last(cx),
128 }
129 true
130 } else {
131 false
132 }
133 }
134
135 pub fn visible(&self) -> bool {
136 match self {
137 CodeContextMenu::Completions(menu) => menu.visible(),
138 CodeContextMenu::CodeActions(menu) => menu.visible(),
139 }
140 }
141
142 pub fn origin(&self) -> ContextMenuOrigin {
143 match self {
144 CodeContextMenu::Completions(menu) => menu.origin(),
145 CodeContextMenu::CodeActions(menu) => menu.origin(),
146 }
147 }
148
149 pub fn render(
150 &self,
151 style: &EditorStyle,
152 max_height_in_lines: u32,
153 window: &mut Window,
154 cx: &mut Context<Editor>,
155 ) -> AnyElement {
156 match self {
157 CodeContextMenu::Completions(menu) => {
158 menu.render(style, max_height_in_lines, window, cx)
159 }
160 CodeContextMenu::CodeActions(menu) => {
161 menu.render(style, max_height_in_lines, window, cx)
162 }
163 }
164 }
165
166 pub fn render_aside(
167 &mut self,
168 max_size: Size<Pixels>,
169 window: &mut Window,
170 cx: &mut Context<Editor>,
171 ) -> Option<AnyElement> {
172 match self {
173 CodeContextMenu::Completions(menu) => menu.render_aside(max_size, window, cx),
174 CodeContextMenu::CodeActions(_) => None,
175 }
176 }
177
178 pub fn focused(&self, window: &mut Window, cx: &mut Context<Editor>) -> bool {
179 match self {
180 CodeContextMenu::Completions(completions_menu) => completions_menu
181 .get_or_create_entry_markdown(completions_menu.selected_item, cx)
182 .as_ref()
183 .is_some_and(|markdown| markdown.focus_handle(cx).contains_focused(window, cx)),
184 CodeContextMenu::CodeActions(_) => false,
185 }
186 }
187}
188
189pub enum ContextMenuOrigin {
190 Cursor,
191 GutterIndicator(DisplayRow),
192 QuickActionBar,
193}
194
195pub struct CompletionsMenu {
196 pub id: CompletionId,
197 pub source: CompletionsMenuSource,
198 sort_completions: bool,
199 pub initial_position: Anchor,
200 pub initial_query: Option<Arc<String>>,
201 pub is_incomplete: bool,
202 pub buffer: Entity<Buffer>,
203 pub completions: Rc<RefCell<Box<[Completion]>>>,
204 match_candidates: Arc<[StringMatchCandidate]>,
205 pub entries: Rc<RefCell<Box<[StringMatch]>>>,
206 pub selected_item: usize,
207 filter_task: Task<()>,
208 cancel_filter: Arc<AtomicBool>,
209 scroll_handle: UniformListScrollHandle,
210 resolve_completions: bool,
211 show_completion_documentation: bool,
212 last_rendered_range: Rc<RefCell<Option<Range<usize>>>>,
213 markdown_cache: Rc<RefCell<VecDeque<(MarkdownCacheKey, Entity<Markdown>)>>>,
214 language_registry: Option<Arc<LanguageRegistry>>,
215 language: Option<LanguageName>,
216 snippet_sort_order: SnippetSortOrder,
217}
218
219#[derive(Clone, Debug, PartialEq)]
220enum MarkdownCacheKey {
221 ForCandidate {
222 candidate_id: usize,
223 },
224 ForCompletionMatch {
225 new_text: String,
226 markdown_source: SharedString,
227 },
228}
229
230#[derive(Copy, Clone, Debug, PartialEq, Eq)]
231pub enum CompletionsMenuSource {
232 Normal,
233 SnippetChoices,
234 Words,
235}
236
237// TODO: There should really be a wrapper around fuzzy match tasks that does this.
238impl Drop for CompletionsMenu {
239 fn drop(&mut self) {
240 self.cancel_filter.store(true, Ordering::Relaxed);
241 }
242}
243
244impl CompletionsMenu {
245 pub fn new(
246 id: CompletionId,
247 source: CompletionsMenuSource,
248 sort_completions: bool,
249 show_completion_documentation: bool,
250 initial_position: Anchor,
251 initial_query: Option<Arc<String>>,
252 is_incomplete: bool,
253 buffer: Entity<Buffer>,
254 completions: Box<[Completion]>,
255 snippet_sort_order: SnippetSortOrder,
256 language_registry: Option<Arc<LanguageRegistry>>,
257 language: Option<LanguageName>,
258 cx: &mut Context<Editor>,
259 ) -> Self {
260 let match_candidates = completions
261 .iter()
262 .enumerate()
263 .map(|(id, completion)| StringMatchCandidate::new(id, completion.label.filter_text()))
264 .collect();
265
266 let completions_menu = Self {
267 id,
268 source,
269 sort_completions,
270 initial_position,
271 initial_query,
272 is_incomplete,
273 buffer,
274 show_completion_documentation,
275 completions: RefCell::new(completions).into(),
276 match_candidates,
277 entries: Rc::new(RefCell::new(Box::new([]))),
278 selected_item: 0,
279 filter_task: Task::ready(()),
280 cancel_filter: Arc::new(AtomicBool::new(false)),
281 scroll_handle: UniformListScrollHandle::new(),
282 resolve_completions: true,
283 last_rendered_range: RefCell::new(None).into(),
284 markdown_cache: RefCell::new(VecDeque::new()).into(),
285 language_registry,
286 language,
287 snippet_sort_order,
288 };
289
290 completions_menu.start_markdown_parse_for_nearby_entries(cx);
291
292 completions_menu
293 }
294
295 pub fn new_snippet_choices(
296 id: CompletionId,
297 sort_completions: bool,
298 choices: &Vec<String>,
299 selection: Range<Anchor>,
300 buffer: Entity<Buffer>,
301 snippet_sort_order: SnippetSortOrder,
302 ) -> Self {
303 let completions = choices
304 .iter()
305 .map(|choice| Completion {
306 replace_range: selection.start.text_anchor..selection.end.text_anchor,
307 new_text: choice.to_string(),
308 label: CodeLabel {
309 text: choice.to_string(),
310 runs: Default::default(),
311 filter_range: Default::default(),
312 },
313 icon_path: None,
314 documentation: None,
315 confirm: None,
316 insert_text_mode: None,
317 source: CompletionSource::Custom,
318 })
319 .collect();
320
321 let match_candidates = choices
322 .iter()
323 .enumerate()
324 .map(|(id, completion)| StringMatchCandidate::new(id, completion))
325 .collect();
326 let entries = choices
327 .iter()
328 .enumerate()
329 .map(|(id, completion)| StringMatch {
330 candidate_id: id,
331 score: 1.,
332 positions: vec![],
333 string: completion.clone(),
334 })
335 .collect();
336 Self {
337 id,
338 source: CompletionsMenuSource::SnippetChoices,
339 sort_completions,
340 initial_position: selection.start,
341 initial_query: None,
342 is_incomplete: false,
343 buffer,
344 completions: RefCell::new(completions).into(),
345 match_candidates,
346 entries: RefCell::new(entries).into(),
347 selected_item: 0,
348 filter_task: Task::ready(()),
349 cancel_filter: Arc::new(AtomicBool::new(false)),
350 scroll_handle: UniformListScrollHandle::new(),
351 resolve_completions: false,
352 show_completion_documentation: false,
353 last_rendered_range: RefCell::new(None).into(),
354 markdown_cache: RefCell::new(VecDeque::new()).into(),
355 language_registry: None,
356 language: None,
357 snippet_sort_order,
358 }
359 }
360
361 fn select_first(
362 &mut self,
363 provider: Option<&dyn CompletionProvider>,
364 window: &mut Window,
365 cx: &mut Context<Editor>,
366 ) {
367 let index = if self.scroll_handle.y_flipped() {
368 self.entries.borrow().len() - 1
369 } else {
370 0
371 };
372 self.update_selection_index(index, provider, window, cx);
373 }
374
375 fn select_last(
376 &mut self,
377 provider: Option<&dyn CompletionProvider>,
378 window: &mut Window,
379 cx: &mut Context<Editor>,
380 ) {
381 let index = if self.scroll_handle.y_flipped() {
382 0
383 } else {
384 self.entries.borrow().len() - 1
385 };
386 self.update_selection_index(index, provider, window, cx);
387 }
388
389 fn select_prev(
390 &mut self,
391 provider: Option<&dyn CompletionProvider>,
392 window: &mut Window,
393 cx: &mut Context<Editor>,
394 ) {
395 let index = if self.scroll_handle.y_flipped() {
396 self.next_match_index()
397 } else {
398 self.prev_match_index()
399 };
400 self.update_selection_index(index, provider, window, cx);
401 }
402
403 fn select_next(
404 &mut self,
405 provider: Option<&dyn CompletionProvider>,
406 window: &mut Window,
407 cx: &mut Context<Editor>,
408 ) {
409 let index = if self.scroll_handle.y_flipped() {
410 self.prev_match_index()
411 } else {
412 self.next_match_index()
413 };
414 self.update_selection_index(index, provider, window, cx);
415 }
416
417 fn update_selection_index(
418 &mut self,
419 match_index: usize,
420 provider: Option<&dyn CompletionProvider>,
421 window: &mut Window,
422 cx: &mut Context<Editor>,
423 ) {
424 if self.selected_item != match_index {
425 self.selected_item = match_index;
426 self.handle_selection_changed(provider, window, cx);
427 }
428 }
429
430 fn prev_match_index(&self) -> usize {
431 if self.selected_item > 0 {
432 self.selected_item - 1
433 } else {
434 self.entries.borrow().len() - 1
435 }
436 }
437
438 fn next_match_index(&self) -> usize {
439 if self.selected_item + 1 < self.entries.borrow().len() {
440 self.selected_item + 1
441 } else {
442 0
443 }
444 }
445
446 fn handle_selection_changed(
447 &mut self,
448 provider: Option<&dyn CompletionProvider>,
449 window: &mut Window,
450 cx: &mut Context<Editor>,
451 ) {
452 self.scroll_handle
453 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
454 if let Some(provider) = provider {
455 let entries = self.entries.borrow();
456 let entry = if self.selected_item < entries.len() {
457 Some(&entries[self.selected_item])
458 } else {
459 None
460 };
461 provider.selection_changed(entry, window, cx);
462 }
463 self.resolve_visible_completions(provider, cx);
464 self.start_markdown_parse_for_nearby_entries(cx);
465 cx.notify();
466 }
467
468 pub fn resolve_visible_completions(
469 &mut self,
470 provider: Option<&dyn CompletionProvider>,
471 cx: &mut Context<Editor>,
472 ) {
473 if !self.resolve_completions {
474 return;
475 }
476 let Some(provider) = provider else {
477 return;
478 };
479
480 let entries = self.entries.borrow();
481 if entries.is_empty() {
482 return;
483 }
484 if self.selected_item >= entries.len() {
485 log::error!(
486 "bug: completion selected_item >= entries.len(): {} >= {}",
487 self.selected_item,
488 entries.len()
489 );
490 self.selected_item = entries.len() - 1;
491 }
492
493 // Attempt to resolve completions for every item that will be displayed. This matters
494 // because single line documentation may be displayed inline with the completion.
495 //
496 // When navigating to the very beginning or end of completions, `last_rendered_range` may
497 // have no overlap with the completions that will be displayed, so instead use a range based
498 // on the last rendered count.
499 const APPROXIMATE_VISIBLE_COUNT: usize = 12;
500 let last_rendered_range = self.last_rendered_range.borrow().clone();
501 let visible_count = last_rendered_range
502 .clone()
503 .map_or(APPROXIMATE_VISIBLE_COUNT, |range| range.count());
504 let entry_range = if self.selected_item == 0 {
505 0..min(visible_count, entries.len())
506 } else if self.selected_item == entries.len() - 1 {
507 entries.len().saturating_sub(visible_count)..entries.len()
508 } else {
509 last_rendered_range.map_or(0..0, |range| {
510 min(range.start, entries.len())..min(range.end, entries.len())
511 })
512 };
513
514 // Expand the range to resolve more completions than are predicted to be visible, to reduce
515 // jank on navigation.
516 let entry_indices = util::expanded_and_wrapped_usize_range(
517 entry_range,
518 RESOLVE_BEFORE_ITEMS,
519 RESOLVE_AFTER_ITEMS,
520 entries.len(),
521 );
522
523 // Avoid work by sometimes filtering out completions that already have documentation.
524 // This filtering doesn't happen if the completions are currently being updated.
525 let completions = self.completions.borrow();
526 let candidate_ids = entry_indices
527 .map(|i| entries[i].candidate_id)
528 .filter(|i| completions[*i].documentation.is_none());
529
530 // Current selection is always resolved even if it already has documentation, to handle
531 // out-of-spec language servers that return more results later.
532 let selected_candidate_id = entries[self.selected_item].candidate_id;
533 let candidate_ids = iter::once(selected_candidate_id)
534 .chain(candidate_ids.filter(|id| *id != selected_candidate_id))
535 .collect::<Vec<usize>>();
536 drop(entries);
537
538 if candidate_ids.is_empty() {
539 return;
540 }
541
542 let resolve_task = provider.resolve_completions(
543 self.buffer.clone(),
544 candidate_ids,
545 self.completions.clone(),
546 cx,
547 );
548
549 let completion_id = self.id;
550 cx.spawn(async move |editor, cx| {
551 if let Some(true) = resolve_task.await.log_err() {
552 editor
553 .update(cx, |editor, cx| {
554 // `resolve_completions` modified state affecting display.
555 cx.notify();
556 editor.with_completions_menu_matching_id(completion_id, |menu| {
557 if let Some(menu) = menu {
558 menu.start_markdown_parse_for_nearby_entries(cx)
559 }
560 });
561 })
562 .ok();
563 }
564 })
565 .detach();
566 }
567
568 fn start_markdown_parse_for_nearby_entries(&self, cx: &mut Context<Editor>) {
569 // Enqueue parse tasks of nearer items first.
570 //
571 // TODO: This means that the nearer items will actually be further back in the cache, which
572 // is not ideal. In practice this is fine because `get_or_create_markdown` moves the current
573 // selection to the front (when `is_render = true`).
574 let entry_indices = util::wrapped_usize_outward_from(
575 self.selected_item,
576 MARKDOWN_CACHE_BEFORE_ITEMS,
577 MARKDOWN_CACHE_AFTER_ITEMS,
578 self.entries.borrow().len(),
579 );
580
581 for index in entry_indices {
582 self.get_or_create_entry_markdown(index, cx);
583 }
584 }
585
586 fn get_or_create_entry_markdown(
587 &self,
588 index: usize,
589 cx: &mut Context<Editor>,
590 ) -> Option<Entity<Markdown>> {
591 let entries = self.entries.borrow();
592 if index >= entries.len() {
593 return None;
594 }
595 let candidate_id = entries[index].candidate_id;
596 let completions = self.completions.borrow();
597 match &completions[candidate_id].documentation {
598 Some(CompletionDocumentation::MultiLineMarkdown(source)) if !source.is_empty() => self
599 .get_or_create_markdown(candidate_id, Some(source), false, &completions, cx)
600 .map(|(_, markdown)| markdown),
601 Some(_) => None,
602 _ => None,
603 }
604 }
605
606 fn get_or_create_markdown(
607 &self,
608 candidate_id: usize,
609 source: Option<&SharedString>,
610 is_render: bool,
611 completions: &[Completion],
612 cx: &mut Context<Editor>,
613 ) -> Option<(bool, Entity<Markdown>)> {
614 let mut markdown_cache = self.markdown_cache.borrow_mut();
615
616 let mut has_completion_match_cache_entry = false;
617 let mut matching_entry = markdown_cache.iter().find_position(|(key, _)| match key {
618 MarkdownCacheKey::ForCandidate { candidate_id: id } => *id == candidate_id,
619 MarkdownCacheKey::ForCompletionMatch { .. } => {
620 has_completion_match_cache_entry = true;
621 false
622 }
623 });
624
625 if has_completion_match_cache_entry && matching_entry.is_none() {
626 if let Some(source) = source {
627 matching_entry = markdown_cache.iter().find_position(|(key, _)| {
628 matches!(key, MarkdownCacheKey::ForCompletionMatch { markdown_source, .. }
629 if markdown_source == source)
630 });
631 } else {
632 // Heuristic guess that documentation can be reused when new_text matches. This is
633 // to mitigate documentation flicker while typing. If this is wrong, then resolution
634 // should cause the correct documentation to be displayed soon.
635 let completion = &completions[candidate_id];
636 matching_entry = markdown_cache.iter().find_position(|(key, _)| {
637 matches!(key, MarkdownCacheKey::ForCompletionMatch { new_text, .. }
638 if new_text == &completion.new_text)
639 });
640 }
641 }
642
643 if let Some((cache_index, (key, markdown))) = matching_entry {
644 let markdown = markdown.clone();
645
646 // Since the markdown source matches, the key can now be ForCandidate.
647 if source.is_some() && matches!(key, MarkdownCacheKey::ForCompletionMatch { .. }) {
648 markdown_cache[cache_index].0 = MarkdownCacheKey::ForCandidate { candidate_id };
649 }
650
651 if is_render && cache_index != 0 {
652 // Move the current selection's cache entry to the front.
653 markdown_cache.rotate_right(1);
654 let cache_len = markdown_cache.len();
655 markdown_cache.swap(0, (cache_index + 1) % cache_len);
656 }
657
658 let is_parsing = markdown.update(cx, |markdown, cx| {
659 if let Some(source) = source {
660 // `reset` is called as it's possible for documentation to change due to resolve
661 // requests. It does nothing if `source` is unchanged.
662 markdown.reset(source.clone(), cx);
663 }
664 markdown.is_parsing()
665 });
666 return Some((is_parsing, markdown));
667 }
668
669 let Some(source) = source else {
670 // Can't create markdown as there is no source.
671 return None;
672 };
673
674 if markdown_cache.len() < MARKDOWN_CACHE_MAX_SIZE {
675 let markdown = cx.new(|cx| {
676 Markdown::new(
677 source.clone(),
678 self.language_registry.clone(),
679 self.language.clone(),
680 cx,
681 )
682 });
683 // Handles redraw when the markdown is done parsing. The current render is for a
684 // deferred draw, and so without this did not redraw when `markdown` notified.
685 cx.observe(&markdown, |_, _, cx| cx.notify()).detach();
686 markdown_cache.push_front((
687 MarkdownCacheKey::ForCandidate { candidate_id },
688 markdown.clone(),
689 ));
690 Some((true, markdown))
691 } else {
692 debug_assert_eq!(markdown_cache.capacity(), MARKDOWN_CACHE_MAX_SIZE);
693 // Moves the last cache entry to the start. The ring buffer is full, so this does no
694 // copying and just shifts indexes.
695 markdown_cache.rotate_right(1);
696 markdown_cache[0].0 = MarkdownCacheKey::ForCandidate { candidate_id };
697 let markdown = &markdown_cache[0].1;
698 markdown.update(cx, |markdown, cx| markdown.reset(source.clone(), cx));
699 Some((true, markdown.clone()))
700 }
701 }
702
703 pub fn visible(&self) -> bool {
704 !self.entries.borrow().is_empty()
705 }
706
707 fn origin(&self) -> ContextMenuOrigin {
708 ContextMenuOrigin::Cursor
709 }
710
711 fn render(
712 &self,
713 style: &EditorStyle,
714 max_height_in_lines: u32,
715 window: &mut Window,
716 cx: &mut Context<Editor>,
717 ) -> AnyElement {
718 let show_completion_documentation = self.show_completion_documentation;
719 let selected_item = self.selected_item;
720 let completions = self.completions.clone();
721 let entries = self.entries.clone();
722 let last_rendered_range = self.last_rendered_range.clone();
723 let style = style.clone();
724 let list = uniform_list(
725 "completions",
726 self.entries.borrow().len(),
727 cx.processor(move |_editor, range: Range<usize>, _window, cx| {
728 last_rendered_range.borrow_mut().replace(range.clone());
729 let start_ix = range.start;
730 let completions_guard = completions.borrow_mut();
731
732 entries.borrow()[range]
733 .iter()
734 .enumerate()
735 .map(|(ix, mat)| {
736 let item_ix = start_ix + ix;
737 let completion = &completions_guard[mat.candidate_id];
738 let documentation = if show_completion_documentation {
739 &completion.documentation
740 } else {
741 &None
742 };
743
744 let filter_start = completion.label.filter_range.start;
745 let highlights = gpui::combine_highlights(
746 mat.ranges().map(|range| {
747 (
748 filter_start + range.start..filter_start + range.end,
749 FontWeight::BOLD.into(),
750 )
751 }),
752 styled_runs_for_code_label(&completion.label, &style.syntax).map(
753 |(range, mut highlight)| {
754 // Ignore font weight for syntax highlighting, as we'll use it
755 // for fuzzy matches.
756 highlight.font_weight = None;
757 if completion
758 .source
759 .lsp_completion(false)
760 .and_then(|lsp_completion| lsp_completion.deprecated)
761 .unwrap_or(false)
762 {
763 highlight.strikethrough = Some(StrikethroughStyle {
764 thickness: 1.0.into(),
765 ..Default::default()
766 });
767 highlight.color = Some(cx.theme().colors().text_muted);
768 }
769
770 (range, highlight)
771 },
772 ),
773 );
774
775 let completion_label = StyledText::new(completion.label.text.clone())
776 .with_default_highlights(&style.text, highlights);
777
778 let documentation_label = match documentation {
779 Some(CompletionDocumentation::SingleLine(text))
780 | Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
781 single_line: text,
782 ..
783 }) => {
784 if text.trim().is_empty() {
785 None
786 } else {
787 Some(
788 Label::new(text.clone())
789 .ml_4()
790 .size(LabelSize::Small)
791 .color(Color::Muted),
792 )
793 }
794 }
795 _ => None,
796 };
797
798 let start_slot = completion
799 .color()
800 .map(|color| {
801 div()
802 .flex_shrink_0()
803 .size_3p5()
804 .rounded_xs()
805 .bg(color)
806 .into_any_element()
807 })
808 .or_else(|| {
809 completion.icon_path.as_ref().map(|path| {
810 Icon::from_path(path)
811 .size(IconSize::XSmall)
812 .color(Color::Muted)
813 .into_any_element()
814 })
815 });
816
817 div().min_w(px(280.)).max_w(px(540.)).child(
818 ListItem::new(mat.candidate_id)
819 .inset(true)
820 .toggle_state(item_ix == selected_item)
821 .on_click(cx.listener(move |editor, _event, window, cx| {
822 cx.stop_propagation();
823 if let Some(task) = editor.confirm_completion(
824 &ConfirmCompletion {
825 item_ix: Some(item_ix),
826 },
827 window,
828 cx,
829 ) {
830 task.detach_and_log_err(cx)
831 }
832 }))
833 .start_slot::<AnyElement>(start_slot)
834 .child(h_flex().overflow_hidden().child(completion_label))
835 .end_slot::<Label>(documentation_label),
836 )
837 })
838 .collect()
839 }),
840 )
841 .occlude()
842 .max_h(max_height_in_lines as f32 * window.line_height())
843 .track_scroll(self.scroll_handle.clone())
844 .with_sizing_behavior(ListSizingBehavior::Infer)
845 .w(rems(34.));
846
847 Popover::new().child(list).into_any_element()
848 }
849
850 fn render_aside(
851 &mut self,
852 max_size: Size<Pixels>,
853 window: &mut Window,
854 cx: &mut Context<Editor>,
855 ) -> Option<AnyElement> {
856 if !self.show_completion_documentation {
857 return None;
858 }
859
860 let mat = &self.entries.borrow()[self.selected_item];
861 let completions = self.completions.borrow_mut();
862 let multiline_docs = match completions[mat.candidate_id].documentation.as_ref() {
863 Some(CompletionDocumentation::MultiLinePlainText(text)) => div().child(text.clone()),
864 Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
865 plain_text: Some(text),
866 ..
867 }) => div().child(text.clone()),
868 Some(CompletionDocumentation::MultiLineMarkdown(source)) if !source.is_empty() => {
869 let Some((false, markdown)) = self.get_or_create_markdown(
870 mat.candidate_id,
871 Some(source),
872 true,
873 &completions,
874 cx,
875 ) else {
876 return None;
877 };
878 Self::render_markdown(markdown, window, cx)
879 }
880 None => {
881 // Handle the case where documentation hasn't yet been resolved but there's a
882 // `new_text` match in the cache.
883 //
884 // TODO: It's inconsistent that documentation caching based on matching `new_text`
885 // only works for markdown. Consider generally caching the results of resolving
886 // completions.
887 let Some((false, markdown)) =
888 self.get_or_create_markdown(mat.candidate_id, None, true, &completions, cx)
889 else {
890 return None;
891 };
892 Self::render_markdown(markdown, window, cx)
893 }
894 Some(CompletionDocumentation::MultiLineMarkdown(_)) => return None,
895 Some(CompletionDocumentation::SingleLine(_)) => return None,
896 Some(CompletionDocumentation::Undocumented) => return None,
897 Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
898 plain_text: None,
899 ..
900 }) => {
901 return None;
902 }
903 };
904
905 Some(
906 Popover::new()
907 .child(
908 multiline_docs
909 .id("multiline_docs")
910 .px(MENU_ASIDE_X_PADDING / 2.)
911 .max_w(max_size.width)
912 .max_h(max_size.height)
913 .overflow_y_scroll()
914 .occlude(),
915 )
916 .into_any_element(),
917 )
918 }
919
920 fn render_markdown(
921 markdown: Entity<Markdown>,
922 window: &mut Window,
923 cx: &mut Context<Editor>,
924 ) -> Div {
925 div().child(
926 MarkdownElement::new(markdown, hover_markdown_style(window, cx))
927 .code_block_renderer(markdown::CodeBlockRenderer::Default {
928 copy_button: false,
929 copy_button_on_hover: false,
930 border: false,
931 })
932 .on_url_click(open_markdown_url),
933 )
934 }
935
936 pub fn filter(
937 &mut self,
938 query: Option<Arc<String>>,
939 provider: Option<Rc<dyn CompletionProvider>>,
940 window: &mut Window,
941 cx: &mut Context<Editor>,
942 ) {
943 self.cancel_filter.store(true, Ordering::Relaxed);
944 if let Some(query) = query {
945 self.cancel_filter = Arc::new(AtomicBool::new(false));
946 let matches = self.do_async_filtering(query, cx);
947 let id = self.id;
948 self.filter_task = cx.spawn_in(window, async move |editor, cx| {
949 let matches = matches.await;
950 editor
951 .update_in(cx, |editor, window, cx| {
952 editor.with_completions_menu_matching_id(id, |this| {
953 if let Some(this) = this {
954 this.set_filter_results(matches, provider, window, cx);
955 }
956 });
957 })
958 .ok();
959 });
960 } else {
961 self.filter_task = Task::ready(());
962 let matches = self.unfiltered_matches();
963 self.set_filter_results(matches, provider, window, cx);
964 }
965 }
966
967 pub fn do_async_filtering(
968 &self,
969 query: Arc<String>,
970 cx: &Context<Editor>,
971 ) -> Task<Vec<StringMatch>> {
972 let matches_task = cx.background_spawn({
973 let query = query.clone();
974 let match_candidates = self.match_candidates.clone();
975 let cancel_filter = self.cancel_filter.clone();
976 let background_executor = cx.background_executor().clone();
977 async move {
978 fuzzy::match_strings(
979 &match_candidates,
980 &query,
981 query.chars().any(|c| c.is_uppercase()),
982 false,
983 1000,
984 &cancel_filter,
985 background_executor,
986 )
987 .await
988 }
989 });
990
991 let completions = self.completions.clone();
992 let sort_completions = self.sort_completions;
993 let snippet_sort_order = self.snippet_sort_order;
994 cx.foreground_executor().spawn(async move {
995 let mut matches = matches_task.await;
996
997 if sort_completions {
998 matches = Self::sort_string_matches(
999 matches,
1000 Some(&query),
1001 snippet_sort_order,
1002 completions.borrow().as_ref(),
1003 );
1004 }
1005
1006 matches
1007 })
1008 }
1009
1010 /// Like `do_async_filtering` but there is no filter query, so no need to spawn tasks.
1011 pub fn unfiltered_matches(&self) -> Vec<StringMatch> {
1012 let mut matches = self
1013 .match_candidates
1014 .iter()
1015 .enumerate()
1016 .map(|(candidate_id, candidate)| StringMatch {
1017 candidate_id,
1018 score: Default::default(),
1019 positions: Default::default(),
1020 string: candidate.string.clone(),
1021 })
1022 .collect();
1023
1024 if self.sort_completions {
1025 matches = Self::sort_string_matches(
1026 matches,
1027 None,
1028 self.snippet_sort_order,
1029 self.completions.borrow().as_ref(),
1030 );
1031 }
1032
1033 matches
1034 }
1035
1036 pub fn set_filter_results(
1037 &mut self,
1038 matches: Vec<StringMatch>,
1039 provider: Option<Rc<dyn CompletionProvider>>,
1040 window: &mut Window,
1041 cx: &mut Context<Editor>,
1042 ) {
1043 *self.entries.borrow_mut() = matches.into_boxed_slice();
1044 self.selected_item = 0;
1045 self.handle_selection_changed(provider.as_deref(), window, cx);
1046 }
1047
1048 pub fn sort_string_matches(
1049 matches: Vec<StringMatch>,
1050 query: Option<&str>,
1051 snippet_sort_order: SnippetSortOrder,
1052 completions: &[Completion],
1053 ) -> Vec<StringMatch> {
1054 let mut matches = matches;
1055
1056 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1057 enum MatchTier<'a> {
1058 WordStartMatch {
1059 sort_exact: Reverse<i32>,
1060 sort_snippet: Reverse<i32>,
1061 sort_score: Reverse<OrderedFloat<f64>>,
1062 sort_positions: Vec<usize>,
1063 sort_text: Option<&'a str>,
1064 sort_kind: usize,
1065 sort_label: &'a str,
1066 },
1067 OtherMatch {
1068 sort_score: Reverse<OrderedFloat<f64>>,
1069 },
1070 }
1071
1072 let query_start_lower = query
1073 .as_ref()
1074 .and_then(|q| q.chars().next())
1075 .and_then(|c| c.to_lowercase().next());
1076
1077 if snippet_sort_order == SnippetSortOrder::None {
1078 matches.retain(|string_match| {
1079 let completion = &completions[string_match.candidate_id];
1080
1081 let is_snippet = matches!(
1082 &completion.source,
1083 CompletionSource::Lsp { lsp_completion, .. }
1084 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
1085 );
1086
1087 !is_snippet
1088 });
1089 }
1090
1091 matches.sort_unstable_by_key(|string_match| {
1092 let completion = &completions[string_match.candidate_id];
1093
1094 let is_snippet = matches!(
1095 &completion.source,
1096 CompletionSource::Lsp { lsp_completion, .. }
1097 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
1098 );
1099
1100 let sort_text = match &completion.source {
1101 CompletionSource::Lsp { lsp_completion, .. } => lsp_completion.sort_text.as_deref(),
1102 CompletionSource::Dap { sort_text } => Some(sort_text.as_str()),
1103 _ => None,
1104 };
1105
1106 let (sort_kind, sort_label) = completion.sort_key();
1107
1108 let score = string_match.score;
1109 let sort_score = Reverse(OrderedFloat(score));
1110
1111 let query_start_doesnt_match_split_words = query_start_lower
1112 .map(|query_char| {
1113 !split_words(&string_match.string).any(|word| {
1114 word.chars().next().and_then(|c| c.to_lowercase().next())
1115 == Some(query_char)
1116 })
1117 })
1118 .unwrap_or(false);
1119
1120 if query_start_doesnt_match_split_words {
1121 MatchTier::OtherMatch { sort_score }
1122 } else {
1123 let sort_snippet = match snippet_sort_order {
1124 SnippetSortOrder::Top => Reverse(if is_snippet { 1 } else { 0 }),
1125 SnippetSortOrder::Bottom => Reverse(if is_snippet { 0 } else { 1 }),
1126 SnippetSortOrder::Inline => Reverse(0),
1127 SnippetSortOrder::None => Reverse(0),
1128 };
1129 let sort_positions = string_match.positions.clone();
1130 let sort_exact = Reverse(if Some(completion.label.filter_text()) == query {
1131 1
1132 } else {
1133 0
1134 });
1135
1136 MatchTier::WordStartMatch {
1137 sort_exact,
1138 sort_snippet,
1139 sort_score,
1140 sort_positions,
1141 sort_text,
1142 sort_kind,
1143 sort_label,
1144 }
1145 }
1146 });
1147
1148 matches
1149 }
1150
1151 pub fn preserve_markdown_cache(&mut self, prev_menu: CompletionsMenu) {
1152 self.markdown_cache = prev_menu.markdown_cache.clone();
1153
1154 // Convert ForCandidate cache keys to ForCompletionMatch keys.
1155 let prev_completions = prev_menu.completions.borrow();
1156 self.markdown_cache
1157 .borrow_mut()
1158 .retain_mut(|(key, _markdown)| match key {
1159 MarkdownCacheKey::ForCompletionMatch { .. } => true,
1160 MarkdownCacheKey::ForCandidate { candidate_id } => {
1161 if let Some(completion) = prev_completions.get(*candidate_id) {
1162 match &completion.documentation {
1163 Some(CompletionDocumentation::MultiLineMarkdown(source)) => {
1164 *key = MarkdownCacheKey::ForCompletionMatch {
1165 new_text: completion.new_text.clone(),
1166 markdown_source: source.clone(),
1167 };
1168 true
1169 }
1170 _ => false,
1171 }
1172 } else {
1173 false
1174 }
1175 }
1176 });
1177 }
1178}
1179
1180#[derive(Clone)]
1181pub struct AvailableCodeAction {
1182 pub excerpt_id: ExcerptId,
1183 pub action: CodeAction,
1184 pub provider: Rc<dyn CodeActionProvider>,
1185}
1186
1187#[derive(Clone)]
1188pub struct CodeActionContents {
1189 tasks: Option<Rc<ResolvedTasks>>,
1190 actions: Option<Rc<[AvailableCodeAction]>>,
1191 debug_scenarios: Vec<DebugScenario>,
1192 pub(crate) context: TaskContext,
1193}
1194
1195impl CodeActionContents {
1196 pub(crate) fn new(
1197 tasks: Option<ResolvedTasks>,
1198 actions: Option<Rc<[AvailableCodeAction]>>,
1199 debug_scenarios: Vec<DebugScenario>,
1200 context: TaskContext,
1201 ) -> Self {
1202 Self {
1203 tasks: tasks.map(Rc::new),
1204 actions,
1205 debug_scenarios,
1206 context,
1207 }
1208 }
1209
1210 pub fn tasks(&self) -> Option<&ResolvedTasks> {
1211 self.tasks.as_deref()
1212 }
1213
1214 fn len(&self) -> usize {
1215 let tasks_len = self.tasks.as_ref().map_or(0, |tasks| tasks.templates.len());
1216 let code_actions_len = self.actions.as_ref().map_or(0, |actions| actions.len());
1217 tasks_len + code_actions_len + self.debug_scenarios.len()
1218 }
1219
1220 pub fn is_empty(&self) -> bool {
1221 self.len() == 0
1222 }
1223
1224 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1225 self.tasks
1226 .iter()
1227 .flat_map(|tasks| {
1228 tasks
1229 .templates
1230 .iter()
1231 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1232 })
1233 .chain(self.actions.iter().flat_map(|actions| {
1234 actions.iter().map(|available| CodeActionsItem::CodeAction {
1235 excerpt_id: available.excerpt_id,
1236 action: available.action.clone(),
1237 provider: available.provider.clone(),
1238 })
1239 }))
1240 .chain(
1241 self.debug_scenarios
1242 .iter()
1243 .cloned()
1244 .map(CodeActionsItem::DebugScenario),
1245 )
1246 }
1247
1248 pub fn get(&self, mut index: usize) -> Option<CodeActionsItem> {
1249 if let Some(tasks) = &self.tasks {
1250 if let Some((kind, task)) = tasks.templates.get(index) {
1251 return Some(CodeActionsItem::Task(kind.clone(), task.clone()));
1252 } else {
1253 index -= tasks.templates.len();
1254 }
1255 }
1256 if let Some(actions) = &self.actions {
1257 if let Some(available) = actions.get(index) {
1258 return Some(CodeActionsItem::CodeAction {
1259 excerpt_id: available.excerpt_id,
1260 action: available.action.clone(),
1261 provider: available.provider.clone(),
1262 });
1263 } else {
1264 index -= actions.len();
1265 }
1266 }
1267
1268 self.debug_scenarios
1269 .get(index)
1270 .cloned()
1271 .map(CodeActionsItem::DebugScenario)
1272 }
1273}
1274
1275#[derive(Clone)]
1276pub enum CodeActionsItem {
1277 Task(TaskSourceKind, ResolvedTask),
1278 CodeAction {
1279 excerpt_id: ExcerptId,
1280 action: CodeAction,
1281 provider: Rc<dyn CodeActionProvider>,
1282 },
1283 DebugScenario(DebugScenario),
1284}
1285
1286impl CodeActionsItem {
1287 fn as_task(&self) -> Option<&ResolvedTask> {
1288 let Self::Task(_, task) = self else {
1289 return None;
1290 };
1291 Some(task)
1292 }
1293
1294 fn as_code_action(&self) -> Option<&CodeAction> {
1295 let Self::CodeAction { action, .. } = self else {
1296 return None;
1297 };
1298 Some(action)
1299 }
1300 fn as_debug_scenario(&self) -> Option<&DebugScenario> {
1301 let Self::DebugScenario(scenario) = self else {
1302 return None;
1303 };
1304 Some(scenario)
1305 }
1306
1307 pub fn label(&self) -> String {
1308 match self {
1309 Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
1310 Self::Task(_, task) => task.resolved_label.clone(),
1311 Self::DebugScenario(scenario) => scenario.label.to_string(),
1312 }
1313 }
1314}
1315
1316pub struct CodeActionsMenu {
1317 pub actions: CodeActionContents,
1318 pub buffer: Entity<Buffer>,
1319 pub selected_item: usize,
1320 pub scroll_handle: UniformListScrollHandle,
1321 pub deployed_from: Option<CodeActionSource>,
1322}
1323
1324impl CodeActionsMenu {
1325 fn select_first(&mut self, cx: &mut Context<Editor>) {
1326 self.selected_item = if self.scroll_handle.y_flipped() {
1327 self.actions.len() - 1
1328 } else {
1329 0
1330 };
1331 self.scroll_handle
1332 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1333 cx.notify()
1334 }
1335
1336 fn select_last(&mut self, cx: &mut Context<Editor>) {
1337 self.selected_item = if self.scroll_handle.y_flipped() {
1338 0
1339 } else {
1340 self.actions.len() - 1
1341 };
1342 self.scroll_handle
1343 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1344 cx.notify()
1345 }
1346
1347 fn select_prev(&mut self, cx: &mut Context<Editor>) {
1348 self.selected_item = if self.scroll_handle.y_flipped() {
1349 self.next_match_index()
1350 } else {
1351 self.prev_match_index()
1352 };
1353 self.scroll_handle
1354 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1355 cx.notify();
1356 }
1357
1358 fn select_next(&mut self, cx: &mut Context<Editor>) {
1359 self.selected_item = if self.scroll_handle.y_flipped() {
1360 self.prev_match_index()
1361 } else {
1362 self.next_match_index()
1363 };
1364 self.scroll_handle
1365 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1366 cx.notify();
1367 }
1368
1369 fn prev_match_index(&self) -> usize {
1370 if self.selected_item > 0 {
1371 self.selected_item - 1
1372 } else {
1373 self.actions.len() - 1
1374 }
1375 }
1376
1377 fn next_match_index(&self) -> usize {
1378 if self.selected_item + 1 < self.actions.len() {
1379 self.selected_item + 1
1380 } else {
1381 0
1382 }
1383 }
1384
1385 pub fn visible(&self) -> bool {
1386 !self.actions.is_empty()
1387 }
1388
1389 fn origin(&self) -> ContextMenuOrigin {
1390 match &self.deployed_from {
1391 Some(CodeActionSource::Indicator(row)) | Some(CodeActionSource::RunMenu(row)) => {
1392 ContextMenuOrigin::GutterIndicator(*row)
1393 }
1394 Some(CodeActionSource::QuickActionBar) => ContextMenuOrigin::QuickActionBar,
1395 None => ContextMenuOrigin::Cursor,
1396 }
1397 }
1398
1399 fn render(
1400 &self,
1401 _style: &EditorStyle,
1402 max_height_in_lines: u32,
1403 window: &mut Window,
1404 cx: &mut Context<Editor>,
1405 ) -> AnyElement {
1406 let actions = self.actions.clone();
1407 let selected_item = self.selected_item;
1408 let list = uniform_list(
1409 "code_actions_menu",
1410 self.actions.len(),
1411 cx.processor(move |_this, range: Range<usize>, _, cx| {
1412 actions
1413 .iter()
1414 .skip(range.start)
1415 .take(range.end - range.start)
1416 .enumerate()
1417 .map(|(ix, action)| {
1418 let item_ix = range.start + ix;
1419 let selected = item_ix == selected_item;
1420 let colors = cx.theme().colors();
1421 div().min_w(px(220.)).max_w(px(540.)).child(
1422 ListItem::new(item_ix)
1423 .inset(true)
1424 .toggle_state(selected)
1425 .when_some(action.as_code_action(), |this, action| {
1426 this.child(
1427 h_flex()
1428 .overflow_hidden()
1429 .child(
1430 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1431 action.lsp_action.title().replace("\n", ""),
1432 )
1433 .when(selected, |this| {
1434 this.text_color(colors.text_accent)
1435 }),
1436 )
1437 })
1438 .when_some(action.as_task(), |this, task| {
1439 this.child(
1440 h_flex()
1441 .overflow_hidden()
1442 .child(task.resolved_label.replace("\n", ""))
1443 .when(selected, |this| {
1444 this.text_color(colors.text_accent)
1445 }),
1446 )
1447 })
1448 .when_some(action.as_debug_scenario(), |this, scenario| {
1449 this.child(
1450 h_flex()
1451 .overflow_hidden()
1452 .child("debug: ")
1453 .child(scenario.label.clone())
1454 .when(selected, |this| {
1455 this.text_color(colors.text_accent)
1456 }),
1457 )
1458 })
1459 .on_click(cx.listener(move |editor, _, window, cx| {
1460 cx.stop_propagation();
1461 if let Some(task) = editor.confirm_code_action(
1462 &ConfirmCodeAction {
1463 item_ix: Some(item_ix),
1464 },
1465 window,
1466 cx,
1467 ) {
1468 task.detach_and_log_err(cx)
1469 }
1470 })),
1471 )
1472 })
1473 .collect()
1474 }),
1475 )
1476 .occlude()
1477 .max_h(max_height_in_lines as f32 * window.line_height())
1478 .track_scroll(self.scroll_handle.clone())
1479 .with_width_from_item(
1480 self.actions
1481 .iter()
1482 .enumerate()
1483 .max_by_key(|(_, action)| match action {
1484 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1485 CodeActionsItem::CodeAction { action, .. } => {
1486 action.lsp_action.title().chars().count()
1487 }
1488 CodeActionsItem::DebugScenario(scenario) => {
1489 format!("debug: {}", scenario.label).chars().count()
1490 }
1491 })
1492 .map(|(ix, _)| ix),
1493 )
1494 .with_sizing_behavior(ListSizingBehavior::Infer);
1495
1496 Popover::new().child(list).into_any_element()
1497 }
1498}