code_context_menus.rs

   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) => hint.label().chars().count(),
 466            })
 467            .map(|(ix, _)| ix);
 468        drop(completions);
 469
 470        let selected_item = self.selected_item;
 471        let completions = self.completions.clone();
 472        let entries = self.entries.clone();
 473        let last_rendered_range = self.last_rendered_range.clone();
 474        let style = style.clone();
 475        let list = uniform_list(
 476            cx.view().clone(),
 477            "completions",
 478            self.entries.borrow().len(),
 479            move |_editor, range, cx| {
 480                last_rendered_range.borrow_mut().replace(range.clone());
 481                let start_ix = range.start;
 482                let completions_guard = completions.borrow_mut();
 483
 484                entries.borrow()[range]
 485                    .iter()
 486                    .enumerate()
 487                    .map(|(ix, mat)| {
 488                        let item_ix = start_ix + ix;
 489                        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 490                        let base_label = h_flex()
 491                            .gap_1()
 492                            .child(div().font(buffer_font.clone()).child("Zed AI"))
 493                            .child(div().px_0p5().child("/").opacity(0.2));
 494
 495                        match mat {
 496                            CompletionEntry::Match(mat) => {
 497                                let candidate_id = mat.candidate_id;
 498                                let completion = &completions_guard[candidate_id];
 499
 500                                let documentation = if show_completion_documentation {
 501                                    &completion.documentation
 502                                } else {
 503                                    &None
 504                                };
 505
 506                                let filter_start = completion.label.filter_range.start;
 507                                let highlights = gpui::combine_highlights(
 508                                    mat.ranges().map(|range| {
 509                                        (
 510                                            filter_start + range.start..filter_start + range.end,
 511                                            FontWeight::BOLD.into(),
 512                                        )
 513                                    }),
 514                                    styled_runs_for_code_label(&completion.label, &style.syntax)
 515                                        .map(|(range, mut highlight)| {
 516                                            // Ignore font weight for syntax highlighting, as we'll use it
 517                                            // for fuzzy matches.
 518                                            highlight.font_weight = None;
 519
 520                                            if completion.lsp_completion.deprecated.unwrap_or(false)
 521                                            {
 522                                                highlight.strikethrough =
 523                                                    Some(StrikethroughStyle {
 524                                                        thickness: 1.0.into(),
 525                                                        ..Default::default()
 526                                                    });
 527                                                highlight.color =
 528                                                    Some(cx.theme().colors().text_muted);
 529                                            }
 530
 531                                            (range, highlight)
 532                                        }),
 533                                );
 534
 535                                let completion_label =
 536                                    StyledText::new(completion.label.text.clone())
 537                                        .with_highlights(&style.text, highlights);
 538                                let documentation_label =
 539                                    if let Some(Documentation::SingleLine(text)) = documentation {
 540                                        if text.trim().is_empty() {
 541                                            None
 542                                        } else {
 543                                            Some(
 544                                                Label::new(text.clone())
 545                                                    .ml_4()
 546                                                    .size(LabelSize::Small)
 547                                                    .color(Color::Muted),
 548                                            )
 549                                        }
 550                                    } else {
 551                                        None
 552                                    };
 553
 554                                let color_swatch = completion
 555                                    .color()
 556                                    .map(|color| div().size_4().bg(color).rounded_sm());
 557
 558                                div().min_w(px(220.)).max_w(px(540.)).child(
 559                                    ListItem::new(mat.candidate_id)
 560                                        .inset(true)
 561                                        .toggle_state(item_ix == selected_item)
 562                                        .on_click(cx.listener(move |editor, _event, cx| {
 563                                            cx.stop_propagation();
 564                                            if let Some(task) = editor.confirm_completion(
 565                                                &ConfirmCompletion {
 566                                                    item_ix: Some(item_ix),
 567                                                },
 568                                                cx,
 569                                            ) {
 570                                                task.detach_and_log_err(cx)
 571                                            }
 572                                        }))
 573                                        .start_slot::<Div>(color_swatch)
 574                                        .child(h_flex().overflow_hidden().child(completion_label))
 575                                        .end_slot::<Label>(documentation_label),
 576                                )
 577                            }
 578                            CompletionEntry::InlineCompletionHint(
 579                                hint @ InlineCompletionMenuHint::None,
 580                            ) => div().min_w(px(250.)).max_w(px(500.)).child(
 581                                ListItem::new("inline-completion")
 582                                    .inset(true)
 583                                    .toggle_state(item_ix == selected_item)
 584                                    .start_slot(Icon::new(IconName::ZedPredict))
 585                                    .child(
 586                                        base_label.child(
 587                                            StyledText::new(hint.label())
 588                                                .with_highlights(&style.text, None),
 589                                        ),
 590                                    ),
 591                            ),
 592                            CompletionEntry::InlineCompletionHint(
 593                                hint @ InlineCompletionMenuHint::Loading,
 594                            ) => div().min_w(px(250.)).max_w(px(500.)).child(
 595                                ListItem::new("inline-completion")
 596                                    .inset(true)
 597                                    .toggle_state(item_ix == selected_item)
 598                                    .start_slot(Icon::new(IconName::ZedPredict))
 599                                    .child(base_label.child({
 600                                        let text_style = style.text.clone();
 601                                        StyledText::new(hint.label())
 602                                            .with_highlights(&text_style, None)
 603                                            .with_animation(
 604                                                "pulsating-label",
 605                                                Animation::new(Duration::from_secs(1))
 606                                                    .repeat()
 607                                                    .with_easing(pulsating_between(0.4, 0.8)),
 608                                                move |text, delta| {
 609                                                    let mut text_style = text_style.clone();
 610                                                    text_style.color =
 611                                                        text_style.color.opacity(delta);
 612                                                    text.with_highlights(&text_style, None)
 613                                                },
 614                                            )
 615                                    })),
 616                            ),
 617                            CompletionEntry::InlineCompletionHint(
 618                                hint @ InlineCompletionMenuHint::Loaded { .. },
 619                            ) => div().min_w(px(250.)).max_w(px(500.)).child(
 620                                ListItem::new("inline-completion")
 621                                    .inset(true)
 622                                    .toggle_state(item_ix == selected_item)
 623                                    .start_slot(Icon::new(IconName::ZedPredict))
 624                                    .child(
 625                                        base_label.child(
 626                                            StyledText::new(hint.label())
 627                                                .with_highlights(&style.text, None),
 628                                        ),
 629                                    )
 630                                    .on_click(cx.listener(move |editor, _event, cx| {
 631                                        cx.stop_propagation();
 632                                        editor.accept_inline_completion(
 633                                            &AcceptInlineCompletion {},
 634                                            cx,
 635                                        );
 636                                    })),
 637                            ),
 638                        }
 639                    })
 640                    .collect()
 641            },
 642        )
 643        .occlude()
 644        .max_h(max_height_in_lines as f32 * cx.line_height())
 645        .track_scroll(self.scroll_handle.clone())
 646        .with_width_from_item(widest_completion_ix)
 647        .with_sizing_behavior(ListSizingBehavior::Infer);
 648
 649        Popover::new().child(list).into_any_element()
 650    }
 651
 652    fn render_aside(
 653        &self,
 654        style: &EditorStyle,
 655        max_size: Size<Pixels>,
 656        workspace: Option<WeakView<Workspace>>,
 657        cx: &mut ViewContext<Editor>,
 658    ) -> Option<AnyElement> {
 659        if !self.show_completion_documentation {
 660            return None;
 661        }
 662
 663        let multiline_docs = match &self.entries.borrow()[self.selected_item] {
 664            CompletionEntry::Match(mat) => {
 665                match self.completions.borrow_mut()[mat.candidate_id]
 666                    .documentation
 667                    .as_ref()?
 668                {
 669                    Documentation::MultiLinePlainText(text) => {
 670                        div().child(SharedString::from(text.clone()))
 671                    }
 672                    Documentation::MultiLineMarkdown(parsed) if !parsed.text.is_empty() => div()
 673                        .child(render_parsed_markdown(
 674                            "completions_markdown",
 675                            parsed,
 676                            &style,
 677                            workspace,
 678                            cx,
 679                        )),
 680                    Documentation::MultiLineMarkdown(_) => return None,
 681                    Documentation::SingleLine(_) => return None,
 682                    Documentation::Undocumented => return None,
 683                }
 684            }
 685            CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::Loaded { text }) => {
 686                match text {
 687                    InlineCompletionText::Edit { text, highlights } => div()
 688                        .mx_1()
 689                        .rounded_md()
 690                        .bg(cx.theme().colors().editor_background)
 691                        .child(
 692                            gpui::StyledText::new(text.clone())
 693                                .with_highlights(&style.text, highlights.clone()),
 694                        ),
 695                    InlineCompletionText::Move(text) => div().child(text.clone()),
 696                }
 697            }
 698            CompletionEntry::InlineCompletionHint(_) => return None,
 699        };
 700
 701        Some(
 702            Popover::new()
 703                .child(
 704                    multiline_docs
 705                        .id("multiline_docs")
 706                        .px(MENU_ASIDE_X_PADDING / 2.)
 707                        .max_w(max_size.width)
 708                        .max_h(max_size.height)
 709                        .overflow_y_scroll()
 710                        .occlude(),
 711                )
 712                .into_any_element(),
 713        )
 714    }
 715
 716    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 717        let mut matches = if let Some(query) = query {
 718            fuzzy::match_strings(
 719                &self.match_candidates,
 720                query,
 721                query.chars().any(|c| c.is_uppercase()),
 722                100,
 723                &Default::default(),
 724                executor,
 725            )
 726            .await
 727        } else {
 728            self.match_candidates
 729                .iter()
 730                .enumerate()
 731                .map(|(candidate_id, candidate)| StringMatch {
 732                    candidate_id,
 733                    score: Default::default(),
 734                    positions: Default::default(),
 735                    string: candidate.string.clone(),
 736                })
 737                .collect()
 738        };
 739
 740        // Remove all candidates where the query's start does not match the start of any word in the candidate
 741        if let Some(query) = query {
 742            if let Some(query_start) = query.chars().next() {
 743                matches.retain(|string_match| {
 744                    split_words(&string_match.string).any(|word| {
 745                        // Check that the first codepoint of the word as lowercase matches the first
 746                        // codepoint of the query as lowercase
 747                        word.chars()
 748                            .flat_map(|codepoint| codepoint.to_lowercase())
 749                            .zip(query_start.to_lowercase())
 750                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 751                    })
 752                });
 753            }
 754        }
 755
 756        let completions = self.completions.borrow_mut();
 757        if self.sort_completions {
 758            matches.sort_unstable_by_key(|mat| {
 759                // We do want to strike a balance here between what the language server tells us
 760                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 761                // `Creat` and there is a local variable called `CreateComponent`).
 762                // So what we do is: we bucket all matches into two buckets
 763                // - Strong matches
 764                // - Weak matches
 765                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 766                // and the Weak matches are the rest.
 767                //
 768                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 769                // matches, we prefer language-server sort_text first.
 770                //
 771                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 772                // Rest of the matches(weak) can be sorted as language-server expects.
 773
 774                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 775                enum MatchScore<'a> {
 776                    Strong {
 777                        score: Reverse<OrderedFloat<f64>>,
 778                        sort_text: Option<&'a str>,
 779                        sort_key: (usize, &'a str),
 780                    },
 781                    Weak {
 782                        sort_text: Option<&'a str>,
 783                        score: Reverse<OrderedFloat<f64>>,
 784                        sort_key: (usize, &'a str),
 785                    },
 786                }
 787
 788                let completion = &completions[mat.candidate_id];
 789                let sort_key = completion.sort_key();
 790                let sort_text = completion.lsp_completion.sort_text.as_deref();
 791                let score = Reverse(OrderedFloat(mat.score));
 792
 793                if mat.score >= 0.2 {
 794                    MatchScore::Strong {
 795                        score,
 796                        sort_text,
 797                        sort_key,
 798                    }
 799                } else {
 800                    MatchScore::Weak {
 801                        sort_text,
 802                        score,
 803                        sort_key,
 804                    }
 805                }
 806            });
 807        }
 808        drop(completions);
 809
 810        let mut entries = self.entries.borrow_mut();
 811        if let Some(CompletionEntry::InlineCompletionHint(_)) = entries.first() {
 812            entries.truncate(1);
 813        } else {
 814            entries.truncate(0);
 815        }
 816        entries.extend(matches.into_iter().map(CompletionEntry::Match));
 817
 818        self.selected_item = 0;
 819    }
 820}
 821
 822#[derive(Clone)]
 823pub struct AvailableCodeAction {
 824    pub excerpt_id: ExcerptId,
 825    pub action: CodeAction,
 826    pub provider: Rc<dyn CodeActionProvider>,
 827}
 828
 829#[derive(Clone)]
 830pub struct CodeActionContents {
 831    pub tasks: Option<Rc<ResolvedTasks>>,
 832    pub actions: Option<Rc<[AvailableCodeAction]>>,
 833}
 834
 835impl CodeActionContents {
 836    fn len(&self) -> usize {
 837        match (&self.tasks, &self.actions) {
 838            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 839            (Some(tasks), None) => tasks.templates.len(),
 840            (None, Some(actions)) => actions.len(),
 841            (None, None) => 0,
 842        }
 843    }
 844
 845    fn is_empty(&self) -> bool {
 846        match (&self.tasks, &self.actions) {
 847            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 848            (Some(tasks), None) => tasks.templates.is_empty(),
 849            (None, Some(actions)) => actions.is_empty(),
 850            (None, None) => true,
 851        }
 852    }
 853
 854    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 855        self.tasks
 856            .iter()
 857            .flat_map(|tasks| {
 858                tasks
 859                    .templates
 860                    .iter()
 861                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 862            })
 863            .chain(self.actions.iter().flat_map(|actions| {
 864                actions.iter().map(|available| CodeActionsItem::CodeAction {
 865                    excerpt_id: available.excerpt_id,
 866                    action: available.action.clone(),
 867                    provider: available.provider.clone(),
 868                })
 869            }))
 870    }
 871
 872    pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
 873        match (&self.tasks, &self.actions) {
 874            (Some(tasks), Some(actions)) => {
 875                if index < tasks.templates.len() {
 876                    tasks
 877                        .templates
 878                        .get(index)
 879                        .cloned()
 880                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 881                } else {
 882                    actions.get(index - tasks.templates.len()).map(|available| {
 883                        CodeActionsItem::CodeAction {
 884                            excerpt_id: available.excerpt_id,
 885                            action: available.action.clone(),
 886                            provider: available.provider.clone(),
 887                        }
 888                    })
 889                }
 890            }
 891            (Some(tasks), None) => tasks
 892                .templates
 893                .get(index)
 894                .cloned()
 895                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 896            (None, Some(actions)) => {
 897                actions
 898                    .get(index)
 899                    .map(|available| CodeActionsItem::CodeAction {
 900                        excerpt_id: available.excerpt_id,
 901                        action: available.action.clone(),
 902                        provider: available.provider.clone(),
 903                    })
 904            }
 905            (None, None) => None,
 906        }
 907    }
 908}
 909
 910#[allow(clippy::large_enum_variant)]
 911#[derive(Clone)]
 912pub enum CodeActionsItem {
 913    Task(TaskSourceKind, ResolvedTask),
 914    CodeAction {
 915        excerpt_id: ExcerptId,
 916        action: CodeAction,
 917        provider: Rc<dyn CodeActionProvider>,
 918    },
 919}
 920
 921impl CodeActionsItem {
 922    fn as_task(&self) -> Option<&ResolvedTask> {
 923        let Self::Task(_, task) = self else {
 924            return None;
 925        };
 926        Some(task)
 927    }
 928
 929    fn as_code_action(&self) -> Option<&CodeAction> {
 930        let Self::CodeAction { action, .. } = self else {
 931            return None;
 932        };
 933        Some(action)
 934    }
 935
 936    pub fn label(&self) -> String {
 937        match self {
 938            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
 939            Self::Task(_, task) => task.resolved_label.clone(),
 940        }
 941    }
 942}
 943
 944pub struct CodeActionsMenu {
 945    pub actions: CodeActionContents,
 946    pub buffer: Model<Buffer>,
 947    pub selected_item: usize,
 948    pub scroll_handle: UniformListScrollHandle,
 949    pub deployed_from_indicator: Option<DisplayRow>,
 950}
 951
 952impl CodeActionsMenu {
 953    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 954        self.selected_item = 0;
 955        self.scroll_handle
 956            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 957        cx.notify()
 958    }
 959
 960    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 961        if self.selected_item > 0 {
 962            self.selected_item -= 1;
 963        } else {
 964            self.selected_item = self.actions.len() - 1;
 965        }
 966        self.scroll_handle
 967            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 968        cx.notify();
 969    }
 970
 971    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 972        if self.selected_item + 1 < self.actions.len() {
 973            self.selected_item += 1;
 974        } else {
 975            self.selected_item = 0;
 976        }
 977        self.scroll_handle
 978            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 979        cx.notify();
 980    }
 981
 982    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 983        self.selected_item = self.actions.len() - 1;
 984        self.scroll_handle
 985            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 986        cx.notify()
 987    }
 988
 989    fn visible(&self) -> bool {
 990        !self.actions.is_empty()
 991    }
 992
 993    fn origin(&self, cursor_position: DisplayPoint) -> ContextMenuOrigin {
 994        if let Some(row) = self.deployed_from_indicator {
 995            ContextMenuOrigin::GutterIndicator(row)
 996        } else {
 997            ContextMenuOrigin::EditorPoint(cursor_position)
 998        }
 999    }
