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