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 inline_completion_was_selected = self.selected_item == 0
720 && self.entries.borrow().first().map_or(false, |entry| {
721 matches!(entry, CompletionEntry::InlineCompletionHint(_))
722 });
723
724 let mut matches = if let Some(query) = query {
725 fuzzy::match_strings(
726 &self.match_candidates,
727 query,
728 query.chars().any(|c| c.is_uppercase()),
729 100,
730 &Default::default(),
731 executor,
732 )
733 .await
734 } else {
735 self.match_candidates
736 .iter()
737 .enumerate()
738 .map(|(candidate_id, candidate)| StringMatch {
739 candidate_id,
740 score: Default::default(),
741 positions: Default::default(),
742 string: candidate.string.clone(),
743 })
744 .collect()
745 };
746
747 // Remove all candidates where the query's start does not match the start of any word in the candidate
748 if let Some(query) = query {
749 if let Some(query_start) = query.chars().next() {
750 matches.retain(|string_match| {
751 split_words(&string_match.string).any(|word| {
752 // Check that the first codepoint of the word as lowercase matches the first
753 // codepoint of the query as lowercase
754 word.chars()
755 .flat_map(|codepoint| codepoint.to_lowercase())
756 .zip(query_start.to_lowercase())
757 .all(|(word_cp, query_cp)| word_cp == query_cp)
758 })
759 });
760 }
761 }
762
763 let completions = self.completions.borrow_mut();
764 if self.sort_completions {
765 matches.sort_unstable_by_key(|mat| {
766 // We do want to strike a balance here between what the language server tells us
767 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
768 // `Creat` and there is a local variable called `CreateComponent`).
769 // So what we do is: we bucket all matches into two buckets
770 // - Strong matches
771 // - Weak matches
772 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
773 // and the Weak matches are the rest.
774 //
775 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
776 // matches, we prefer language-server sort_text first.
777 //
778 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
779 // Rest of the matches(weak) can be sorted as language-server expects.
780
781 #[derive(PartialEq, Eq, PartialOrd, Ord)]
782 enum MatchScore<'a> {
783 Strong {
784 score: Reverse<OrderedFloat<f64>>,
785 sort_text: Option<&'a str>,
786 sort_key: (usize, &'a str),
787 },
788 Weak {
789 sort_text: Option<&'a str>,
790 score: Reverse<OrderedFloat<f64>>,
791 sort_key: (usize, &'a str),
792 },
793 }
794
795 let completion = &completions[mat.candidate_id];
796 let sort_key = completion.sort_key();
797 let sort_text = completion.lsp_completion.sort_text.as_deref();
798 let score = Reverse(OrderedFloat(mat.score));
799
800 if mat.score >= 0.2 {
801 MatchScore::Strong {
802 score,
803 sort_text,
804 sort_key,
805 }
806 } else {
807 MatchScore::Weak {
808 sort_text,
809 score,
810 sort_key,
811 }
812 }
813 });
814 }
815 drop(completions);
816
817 let mut entries = self.entries.borrow_mut();
818 if let Some(CompletionEntry::InlineCompletionHint(_)) = entries.first() {
819 entries.truncate(1);
820 if inline_completion_was_selected || matches.is_empty() {
821 self.selected_item = 0;
822 } else {
823 self.selected_item = 1;
824 }
825 } else {
826 entries.truncate(0);
827 self.selected_item = 0;
828 }
829 entries.extend(matches.into_iter().map(CompletionEntry::Match));
830 }
831}
832
833#[derive(Clone)]
834pub struct AvailableCodeAction {
835 pub excerpt_id: ExcerptId,
836 pub action: CodeAction,
837 pub provider: Rc<dyn CodeActionProvider>,
838}
839
840#[derive(Clone)]
841pub struct CodeActionContents {
842 pub tasks: Option<Rc<ResolvedTasks>>,
843 pub actions: Option<Rc<[AvailableCodeAction]>>,
844}
845
846impl CodeActionContents {
847 fn len(&self) -> usize {
848 match (&self.tasks, &self.actions) {
849 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
850 (Some(tasks), None) => tasks.templates.len(),
851 (None, Some(actions)) => actions.len(),
852 (None, None) => 0,
853 }
854 }
855
856 fn is_empty(&self) -> bool {
857 match (&self.tasks, &self.actions) {
858 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
859 (Some(tasks), None) => tasks.templates.is_empty(),
860 (None, Some(actions)) => actions.is_empty(),
861 (None, None) => true,
862 }
863 }
864
865 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
866 self.tasks
867 .iter()
868 .flat_map(|tasks| {
869 tasks
870 .templates
871 .iter()
872 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
873 })
874 .chain(self.actions.iter().flat_map(|actions| {
875 actions.iter().map(|available| CodeActionsItem::CodeAction {
876 excerpt_id: available.excerpt_id,
877 action: available.action.clone(),
878 provider: available.provider.clone(),
879 })
880 }))
881 }
882
883 pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
884 match (&self.tasks, &self.actions) {
885 (Some(tasks), Some(actions)) => {
886 if index < tasks.templates.len() {
887 tasks
888 .templates
889 .get(index)
890 .cloned()
891 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
892 } else {
893 actions.get(index - tasks.templates.len()).map(|available| {
894 CodeActionsItem::CodeAction {
895 excerpt_id: available.excerpt_id,
896 action: available.action.clone(),
897 provider: available.provider.clone(),
898 }
899 })
900 }
901 }
902 (Some(tasks), None) => tasks
903 .templates
904 .get(index)
905 .cloned()
906 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
907 (None, Some(actions)) => {
908 actions
909 .get(index)
910 .map(|available| CodeActionsItem::CodeAction {
911 excerpt_id: available.excerpt_id,
912 action: available.action.clone(),
913 provider: available.provider.clone(),
914 })
915 }
916 (None, None) => None,
917 }
918 }
919}
920
921#[allow(clippy::large_enum_variant)]
922#[derive(Clone)]
923pub enum CodeActionsItem {
924 Task(TaskSourceKind, ResolvedTask),
925 CodeAction {
926 excerpt_id: ExcerptId,
927 action: CodeAction,
928 provider: Rc<dyn CodeActionProvider>,
929 },
930}
931
932impl CodeActionsItem {
933 fn as_task(&self) -> Option<&ResolvedTask> {
934 let Self::Task(_, task) = self else {
935 return None;
936 };
937 Some(task)
938 }
939
940 fn as_code_action(&self) -> Option<&CodeAction> {
941 let Self::CodeAction { action, .. } = self else {
942 return None;
943 };
944 Some(action)
945 }
946
947 pub fn label(&self) -> String {
948 match self {
949 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
950 Self::Task(_, task) => task.resolved_label.clone(),
951 }
952 }
953}
954
955pub struct CodeActionsMenu {
956 pub actions: CodeActionContents,
957 pub buffer: Model<Buffer>,
958 pub selected_item: usize,
959 pub scroll_handle: UniformListScrollHandle,
960 pub deployed_from_indicator: Option<DisplayRow>,
961}
962
963impl CodeActionsMenu {
964 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
965 self.selected_item = 0;
966 self.scroll_handle
967 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
968 cx.notify()
969 }
970
971 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
972 if self.selected_item > 0 {
973 self.selected_item -= 1;
974 } else {
975 self.selected_item = self.actions.len() - 1;
976 }
977 self.scroll_handle
978 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
979 cx.notify();
980 }
981
982 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
983 if self.selected_item + 1 < self.actions.len() {
984 self.selected_item += 1;
985 } else {
986 self.selected_item = 0;
987 }
988 self.scroll_handle
989 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
990 cx.notify();
991 }
992
993 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
994 self.selected_item = self.actions.len() - 1;
995 self.scroll_handle
996 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
997 cx.notify()
998 }
999
1000 fn visible(&self) -> bool {
1001 !self.actions.is_empty()
1002 }
1003
1004 fn origin(&self, cursor_position: DisplayPoint) -> ContextMenuOrigin {
1005 if let Some(row) = self.deployed_from_indicator {
1006 ContextMenuOrigin::GutterIndicator(row)
1007 } else {
1008 ContextMenuOrigin::EditorPoint(cursor_position)
1009 }
1010 }
1011
1012 fn render(
1013 &self,
1014 _style: &EditorStyle,
1015 max_height_in_lines: u32,
1016 cx: &mut ViewContext<Editor>,
1017 ) -> AnyElement {
1018 let actions = self.actions.clone();
1019 let selected_item = self.selected_item;
1020 let list = uniform_list(
1021 cx.view().clone(),
1022 "code_actions_menu",
1023 self.actions.len(),
1024 move |_this, range, cx| {
1025 actions
1026 .iter()
1027 .skip(range.start)
1028 .take(range.end - range.start)
1029 .enumerate()
1030 .map(|(ix, action)| {
1031 let item_ix = range.start + ix;
1032 let selected = item_ix == selected_item;
1033 let colors = cx.theme().colors();
1034 div().min_w(px(220.)).max_w(px(540.)).child(
1035 ListItem::new(item_ix)
1036 .inset(true)
1037 .toggle_state(selected)
1038 .when_some(action.as_code_action(), |this, action| {
1039 this.on_click(cx.listener(move |editor, _, cx| {
1040 cx.stop_propagation();
1041 if let Some(task) = editor.confirm_code_action(
1042 &ConfirmCodeAction {
1043 item_ix: Some(item_ix),
1044 },
1045 cx,
1046 ) {
1047 task.detach_and_log_err(cx)
1048 }
1049 }))
1050 .child(
1051 h_flex()
1052 .overflow_hidden()
1053 .child(
1054 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1055 action.lsp_action.title.replace("\n", ""),
1056 )
1057 .when(selected, |this| {
1058 this.text_color(colors.text_accent)
1059 }),
1060 )
1061 })
1062 .when_some(action.as_task(), |this, task| {
1063 this.on_click(cx.listener(move |editor, _, cx| {
1064 cx.stop_propagation();
1065 if let Some(task) = editor.confirm_code_action(
1066 &ConfirmCodeAction {
1067 item_ix: Some(item_ix),
1068 },
1069 cx,
1070 ) {
1071 task.detach_and_log_err(cx)
1072 }
1073 }))
1074 .child(
1075 h_flex()
1076 .overflow_hidden()
1077 .child(task.resolved_label.replace("\n", ""))
1078 .when(selected, |this| {
1079 this.text_color(colors.text_accent)
1080 }),
1081 )
1082 }),
1083 )
1084 })
1085 .collect()
1086 },
1087 )
1088 .occlude()
1089 .max_h(max_height_in_lines as f32 * cx.line_height())
1090 .track_scroll(self.scroll_handle.clone())
1091 .with_width_from_item(
1092 self.actions
1093 .iter()
1094 .enumerate()
1095 .max_by_key(|(_, action)| match action {
1096 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1097 CodeActionsItem::CodeAction { action, .. } => {
1098 action.lsp_action.title.chars().count()
1099 }
1100 })
1101 .map(|(ix, _)| ix),
1102 )
1103 .with_sizing_behavior(ListSizingBehavior::Infer);
1104
1105 Popover::new().child(list).into_any_element()
1106 }
1107}