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