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