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