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