1use fuzzy::{StringMatch, StringMatchCandidate};
2use gpui::{
3 AnyElement, BackgroundExecutor, Entity, Focusable, FontWeight, ListSizingBehavior,
4 ScrollStrategy, SharedString, Size, StrikethroughStyle, StyledText, UniformListScrollHandle,
5 div, px, uniform_list,
6};
7use language::Buffer;
8use language::CodeLabel;
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::{
19 cell::RefCell,
20 cmp::{Reverse, min},
21 iter,
22 ops::Range,
23 rc::Rc,
24};
25use task::ResolvedTask;
26use ui::{Color, IntoElement, ListItem, Pixels, Popover, Styled, prelude::*};
27use util::ResultExt;
28
29use crate::editor_settings::SnippetSortOrder;
30use crate::hover_popover::{hover_markdown_style, open_markdown_url};
31use crate::{
32 CodeActionProvider, CompletionId, CompletionItemKind, CompletionProvider, DisplayRow, Editor,
33 EditorStyle, ResolvedTasks,
34 actions::{ConfirmCodeAction, ConfirmCompletion},
35 split_words, styled_runs_for_code_label,
36};
37
38pub const MENU_GAP: Pixels = px(4.);
39pub const MENU_ASIDE_X_PADDING: Pixels = px(16.);
40pub const MENU_ASIDE_MIN_WIDTH: Pixels = px(260.);
41pub const MENU_ASIDE_MAX_WIDTH: Pixels = px(500.);
42
43pub enum CodeContextMenu {
44 Completions(CompletionsMenu),
45 CodeActions(CodeActionsMenu),
46}
47
48impl CodeContextMenu {
49 pub fn select_first(
50 &mut self,
51 provider: Option<&dyn CompletionProvider>,
52 cx: &mut Context<Editor>,
53 ) -> bool {
54 if self.visible() {
55 match self {
56 CodeContextMenu::Completions(menu) => menu.select_first(provider, cx),
57 CodeContextMenu::CodeActions(menu) => menu.select_first(cx),
58 }
59 true
60 } else {
61 false
62 }
63 }
64
65 pub fn select_prev(
66 &mut self,
67 provider: Option<&dyn CompletionProvider>,
68 cx: &mut Context<Editor>,
69 ) -> bool {
70 if self.visible() {
71 match self {
72 CodeContextMenu::Completions(menu) => menu.select_prev(provider, cx),
73 CodeContextMenu::CodeActions(menu) => menu.select_prev(cx),
74 }
75 true
76 } else {
77 false
78 }
79 }
80
81 pub fn select_next(
82 &mut self,
83 provider: Option<&dyn CompletionProvider>,
84 cx: &mut Context<Editor>,
85 ) -> bool {
86 if self.visible() {
87 match self {
88 CodeContextMenu::Completions(menu) => menu.select_next(provider, cx),
89 CodeContextMenu::CodeActions(menu) => menu.select_next(cx),
90 }
91 true
92 } else {
93 false
94 }
95 }
96
97 pub fn select_last(
98 &mut self,
99 provider: Option<&dyn CompletionProvider>,
100 cx: &mut Context<Editor>,
101 ) -> bool {
102 if self.visible() {
103 match self {
104 CodeContextMenu::Completions(menu) => menu.select_last(provider, cx),
105 CodeContextMenu::CodeActions(menu) => menu.select_last(cx),
106 }
107 true
108 } else {
109 false
110 }
111 }
112
113 pub fn visible(&self) -> bool {
114 match self {
115 CodeContextMenu::Completions(menu) => menu.visible(),
116 CodeContextMenu::CodeActions(menu) => menu.visible(),
117 }
118 }
119
120 pub fn origin(&self) -> ContextMenuOrigin {
121 match self {
122 CodeContextMenu::Completions(menu) => menu.origin(),
123 CodeContextMenu::CodeActions(menu) => menu.origin(),
124 }
125 }
126
127 pub fn render(
128 &self,
129 style: &EditorStyle,
130 max_height_in_lines: u32,
131 window: &mut Window,
132 cx: &mut Context<Editor>,
133 ) -> AnyElement {
134 match self {
135 CodeContextMenu::Completions(menu) => {
136 menu.render(style, max_height_in_lines, window, cx)
137 }
138 CodeContextMenu::CodeActions(menu) => {
139 menu.render(style, max_height_in_lines, window, cx)
140 }
141 }
142 }
143
144 pub fn render_aside(
145 &mut self,
146 editor: &Editor,
147 max_size: Size<Pixels>,
148 window: &mut Window,
149 cx: &mut Context<Editor>,
150 ) -> Option<AnyElement> {
151 match self {
152 CodeContextMenu::Completions(menu) => menu.render_aside(editor, max_size, window, cx),
153 CodeContextMenu::CodeActions(_) => None,
154 }
155 }
156
157 pub fn focused(&self, window: &mut Window, cx: &mut Context<Editor>) -> bool {
158 match self {
159 CodeContextMenu::Completions(completions_menu) => completions_menu
160 .markdown_element
161 .as_ref()
162 .is_some_and(|markdown| markdown.focus_handle(cx).contains_focused(window, cx)),
163 CodeContextMenu::CodeActions(_) => false,
164 }
165 }
166}
167
168pub enum ContextMenuOrigin {
169 Cursor,
170 GutterIndicator(DisplayRow),
171}
172
173#[derive(Clone, Debug)]
174pub struct CompletionsMenu {
175 pub id: CompletionId,
176 sort_completions: bool,
177 pub initial_position: Anchor,
178 pub buffer: Entity<Buffer>,
179 pub completions: Rc<RefCell<Box<[Completion]>>>,
180 match_candidates: Rc<[StringMatchCandidate]>,
181 pub entries: Rc<RefCell<Vec<StringMatch>>>,
182 pub selected_item: usize,
183 scroll_handle: UniformListScrollHandle,
184 resolve_completions: bool,
185 show_completion_documentation: bool,
186 pub(super) ignore_completion_provider: bool,
187 last_rendered_range: Rc<RefCell<Option<Range<usize>>>>,
188 markdown_element: Option<Entity<Markdown>>,
189 snippet_sort_order: SnippetSortOrder,
190}
191
192impl CompletionsMenu {
193 pub fn new(
194 id: CompletionId,
195 sort_completions: bool,
196 show_completion_documentation: bool,
197 ignore_completion_provider: bool,
198 initial_position: Anchor,
199 buffer: Entity<Buffer>,
200 completions: Box<[Completion]>,
201 snippet_sort_order: SnippetSortOrder,
202 ) -> Self {
203 let match_candidates = completions
204 .iter()
205 .enumerate()
206 .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
207 .collect();
208
209 Self {
210 id,
211 sort_completions,
212 initial_position,
213 buffer,
214 show_completion_documentation,
215 ignore_completion_provider,
216 completions: RefCell::new(completions).into(),
217 match_candidates,
218 entries: RefCell::new(Vec::new()).into(),
219 selected_item: 0,
220 scroll_handle: UniformListScrollHandle::new(),
221 resolve_completions: true,
222 last_rendered_range: RefCell::new(None).into(),
223 markdown_element: None,
224 snippet_sort_order,
225 }
226 }
227
228 pub fn new_snippet_choices(
229 id: CompletionId,
230 sort_completions: bool,
231 choices: &Vec<String>,
232 selection: Range<Anchor>,
233 buffer: Entity<Buffer>,
234 snippet_sort_order: SnippetSortOrder,
235 ) -> Self {
236 let completions = choices
237 .iter()
238 .map(|choice| Completion {
239 replace_range: selection.start.text_anchor..selection.end.text_anchor,
240 new_text: choice.to_string(),
241 label: CodeLabel {
242 text: choice.to_string(),
243 runs: Default::default(),
244 filter_range: Default::default(),
245 },
246 icon_path: None,
247 documentation: None,
248 confirm: None,
249 insert_text_mode: None,
250 source: CompletionSource::Custom,
251 })
252 .collect();
253
254 let match_candidates = choices
255 .iter()
256 .enumerate()
257 .map(|(id, completion)| StringMatchCandidate::new(id, &completion))
258 .collect();
259 let entries = choices
260 .iter()
261 .enumerate()
262 .map(|(id, completion)| StringMatch {
263 candidate_id: id,
264 score: 1.,
265 positions: vec![],
266 string: completion.clone(),
267 })
268 .collect::<Vec<_>>();
269 Self {
270 id,
271 sort_completions,
272 initial_position: selection.start,
273 buffer,
274 completions: RefCell::new(completions).into(),
275 match_candidates,
276 entries: RefCell::new(entries).into(),
277 selected_item: 0,
278 scroll_handle: UniformListScrollHandle::new(),
279 resolve_completions: false,
280 show_completion_documentation: false,
281 ignore_completion_provider: false,
282 last_rendered_range: RefCell::new(None).into(),
283 markdown_element: None,
284 snippet_sort_order,
285 }
286 }
287
288 fn select_first(
289 &mut self,
290 provider: Option<&dyn CompletionProvider>,
291 cx: &mut Context<Editor>,
292 ) {
293 let index = if self.scroll_handle.y_flipped() {
294 self.entries.borrow().len() - 1
295 } else {
296 0
297 };
298 self.update_selection_index(index, provider, cx);
299 }
300
301 fn select_last(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
302 let index = if self.scroll_handle.y_flipped() {
303 0
304 } else {
305 self.entries.borrow().len() - 1
306 };
307 self.update_selection_index(index, provider, cx);
308 }
309
310 fn select_prev(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
311 let index = if self.scroll_handle.y_flipped() {
312 self.next_match_index()
313 } else {
314 self.prev_match_index()
315 };
316 self.update_selection_index(index, provider, cx);
317 }
318
319 fn select_next(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
320 let index = if self.scroll_handle.y_flipped() {
321 self.prev_match_index()
322 } else {
323 self.next_match_index()
324 };
325 self.update_selection_index(index, provider, cx);
326 }
327
328 fn update_selection_index(
329 &mut self,
330 match_index: usize,
331 provider: Option<&dyn CompletionProvider>,
332 cx: &mut Context<Editor>,
333 ) {
334 if self.selected_item != match_index {
335 self.selected_item = match_index;
336 self.scroll_handle
337 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
338 self.resolve_visible_completions(provider, cx);
339 cx.notify();
340 }
341 }
342
343 fn prev_match_index(&self) -> usize {
344 if self.selected_item > 0 {
345 self.selected_item - 1
346 } else {
347 self.entries.borrow().len() - 1
348 }
349 }
350
351 fn next_match_index(&self) -> usize {
352 if self.selected_item + 1 < self.entries.borrow().len() {
353 self.selected_item + 1
354 } else {
355 0
356 }
357 }
358
359 pub fn resolve_visible_completions(
360 &mut self,
361 provider: Option<&dyn CompletionProvider>,
362 cx: &mut Context<Editor>,
363 ) {
364 if !self.resolve_completions {
365 return;
366 }
367 let Some(provider) = provider else {
368 return;
369 };
370
371 // Attempt to resolve completions for every item that will be displayed. This matters
372 // because single line documentation may be displayed inline with the completion.
373 //
374 // When navigating to the very beginning or end of completions, `last_rendered_range` may
375 // have no overlap with the completions that will be displayed, so instead use a range based
376 // on the last rendered count.
377 const APPROXIMATE_VISIBLE_COUNT: usize = 12;
378 let last_rendered_range = self.last_rendered_range.borrow().clone();
379 let visible_count = last_rendered_range
380 .clone()
381 .map_or(APPROXIMATE_VISIBLE_COUNT, |range| range.count());
382 let entries = self.entries.borrow();
383 let entry_range = if self.selected_item == 0 {
384 0..min(visible_count, entries.len())
385 } else if self.selected_item == entries.len() - 1 {
386 entries.len().saturating_sub(visible_count)..entries.len()
387 } else {
388 last_rendered_range.map_or(0..0, |range| {
389 min(range.start, entries.len())..min(range.end, entries.len())
390 })
391 };
392
393 // Expand the range to resolve more completions than are predicted to be visible, to reduce
394 // jank on navigation.
395 const EXTRA_TO_RESOLVE: usize = 4;
396 let entry_indices = util::iterate_expanded_and_wrapped_usize_range(
397 entry_range.clone(),
398 EXTRA_TO_RESOLVE,
399 EXTRA_TO_RESOLVE,
400 entries.len(),
401 );
402
403 // Avoid work by sometimes filtering out completions that already have documentation.
404 // This filtering doesn't happen if the completions are currently being updated.
405 let completions = self.completions.borrow();
406 let candidate_ids = entry_indices
407 .map(|i| entries[i].candidate_id)
408 .filter(|i| completions[*i].documentation.is_none());
409
410 // Current selection is always resolved even if it already has documentation, to handle
411 // out-of-spec language servers that return more results later.
412 let selected_candidate_id = entries[self.selected_item].candidate_id;
413 let candidate_ids = iter::once(selected_candidate_id)
414 .chain(candidate_ids.filter(|id| *id != selected_candidate_id))
415 .collect::<Vec<usize>>();
416 drop(entries);
417
418 if candidate_ids.is_empty() {
419 return;
420 }
421
422 let resolve_task = provider.resolve_completions(
423 self.buffer.clone(),
424 candidate_ids,
425 self.completions.clone(),
426 cx,
427 );
428
429 cx.spawn(async move |editor, cx| {
430 if let Some(true) = resolve_task.await.log_err() {
431 editor.update(cx, |_, cx| cx.notify()).ok();
432 }
433 })
434 .detach();
435 }
436
437 pub fn visible(&self) -> bool {
438 !self.entries.borrow().is_empty()
439 }
440
441 fn origin(&self) -> ContextMenuOrigin {
442 ContextMenuOrigin::Cursor
443 }
444
445 fn render(
446 &self,
447 style: &EditorStyle,
448 max_height_in_lines: u32,
449 window: &mut Window,
450 cx: &mut Context<Editor>,
451 ) -> AnyElement {
452 let show_completion_documentation = self.show_completion_documentation;
453 let selected_item = self.selected_item;
454 let completions = self.completions.clone();
455 let entries = self.entries.clone();
456 let last_rendered_range = self.last_rendered_range.clone();
457 let style = style.clone();
458 let list = uniform_list(
459 cx.entity().clone(),
460 "completions",
461 self.entries.borrow().len(),
462 move |_editor, range, _window, cx| {
463 last_rendered_range.borrow_mut().replace(range.clone());
464 let start_ix = range.start;
465 let completions_guard = completions.borrow_mut();
466
467 entries.borrow()[range]
468 .iter()
469 .enumerate()
470 .map(|(ix, mat)| {
471 let item_ix = start_ix + ix;
472 let completion = &completions_guard[mat.candidate_id];
473 let documentation = if show_completion_documentation {
474 &completion.documentation
475 } else {
476 &None
477 };
478
479 let filter_start = completion.label.filter_range.start;
480 let highlights = gpui::combine_highlights(
481 mat.ranges().map(|range| {
482 (
483 filter_start + range.start..filter_start + range.end,
484 FontWeight::BOLD.into(),
485 )
486 }),
487 styled_runs_for_code_label(&completion.label, &style.syntax).map(
488 |(range, mut highlight)| {
489 // Ignore font weight for syntax highlighting, as we'll use it
490 // for fuzzy matches.
491 highlight.font_weight = None;
492 if completion
493 .source
494 .lsp_completion(false)
495 .and_then(|lsp_completion| lsp_completion.deprecated)
496 .unwrap_or(false)
497 {
498 highlight.strikethrough = Some(StrikethroughStyle {
499 thickness: 1.0.into(),
500 ..Default::default()
501 });
502 highlight.color = Some(cx.theme().colors().text_muted);
503 }
504
505 (range, highlight)
506 },
507 ),
508 );
509
510 let completion_label = StyledText::new(completion.label.text.clone())
511 .with_default_highlights(&style.text, highlights);
512
513 let documentation_label = match documentation {
514 Some(CompletionDocumentation::SingleLine(text))
515 | Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
516 single_line: text,
517 ..
518 }) => {
519 if text.trim().is_empty() {
520 None
521 } else {
522 Some(
523 Label::new(text.clone())
524 .ml_4()
525 .size(LabelSize::Small)
526 .color(Color::Muted),
527 )
528 }
529 }
530 _ => None,
531 };
532
533 let start_slot = completion
534 .color()
535 .map(|color| {
536 div()
537 .flex_shrink_0()
538 .size_3p5()
539 .rounded_xs()
540 .bg(color)
541 .into_any_element()
542 })
543 .or_else(|| {
544 completion.icon_path.as_ref().map(|path| {
545 Icon::from_path(path)
546 .size(IconSize::XSmall)
547 .color(Color::Muted)
548 .into_any_element()
549 })
550 });
551
552 div().min_w(px(280.)).max_w(px(540.)).child(
553 ListItem::new(mat.candidate_id)
554 .inset(true)
555 .toggle_state(item_ix == selected_item)
556 .on_click(cx.listener(move |editor, _event, window, cx| {
557 cx.stop_propagation();
558 if let Some(task) = editor.confirm_completion(
559 &ConfirmCompletion {
560 item_ix: Some(item_ix),
561 },
562 window,
563 cx,
564 ) {
565 task.detach_and_log_err(cx)
566 }
567 }))
568 .start_slot::<AnyElement>(start_slot)
569 .child(h_flex().overflow_hidden().child(completion_label))
570 .end_slot::<Label>(documentation_label),
571 )
572 })
573 .collect()
574 },
575 )
576 .occlude()
577 .max_h(max_height_in_lines as f32 * window.line_height())
578 .track_scroll(self.scroll_handle.clone())
579 .with_sizing_behavior(ListSizingBehavior::Infer)
580 .w(rems(34.));
581
582 Popover::new().child(list).into_any_element()
583 }
584
585 fn render_aside(
586 &mut self,
587 editor: &Editor,
588 max_size: Size<Pixels>,
589 window: &mut Window,
590 cx: &mut Context<Editor>,
591 ) -> Option<AnyElement> {
592 if !self.show_completion_documentation {
593 return None;
594 }
595
596 let mat = &self.entries.borrow()[self.selected_item];
597 let multiline_docs = match self.completions.borrow_mut()[mat.candidate_id]
598 .documentation
599 .as_ref()?
600 {
601 CompletionDocumentation::MultiLinePlainText(text) => div().child(text.clone()),
602 CompletionDocumentation::SingleLineAndMultiLinePlainText {
603 plain_text: Some(text),
604 ..
605 } => div().child(text.clone()),
606 CompletionDocumentation::MultiLineMarkdown(parsed) if !parsed.is_empty() => {
607 let markdown = self.markdown_element.get_or_insert_with(|| {
608 cx.new(|cx| {
609 let languages = editor
610 .workspace
611 .as_ref()
612 .and_then(|(workspace, _)| workspace.upgrade())
613 .map(|workspace| workspace.read(cx).app_state().languages.clone());
614 let language = editor
615 .language_at(self.initial_position, cx)
616 .map(|l| l.name().to_proto());
617 Markdown::new(SharedString::default(), languages, language, cx)
618 })
619 });
620 markdown.update(cx, |markdown, cx| {
621 markdown.reset(parsed.clone(), cx);
622 });
623 div().child(
624 MarkdownElement::new(markdown.clone(), hover_markdown_style(window, cx))
625 .code_block_renderer(markdown::CodeBlockRenderer::Default {
626 copy_button: false,
627 copy_button_on_hover: false,
628 border: false,
629 })
630 .on_url_click(open_markdown_url),
631 )
632 }
633 CompletionDocumentation::MultiLineMarkdown(_) => return None,
634 CompletionDocumentation::SingleLine(_) => return None,
635 CompletionDocumentation::Undocumented => return None,
636 CompletionDocumentation::SingleLineAndMultiLinePlainText {
637 plain_text: None, ..
638 } => {
639 return None;
640 }
641 };
642
643 Some(
644 Popover::new()
645 .child(
646 multiline_docs
647 .id("multiline_docs")
648 .px(MENU_ASIDE_X_PADDING / 2.)
649 .max_w(max_size.width)
650 .max_h(max_size.height)
651 .overflow_y_scroll()
652 .occlude(),
653 )
654 .into_any_element(),
655 )
656 }
657
658 pub fn sort_matches(
659 matches: &mut Vec<SortableMatch<'_>>,
660 query: Option<&str>,
661 snippet_sort_order: SnippetSortOrder,
662 ) {
663 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
664 enum MatchTier<'a> {
665 WordStartMatch {
666 sort_mixed_case_prefix_length: Reverse<usize>,
667 sort_snippet: Reverse<i32>,
668 sort_kind: usize,
669 sort_fuzzy_bracket: Reverse<usize>,
670 sort_text: Option<&'a str>,
671 sort_score: Reverse<OrderedFloat<f64>>,
672 sort_label: &'a str,
673 },
674 OtherMatch {
675 sort_score: Reverse<OrderedFloat<f64>>,
676 },
677 }
678
679 // Our goal here is to intelligently sort completion suggestions. We want to
680 // balance the raw fuzzy match score with hints from the language server
681
682 // In a fuzzy bracket, matches with a score of 1.0 are prioritized.
683 // The remaining matches are partitioned into two groups at 3/5 of the max_score.
684 let max_score = matches
685 .iter()
686 .map(|mat| mat.string_match.score)
687 .fold(0.0, f64::max);
688 let fuzzy_bracket_threshold = max_score * (3.0 / 5.0);
689
690 let query_start_lower = query
691 .and_then(|q| q.chars().next())
692 .and_then(|c| c.to_lowercase().next());
693
694 matches.sort_unstable_by_key(|mat| {
695 let score = mat.string_match.score;
696 let sort_score = Reverse(OrderedFloat(score));
697
698 let query_start_doesnt_match_split_words = query_start_lower
699 .map(|query_char| {
700 !split_words(&mat.string_match.string).any(|word| {
701 word.chars()
702 .next()
703 .and_then(|c| c.to_lowercase().next())
704 .map_or(false, |word_char| word_char == query_char)
705 })
706 })
707 .unwrap_or(false);
708
709 if query_start_doesnt_match_split_words {
710 MatchTier::OtherMatch { sort_score }
711 } else {
712 let sort_fuzzy_bracket = Reverse(if score >= fuzzy_bracket_threshold {
713 1
714 } else {
715 0
716 });
717 let sort_snippet = match snippet_sort_order {
718 SnippetSortOrder::Top => Reverse(if mat.is_snippet { 1 } else { 0 }),
719 SnippetSortOrder::Bottom => Reverse(if mat.is_snippet { 0 } else { 1 }),
720 SnippetSortOrder::Inline => Reverse(0),
721 };
722 let sort_mixed_case_prefix_length = Reverse(
723 query
724 .map(|q| {
725 q.chars()
726 .zip(mat.string_match.string.chars())
727 .enumerate()
728 .take_while(|(i, (q_char, match_char))| {
729 if *i == 0 {
730 // Case-sensitive comparison for first character
731 q_char == match_char
732 } else {
733 // Case-insensitive comparison for other characters
734 q_char.to_lowercase().eq(match_char.to_lowercase())
735 }
736 })
737 .count()
738 })
739 .unwrap_or(0),
740 );
741 MatchTier::WordStartMatch {
742 sort_mixed_case_prefix_length,
743 sort_snippet,
744 sort_kind: mat.sort_kind,
745 sort_fuzzy_bracket,
746 sort_text: mat.sort_text,
747 sort_score,
748 sort_label: mat.sort_label,
749 }
750 }
751 });
752 }
753
754 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
755 let mut matches = if let Some(query) = query {
756 fuzzy::match_strings(
757 &self.match_candidates,
758 query,
759 query.chars().any(|c| c.is_uppercase()),
760 100,
761 &Default::default(),
762 executor,
763 )
764 .await
765 } else {
766 self.match_candidates
767 .iter()
768 .enumerate()
769 .map(|(candidate_id, candidate)| StringMatch {
770 candidate_id,
771 score: Default::default(),
772 positions: Default::default(),
773 string: candidate.string.clone(),
774 })
775 .collect()
776 };
777
778 if self.sort_completions {
779 let completions = self.completions.borrow();
780
781 let mut sortable_items: Vec<SortableMatch<'_>> = matches
782 .into_iter()
783 .map(|string_match| {
784 let completion = &completions[string_match.candidate_id];
785
786 let is_snippet = matches!(
787 &completion.source,
788 CompletionSource::Lsp { lsp_completion, .. }
789 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
790 );
791
792 let sort_text =
793 if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
794 lsp_completion.sort_text.as_deref()
795 } else {
796 None
797 };
798
799 let (sort_kind, sort_label) = completion.sort_key();
800
801 SortableMatch {
802 string_match,
803 is_snippet,
804 sort_text,
805 sort_kind,
806 sort_label,
807 }
808 })
809 .collect();
810
811 Self::sort_matches(&mut sortable_items, query, self.snippet_sort_order);
812
813 matches = sortable_items
814 .into_iter()
815 .map(|sortable| sortable.string_match)
816 .collect();
817 }
818
819 *self.entries.borrow_mut() = matches;
820 self.selected_item = 0;
821 // This keeps the display consistent when y_flipped.
822 self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
823 }
824}
825
826#[derive(Debug)]
827pub struct SortableMatch<'a> {
828 pub string_match: StringMatch,
829 pub is_snippet: bool,
830 pub sort_text: Option<&'a str>,
831 pub sort_kind: usize,
832 pub sort_label: &'a str,
833}
834
835#[derive(Clone)]
836pub struct AvailableCodeAction {
837 pub excerpt_id: ExcerptId,
838 pub action: CodeAction,
839 pub provider: Rc<dyn CodeActionProvider>,
840}
841
842#[derive(Clone)]
843pub(crate) struct CodeActionContents {
844 tasks: Option<Rc<ResolvedTasks>>,
845 actions: Option<Rc<[AvailableCodeAction]>>,
846 debug_scenarios: Vec<DebugScenario>,
847 pub(crate) context: TaskContext,
848}
849
850impl CodeActionContents {
851 pub(crate) fn new(
852 tasks: Option<ResolvedTasks>,
853 actions: Option<Rc<[AvailableCodeAction]>>,
854 debug_scenarios: Vec<DebugScenario>,
855 context: TaskContext,
856 ) -> Self {
857 Self {
858 tasks: tasks.map(Rc::new),
859 actions,
860 debug_scenarios,
861 context,
862 }
863 }
864
865 pub fn tasks(&self) -> Option<&ResolvedTasks> {
866 self.tasks.as_deref()
867 }
868
869 fn len(&self) -> usize {
870 let tasks_len = self.tasks.as_ref().map_or(0, |tasks| tasks.templates.len());
871 let code_actions_len = self.actions.as_ref().map_or(0, |actions| actions.len());
872 tasks_len + code_actions_len + self.debug_scenarios.len()
873 }
874
875 fn is_empty(&self) -> bool {
876 self.len() == 0
877 }
878
879 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
880 self.tasks
881 .iter()
882 .flat_map(|tasks| {
883 tasks
884 .templates
885 .iter()
886 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
887 })
888 .chain(self.actions.iter().flat_map(|actions| {
889 actions.iter().map(|available| CodeActionsItem::CodeAction {
890 excerpt_id: available.excerpt_id,
891 action: available.action.clone(),
892 provider: available.provider.clone(),
893 })
894 }))
895 .chain(
896 self.debug_scenarios
897 .iter()
898 .cloned()
899 .map(CodeActionsItem::DebugScenario),
900 )
901 }
902
903 pub fn get(&self, mut index: usize) -> Option<CodeActionsItem> {
904 if let Some(tasks) = &self.tasks {
905 if let Some((kind, task)) = tasks.templates.get(index) {
906 return Some(CodeActionsItem::Task(kind.clone(), task.clone()));
907 } else {
908 index -= tasks.templates.len();
909 }
910 }
911 if let Some(actions) = &self.actions {
912 if let Some(available) = actions.get(index) {
913 return Some(CodeActionsItem::CodeAction {
914 excerpt_id: available.excerpt_id,
915 action: available.action.clone(),
916 provider: available.provider.clone(),
917 });
918 } else {
919 index -= actions.len();
920 }
921 }
922
923 self.debug_scenarios
924 .get(index)
925 .cloned()
926 .map(CodeActionsItem::DebugScenario)
927 }
928}
929
930#[derive(Clone)]
931pub enum CodeActionsItem {
932 Task(TaskSourceKind, ResolvedTask),
933 CodeAction {
934 excerpt_id: ExcerptId,
935 action: CodeAction,
936 provider: Rc<dyn CodeActionProvider>,
937 },
938 DebugScenario(DebugScenario),
939}
940
941impl CodeActionsItem {
942 fn as_task(&self) -> Option<&ResolvedTask> {
943 let Self::Task(_, task) = self else {
944 return None;
945 };
946 Some(task)
947 }
948
949 fn as_code_action(&self) -> Option<&CodeAction> {
950 let Self::CodeAction { action, .. } = self else {
951 return None;
952 };
953 Some(action)
954 }
955 fn as_debug_scenario(&self) -> Option<&DebugScenario> {
956 let Self::DebugScenario(scenario) = self else {
957 return None;
958 };
959 Some(scenario)
960 }
961
962 pub fn label(&self) -> String {
963 match self {
964 Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
965 Self::Task(_, task) => task.resolved_label.clone(),
966 Self::DebugScenario(scenario) => scenario.label.to_string(),
967 }
968 }
969}
970
971pub(crate) struct CodeActionsMenu {
972 pub actions: CodeActionContents,
973 pub buffer: Entity<Buffer>,
974 pub selected_item: usize,
975 pub scroll_handle: UniformListScrollHandle,
976 pub deployed_from_indicator: Option<DisplayRow>,
977}
978
979impl CodeActionsMenu {
980 fn select_first(&mut self, cx: &mut Context<Editor>) {
981 self.selected_item = if self.scroll_handle.y_flipped() {
982 self.actions.len() - 1
983 } else {
984 0
985 };
986 self.scroll_handle
987 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
988 cx.notify()
989 }
990
991 fn select_last(&mut self, cx: &mut Context<Editor>) {
992 self.selected_item = if self.scroll_handle.y_flipped() {
993 0
994 } else {
995 self.actions.len() - 1
996 };
997 self.scroll_handle
998 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
999 cx.notify()
1000 }
1001
1002 fn select_prev(&mut self, cx: &mut Context<Editor>) {
1003 self.selected_item = if self.scroll_handle.y_flipped() {
1004 self.next_match_index()
1005 } else {
1006 self.prev_match_index()
1007 };
1008 self.scroll_handle
1009 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1010 cx.notify();
1011 }
1012
1013 fn select_next(&mut self, cx: &mut Context<Editor>) {
1014 self.selected_item = if self.scroll_handle.y_flipped() {
1015 self.prev_match_index()
1016 } else {
1017 self.next_match_index()
1018 };
1019 self.scroll_handle
1020 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1021 cx.notify();
1022 }
1023
1024 fn prev_match_index(&self) -> usize {
1025 if self.selected_item > 0 {
1026 self.selected_item - 1
1027 } else {
1028 self.actions.len() - 1
1029 }
1030 }
1031
1032 fn next_match_index(&self) -> usize {
1033 if self.selected_item + 1 < self.actions.len() {
1034 self.selected_item + 1
1035 } else {
1036 0
1037 }
1038 }
1039
1040 fn visible(&self) -> bool {
1041 !self.actions.is_empty()
1042 }
1043
1044 fn origin(&self) -> ContextMenuOrigin {
1045 if let Some(row) = self.deployed_from_indicator {
1046 ContextMenuOrigin::GutterIndicator(row)
1047 } else {
1048 ContextMenuOrigin::Cursor
1049 }
1050 }
1051
1052 fn render(
1053 &self,
1054 _style: &EditorStyle,
1055 max_height_in_lines: u32,
1056 window: &mut Window,
1057 cx: &mut Context<Editor>,
1058 ) -> AnyElement {
1059 let actions = self.actions.clone();
1060 let selected_item = self.selected_item;
1061 let list = uniform_list(
1062 cx.entity().clone(),
1063 "code_actions_menu",
1064 self.actions.len(),
1065 move |_this, range, _, cx| {
1066 actions
1067 .iter()
1068 .skip(range.start)
1069 .take(range.end - range.start)
1070 .enumerate()
1071 .map(|(ix, action)| {
1072 let item_ix = range.start + ix;
1073 let selected = item_ix == selected_item;
1074 let colors = cx.theme().colors();
1075 div().min_w(px(220.)).max_w(px(540.)).child(
1076 ListItem::new(item_ix)
1077 .inset(true)
1078 .toggle_state(selected)
1079 .when_some(action.as_code_action(), |this, action| {
1080 this.child(
1081 h_flex()
1082 .overflow_hidden()
1083 .child(
1084 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1085 action.lsp_action.title().replace("\n", ""),
1086 )
1087 .when(selected, |this| {
1088 this.text_color(colors.text_accent)
1089 }),
1090 )
1091 })
1092 .when_some(action.as_task(), |this, task| {
1093 this.child(
1094 h_flex()
1095 .overflow_hidden()
1096 .child(task.resolved_label.replace("\n", ""))
1097 .when(selected, |this| {
1098 this.text_color(colors.text_accent)
1099 }),
1100 )
1101 })
1102 .when_some(action.as_debug_scenario(), |this, scenario| {
1103 this.child(
1104 h_flex()
1105 .overflow_hidden()
1106 .child("debug: ")
1107 .child(scenario.label.clone())
1108 .when(selected, |this| {
1109 this.text_color(colors.text_accent)
1110 }),
1111 )
1112 })
1113 .on_click(cx.listener(move |editor, _, window, cx| {
1114 cx.stop_propagation();
1115 if let Some(task) = editor.confirm_code_action(
1116 &ConfirmCodeAction {
1117 item_ix: Some(item_ix),
1118 },
1119 window,
1120 cx,
1121 ) {
1122 task.detach_and_log_err(cx)
1123 }
1124 })),
1125 )
1126 })
1127 .collect()
1128 },
1129 )
1130 .occlude()
1131 .max_h(max_height_in_lines as f32 * window.line_height())
1132 .track_scroll(self.scroll_handle.clone())
1133 .with_width_from_item(
1134 self.actions
1135 .iter()
1136 .enumerate()
1137 .max_by_key(|(_, action)| match action {
1138 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1139 CodeActionsItem::CodeAction { action, .. } => {
1140 action.lsp_action.title().chars().count()
1141 }
1142 CodeActionsItem::DebugScenario(scenario) => {
1143 format!("debug: {}", scenario.label).chars().count()
1144 }
1145 })
1146 .map(|(ix, _)| ix),
1147 )
1148 .with_sizing_behavior(ListSizingBehavior::Infer);
1149
1150 Popover::new().child(list).into_any_element()
1151 }
1152}