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_prefix: Reverse<usize>,
675 sort_snippet: Reverse<i32>,
676 sort_text: Option<&'a str>,
677 sort_score: Reverse<OrderedFloat<f64>>,
678 sort_key: (usize, &'a str),
679 },
680 OtherMatch {
681 sort_score: Reverse<OrderedFloat<f64>>,
682 },
683 }
684
685 // Our goal here is to intelligently sort completion suggestions. We want to
686 // balance the raw fuzzy match score with hints from the language server
687
688 let query_start_lower = query
689 .and_then(|q| q.chars().next())
690 .and_then(|c| c.to_lowercase().next());
691
692 matches.sort_unstable_by_key(|mat| {
693 let score = mat.string_match.score;
694 let sort_score = Reverse(OrderedFloat(score));
695
696 let query_start_doesnt_match_split_words = query_start_lower
697 .map(|query_char| {
698 !split_words(&mat.string_match.string).any(|word| {
699 word.chars()
700 .next()
701 .and_then(|c| c.to_lowercase().next())
702 .map_or(false, |word_char| word_char == query_char)
703 })
704 })
705 .unwrap_or(false);
706
707 if query_start_doesnt_match_split_words {
708 MatchTier::OtherMatch { sort_score }
709 } else {
710 let sort_snippet = match snippet_sort_order {
711 SnippetSortOrder::Top => Reverse(if mat.is_snippet { 1 } else { 0 }),
712 SnippetSortOrder::Bottom => Reverse(if mat.is_snippet { 0 } else { 1 }),
713 SnippetSortOrder::Inline => Reverse(0),
714 };
715 let mixed_case_prefix_length = Reverse(
716 query
717 .map(|q| {
718 q.chars()
719 .zip(mat.string_match.string.chars())
720 .enumerate()
721 .take_while(|(i, (q_char, match_char))| {
722 if *i == 0 {
723 // Case-sensitive comparison for first character
724 q_char == match_char
725 } else {
726 // Case-insensitive comparison for other characters
727 q_char.to_lowercase().eq(match_char.to_lowercase())
728 }
729 })
730 .count()
731 })
732 .unwrap_or(0),
733 );
734 MatchTier::WordStartMatch {
735 sort_prefix: mixed_case_prefix_length,
736 sort_snippet,
737 sort_text: mat.sort_text,
738 sort_score,
739 sort_key: mat.sort_key,
740 }
741 }
742 });
743 }
744
745 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
746 let mut matches = if let Some(query) = query {
747 fuzzy::match_strings(
748 &self.match_candidates,
749 query,
750 query.chars().any(|c| c.is_uppercase()),
751 100,
752 &Default::default(),
753 executor,
754 )
755 .await
756 } else {
757 self.match_candidates
758 .iter()
759 .enumerate()
760 .map(|(candidate_id, candidate)| StringMatch {
761 candidate_id,
762 score: Default::default(),
763 positions: Default::default(),
764 string: candidate.string.clone(),
765 })
766 .collect()
767 };
768
769 if self.sort_completions {
770 let completions = self.completions.borrow();
771
772 let mut sortable_items: Vec<SortableMatch<'_>> = matches
773 .into_iter()
774 .map(|string_match| {
775 let completion = &completions[string_match.candidate_id];
776
777 let is_snippet = matches!(
778 &completion.source,
779 CompletionSource::Lsp { lsp_completion, .. }
780 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
781 );
782
783 let sort_text =
784 if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
785 lsp_completion.sort_text.as_deref()
786 } else {
787 None
788 };
789
790 let sort_key = completion.sort_key();
791
792 SortableMatch {
793 string_match,
794 is_snippet,
795 sort_text,
796 sort_key,
797 }
798 })
799 .collect();
800
801 Self::sort_matches(&mut sortable_items, query, self.snippet_sort_order);
802
803 matches = sortable_items
804 .into_iter()
805 .map(|sortable| sortable.string_match)
806 .collect();
807 }
808
809 *self.entries.borrow_mut() = matches;
810 self.selected_item = 0;
811 // This keeps the display consistent when y_flipped.
812 self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
813 }
814}
815
816#[derive(Debug)]
817pub struct SortableMatch<'a> {
818 pub string_match: StringMatch,
819 pub is_snippet: bool,
820 pub sort_text: Option<&'a str>,
821 pub sort_key: (usize, &'a str),
822}
823
824#[derive(Clone)]
825pub struct AvailableCodeAction {
826 pub excerpt_id: ExcerptId,
827 pub action: CodeAction,
828 pub provider: Rc<dyn CodeActionProvider>,
829}
830
831#[derive(Clone)]
832pub struct CodeActionContents {
833 tasks: Option<Rc<ResolvedTasks>>,
834 actions: Option<Rc<[AvailableCodeAction]>>,
835}
836
837impl CodeActionContents {
838 pub fn new(
839 mut tasks: Option<ResolvedTasks>,
840 actions: Option<Rc<[AvailableCodeAction]>>,
841 cx: &App,
842 ) -> Self {
843 if !cx.has_flag::<DebuggerFeatureFlag>() {
844 if let Some(tasks) = &mut tasks {
845 tasks
846 .templates
847 .retain(|(_, task)| !matches!(task.task_type(), task::TaskType::Debug(_)));
848 }
849 }
850
851 Self {
852 tasks: tasks.map(Rc::new),
853 actions,
854 }
855 }
856
857 pub fn tasks(&self) -> Option<&ResolvedTasks> {
858 self.tasks.as_deref()
859 }
860
861 fn len(&self) -> usize {
862 match (&self.tasks, &self.actions) {
863 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
864 (Some(tasks), None) => tasks.templates.len(),
865 (None, Some(actions)) => actions.len(),
866 (None, None) => 0,
867 }
868 }
869
870 fn is_empty(&self) -> bool {
871 match (&self.tasks, &self.actions) {
872 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
873 (Some(tasks), None) => tasks.templates.is_empty(),
874 (None, Some(actions)) => actions.is_empty(),
875 (None, None) => true,
876 }
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 }
896
897 pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
898 match (&self.tasks, &self.actions) {
899 (Some(tasks), Some(actions)) => {
900 if index < tasks.templates.len() {
901 tasks
902 .templates
903 .get(index)
904 .cloned()
905 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
906 } else {
907 actions.get(index - tasks.templates.len()).map(|available| {
908 CodeActionsItem::CodeAction {
909 excerpt_id: available.excerpt_id,
910 action: available.action.clone(),
911 provider: available.provider.clone(),
912 }
913 })
914 }
915 }
916 (Some(tasks), None) => tasks
917 .templates
918 .get(index)
919 .cloned()
920 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
921 (None, Some(actions)) => {
922 actions
923 .get(index)
924 .map(|available| CodeActionsItem::CodeAction {
925 excerpt_id: available.excerpt_id,
926 action: available.action.clone(),
927 provider: available.provider.clone(),
928 })
929 }
930 (None, None) => None,
931 }
932 }
933}
934
935#[allow(clippy::large_enum_variant)]
936#[derive(Clone)]
937pub enum CodeActionsItem {
938 Task(TaskSourceKind, ResolvedTask),
939 CodeAction {
940 excerpt_id: ExcerptId,
941 action: CodeAction,
942 provider: Rc<dyn CodeActionProvider>,
943 },
944}
945
946impl CodeActionsItem {
947 fn as_task(&self) -> Option<&ResolvedTask> {
948 let Self::Task(_, task) = self else {
949 return None;
950 };
951 Some(task)
952 }
953
954 fn as_code_action(&self) -> Option<&CodeAction> {
955 let Self::CodeAction { action, .. } = self else {
956 return None;
957 };
958 Some(action)
959 }
960
961 pub fn label(&self) -> String {
962 match self {
963 Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
964 Self::Task(_, task) => task.resolved_label.clone(),
965 }
966 }
967}
968
969pub struct CodeActionsMenu {
970 pub actions: CodeActionContents,
971 pub buffer: Entity<Buffer>,
972 pub selected_item: usize,
973 pub scroll_handle: UniformListScrollHandle,
974 pub deployed_from_indicator: Option<DisplayRow>,
975}
976
977impl CodeActionsMenu {
978 fn select_first(&mut self, cx: &mut Context<Editor>) {
979 self.selected_item = if self.scroll_handle.y_flipped() {
980 self.actions.len() - 1
981 } else {
982 0
983 };
984 self.scroll_handle
985 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
986 cx.notify()
987 }
988
989 fn select_last(&mut self, cx: &mut Context<Editor>) {
990 self.selected_item = if self.scroll_handle.y_flipped() {
991 0
992 } else {
993 self.actions.len() - 1
994 };
995 self.scroll_handle
996 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
997 cx.notify()
998 }
999
1000 fn select_prev(&mut self, cx: &mut Context<Editor>) {
1001 self.selected_item = if self.scroll_handle.y_flipped() {
1002 self.next_match_index()
1003 } else {
1004 self.prev_match_index()
1005 };
1006 self.scroll_handle
1007 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1008 cx.notify();
1009 }
1010
1011 fn select_next(&mut self, cx: &mut Context<Editor>) {
1012 self.selected_item = if self.scroll_handle.y_flipped() {
1013 self.prev_match_index()
1014 } else {
1015 self.next_match_index()
1016 };
1017 self.scroll_handle
1018 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1019 cx.notify();
1020 }
1021
1022 fn prev_match_index(&self) -> usize {
1023 if self.selected_item > 0 {
1024 self.selected_item - 1
1025 } else {
1026 self.actions.len() - 1
1027 }
1028 }
1029
1030 fn next_match_index(&self) -> usize {
1031 if self.selected_item + 1 < self.actions.len() {
1032 self.selected_item + 1
1033 } else {
1034 0
1035 }
1036 }
1037
1038 fn visible(&self) -> bool {
1039 !self.actions.is_empty()
1040 }
1041
1042 fn origin(&self) -> ContextMenuOrigin {
1043 if let Some(row) = self.deployed_from_indicator {
1044 ContextMenuOrigin::GutterIndicator(row)
1045 } else {
1046 ContextMenuOrigin::Cursor
1047 }
1048 }
1049
1050 fn render(
1051 &self,
1052 _style: &EditorStyle,
1053 max_height_in_lines: u32,
1054 window: &mut Window,
1055 cx: &mut Context<Editor>,
1056 ) -> AnyElement {
1057 let actions = self.actions.clone();
1058 let selected_item = self.selected_item;
1059 let list = uniform_list(
1060 cx.entity().clone(),
1061 "code_actions_menu",
1062 self.actions.len(),
1063 move |_this, range, _, cx| {
1064 actions
1065 .iter()
1066 .skip(range.start)
1067 .take(range.end - range.start)
1068 .enumerate()
1069 .map(|(ix, action)| {
1070 let item_ix = range.start + ix;
1071 let selected = item_ix == selected_item;
1072 let colors = cx.theme().colors();
1073 div().min_w(px(220.)).max_w(px(540.)).child(
1074 ListItem::new(item_ix)
1075 .inset(true)
1076 .toggle_state(selected)
1077 .when_some(action.as_code_action(), |this, action| {
1078 this.on_click(cx.listener(move |editor, _, window, cx| {
1079 cx.stop_propagation();
1080 if let Some(task) = editor.confirm_code_action(
1081 &ConfirmCodeAction {
1082 item_ix: Some(item_ix),
1083 },
1084 window,
1085 cx,
1086 ) {
1087 task.detach_and_log_err(cx)
1088 }
1089 }))
1090 .child(
1091 h_flex()
1092 .overflow_hidden()
1093 .child(
1094 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1095 action.lsp_action.title().replace("\n", ""),
1096 )
1097 .when(selected, |this| {
1098 this.text_color(colors.text_accent)
1099 }),
1100 )
1101 })
1102 .when_some(action.as_task(), |this, task| {
1103 this.on_click(cx.listener(move |editor, _, window, cx| {
1104 cx.stop_propagation();
1105 if let Some(task) = editor.confirm_code_action(
1106 &ConfirmCodeAction {
1107 item_ix: Some(item_ix),
1108 },
1109 window,
1110 cx,
1111 ) {
1112 task.detach_and_log_err(cx)
1113 }
1114 }))
1115 .child(
1116 h_flex()
1117 .overflow_hidden()
1118 .child(task.resolved_label.replace("\n", ""))
1119 .when(selected, |this| {
1120 this.text_color(colors.text_accent)
1121 }),
1122 )
1123 }),
1124 )
1125 })
1126 .collect()
1127 },
1128 )
1129 .occlude()
1130 .max_h(max_height_in_lines as f32 * window.line_height())
1131 .track_scroll(self.scroll_handle.clone())
1132 .with_width_from_item(
1133 self.actions
1134 .iter()
1135 .enumerate()
1136 .max_by_key(|(_, action)| match action {
1137 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1138 CodeActionsItem::CodeAction { action, .. } => {
1139 action.lsp_action.title().chars().count()
1140 }
1141 })
1142 .map(|(ix, _)| ix),
1143 )
1144 .with_sizing_behavior(ListSizingBehavior::Infer);
1145
1146 Popover::new().child(list).into_any_element()
1147 }
1148}