1000
1001    fn render(
1002        &self,
1003        _style: &EditorStyle,
1004        max_height_in_lines: u32,
1005        cx: &mut ViewContext<Editor>,
1006    ) -> AnyElement {
1007        let actions = self.actions.clone();
1008        let selected_item = self.selected_item;
1009        let list = uniform_list(
1010            cx.view().clone(),
1011            "code_actions_menu",
1012            self.actions.len(),
1013            move |_this, range, cx| {
1014                actions
1015                    .iter()
1016                    .skip(range.start)
1017                    .take(range.end - range.start)
1018                    .enumerate()
1019                    .map(|(ix, action)| {
1020                        let item_ix = range.start + ix;
1021                        let selected = item_ix == selected_item;
1022                        let colors = cx.theme().colors();
1023                        div().min_w(px(220.)).max_w(px(540.)).child(
1024                            ListItem::new(item_ix)
1025                                .inset(true)
1026                                .toggle_state(selected)
1027                                .when_some(action.as_code_action(), |this, action| {
1028                                    this.on_click(cx.listener(move |editor, _, cx| {
1029                                        cx.stop_propagation();
1030                                        if let Some(task) = editor.confirm_code_action(
1031                                            &ConfirmCodeAction {
1032                                                item_ix: Some(item_ix),
1033                                            },
1034                                            cx,
1035                                        ) {
1036                                            task.detach_and_log_err(cx)
1037                                        }
1038                                    }))
1039                                    .child(
1040                                        h_flex()
1041                                            .overflow_hidden()
1042                                            .child(
1043                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1044                                                action.lsp_action.title.replace("\n", ""),
1045                                            )
1046                                            .when(selected, |this| {
1047                                                this.text_color(colors.text_accent)
1048                                            }),
1049                                    )
1050                                })
1051                                .when_some(action.as_task(), |this, task| {
1052                                    this.on_click(cx.listener(move |editor, _, cx| {
1053                                        cx.stop_propagation();
1054                                        if let Some(task) = editor.confirm_code_action(
1055                                            &ConfirmCodeAction {
1056                                                item_ix: Some(item_ix),
1057                                            },
1058                                            cx,
1059                                        ) {
1060                                            task.detach_and_log_err(cx)
1061                                        }
1062                                    }))
1063                                    .child(
1064                                        h_flex()
1065                                            .overflow_hidden()
1066                                            .child(task.resolved_label.replace("\n", ""))
1067                                            .when(selected, |this| {
1068                                                this.text_color(colors.text_accent)
1069                                            }),
1070                                    )
1071                                }),
1072                        )
1073                    })
1074                    .collect()
1075            },
1076        )
1077        .occlude()
1078        .max_h(max_height_in_lines as f32 * cx.line_height())
1079        .track_scroll(self.scroll_handle.clone())
1080        .with_width_from_item(
1081            self.actions
1082                .iter()
1083                .enumerate()
1084                .max_by_key(|(_, action)| match action {
1085                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1086                    CodeActionsItem::CodeAction { action, .. } => {
1087                        action.lsp_action.title.chars().count()
1088                    }
1089                })
1090                .map(|(ix, _)| ix),
1091        )
1092        .with_sizing_behavior(ListSizingBehavior::Infer);
1093
1094        Popover::new().child(list).into_any_element()
1095    }
1096}