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.clone(),
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 cx.entity().clone(),
726 "completions",
727 self.entries.borrow().len(),
728 move |_editor, range, _window, cx| {
729 last_rendered_range.borrow_mut().replace(range.clone());
730 let start_ix = range.start;
731 let completions_guard = completions.borrow_mut();
732
733 entries.borrow()[range]
734 .iter()
735 .enumerate()
736 .map(|(ix, mat)| {
737 let item_ix = start_ix + ix;
738 let completion = &completions_guard[mat.candidate_id];
739 let documentation = if show_completion_documentation {
740 &completion.documentation
741 } else {
742 &None
743 };
744
745 let filter_start = completion.label.filter_range.start;
746 let highlights = gpui::combine_highlights(
747 mat.ranges().map(|range| {
748 (
749 filter_start + range.start..filter_start + range.end,
750 FontWeight::BOLD.into(),
751 )
752 }),
753 styled_runs_for_code_label(&completion.label, &style.syntax).map(
754 |(range, mut highlight)| {
755 // Ignore font weight for syntax highlighting, as we'll use it
756 // for fuzzy matches.
757 highlight.font_weight = None;
758 if completion
759 .source
760 .lsp_completion(false)
761 .and_then(|lsp_completion| lsp_completion.deprecated)
762 .unwrap_or(false)
763 {
764 highlight.strikethrough = Some(StrikethroughStyle {
765 thickness: 1.0.into(),
766 ..Default::default()
767 });
768 highlight.color = Some(cx.theme().colors().text_muted);
769 }
770
771 (range, highlight)
772 },
773 ),
774 );
775
776 let completion_label = StyledText::new(completion.label.text.clone())
777 .with_default_highlights(&style.text, highlights);
778
779 let documentation_label = match documentation {
780 Some(CompletionDocumentation::SingleLine(text))
781 | Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
782 single_line: text,
783 ..
784 }) => {
785 if text.trim().is_empty() {
786 None
787 } else {
788 Some(
789 Label::new(text.clone())
790 .ml_4()
791 .size(LabelSize::Small)
792 .color(Color::Muted),
793 )
794 }
795 }
796 _ => None,
797 };
798
799 let start_slot = completion
800 .color()
801 .map(|color| {
802 div()
803 .flex_shrink_0()
804 .size_3p5()
805 .rounded_xs()
806 .bg(color)
807 .into_any_element()
808 })
809 .or_else(|| {
810 completion.icon_path.as_ref().map(|path| {
811 Icon::from_path(path)
812 .size(IconSize::XSmall)
813 .color(Color::Muted)
814 .into_any_element()
815 })
816 });
817
818 div().min_w(px(280.)).max_w(px(540.)).child(
819 ListItem::new(mat.candidate_id)
820 .inset(true)
821 .toggle_state(item_ix == selected_item)
822 .on_click(cx.listener(move |editor, _event, window, cx| {
823 cx.stop_propagation();
824 if let Some(task) = editor.confirm_completion(
825 &ConfirmCompletion {
826 item_ix: Some(item_ix),
827 },
828 window,
829 cx,
830 ) {
831 task.detach_and_log_err(cx)
832 }
833 }))
834 .start_slot::<AnyElement>(start_slot)
835 .child(h_flex().overflow_hidden().child(completion_label))
836 .end_slot::<Label>(documentation_label),
837 )
838 })
839 .collect()
840 },
841 )
842 .occlude()
843 .max_h(max_height_in_lines as f32 * window.line_height())
844 .track_scroll(self.scroll_handle.clone())
845 .with_sizing_behavior(ListSizingBehavior::Infer)
846 .w(rems(34.));
847
848 Popover::new().child(list).into_any_element()
849 }
850
851 fn render_aside(
852 &mut self,
853 max_size: Size<Pixels>,
854 window: &mut Window,
855 cx: &mut Context<Editor>,
856 ) -> Option<AnyElement> {
857 if !self.show_completion_documentation {
858 return None;
859 }
860
861 let mat = &self.entries.borrow()[self.selected_item];
862 let completions = self.completions.borrow_mut();
863 let multiline_docs = match completions[mat.candidate_id].documentation.as_ref() {
864 Some(CompletionDocumentation::MultiLinePlainText(text)) => div().child(text.clone()),
865 Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
866 plain_text: Some(text),
867 ..
868 }) => div().child(text.clone()),
869 Some(CompletionDocumentation::MultiLineMarkdown(source)) if !source.is_empty() => {
870 let Some((false, markdown)) = self.get_or_create_markdown(
871 mat.candidate_id,
872 Some(source),
873 true,
874 &completions,
875 cx,
876 ) else {
877 return None;
878 };
879 Self::render_markdown(markdown, window, cx)
880 }
881 None => {
882 // Handle the case where documentation hasn't yet been resolved but there's a
883 // `new_text` match in the cache.
884 //
885 // TODO: It's inconsistent that documentation caching based on matching `new_text`
886 // only works for markdown. Consider generally caching the results of resolving
887 // completions.
888 let Some((false, markdown)) =
889 self.get_or_create_markdown(mat.candidate_id, None, true, &completions, cx)
890 else {
891 return None;
892 };
893 Self::render_markdown(markdown, window, cx)
894 }
895 Some(CompletionDocumentation::MultiLineMarkdown(_)) => return None,
896 Some(CompletionDocumentation::SingleLine(_)) => return None,
897 Some(CompletionDocumentation::Undocumented) => return None,
898 Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
899 plain_text: None,
900 ..
901 }) => {
902 return None;
903 }
904 };
905
906 Some(
907 Popover::new()
908 .child(
909 multiline_docs
910 .id("multiline_docs")
911 .px(MENU_ASIDE_X_PADDING / 2.)
912 .max_w(max_size.width)
913 .max_h(max_size.height)
914 .overflow_y_scroll()
915 .occlude(),
916 )
917 .into_any_element(),
918 )
919 }
920
921 fn render_markdown(
922 markdown: Entity<Markdown>,
923 window: &mut Window,
924 cx: &mut Context<Editor>,
925 ) -> Div {
926 div().child(
927 MarkdownElement::new(markdown, hover_markdown_style(window, cx))
928 .code_block_renderer(markdown::CodeBlockRenderer::Default {
929 copy_button: false,
930 copy_button_on_hover: false,
931 border: false,
932 })
933 .on_url_click(open_markdown_url),
934 )
935 }
936
937 pub fn filter(
938 &mut self,
939 query: Option<Arc<String>>,
940 provider: Option<Rc<dyn CompletionProvider>>,
941 window: &mut Window,
942 cx: &mut Context<Editor>,
943 ) {
944 self.cancel_filter.store(true, Ordering::Relaxed);
945 if let Some(query) = query {
946 self.cancel_filter = Arc::new(AtomicBool::new(false));
947 let matches = self.do_async_filtering(query, cx);
948 let id = self.id;
949 self.filter_task = cx.spawn_in(window, async move |editor, cx| {
950 let matches = matches.await;
951 editor
952 .update_in(cx, |editor, window, cx| {
953 editor.with_completions_menu_matching_id(id, |this| {
954 if let Some(this) = this {
955 this.set_filter_results(matches, provider, window, cx);
956 }
957 });
958 })
959 .ok();
960 });
961 } else {
962 self.filter_task = Task::ready(());
963 let matches = self.unfiltered_matches();
964 self.set_filter_results(matches, provider, window, cx);
965 }
966 }
967
968 pub fn do_async_filtering(
969 &self,
970 query: Arc<String>,
971 cx: &Context<Editor>,
972 ) -> Task<Vec<StringMatch>> {
973 let matches_task = cx.background_spawn({
974 let query = query.clone();
975 let match_candidates = self.match_candidates.clone();
976 let cancel_filter = self.cancel_filter.clone();
977 let background_executor = cx.background_executor().clone();
978 async move {
979 fuzzy::match_strings(
980 &match_candidates,
981 &query,
982 query.chars().any(|c| c.is_uppercase()),
983 100,
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 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 sortable_items: Vec<SortableMatch<'_>> = matches
1055 .into_iter()
1056 .map(|string_match| {
1057 let completion = &completions[string_match.candidate_id];
1058
1059 let is_snippet = matches!(
1060 &completion.source,
1061 CompletionSource::Lsp { lsp_completion, .. }
1062 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
1063 );
1064
1065 let sort_text =
1066 if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
1067 lsp_completion.sort_text.as_deref()
1068 } else {
1069 None
1070 };
1071
1072 let (sort_kind, sort_label) = completion.sort_key();
1073
1074 SortableMatch {
1075 string_match,
1076 is_snippet,
1077 sort_text,
1078 sort_kind,
1079 sort_label,
1080 }
1081 })
1082 .collect();
1083
1084 Self::sort_matches(&mut sortable_items, query, snippet_sort_order);
1085
1086 sortable_items
1087 .into_iter()
1088 .map(|sortable| sortable.string_match)
1089 .collect()
1090 }
1091
1092 pub fn sort_matches(
1093 matches: &mut Vec<SortableMatch<'_>>,
1094 query: Option<&str>,
1095 snippet_sort_order: SnippetSortOrder,
1096 ) {
1097 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1098 enum MatchTier<'a> {
1099 WordStartMatch {
1100 sort_mixed_case_prefix_length: Reverse<usize>,
1101 sort_snippet: Reverse<i32>,
1102 sort_kind: usize,
1103 sort_fuzzy_bracket: Reverse<usize>,
1104 sort_text: Option<&'a str>,
1105 sort_score: Reverse<OrderedFloat<f64>>,
1106 sort_label: &'a str,
1107 },
1108 OtherMatch {
1109 sort_score: Reverse<OrderedFloat<f64>>,
1110 },
1111 }
1112
1113 // Our goal here is to intelligently sort completion suggestions. We want to
1114 // balance the raw fuzzy match score with hints from the language server
1115
1116 // In a fuzzy bracket, matches with a score of 1.0 are prioritized.
1117 // The remaining matches are partitioned into two groups at 3/5 of the max_score.
1118 let max_score = matches
1119 .iter()
1120 .map(|mat| mat.string_match.score)
1121 .fold(0.0, f64::max);
1122 let fuzzy_bracket_threshold = max_score * (3.0 / 5.0);
1123
1124 let query_start_lower = query
1125 .as_ref()
1126 .and_then(|q| q.chars().next())
1127 .and_then(|c| c.to_lowercase().next());
1128
1129 matches.sort_unstable_by_key(|mat| {
1130 let score = mat.string_match.score;
1131 let sort_score = Reverse(OrderedFloat(score));
1132
1133 let query_start_doesnt_match_split_words = query_start_lower
1134 .map(|query_char| {
1135 !split_words(&mat.string_match.string).any(|word| {
1136 word.chars()
1137 .next()
1138 .and_then(|c| c.to_lowercase().next())
1139 .map_or(false, |word_char| word_char == query_char)
1140 })
1141 })
1142 .unwrap_or(false);
1143
1144 if query_start_doesnt_match_split_words {
1145 MatchTier::OtherMatch { sort_score }
1146 } else {
1147 let sort_fuzzy_bracket = Reverse(if score >= fuzzy_bracket_threshold {
1148 1
1149 } else {
1150 0
1151 });
1152 let sort_snippet = match snippet_sort_order {
1153 SnippetSortOrder::Top => Reverse(if mat.is_snippet { 1 } else { 0 }),
1154 SnippetSortOrder::Bottom => Reverse(if mat.is_snippet { 0 } else { 1 }),
1155 SnippetSortOrder::Inline => Reverse(0),
1156 };
1157 let sort_mixed_case_prefix_length = Reverse(
1158 query
1159 .as_ref()
1160 .map(|q| {
1161 q.chars()
1162 .zip(mat.string_match.string.chars())
1163 .enumerate()
1164 .take_while(|(i, (q_char, match_char))| {
1165 if *i == 0 {
1166 // Case-sensitive comparison for first character
1167 q_char == match_char
1168 } else {
1169 // Case-insensitive comparison for other characters
1170 q_char.to_lowercase().eq(match_char.to_lowercase())
1171 }
1172 })
1173 .count()
1174 })
1175 .unwrap_or(0),
1176 );
1177 MatchTier::WordStartMatch {
1178 sort_mixed_case_prefix_length,
1179 sort_snippet,
1180 sort_kind: mat.sort_kind,
1181 sort_fuzzy_bracket,
1182 sort_text: mat.sort_text,
1183 sort_score,
1184 sort_label: mat.sort_label,
1185 }
1186 }
1187 });
1188 }
1189
1190 pub fn preserve_markdown_cache(&mut self, prev_menu: CompletionsMenu) {
1191 self.markdown_cache = prev_menu.markdown_cache.clone();
1192
1193 // Convert ForCandidate cache keys to ForCompletionMatch keys.
1194 let prev_completions = prev_menu.completions.borrow();
1195 self.markdown_cache
1196 .borrow_mut()
1197 .retain_mut(|(key, _markdown)| match key {
1198 MarkdownCacheKey::ForCompletionMatch { .. } => true,
1199 MarkdownCacheKey::ForCandidate { candidate_id } => {
1200 if let Some(completion) = prev_completions.get(*candidate_id) {
1201 match &completion.documentation {
1202 Some(CompletionDocumentation::MultiLineMarkdown(source)) => {
1203 *key = MarkdownCacheKey::ForCompletionMatch {
1204 new_text: completion.new_text.clone(),
1205 markdown_source: source.clone(),
1206 };
1207 true
1208 }
1209 _ => false,
1210 }
1211 } else {
1212 false
1213 }
1214 }
1215 });
1216 }
1217}
1218
1219#[derive(Debug)]
1220pub struct SortableMatch<'a> {
1221 pub string_match: StringMatch,
1222 pub is_snippet: bool,
1223 pub sort_text: Option<&'a str>,
1224 pub sort_kind: usize,
1225 pub sort_label: &'a str,
1226}
1227
1228#[derive(Clone)]
1229pub struct AvailableCodeAction {
1230 pub excerpt_id: ExcerptId,
1231 pub action: CodeAction,
1232 pub provider: Rc<dyn CodeActionProvider>,
1233}
1234
1235#[derive(Clone)]
1236pub struct CodeActionContents {
1237 tasks: Option<Rc<ResolvedTasks>>,
1238 actions: Option<Rc<[AvailableCodeAction]>>,
1239 debug_scenarios: Vec<DebugScenario>,
1240 pub(crate) context: TaskContext,
1241}
1242
1243impl CodeActionContents {
1244 pub(crate) fn new(
1245 tasks: Option<ResolvedTasks>,
1246 actions: Option<Rc<[AvailableCodeAction]>>,
1247 debug_scenarios: Vec<DebugScenario>,
1248 context: TaskContext,
1249 ) -> Self {
1250 Self {
1251 tasks: tasks.map(Rc::new),
1252 actions,
1253 debug_scenarios,
1254 context,
1255 }
1256 }
1257
1258 pub fn tasks(&self) -> Option<&ResolvedTasks> {
1259 self.tasks.as_deref()
1260 }
1261
1262 fn len(&self) -> usize {
1263 let tasks_len = self.tasks.as_ref().map_or(0, |tasks| tasks.templates.len());
1264 let code_actions_len = self.actions.as_ref().map_or(0, |actions| actions.len());
1265 tasks_len + code_actions_len + self.debug_scenarios.len()
1266 }
1267
1268 fn is_empty(&self) -> bool {
1269 self.len() == 0
1270 }
1271
1272 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1273 self.tasks
1274 .iter()
1275 .flat_map(|tasks| {
1276 tasks
1277 .templates
1278 .iter()
1279 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1280 })
1281 .chain(self.actions.iter().flat_map(|actions| {
1282 actions.iter().map(|available| CodeActionsItem::CodeAction {
1283 excerpt_id: available.excerpt_id,
1284 action: available.action.clone(),
1285 provider: available.provider.clone(),
1286 })
1287 }))
1288 .chain(
1289 self.debug_scenarios
1290 .iter()
1291 .cloned()
1292 .map(CodeActionsItem::DebugScenario),
1293 )
1294 }
1295
1296 pub fn get(&self, mut index: usize) -> Option<CodeActionsItem> {
1297 if let Some(tasks) = &self.tasks {
1298 if let Some((kind, task)) = tasks.templates.get(index) {
1299 return Some(CodeActionsItem::Task(kind.clone(), task.clone()));
1300 } else {
1301 index -= tasks.templates.len();
1302 }
1303 }
1304 if let Some(actions) = &self.actions {
1305 if let Some(available) = actions.get(index) {
1306 return Some(CodeActionsItem::CodeAction {
1307 excerpt_id: available.excerpt_id,
1308 action: available.action.clone(),
1309 provider: available.provider.clone(),
1310 });
1311 } else {
1312 index -= actions.len();
1313 }
1314 }
1315
1316 self.debug_scenarios
1317 .get(index)
1318 .cloned()
1319 .map(CodeActionsItem::DebugScenario)
1320 }
1321}
1322
1323#[derive(Clone)]
1324pub enum CodeActionsItem {
1325 Task(TaskSourceKind, ResolvedTask),
1326 CodeAction {
1327 excerpt_id: ExcerptId,
1328 action: CodeAction,
1329 provider: Rc<dyn CodeActionProvider>,
1330 },
1331 DebugScenario(DebugScenario),
1332}
1333
1334impl CodeActionsItem {
1335 fn as_task(&self) -> Option<&ResolvedTask> {
1336 let Self::Task(_, task) = self else {
1337 return None;
1338 };
1339 Some(task)
1340 }
1341
1342 fn as_code_action(&self) -> Option<&CodeAction> {
1343 let Self::CodeAction { action, .. } = self else {
1344 return None;
1345 };
1346 Some(action)
1347 }
1348 fn as_debug_scenario(&self) -> Option<&DebugScenario> {
1349 let Self::DebugScenario(scenario) = self else {
1350 return None;
1351 };
1352 Some(scenario)
1353 }
1354
1355 pub fn label(&self) -> String {
1356 match self {
1357 Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
1358 Self::Task(_, task) => task.resolved_label.clone(),
1359 Self::DebugScenario(scenario) => scenario.label.to_string(),
1360 }
1361 }
1362}
1363
1364pub struct CodeActionsMenu {
1365 pub actions: CodeActionContents,
1366 pub buffer: Entity<Buffer>,
1367 pub selected_item: usize,
1368 pub scroll_handle: UniformListScrollHandle,
1369 pub deployed_from: Option<CodeActionSource>,
1370}
1371
1372impl CodeActionsMenu {
1373 fn select_first(&mut self, cx: &mut Context<Editor>) {
1374 self.selected_item = if self.scroll_handle.y_flipped() {
1375 self.actions.len() - 1
1376 } else {
1377 0
1378 };
1379 self.scroll_handle
1380 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1381 cx.notify()
1382 }
1383
1384 fn select_last(&mut self, cx: &mut Context<Editor>) {
1385 self.selected_item = if self.scroll_handle.y_flipped() {
1386 0
1387 } else {
1388 self.actions.len() - 1
1389 };
1390 self.scroll_handle
1391 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1392 cx.notify()
1393 }
1394
1395 fn select_prev(&mut self, cx: &mut Context<Editor>) {
1396 self.selected_item = if self.scroll_handle.y_flipped() {
1397 self.next_match_index()
1398 } else {
1399 self.prev_match_index()
1400 };
1401 self.scroll_handle
1402 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1403 cx.notify();
1404 }
1405
1406 fn select_next(&mut self, cx: &mut Context<Editor>) {
1407 self.selected_item = if self.scroll_handle.y_flipped() {
1408 self.prev_match_index()
1409 } else {
1410 self.next_match_index()
1411 };
1412 self.scroll_handle
1413 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1414 cx.notify();
1415 }
1416
1417 fn prev_match_index(&self) -> usize {
1418 if self.selected_item > 0 {
1419 self.selected_item - 1
1420 } else {
1421 self.actions.len() - 1
1422 }
1423 }
1424
1425 fn next_match_index(&self) -> usize {
1426 if self.selected_item + 1 < self.actions.len() {
1427 self.selected_item + 1
1428 } else {
1429 0
1430 }
1431 }
1432
1433 fn visible(&self) -> bool {
1434 !self.actions.is_empty()
1435 }
1436
1437 fn origin(&self) -> ContextMenuOrigin {
1438 match &self.deployed_from {
1439 Some(CodeActionSource::Indicator(row)) => ContextMenuOrigin::GutterIndicator(*row),
1440 Some(CodeActionSource::QuickActionBar) => ContextMenuOrigin::QuickActionBar,
1441 None => ContextMenuOrigin::Cursor,
1442 }
1443 }
1444
1445 fn render(
1446 &self,
1447 _style: &EditorStyle,
1448 max_height_in_lines: u32,
1449 window: &mut Window,
1450 cx: &mut Context<Editor>,
1451 ) -> AnyElement {
1452 let actions = self.actions.clone();
1453 let selected_item = self.selected_item;
1454 let list = uniform_list(
1455 cx.entity().clone(),
1456 "code_actions_menu",
1457 self.actions.len(),
1458 move |_this, range, _, cx| {
1459 actions
1460 .iter()
1461 .skip(range.start)
1462 .take(range.end - range.start)
1463 .enumerate()
1464 .map(|(ix, action)| {
1465 let item_ix = range.start + ix;
1466 let selected = item_ix == selected_item;
1467 let colors = cx.theme().colors();
1468 div().min_w(px(220.)).max_w(px(540.)).child(
1469 ListItem::new(item_ix)
1470 .inset(true)
1471 .toggle_state(selected)
1472 .when_some(action.as_code_action(), |this, action| {
1473 this.child(
1474 h_flex()
1475 .overflow_hidden()
1476 .child(
1477 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1478 action.lsp_action.title().replace("\n", ""),
1479 )
1480 .when(selected, |this| {
1481 this.text_color(colors.text_accent)
1482 }),
1483 )
1484 })
1485 .when_some(action.as_task(), |this, task| {
1486 this.child(
1487 h_flex()
1488 .overflow_hidden()
1489 .child(task.resolved_label.replace("\n", ""))
1490 .when(selected, |this| {
1491 this.text_color(colors.text_accent)
1492 }),
1493 )
1494 })
1495 .when_some(action.as_debug_scenario(), |this, scenario| {
1496 this.child(
1497 h_flex()
1498 .overflow_hidden()
1499 .child("debug: ")
1500 .child(scenario.label.clone())
1501 .when(selected, |this| {
1502 this.text_color(colors.text_accent)
1503 }),
1504 )
1505 })
1506 .on_click(cx.listener(move |editor, _, window, cx| {
1507 cx.stop_propagation();
1508 if let Some(task) = editor.confirm_code_action(
1509 &ConfirmCodeAction {
1510 item_ix: Some(item_ix),
1511 },
1512 window,
1513 cx,
1514 ) {
1515 task.detach_and_log_err(cx)
1516 }
1517 })),
1518 )
1519 })
1520 .collect()
1521 },
1522 )
1523 .occlude()
1524 .max_h(max_height_in_lines as f32 * window.line_height())
1525 .track_scroll(self.scroll_handle.clone())
1526 .with_width_from_item(
1527 self.actions
1528 .iter()
1529 .enumerate()
1530 .max_by_key(|(_, action)| match action {
1531 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1532 CodeActionsItem::CodeAction { action, .. } => {
1533 action.lsp_action.title().chars().count()
1534 }
1535 CodeActionsItem::DebugScenario(scenario) => {
1536 format!("debug: {}", scenario.label).chars().count()
1537 }
1538 })
1539 .map(|(ix, _)| ix),
1540 )
1541 .with_sizing_behavior(ListSizingBehavior::Infer);
1542
1543 Popover::new().child(list).into_any_element()
1544 }
1545}