code_context_menus.rs

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