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