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 "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 100,
983 &cancel_filter,
984 background_executor,
985 )
986 .await
987 }
988 });
989
990 let completions = self.completions.clone();
991 let sort_completions = self.sort_completions;
992 let snippet_sort_order = self.snippet_sort_order;
993 cx.foreground_executor().spawn(async move {
994 let mut matches = matches_task.await;
995
996 if sort_completions {
997 matches = Self::sort_string_matches(
998 matches,
999 Some(&query),
1000 snippet_sort_order,
1001 completions.borrow().as_ref(),
1002 );
1003 }
1004
1005 matches
1006 })
1007 }
1008
1009 /// Like `do_async_filtering` but there is no filter query, so no need to spawn tasks.
1010 pub fn unfiltered_matches(&self) -> Vec<StringMatch> {
1011 let mut matches = self
1012 .match_candidates
1013 .iter()
1014 .enumerate()
1015 .map(|(candidate_id, candidate)| StringMatch {
1016 candidate_id,
1017 score: Default::default(),
1018 positions: Default::default(),
1019 string: candidate.string.clone(),
1020 })
1021 .collect();
1022
1023 if self.sort_completions {
1024 matches = Self::sort_string_matches(
1025 matches,
1026 None,
1027 self.snippet_sort_order,
1028 self.completions.borrow().as_ref(),
1029 );
1030 }
1031
1032 matches
1033 }
1034
1035 pub fn set_filter_results(
1036 &mut self,
1037 matches: Vec<StringMatch>,
1038 provider: Option<Rc<dyn CompletionProvider>>,
1039 window: &mut Window,
1040 cx: &mut Context<Editor>,
1041 ) {
1042 *self.entries.borrow_mut() = matches.into_boxed_slice();
1043 self.selected_item = 0;
1044 self.handle_selection_changed(provider.as_deref(), window, cx);
1045 }
1046
1047 pub fn sort_string_matches(
1048 matches: Vec<StringMatch>,
1049 query: Option<&str>,
1050 snippet_sort_order: SnippetSortOrder,
1051 completions: &[Completion],
1052 ) -> Vec<StringMatch> {
1053 let mut matches = matches;
1054
1055 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1056 enum MatchTier<'a> {
1057 WordStartMatch {
1058 sort_mixed_case_prefix_length: Reverse<usize>,
1059 sort_snippet: Reverse<i32>,
1060 sort_kind: usize,
1061 sort_fuzzy_bracket: Reverse<usize>,
1062 sort_text: Option<&'a str>,
1063 sort_score: Reverse<OrderedFloat<f64>>,
1064 sort_label: &'a str,
1065 },
1066 OtherMatch {
1067 sort_score: Reverse<OrderedFloat<f64>>,
1068 },
1069 }
1070
1071 // Our goal here is to intelligently sort completion suggestions. We want to
1072 // balance the raw fuzzy match score with hints from the language server
1073
1074 // In a fuzzy bracket, matches with a score of 1.0 are prioritized.
1075 // The remaining matches are partitioned into two groups at 3/5 of the max_score.
1076 let max_score = matches.iter().map(|mat| mat.score).fold(0.0, f64::max);
1077 let fuzzy_bracket_threshold = max_score * (3.0 / 5.0);
1078
1079 let query_start_lower = query
1080 .as_ref()
1081 .and_then(|q| q.chars().next())
1082 .and_then(|c| c.to_lowercase().next());
1083
1084 matches.sort_unstable_by_key(|string_match| {
1085 let completion = &completions[string_match.candidate_id];
1086
1087 let is_snippet = matches!(
1088 &completion.source,
1089 CompletionSource::Lsp { lsp_completion, .. }
1090 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
1091 );
1092
1093 let sort_text = if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source
1094 {
1095 lsp_completion.sort_text.as_deref()
1096 } else {
1097 None
1098 };
1099
1100 let (sort_kind, sort_label) = completion.sort_key();
1101
1102 let score = string_match.score;
1103 let sort_score = Reverse(OrderedFloat(score));
1104
1105 let query_start_doesnt_match_split_words = query_start_lower
1106 .map(|query_char| {
1107 !split_words(&string_match.string).any(|word| {
1108 word.chars()
1109 .next()
1110 .and_then(|c| c.to_lowercase().next())
1111 .map_or(false, |word_char| word_char == query_char)
1112 })
1113 })
1114 .unwrap_or(false);
1115
1116 if query_start_doesnt_match_split_words {
1117 MatchTier::OtherMatch { sort_score }
1118 } else {
1119 let sort_fuzzy_bracket = Reverse(if score >= fuzzy_bracket_threshold {
1120 1
1121 } else {
1122 0
1123 });
1124 let sort_snippet = match snippet_sort_order {
1125 SnippetSortOrder::Top => Reverse(if is_snippet { 1 } else { 0 }),
1126 SnippetSortOrder::Bottom => Reverse(if is_snippet { 0 } else { 1 }),
1127 SnippetSortOrder::Inline => Reverse(0),
1128 };
1129 let sort_mixed_case_prefix_length = Reverse(
1130 query
1131 .as_ref()
1132 .map(|q| {
1133 q.chars()
1134 .zip(string_match.string.chars())
1135 .enumerate()
1136 .take_while(|(i, (q_char, match_char))| {
1137 if *i == 0 {
1138 // Case-sensitive comparison for first character
1139 q_char == match_char
1140 } else {
1141 // Case-insensitive comparison for other characters
1142 q_char.to_lowercase().eq(match_char.to_lowercase())
1143 }
1144 })
1145 .count()
1146 })
1147 .unwrap_or(0),
1148 );
1149 MatchTier::WordStartMatch {
1150 sort_mixed_case_prefix_length,
1151 sort_snippet,
1152 sort_kind,
1153 sort_fuzzy_bracket,
1154 sort_text,
1155 sort_score,
1156 sort_label,
1157 }
1158 }
1159 });
1160
1161 matches
1162 }
1163
1164 pub fn preserve_markdown_cache(&mut self, prev_menu: CompletionsMenu) {
1165 self.markdown_cache = prev_menu.markdown_cache.clone();
1166
1167 // Convert ForCandidate cache keys to ForCompletionMatch keys.
1168 let prev_completions = prev_menu.completions.borrow();
1169 self.markdown_cache
1170 .borrow_mut()
1171 .retain_mut(|(key, _markdown)| match key {
1172 MarkdownCacheKey::ForCompletionMatch { .. } => true,
1173 MarkdownCacheKey::ForCandidate { candidate_id } => {
1174 if let Some(completion) = prev_completions.get(*candidate_id) {
1175 match &completion.documentation {
1176 Some(CompletionDocumentation::MultiLineMarkdown(source)) => {
1177 *key = MarkdownCacheKey::ForCompletionMatch {
1178 new_text: completion.new_text.clone(),
1179 markdown_source: source.clone(),
1180 };
1181 true
1182 }
1183 _ => false,
1184 }
1185 } else {
1186 false
1187 }
1188 }
1189 });
1190 }
1191}
1192
1193#[derive(Clone)]
1194pub struct AvailableCodeAction {
1195 pub excerpt_id: ExcerptId,
1196 pub action: CodeAction,
1197 pub provider: Rc<dyn CodeActionProvider>,
1198}
1199
1200#[derive(Clone)]
1201pub struct CodeActionContents {
1202 tasks: Option<Rc<ResolvedTasks>>,
1203 actions: Option<Rc<[AvailableCodeAction]>>,
1204 debug_scenarios: Vec<DebugScenario>,
1205 pub(crate) context: TaskContext,
1206}
1207
1208impl CodeActionContents {
1209 pub(crate) fn new(
1210 tasks: Option<ResolvedTasks>,
1211 actions: Option<Rc<[AvailableCodeAction]>>,
1212 debug_scenarios: Vec<DebugScenario>,
1213 context: TaskContext,
1214 ) -> Self {
1215 Self {
1216 tasks: tasks.map(Rc::new),
1217 actions,
1218 debug_scenarios,
1219 context,
1220 }
1221 }
1222
1223 pub fn tasks(&self) -> Option<&ResolvedTasks> {
1224 self.tasks.as_deref()
1225 }
1226
1227 fn len(&self) -> usize {
1228 let tasks_len = self.tasks.as_ref().map_or(0, |tasks| tasks.templates.len());
1229 let code_actions_len = self.actions.as_ref().map_or(0, |actions| actions.len());
1230 tasks_len + code_actions_len + self.debug_scenarios.len()
1231 }
1232
1233 fn is_empty(&self) -> bool {
1234 self.len() == 0
1235 }
1236
1237 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1238 self.tasks
1239 .iter()
1240 .flat_map(|tasks| {
1241 tasks
1242 .templates
1243 .iter()
1244 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1245 })
1246 .chain(self.actions.iter().flat_map(|actions| {
1247 actions.iter().map(|available| CodeActionsItem::CodeAction {
1248 excerpt_id: available.excerpt_id,
1249 action: available.action.clone(),
1250 provider: available.provider.clone(),
1251 })
1252 }))
1253 .chain(
1254 self.debug_scenarios
1255 .iter()
1256 .cloned()
1257 .map(CodeActionsItem::DebugScenario),
1258 )
1259 }
1260
1261 pub fn get(&self, mut index: usize) -> Option<CodeActionsItem> {
1262 if let Some(tasks) = &self.tasks {
1263 if let Some((kind, task)) = tasks.templates.get(index) {
1264 return Some(CodeActionsItem::Task(kind.clone(), task.clone()));
1265 } else {
1266 index -= tasks.templates.len();
1267 }
1268 }
1269 if let Some(actions) = &self.actions {
1270 if let Some(available) = actions.get(index) {
1271 return Some(CodeActionsItem::CodeAction {
1272 excerpt_id: available.excerpt_id,
1273 action: available.action.clone(),
1274 provider: available.provider.clone(),
1275 });
1276 } else {
1277 index -= actions.len();
1278 }
1279 }
1280
1281 self.debug_scenarios
1282 .get(index)
1283 .cloned()
1284 .map(CodeActionsItem::DebugScenario)
1285 }
1286}
1287
1288#[derive(Clone)]
1289pub enum CodeActionsItem {
1290 Task(TaskSourceKind, ResolvedTask),
1291 CodeAction {
1292 excerpt_id: ExcerptId,
1293 action: CodeAction,
1294 provider: Rc<dyn CodeActionProvider>,
1295 },
1296 DebugScenario(DebugScenario),
1297}
1298
1299impl CodeActionsItem {
1300 fn as_task(&self) -> Option<&ResolvedTask> {
1301 let Self::Task(_, task) = self else {
1302 return None;
1303 };
1304 Some(task)
1305 }
1306
1307 fn as_code_action(&self) -> Option<&CodeAction> {
1308 let Self::CodeAction { action, .. } = self else {
1309 return None;
1310 };
1311 Some(action)
1312 }
1313 fn as_debug_scenario(&self) -> Option<&DebugScenario> {
1314 let Self::DebugScenario(scenario) = self else {
1315 return None;
1316 };
1317 Some(scenario)
1318 }
1319
1320 pub fn label(&self) -> String {
1321 match self {
1322 Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
1323 Self::Task(_, task) => task.resolved_label.clone(),
1324 Self::DebugScenario(scenario) => scenario.label.to_string(),
1325 }
1326 }
1327}
1328
1329pub struct CodeActionsMenu {
1330 pub actions: CodeActionContents,
1331 pub buffer: Entity<Buffer>,
1332 pub selected_item: usize,
1333 pub scroll_handle: UniformListScrollHandle,
1334 pub deployed_from: Option<CodeActionSource>,
1335}
1336
1337impl CodeActionsMenu {
1338 fn select_first(&mut self, cx: &mut Context<Editor>) {
1339 self.selected_item = if self.scroll_handle.y_flipped() {
1340 self.actions.len() - 1
1341 } else {
1342 0
1343 };
1344 self.scroll_handle
1345 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1346 cx.notify()
1347 }
1348
1349 fn select_last(&mut self, cx: &mut Context<Editor>) {
1350 self.selected_item = if self.scroll_handle.y_flipped() {
1351 0
1352 } else {
1353 self.actions.len() - 1
1354 };
1355 self.scroll_handle
1356 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1357 cx.notify()
1358 }
1359
1360 fn select_prev(&mut self, cx: &mut Context<Editor>) {
1361 self.selected_item = if self.scroll_handle.y_flipped() {
1362 self.next_match_index()
1363 } else {
1364 self.prev_match_index()
1365 };
1366 self.scroll_handle
1367 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1368 cx.notify();
1369 }
1370
1371 fn select_next(&mut self, cx: &mut Context<Editor>) {
1372 self.selected_item = if self.scroll_handle.y_flipped() {
1373 self.prev_match_index()
1374 } else {
1375 self.next_match_index()
1376 };
1377 self.scroll_handle
1378 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1379 cx.notify();
1380 }
1381
1382 fn prev_match_index(&self) -> usize {
1383 if self.selected_item > 0 {
1384 self.selected_item - 1
1385 } else {
1386 self.actions.len() - 1
1387 }
1388 }
1389
1390 fn next_match_index(&self) -> usize {
1391 if self.selected_item + 1 < self.actions.len() {
1392 self.selected_item + 1
1393 } else {
1394 0
1395 }
1396 }
1397
1398 fn visible(&self) -> bool {
1399 !self.actions.is_empty()
1400 }
1401
1402 fn origin(&self) -> ContextMenuOrigin {
1403 match &self.deployed_from {
1404 Some(CodeActionSource::Indicator(row)) | Some(CodeActionSource::RunMenu(row)) => {
1405 ContextMenuOrigin::GutterIndicator(*row)
1406 }
1407 Some(CodeActionSource::QuickActionBar) => ContextMenuOrigin::QuickActionBar,
1408 None => ContextMenuOrigin::Cursor,
1409 }
1410 }
1411
1412 fn render(
1413 &self,
1414 _style: &EditorStyle,
1415 max_height_in_lines: u32,
1416 window: &mut Window,
1417 cx: &mut Context<Editor>,
1418 ) -> AnyElement {
1419 let actions = self.actions.clone();
1420 let selected_item = self.selected_item;
1421 let list = uniform_list(
1422 "code_actions_menu",
1423 self.actions.len(),
1424 cx.processor(move |_this, range: Range<usize>, _, cx| {
1425 actions
1426 .iter()
1427 .skip(range.start)
1428 .take(range.end - range.start)
1429 .enumerate()
1430 .map(|(ix, action)| {
1431 let item_ix = range.start + ix;
1432 let selected = item_ix == selected_item;
1433 let colors = cx.theme().colors();
1434 div().min_w(px(220.)).max_w(px(540.)).child(
1435 ListItem::new(item_ix)
1436 .inset(true)
1437 .toggle_state(selected)
1438 .when_some(action.as_code_action(), |this, action| {
1439 this.child(
1440 h_flex()
1441 .overflow_hidden()
1442 .child(
1443 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1444 action.lsp_action.title().replace("\n", ""),
1445 )
1446 .when(selected, |this| {
1447 this.text_color(colors.text_accent)
1448 }),
1449 )
1450 })
1451 .when_some(action.as_task(), |this, task| {
1452 this.child(
1453 h_flex()
1454 .overflow_hidden()
1455 .child(task.resolved_label.replace("\n", ""))
1456 .when(selected, |this| {
1457 this.text_color(colors.text_accent)
1458 }),
1459 )
1460 })
1461 .when_some(action.as_debug_scenario(), |this, scenario| {
1462 this.child(
1463 h_flex()
1464 .overflow_hidden()
1465 .child("debug: ")
1466 .child(scenario.label.clone())
1467 .when(selected, |this| {
1468 this.text_color(colors.text_accent)
1469 }),
1470 )
1471 })
1472 .on_click(cx.listener(move |editor, _, window, cx| {
1473 cx.stop_propagation();
1474 if let Some(task) = editor.confirm_code_action(
1475 &ConfirmCodeAction {
1476 item_ix: Some(item_ix),
1477 },
1478 window,
1479 cx,
1480 ) {
1481 task.detach_and_log_err(cx)
1482 }
1483 })),
1484 )
1485 })
1486 .collect()
1487 }),
1488 )
1489 .occlude()
1490 .max_h(max_height_in_lines as f32 * window.line_height())
1491 .track_scroll(self.scroll_handle.clone())
1492 .with_width_from_item(
1493 self.actions
1494 .iter()
1495 .enumerate()
1496 .max_by_key(|(_, action)| match action {
1497 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1498 CodeActionsItem::CodeAction { action, .. } => {
1499 action.lsp_action.title().chars().count()
1500 }
1501 CodeActionsItem::DebugScenario(scenario) => {
1502 format!("debug: {}", scenario.label).chars().count()
1503 }
1504 })
1505 .map(|(ix, _)| ix),
1506 )
1507 .with_sizing_behavior(ListSizingBehavior::Infer);
1508
1509 Popover::new().child(list).into_any_element()
1510 }
1511}