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