code_context_menus.rs

   1use fuzzy::{StringMatch, StringMatchCandidate};
   2use gpui::{
   3    AnyElement, Entity, Focusable, FontWeight, ListSizingBehavior, ScrollStrategy, SharedString,
   4    Size, StrikethroughStyle, StyledText, Task, UniformListScrollHandle, div, px, uniform_list,
   5};
   6use itertools::Itertools;
   7use language::CodeLabel;
   8use language::{Buffer, LanguageName, LanguageRegistry};
   9use markdown::{Markdown, MarkdownElement};
  10use multi_buffer::{Anchor, ExcerptId};
  11use ordered_float::OrderedFloat;
  12use project::CompletionSource;
  13use project::lsp_store::CompletionDocumentation;
  14use project::{CodeAction, Completion, TaskSourceKind};
  15use task::DebugScenario;
  16use task::TaskContext;
  17
  18use std::collections::VecDeque;
  19use std::sync::Arc;
  20use std::sync::atomic::{AtomicBool, Ordering};
  21use std::{
  22    cell::RefCell,
  23    cmp::{Reverse, min},
  24    iter,
  25    ops::Range,
  26    rc::Rc,
  27};
  28use task::ResolvedTask;
  29use ui::{Color, IntoElement, ListItem, Pixels, Popover, Styled, prelude::*};
  30use util::ResultExt;
  31
  32use crate::CodeActionSource;
  33use crate::editor_settings::SnippetSortOrder;
  34use crate::hover_popover::{hover_markdown_style, open_markdown_url};
  35use crate::{
  36    CodeActionProvider, CompletionId, CompletionItemKind, CompletionProvider, DisplayRow, Editor,
  37    EditorStyle, ResolvedTasks,
  38    actions::{ConfirmCodeAction, ConfirmCompletion},
  39    split_words, styled_runs_for_code_label,
  40};
  41
  42pub const MENU_GAP: Pixels = px(4.);
  43pub const MENU_ASIDE_X_PADDING: Pixels = px(16.);
  44pub const MENU_ASIDE_MIN_WIDTH: Pixels = px(260.);
  45pub const MENU_ASIDE_MAX_WIDTH: Pixels = px(500.);
  46
  47// Constants for the markdown cache. The purpose of this cache is to reduce flickering due to
  48// documentation not yet being parsed.
  49//
  50// The size of the cache is set to 16, which is roughly 3 times more than the number of items
  51// fetched around the current selection. This way documentation is more often ready for render when
  52// revisiting previous entries, such as when pressing backspace.
  53const MARKDOWN_CACHE_MAX_SIZE: usize = 16;
  54const MARKDOWN_CACHE_BEFORE_ITEMS: usize = 2;
  55const MARKDOWN_CACHE_AFTER_ITEMS: usize = 2;
  56
  57// Number of items beyond the visible items to resolve documentation.
  58const RESOLVE_BEFORE_ITEMS: usize = 4;
  59const RESOLVE_AFTER_ITEMS: usize = 4;
  60
  61pub enum CodeContextMenu {
  62    Completions(CompletionsMenu),
  63    CodeActions(CodeActionsMenu),
  64}
  65
  66impl CodeContextMenu {
  67    pub fn select_first(
  68        &mut self,
  69        provider: Option<&dyn CompletionProvider>,
  70        window: &mut Window,
  71        cx: &mut Context<Editor>,
  72    ) -> bool {
  73        if self.visible() {
  74            match self {
  75                CodeContextMenu::Completions(menu) => menu.select_first(provider, window, cx),
  76                CodeContextMenu::CodeActions(menu) => menu.select_first(cx),
  77            }
  78            true
  79        } else {
  80            false
  81        }
  82    }
  83
  84    pub fn select_prev(
  85        &mut self,
  86        provider: Option<&dyn CompletionProvider>,
  87        window: &mut Window,
  88        cx: &mut Context<Editor>,
  89    ) -> bool {
  90        if self.visible() {
  91            match self {
  92                CodeContextMenu::Completions(menu) => menu.select_prev(provider, window, cx),
  93                CodeContextMenu::CodeActions(menu) => menu.select_prev(cx),
  94            }
  95            true
  96        } else {
  97            false
  98        }
  99    }
 100
 101    pub fn select_next(
 102        &mut self,
 103        provider: Option<&dyn CompletionProvider>,
 104        window: &mut Window,
 105        cx: &mut Context<Editor>,
 106    ) -> bool {
 107        if self.visible() {
 108            match self {
 109                CodeContextMenu::Completions(menu) => menu.select_next(provider, window, cx),
 110                CodeContextMenu::CodeActions(menu) => menu.select_next(cx),
 111            }
 112            true
 113        } else {
 114            false
 115        }
 116    }
 117
 118    pub fn select_last(
 119        &mut self,
 120        provider: Option<&dyn CompletionProvider>,
 121        window: &mut Window,
 122        cx: &mut Context<Editor>,
 123    ) -> bool {
 124        if self.visible() {
 125            match self {
 126                CodeContextMenu::Completions(menu) => menu.select_last(provider, window, cx),
 127                CodeContextMenu::CodeActions(menu) => menu.select_last(cx),
 128            }
 129            true
 130        } else {
 131            false
 132        }
 133    }
 134
 135    pub fn visible(&self) -> bool {
 136        match self {
 137            CodeContextMenu::Completions(menu) => menu.visible(),
 138            CodeContextMenu::CodeActions(menu) => menu.visible(),
 139        }
 140    }
 141
 142    pub fn origin(&self) -> ContextMenuOrigin {
 143        match self {
 144            CodeContextMenu::Completions(menu) => menu.origin(),
 145            CodeContextMenu::CodeActions(menu) => menu.origin(),
 146        }
 147    }
 148
 149    pub fn render(
 150        &self,
 151        style: &EditorStyle,
 152        max_height_in_lines: u32,
 153        window: &mut Window,
 154        cx: &mut Context<Editor>,
 155    ) -> AnyElement {
 156        match self {
 157            CodeContextMenu::Completions(menu) => {
 158                menu.render(style, max_height_in_lines, window, cx)
 159            }
 160            CodeContextMenu::CodeActions(menu) => {
 161                menu.render(style, max_height_in_lines, window, cx)
 162            }
 163        }
 164    }
 165
 166    pub fn render_aside(
 167        &mut self,
 168        max_size: Size<Pixels>,
 169        window: &mut Window,
 170        cx: &mut Context<Editor>,
 171    ) -> Option<AnyElement> {
 172        match self {
 173            CodeContextMenu::Completions(menu) => menu.render_aside(max_size, window, cx),
 174            CodeContextMenu::CodeActions(_) => None,
 175        }
 176    }
 177
 178    pub fn focused(&self, window: &mut Window, cx: &mut Context<Editor>) -> bool {
 179        match self {
 180            CodeContextMenu::Completions(completions_menu) => completions_menu
 181                .get_or_create_entry_markdown(completions_menu.selected_item, cx)
 182                .as_ref()
 183                .is_some_and(|markdown| markdown.focus_handle(cx).contains_focused(window, cx)),
 184            CodeContextMenu::CodeActions(_) => false,
 185        }
 186    }
 187}
 188
 189pub enum ContextMenuOrigin {
 190    Cursor,
 191    GutterIndicator(DisplayRow),
 192    QuickActionBar,
 193}
 194
 195pub struct CompletionsMenu {
 196    pub id: CompletionId,
 197    pub source: CompletionsMenuSource,
 198    sort_completions: bool,
 199    pub initial_position: Anchor,
 200    pub initial_query: Option<Arc<String>>,
 201    pub is_incomplete: bool,
 202    pub buffer: Entity<Buffer>,
 203    pub completions: Rc<RefCell<Box<[Completion]>>>,
 204    match_candidates: Arc<[StringMatchCandidate]>,
 205    pub entries: Rc<RefCell<Box<[StringMatch]>>>,
 206    pub selected_item: usize,
 207    filter_task: Task<()>,
 208    cancel_filter: Arc<AtomicBool>,
 209    scroll_handle: UniformListScrollHandle,
 210    resolve_completions: bool,
 211    show_completion_documentation: bool,
 212    last_rendered_range: Rc<RefCell<Option<Range<usize>>>>,
 213    markdown_cache: Rc<RefCell<VecDeque<(MarkdownCacheKey, Entity<Markdown>)>>>,
 214    language_registry: Option<Arc<LanguageRegistry>>,
 215    language: Option<LanguageName>,
 216    snippet_sort_order: SnippetSortOrder,
 217}
 218
 219#[derive(Clone, Debug, PartialEq)]
 220enum MarkdownCacheKey {
 221    ForCandidate {
 222        candidate_id: usize,
 223    },
 224    ForCompletionMatch {
 225        new_text: String,
 226        markdown_source: SharedString,
 227    },
 228}
 229
 230#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 231pub enum CompletionsMenuSource {
 232    Normal,
 233    SnippetChoices,
 234    Words,
 235}
 236
 237// TODO: There should really be a wrapper around fuzzy match tasks that does this.
 238impl Drop for CompletionsMenu {
 239    fn drop(&mut self) {
 240        self.cancel_filter.store(true, Ordering::Relaxed);
 241    }
 242}
 243
 244impl CompletionsMenu {
 245    pub fn new(
 246        id: CompletionId,
 247        source: CompletionsMenuSource,
 248        sort_completions: bool,
 249        show_completion_documentation: bool,
 250        initial_position: Anchor,
 251        initial_query: Option<Arc<String>>,
 252        is_incomplete: bool,
 253        buffer: Entity<Buffer>,
 254        completions: Box<[Completion]>,
 255        snippet_sort_order: SnippetSortOrder,
 256        language_registry: Option<Arc<LanguageRegistry>>,
 257        language: Option<LanguageName>,
 258        cx: &mut Context<Editor>,
 259    ) -> Self {
 260        let match_candidates = completions
 261            .iter()
 262            .enumerate()
 263            .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
 264            .collect();
 265
 266        let completions_menu = Self {
 267            id,
 268            source,
 269            sort_completions,
 270            initial_position,
 271            initial_query,
 272            is_incomplete,
 273            buffer,
 274            show_completion_documentation,
 275            completions: RefCell::new(completions).into(),
 276            match_candidates,
 277            entries: Rc::new(RefCell::new(Box::new([]))),
 278            selected_item: 0,
 279            filter_task: Task::ready(()),
 280            cancel_filter: Arc::new(AtomicBool::new(false)),
 281            scroll_handle: UniformListScrollHandle::new(),
 282            resolve_completions: true,
 283            last_rendered_range: RefCell::new(None).into(),
 284            markdown_cache: RefCell::new(VecDeque::new()).into(),
 285            language_registry,
 286            language,
 287            snippet_sort_order,
 288        };
 289
 290        completions_menu.start_markdown_parse_for_nearby_entries(cx);
 291
 292        completions_menu
 293    }
 294
 295    pub fn new_snippet_choices(
 296        id: CompletionId,
 297        sort_completions: bool,
 298        choices: &Vec<String>,
 299        selection: Range<Anchor>,
 300        buffer: Entity<Buffer>,
 301        snippet_sort_order: SnippetSortOrder,
 302    ) -> Self {
 303        let completions = choices
 304            .iter()
 305            .map(|choice| Completion {
 306                replace_range: selection.start.text_anchor..selection.end.text_anchor,
 307                new_text: choice.to_string(),
 308                label: CodeLabel {
 309                    text: choice.to_string(),
 310                    runs: Default::default(),
 311                    filter_range: Default::default(),
 312                },
 313                icon_path: None,
 314                documentation: None,
 315                confirm: None,
 316                insert_text_mode: None,
 317                source: CompletionSource::Custom,
 318            })
 319            .collect();
 320
 321        let match_candidates = choices
 322            .iter()
 323            .enumerate()
 324            .map(|(id, completion)| StringMatchCandidate::new(id, &completion))
 325            .collect();
 326        let entries = choices
 327            .iter()
 328            .enumerate()
 329            .map(|(id, completion)| StringMatch {
 330                candidate_id: id,
 331                score: 1.,
 332                positions: vec![],
 333                string: completion.clone(),
 334            })
 335            .collect();
 336        Self {
 337            id,
 338            source: CompletionsMenuSource::SnippetChoices,
 339            sort_completions,
 340            initial_position: selection.start,
 341            initial_query: None,
 342            is_incomplete: false,
 343            buffer,
 344            completions: RefCell::new(completions).into(),
 345            match_candidates,
 346            entries: RefCell::new(entries).into(),
 347            selected_item: 0,
 348            filter_task: Task::ready(()),
 349            cancel_filter: Arc::new(AtomicBool::new(false)),
 350            scroll_handle: UniformListScrollHandle::new(),
 351            resolve_completions: false,
 352            show_completion_documentation: false,
 353            last_rendered_range: RefCell::new(None).into(),
 354            markdown_cache: RefCell::new(VecDeque::new()).into(),
 355            language_registry: None,
 356            language: None,
 357            snippet_sort_order,
 358        }
 359    }
 360
 361    fn select_first(
 362        &mut self,
 363        provider: Option<&dyn CompletionProvider>,
 364        window: &mut Window,
 365        cx: &mut Context<Editor>,
 366    ) {
 367        let index = if self.scroll_handle.y_flipped() {
 368            self.entries.borrow().len() - 1
 369        } else {
 370            0
 371        };
 372        self.update_selection_index(index, provider, window, cx);
 373    }
 374
 375    fn select_last(
 376        &mut self,
 377        provider: Option<&dyn CompletionProvider>,
 378        window: &mut Window,
 379        cx: &mut Context<Editor>,
 380    ) {
 381        let index = if self.scroll_handle.y_flipped() {
 382            0
 383        } else {
 384            self.entries.borrow().len() - 1
 385        };
 386        self.update_selection_index(index, provider, window, cx);
 387    }
 388
 389    fn select_prev(
 390        &mut self,
 391        provider: Option<&dyn CompletionProvider>,
 392        window: &mut Window,
 393        cx: &mut Context<Editor>,
 394    ) {
 395        let index = if self.scroll_handle.y_flipped() {
 396            self.next_match_index()
 397        } else {
 398            self.prev_match_index()
 399        };
 400        self.update_selection_index(index, provider, window, cx);
 401    }
 402
 403    fn select_next(
 404        &mut self,
 405        provider: Option<&dyn CompletionProvider>,
 406        window: &mut Window,
 407        cx: &mut Context<Editor>,
 408    ) {
 409        let index = if self.scroll_handle.y_flipped() {
 410            self.prev_match_index()
 411        } else {
 412            self.next_match_index()
 413        };
 414        self.update_selection_index(index, provider, window, cx);
 415    }
 416
 417    fn update_selection_index(
 418        &mut self,
 419        match_index: usize,
 420        provider: Option<&dyn CompletionProvider>,
 421        window: &mut Window,
 422        cx: &mut Context<Editor>,
 423    ) {
 424        if self.selected_item != match_index {
 425            self.selected_item = match_index;
 426            self.handle_selection_changed(provider, window, cx);
 427        }
 428    }
 429
 430    fn prev_match_index(&self) -> usize {
 431        if self.selected_item > 0 {
 432            self.selected_item - 1
 433        } else {
 434            self.entries.borrow().len() - 1
 435        }
 436    }
 437
 438    fn next_match_index(&self) -> usize {
 439        if self.selected_item + 1 < self.entries.borrow().len() {
 440            self.selected_item + 1
 441        } else {
 442            0
 443        }
 444    }
 445
 446    fn handle_selection_changed(
 447        &mut self,
 448        provider: Option<&dyn CompletionProvider>,
 449        window: &mut Window,
 450        cx: &mut Context<Editor>,
 451    ) {
 452        self.scroll_handle
 453            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 454        if let Some(provider) = provider {
 455            let entries = self.entries.borrow();
 456            let entry = if self.selected_item < entries.len() {
 457                Some(&entries[self.selected_item])
 458            } else {
 459                None
 460            };
 461            provider.selection_changed(entry, window, cx);
 462        }
 463        self.resolve_visible_completions(provider, cx);
 464        self.start_markdown_parse_for_nearby_entries(cx);
 465        cx.notify();
 466    }
 467
 468    pub fn resolve_visible_completions(
 469        &mut self,
 470        provider: Option<&dyn CompletionProvider>,
 471        cx: &mut Context<Editor>,
 472    ) {
 473        if !self.resolve_completions {
 474            return;
 475        }
 476        let Some(provider) = provider else {
 477            return;
 478        };
 479
 480        let entries = self.entries.borrow();
 481        if entries.is_empty() {
 482            return;
 483        }
 484        if self.selected_item >= entries.len() {
 485            log::error!(
 486                "bug: completion selected_item >= entries.len(): {} >= {}",
 487                self.selected_item,
 488                entries.len()
 489            );
 490            self.selected_item = entries.len() - 1;
 491        }
 492
 493        // Attempt to resolve completions for every item that will be displayed. This matters
 494        // because single line documentation may be displayed inline with the completion.
 495        //
 496        // When navigating to the very beginning or end of completions, `last_rendered_range` may
 497        // have no overlap with the completions that will be displayed, so instead use a range based
 498        // on the last rendered count.
 499        const APPROXIMATE_VISIBLE_COUNT: usize = 12;
 500        let last_rendered_range = self.last_rendered_range.borrow().clone();
 501        let visible_count = last_rendered_range
 502            .clone()
 503            .map_or(APPROXIMATE_VISIBLE_COUNT, |range| range.count());
 504        let entry_range = if self.selected_item == 0 {
 505            0..min(visible_count, entries.len())
 506        } else if self.selected_item == entries.len() - 1 {
 507            entries.len().saturating_sub(visible_count)..entries.len()
 508        } else {
 509            last_rendered_range.map_or(0..0, |range| {
 510                min(range.start, entries.len())..min(range.end, entries.len())
 511            })
 512        };
 513
 514        // Expand the range to resolve more completions than are predicted to be visible, to reduce
 515        // jank on navigation.
 516        let entry_indices = util::expanded_and_wrapped_usize_range(
 517            entry_range.clone(),
 518            RESOLVE_BEFORE_ITEMS,
 519            RESOLVE_AFTER_ITEMS,
 520            entries.len(),
 521        );
 522
 523        // Avoid work by sometimes filtering out completions that already have documentation.
 524        // This filtering doesn't happen if the completions are currently being updated.
 525        let completions = self.completions.borrow();
 526        let candidate_ids = entry_indices
 527            .map(|i| entries[i].candidate_id)
 528            .filter(|i| completions[*i].documentation.is_none());
 529
 530        // Current selection is always resolved even if it already has documentation, to handle
 531        // out-of-spec language servers that return more results later.
 532        let selected_candidate_id = entries[self.selected_item].candidate_id;
 533        let candidate_ids = iter::once(selected_candidate_id)
 534            .chain(candidate_ids.filter(|id| *id != selected_candidate_id))
 535            .collect::<Vec<usize>>();
 536        drop(entries);
 537
 538        if candidate_ids.is_empty() {
 539            return;
 540        }
 541
 542        let resolve_task = provider.resolve_completions(
 543            self.buffer.clone(),
 544            candidate_ids,
 545            self.completions.clone(),
 546            cx,
 547        );
 548
 549        let completion_id = self.id;
 550        cx.spawn(async move |editor, cx| {
 551            if let Some(true) = resolve_task.await.log_err() {
 552                editor
 553                    .update(cx, |editor, cx| {
 554                        // `resolve_completions` modified state affecting display.
 555                        cx.notify();
 556                        editor.with_completions_menu_matching_id(completion_id, |menu| {
 557                            if let Some(menu) = menu {
 558                                menu.start_markdown_parse_for_nearby_entries(cx)
 559                            }
 560                        });
 561                    })
 562                    .ok();
 563            }
 564        })
 565        .detach();
 566    }
 567
 568    fn start_markdown_parse_for_nearby_entries(&self, cx: &mut Context<Editor>) {
 569        // Enqueue parse tasks of nearer items first.
 570        //
 571        // TODO: This means that the nearer items will actually be further back in the cache, which
 572        // is not ideal. In practice this is fine because `get_or_create_markdown` moves the current
 573        // selection to the front (when `is_render = true`).
 574        let entry_indices = util::wrapped_usize_outward_from(
 575            self.selected_item,
 576            MARKDOWN_CACHE_BEFORE_ITEMS,
 577            MARKDOWN_CACHE_AFTER_ITEMS,
 578            self.entries.borrow().len(),
 579        );
 580
 581        for index in entry_indices {
 582            self.get_or_create_entry_markdown(index, cx);
 583        }
 584    }
 585
 586    fn get_or_create_entry_markdown(
 587        &self,
 588        index: usize,
 589        cx: &mut Context<Editor>,
 590    ) -> Option<Entity<Markdown>> {
 591        let entries = self.entries.borrow();
 592        if index >= entries.len() {
 593            return None;
 594        }
 595        let candidate_id = entries[index].candidate_id;
 596        let completions = self.completions.borrow();
 597        match &completions[candidate_id].documentation {
 598            Some(CompletionDocumentation::MultiLineMarkdown(source)) if !source.is_empty() => self
 599                .get_or_create_markdown(candidate_id, Some(source), false, &completions, cx)
 600                .map(|(_, markdown)| markdown),
 601            Some(_) => None,
 602            _ => None,
 603        }
 604    }
 605
 606    fn get_or_create_markdown(
 607        &self,
 608        candidate_id: usize,
 609        source: Option<&SharedString>,
 610        is_render: bool,
 611        completions: &[Completion],
 612        cx: &mut Context<Editor>,
 613    ) -> Option<(bool, Entity<Markdown>)> {
 614        let mut markdown_cache = self.markdown_cache.borrow_mut();
 615
 616        let mut has_completion_match_cache_entry = false;
 617        let mut matching_entry = markdown_cache.iter().find_position(|(key, _)| match key {
 618            MarkdownCacheKey::ForCandidate { candidate_id: id } => *id == candidate_id,
 619            MarkdownCacheKey::ForCompletionMatch { .. } => {
 620                has_completion_match_cache_entry = true;
 621                false
 622            }
 623        });
 624
 625        if has_completion_match_cache_entry && matching_entry.is_none() {
 626            if let Some(source) = source {
 627                matching_entry = markdown_cache.iter().find_position(|(key, _)| {
 628                    matches!(key, MarkdownCacheKey::ForCompletionMatch { markdown_source, .. }
 629                                if markdown_source == source)
 630                });
 631            } else {
 632                // Heuristic guess that documentation can be reused when new_text matches. This is
 633                // to mitigate documentation flicker while typing. If this is wrong, then resolution
 634                // should cause the correct documentation to be displayed soon.
 635                let completion = &completions[candidate_id];
 636                matching_entry = markdown_cache.iter().find_position(|(key, _)| {
 637                    matches!(key, MarkdownCacheKey::ForCompletionMatch { new_text, .. }
 638                                if new_text == &completion.new_text)
 639                });
 640            }
 641        }
 642
 643        if let Some((cache_index, (key, markdown))) = matching_entry {
 644            let markdown = markdown.clone();
 645
 646            // Since the markdown source matches, the key can now be ForCandidate.
 647            if source.is_some() && matches!(key, MarkdownCacheKey::ForCompletionMatch { .. }) {
 648                markdown_cache[cache_index].0 = MarkdownCacheKey::ForCandidate { candidate_id };
 649            }
 650
 651            if is_render && cache_index != 0 {
 652                // Move the current selection's cache entry to the front.
 653                markdown_cache.rotate_right(1);
 654                let cache_len = markdown_cache.len();
 655                markdown_cache.swap(0, (cache_index + 1) % cache_len);
 656            }
 657
 658            let is_parsing = markdown.update(cx, |markdown, cx| {
 659                if let Some(source) = source {
 660                    // `reset` is called as it's possible for documentation to change due to resolve
 661                    // requests. It does nothing if `source` is unchanged.
 662                    markdown.reset(source.clone(), cx);
 663                }
 664                markdown.is_parsing()
 665            });
 666            return Some((is_parsing, markdown));
 667        }
 668
 669        let Some(source) = source else {
 670            // Can't create markdown as there is no source.
 671            return None;
 672        };
 673
 674        if markdown_cache.len() < MARKDOWN_CACHE_MAX_SIZE {
 675            let markdown = cx.new(|cx| {
 676                Markdown::new(
 677                    source.clone(),
 678                    self.language_registry.clone(),
 679                    self.language.clone(),
 680                    cx,
 681                )
 682            });
 683            // Handles redraw when the markdown is done parsing. The current render is for a
 684            // deferred draw, and so without this did not redraw when `markdown` notified.
 685            cx.observe(&markdown, |_, _, cx| cx.notify()).detach();
 686            markdown_cache.push_front((
 687                MarkdownCacheKey::ForCandidate { candidate_id },
 688                markdown.clone(),
 689            ));
 690            Some((true, markdown))
 691        } else {
 692            debug_assert_eq!(markdown_cache.capacity(), MARKDOWN_CACHE_MAX_SIZE);
 693            // Moves the last cache entry to the start. The ring buffer is full, so this does no
 694            // copying and just shifts indexes.
 695            markdown_cache.rotate_right(1);
 696            markdown_cache[0].0 = MarkdownCacheKey::ForCandidate { candidate_id };
 697            let markdown = &markdown_cache[0].1;
 698            markdown.update(cx, |markdown, cx| markdown.reset(source.clone(), cx));
 699            Some((true, markdown.clone()))
 700        }
 701    }
 702
 703    pub fn visible(&self) -> bool {
 704        !self.entries.borrow().is_empty()
 705    }
 706
 707    fn origin(&self) -> ContextMenuOrigin {
 708        ContextMenuOrigin::Cursor
 709    }
 710
 711    fn render(
 712        &self,
 713        style: &EditorStyle,
 714        max_height_in_lines: u32,
 715        window: &mut Window,
 716        cx: &mut Context<Editor>,
 717    ) -> AnyElement {
 718        let show_completion_documentation = self.show_completion_documentation;
 719        let selected_item = self.selected_item;
 720        let completions = self.completions.clone();
 721        let entries = self.entries.clone();
 722        let last_rendered_range = self.last_rendered_range.clone();
 723        let style = style.clone();
 724        let list = uniform_list(
 725            "completions",
 726            self.entries.borrow().len(),
 727            cx.processor(move |_editor, range: Range<usize>, _window, cx| {
 728                last_rendered_range.borrow_mut().replace(range.clone());
 729                let start_ix = range.start;
 730                let completions_guard = completions.borrow_mut();
 731
 732                entries.borrow()[range]
 733                    .iter()
 734                    .enumerate()
 735                    .map(|(ix, mat)| {
 736                        let item_ix = start_ix + ix;
 737                        let completion = &completions_guard[mat.candidate_id];
 738                        let documentation = if show_completion_documentation {
 739                            &completion.documentation
 740                        } else {
 741                            &None
 742                        };
 743
 744                        let filter_start = completion.label.filter_range.start;
 745                        let highlights = gpui::combine_highlights(
 746                            mat.ranges().map(|range| {
 747                                (
 748                                    filter_start + range.start..filter_start + range.end,
 749                                    FontWeight::BOLD.into(),
 750                                )
 751                            }),
 752                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 753                                |(range, mut highlight)| {
 754                                    // Ignore font weight for syntax highlighting, as we'll use it
 755                                    // for fuzzy matches.
 756                                    highlight.font_weight = None;
 757                                    if completion
 758                                        .source
 759                                        .lsp_completion(false)
 760                                        .and_then(|lsp_completion| lsp_completion.deprecated)
 761                                        .unwrap_or(false)
 762                                    {
 763                                        highlight.strikethrough = Some(StrikethroughStyle {
 764                                            thickness: 1.0.into(),
 765                                            ..Default::default()
 766                                        });
 767                                        highlight.color = Some(cx.theme().colors().text_muted);
 768                                    }
 769
 770                                    (range, highlight)
 771                                },
 772                            ),
 773                        );
 774
 775                        let completion_label = StyledText::new(completion.label.text.clone())
 776                            .with_default_highlights(&style.text, highlights);
 777
 778                        let documentation_label = match documentation {
 779                            Some(CompletionDocumentation::SingleLine(text))
 780                            | Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
 781                                single_line: text,
 782                                ..
 783                            }) => {
 784                                if text.trim().is_empty() {
 785                                    None
 786                                } else {
 787                                    Some(
 788                                        Label::new(text.clone())
 789                                            .ml_4()
 790                                            .size(LabelSize::Small)
 791                                            .color(Color::Muted),
 792                                    )
 793                                }
 794                            }
 795                            _ => None,
 796                        };
 797
 798                        let start_slot = completion
 799                            .color()
 800                            .map(|color| {
 801                                div()
 802                                    .flex_shrink_0()
 803                                    .size_3p5()
 804                                    .rounded_xs()
 805                                    .bg(color)
 806                                    .into_any_element()
 807                            })
 808                            .or_else(|| {
 809                                completion.icon_path.as_ref().map(|path| {
 810                                    Icon::from_path(path)
 811                                        .size(IconSize::XSmall)
 812                                        .color(Color::Muted)
 813                                        .into_any_element()
 814                                })
 815                            });
 816
 817                        div().min_w(px(280.)).max_w(px(540.)).child(
 818                            ListItem::new(mat.candidate_id)
 819                                .inset(true)
 820                                .toggle_state(item_ix == selected_item)
 821                                .on_click(cx.listener(move |editor, _event, window, cx| {
 822                                    cx.stop_propagation();
 823                                    if let Some(task) = editor.confirm_completion(
 824                                        &ConfirmCompletion {
 825                                            item_ix: Some(item_ix),
 826                                        },
 827                                        window,
 828                                        cx,
 829                                    ) {
 830                                        task.detach_and_log_err(cx)
 831                                    }
 832                                }))
 833                                .start_slot::<AnyElement>(start_slot)
 834                                .child(h_flex().overflow_hidden().child(completion_label))
 835                                .end_slot::<Label>(documentation_label),
 836                        )
 837                    })
 838                    .collect()
 839            }),
 840        )
 841        .occlude()
 842        .max_h(max_height_in_lines as f32 * window.line_height())
 843        .track_scroll(self.scroll_handle.clone())
 844        .with_sizing_behavior(ListSizingBehavior::Infer)
 845        .w(rems(34.));
 846
 847        Popover::new().child(list).into_any_element()
 848    }
 849
 850    fn render_aside(
 851        &mut self,
 852        max_size: Size<Pixels>,
 853        window: &mut Window,
 854        cx: &mut Context<Editor>,
 855    ) -> Option<AnyElement> {
 856        if !self.show_completion_documentation {
 857            return None;
 858        }
 859
 860        let mat = &self.entries.borrow()[self.selected_item];
 861        let completions = self.completions.borrow_mut();
 862        let multiline_docs = match completions[mat.candidate_id].documentation.as_ref() {
 863            Some(CompletionDocumentation::MultiLinePlainText(text)) => div().child(text.clone()),
 864            Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
 865                plain_text: Some(text),
 866                ..
 867            }) => div().child(text.clone()),
 868            Some(CompletionDocumentation::MultiLineMarkdown(source)) if !source.is_empty() => {
 869                let Some((false, markdown)) = self.get_or_create_markdown(
 870                    mat.candidate_id,
 871                    Some(source),
 872                    true,
 873                    &completions,
 874                    cx,
 875                ) else {
 876                    return None;
 877                };
 878                Self::render_markdown(markdown, window, cx)
 879            }
 880            None => {
 881                // Handle the case where documentation hasn't yet been resolved but there's a
 882                // `new_text` match in the cache.
 883                //
 884                // TODO: It's inconsistent that documentation caching based on matching `new_text`
 885                // only works for markdown. Consider generally caching the results of resolving
 886                // completions.
 887                let Some((false, markdown)) =
 888                    self.get_or_create_markdown(mat.candidate_id, None, true, &completions, cx)
 889                else {
 890                    return None;
 891                };
 892                Self::render_markdown(markdown, window, cx)
 893            }
 894            Some(CompletionDocumentation::MultiLineMarkdown(_)) => return None,
 895            Some(CompletionDocumentation::SingleLine(_)) => return None,
 896            Some(CompletionDocumentation::Undocumented) => return None,
 897            Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
 898                plain_text: None,
 899                ..
 900            }) => {
 901                return None;
 902            }
 903        };
 904
 905        Some(
 906            Popover::new()
 907                .child(
 908                    multiline_docs
 909                        .id("multiline_docs")
 910                        .px(MENU_ASIDE_X_PADDING / 2.)
 911                        .max_w(max_size.width)
 912                        .max_h(max_size.height)
 913                        .overflow_y_scroll()
 914                        .occlude(),
 915                )
 916                .into_any_element(),
 917        )
 918    }
 919
 920    fn render_markdown(
 921        markdown: Entity<Markdown>,
 922        window: &mut Window,
 923        cx: &mut Context<Editor>,
 924    ) -> Div {
 925        div().child(
 926            MarkdownElement::new(markdown, hover_markdown_style(window, cx))
 927                .code_block_renderer(markdown::CodeBlockRenderer::Default {
 928                    copy_button: false,
 929                    copy_button_on_hover: false,
 930                    border: false,
 931                })
 932                .on_url_click(open_markdown_url),
 933        )
 934    }
 935
 936    pub fn filter(
 937        &mut self,
 938        query: Option<Arc<String>>,
 939        provider: Option<Rc<dyn CompletionProvider>>,
 940        window: &mut Window,
 941        cx: &mut Context<Editor>,
 942    ) {
 943        self.cancel_filter.store(true, Ordering::Relaxed);
 944        if let Some(query) = query {
 945            self.cancel_filter = Arc::new(AtomicBool::new(false));
 946            let matches = self.do_async_filtering(query, cx);
 947            let id = self.id;
 948            self.filter_task = cx.spawn_in(window, async move |editor, cx| {
 949                let matches = matches.await;
 950                editor
 951                    .update_in(cx, |editor, window, cx| {
 952                        editor.with_completions_menu_matching_id(id, |this| {
 953                            if let Some(this) = this {
 954                                this.set_filter_results(matches, provider, window, cx);
 955                            }
 956                        });
 957                    })
 958                    .ok();
 959            });
 960        } else {
 961            self.filter_task = Task::ready(());
 962            let matches = self.unfiltered_matches();
 963            self.set_filter_results(matches, provider, window, cx);
 964        }
 965    }
 966
 967    pub fn do_async_filtering(
 968        &self,
 969        query: Arc<String>,
 970        cx: &Context<Editor>,
 971    ) -> Task<Vec<StringMatch>> {
 972        let matches_task = cx.background_spawn({
 973            let query = query.clone();
 974            let match_candidates = self.match_candidates.clone();
 975            let cancel_filter = self.cancel_filter.clone();
 976            let background_executor = cx.background_executor().clone();
 977            async move {
 978                fuzzy::match_strings(
 979                    &match_candidates,
 980                    &query,
 981                    query.chars().any(|c| c.is_uppercase()),
 982                    100,
 983                    &cancel_filter,
 984                    background_executor,
 985                )
 986                .await
 987            }
 988        });
 989
 990        let completions = self.completions.clone();
 991        let sort_completions = self.sort_completions;
 992        let snippet_sort_order = self.snippet_sort_order;
 993        cx.foreground_executor().spawn(async move {
 994            let mut matches = matches_task.await;
 995
 996            if sort_completions {
 997                matches = Self::sort_string_matches(
 998                    matches,
 999                    Some(&query),
1000                    snippet_sort_order,
1001                    completions.borrow().as_ref(),
1002                );
1003            }
1004
1005            matches
1006        })
1007    }
1008
1009    /// Like `do_async_filtering` but there is no filter query, so no need to spawn tasks.
1010    pub fn unfiltered_matches(&self) -> Vec<StringMatch> {
1011        let mut matches = self
1012            .match_candidates
1013            .iter()
1014            .enumerate()
1015            .map(|(candidate_id, candidate)| StringMatch {
1016                candidate_id,
1017                score: Default::default(),
1018                positions: Default::default(),
1019                string: candidate.string.clone(),
1020            })
1021            .collect();
1022
1023        if self.sort_completions {
1024            matches = Self::sort_string_matches(
1025                matches,
1026                None,
1027                self.snippet_sort_order,
1028                self.completions.borrow().as_ref(),
1029            );
1030        }
1031
1032        matches
1033    }
1034
1035    pub fn set_filter_results(
1036        &mut self,
1037        matches: Vec<StringMatch>,
1038        provider: Option<Rc<dyn CompletionProvider>>,
1039        window: &mut Window,
1040        cx: &mut Context<Editor>,
1041    ) {
1042        *self.entries.borrow_mut() = matches.into_boxed_slice();
1043        self.selected_item = 0;
1044        self.handle_selection_changed(provider.as_deref(), window, cx);
1045    }
1046
1047    fn sort_string_matches(
1048        matches: Vec<StringMatch>,
1049        query: Option<&str>,
1050        snippet_sort_order: SnippetSortOrder,
1051        completions: &[Completion],
1052    ) -> Vec<StringMatch> {
1053        let mut sortable_items: Vec<SortableMatch<'_>> = matches
1054            .into_iter()
1055            .map(|string_match| {
1056                let completion = &completions[string_match.candidate_id];
1057
1058                let is_snippet = matches!(
1059                    &completion.source,
1060                    CompletionSource::Lsp { lsp_completion, .. }
1061                    if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
1062                );
1063
1064                let sort_text =
1065                    if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
1066                        lsp_completion.sort_text.as_deref()
1067                    } else {
1068                        None
1069                    };
1070
1071                let (sort_kind, sort_label) = completion.sort_key();
1072
1073                SortableMatch {
1074                    string_match,
1075                    is_snippet,
1076                    sort_text,
1077                    sort_kind,
1078                    sort_label,
1079                }
1080            })
1081            .collect();
1082
1083        Self::sort_matches(&mut sortable_items, query, snippet_sort_order);
1084
1085        sortable_items
1086            .into_iter()
1087            .map(|sortable| sortable.string_match)
1088            .collect()
1089    }
1090
1091    pub fn sort_matches(
1092        matches: &mut Vec<SortableMatch<'_>>,
1093        query: Option<&str>,
1094        snippet_sort_order: SnippetSortOrder,
1095    ) {
1096        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1097        enum MatchTier<'a> {
1098            WordStartMatch {
1099                sort_mixed_case_prefix_length: Reverse<usize>,
1100                sort_snippet: Reverse<i32>,
1101                sort_kind: usize,
1102                sort_fuzzy_bracket: Reverse<usize>,
1103                sort_text: Option<&'a str>,
1104                sort_score: Reverse<OrderedFloat<f64>>,
1105                sort_label: &'a str,
1106            },
1107            OtherMatch {
1108                sort_score: Reverse<OrderedFloat<f64>>,
1109            },
1110        }
1111
1112        // Our goal here is to intelligently sort completion suggestions. We want to
1113        // balance the raw fuzzy match score with hints from the language server
1114
1115        // In a fuzzy bracket, matches with a score of 1.0 are prioritized.
1116        // The remaining matches are partitioned into two groups at 3/5 of the max_score.
1117        let max_score = matches
1118            .iter()
1119            .map(|mat| mat.string_match.score)
1120            .fold(0.0, f64::max);
1121        let fuzzy_bracket_threshold = max_score * (3.0 / 5.0);
1122
1123        let query_start_lower = query
1124            .as_ref()
1125            .and_then(|q| q.chars().next())
1126            .and_then(|c| c.to_lowercase().next());
1127
1128        matches.sort_unstable_by_key(|mat| {
1129            let score = mat.string_match.score;
1130            let sort_score = Reverse(OrderedFloat(score));
1131
1132            let query_start_doesnt_match_split_words = query_start_lower
1133                .map(|query_char| {
1134                    !split_words(&mat.string_match.string).any(|word| {
1135                        word.chars()
1136                            .next()
1137                            .and_then(|c| c.to_lowercase().next())
1138                            .map_or(false, |word_char| word_char == query_char)
1139                    })
1140                })
1141                .unwrap_or(false);
1142
1143            if query_start_doesnt_match_split_words {
1144                MatchTier::OtherMatch { sort_score }
1145            } else {
1146                let sort_fuzzy_bracket = Reverse(if score >= fuzzy_bracket_threshold {
1147                    1
1148                } else {
1149                    0
1150                });
1151                let sort_snippet = match snippet_sort_order {
1152                    SnippetSortOrder::Top => Reverse(if mat.is_snippet { 1 } else { 0 }),
1153                    SnippetSortOrder::Bottom => Reverse(if mat.is_snippet { 0 } else { 1 }),
1154                    SnippetSortOrder::Inline => Reverse(0),
1155                };
1156                let sort_mixed_case_prefix_length = Reverse(
1157                    query
1158                        .as_ref()
1159                        .map(|q| {
1160                            q.chars()
1161                                .zip(mat.string_match.string.chars())
1162                                .enumerate()
1163                                .take_while(|(i, (q_char, match_char))| {
1164                                    if *i == 0 {
1165                                        // Case-sensitive comparison for first character
1166                                        q_char == match_char
1167                                    } else {
1168                                        // Case-insensitive comparison for other characters
1169                                        q_char.to_lowercase().eq(match_char.to_lowercase())
1170                                    }
1171                                })
1172                                .count()
1173                        })
1174                        .unwrap_or(0),
1175                );
1176                MatchTier::WordStartMatch {
1177                    sort_mixed_case_prefix_length,
1178                    sort_snippet,
1179                    sort_kind: mat.sort_kind,
1180                    sort_fuzzy_bracket,
1181                    sort_text: mat.sort_text,
1182                    sort_score,
1183                    sort_label: mat.sort_label,
1184                }
1185            }
1186        });
1187    }
1188
1189    pub fn preserve_markdown_cache(&mut self, prev_menu: CompletionsMenu) {
1190        self.markdown_cache = prev_menu.markdown_cache.clone();
1191
1192        // Convert ForCandidate cache keys to ForCompletionMatch keys.
1193        let prev_completions = prev_menu.completions.borrow();
1194        self.markdown_cache
1195            .borrow_mut()
1196            .retain_mut(|(key, _markdown)| match key {
1197                MarkdownCacheKey::ForCompletionMatch { .. } => true,
1198                MarkdownCacheKey::ForCandidate { candidate_id } => {
1199                    if let Some(completion) = prev_completions.get(*candidate_id) {
1200                        match &completion.documentation {
1201                            Some(CompletionDocumentation::MultiLineMarkdown(source)) => {
1202                                *key = MarkdownCacheKey::ForCompletionMatch {
1203                                    new_text: completion.new_text.clone(),
1204                                    markdown_source: source.clone(),
1205                                };
1206                                true
1207                            }
1208                            _ => false,
1209                        }
1210                    } else {
1211                        false
1212                    }
1213                }
1214            });
1215    }
1216}
1217
1218#[derive(Debug)]
1219pub struct SortableMatch<'a> {
1220    pub string_match: StringMatch,
1221    pub is_snippet: bool,
1222    pub sort_text: Option<&'a str>,
1223    pub sort_kind: usize,
1224    pub sort_label: &'a str,
1225}
1226
1227#[derive(Clone)]
1228pub struct AvailableCodeAction {
1229    pub excerpt_id: ExcerptId,
1230    pub action: CodeAction,
1231    pub provider: Rc<dyn CodeActionProvider>,
1232}
1233
1234#[derive(Clone)]
1235pub struct CodeActionContents {
1236    tasks: Option<Rc<ResolvedTasks>>,
1237    actions: Option<Rc<[AvailableCodeAction]>>,
1238    debug_scenarios: Vec<DebugScenario>,
1239    pub(crate) context: TaskContext,
1240}
1241
1242impl CodeActionContents {
1243    pub(crate) fn new(
1244        tasks: Option<ResolvedTasks>,
1245        actions: Option<Rc<[AvailableCodeAction]>>,
1246        debug_scenarios: Vec<DebugScenario>,
1247        context: TaskContext,
1248    ) -> Self {
1249        Self {
1250            tasks: tasks.map(Rc::new),
1251            actions,
1252            debug_scenarios,
1253            context,
1254        }
1255    }
1256
1257    pub fn tasks(&self) -> Option<&ResolvedTasks> {
1258        self.tasks.as_deref()
1259    }
1260
1261    fn len(&self) -> usize {
1262        let tasks_len = self.tasks.as_ref().map_or(0, |tasks| tasks.templates.len());
1263        let code_actions_len = self.actions.as_ref().map_or(0, |actions| actions.len());
1264        tasks_len + code_actions_len + self.debug_scenarios.len()
1265    }
1266
1267    fn is_empty(&self) -> bool {
1268        self.len() == 0
1269    }
1270
1271    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1272        self.tasks
1273            .iter()
1274            .flat_map(|tasks| {
1275                tasks
1276                    .templates
1277                    .iter()
1278                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1279            })
1280            .chain(self.actions.iter().flat_map(|actions| {
1281                actions.iter().map(|available| CodeActionsItem::CodeAction {
1282                    excerpt_id: available.excerpt_id,
1283                    action: available.action.clone(),
1284                    provider: available.provider.clone(),
1285                })
1286            }))
1287            .chain(
1288                self.debug_scenarios
1289                    .iter()
1290                    .cloned()
1291                    .map(CodeActionsItem::DebugScenario),
1292            )
1293    }
1294
1295    pub fn get(&self, mut index: usize) -> Option<CodeActionsItem> {
1296        if let Some(tasks) = &self.tasks {
1297            if let Some((kind, task)) = tasks.templates.get(index) {
1298                return Some(CodeActionsItem::Task(kind.clone(), task.clone()));
1299            } else {
1300                index -= tasks.templates.len();
1301            }
1302        }
1303        if let Some(actions) = &self.actions {
1304            if let Some(available) = actions.get(index) {
1305                return Some(CodeActionsItem::CodeAction {
1306                    excerpt_id: available.excerpt_id,
1307                    action: available.action.clone(),
1308                    provider: available.provider.clone(),
1309                });
1310            } else {
1311                index -= actions.len();
1312            }
1313        }
1314
1315        self.debug_scenarios
1316            .get(index)
1317            .cloned()
1318            .map(CodeActionsItem::DebugScenario)
1319    }
1320}
1321
1322#[derive(Clone)]
1323pub enum CodeActionsItem {
1324    Task(TaskSourceKind, ResolvedTask),
1325    CodeAction {
1326        excerpt_id: ExcerptId,
1327        action: CodeAction,
1328        provider: Rc<dyn CodeActionProvider>,
1329    },
1330    DebugScenario(DebugScenario),
1331}
1332
1333impl CodeActionsItem {
1334    fn as_task(&self) -> Option<&ResolvedTask> {
1335        let Self::Task(_, task) = self else {
1336            return None;
1337        };
1338        Some(task)
1339    }
1340
1341    fn as_code_action(&self) -> Option<&CodeAction> {
1342        let Self::CodeAction { action, .. } = self else {
1343            return None;
1344        };
1345        Some(action)
1346    }
1347    fn as_debug_scenario(&self) -> Option<&DebugScenario> {
1348        let Self::DebugScenario(scenario) = self else {
1349            return None;
1350        };
1351        Some(scenario)
1352    }
1353
1354    pub fn label(&self) -> String {
1355        match self {
1356            Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
1357            Self::Task(_, task) => task.resolved_label.clone(),
1358            Self::DebugScenario(scenario) => scenario.label.to_string(),
1359        }
1360    }
1361}
1362
1363pub struct CodeActionsMenu {
1364    pub actions: CodeActionContents,
1365    pub buffer: Entity<Buffer>,
1366    pub selected_item: usize,
1367    pub scroll_handle: UniformListScrollHandle,
1368    pub deployed_from: Option<CodeActionSource>,
1369}
1370
1371impl CodeActionsMenu {
1372    fn select_first(&mut self, cx: &mut Context<Editor>) {
1373        self.selected_item = if self.scroll_handle.y_flipped() {
1374            self.actions.len() - 1
1375        } else {
1376            0
1377        };
1378        self.scroll_handle
1379            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1380        cx.notify()
1381    }
1382
1383    fn select_last(&mut self, cx: &mut Context<Editor>) {
1384        self.selected_item = if self.scroll_handle.y_flipped() {
1385            0
1386        } else {
1387            self.actions.len() - 1
1388        };
1389        self.scroll_handle
1390            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1391        cx.notify()
1392    }
1393
1394    fn select_prev(&mut self, cx: &mut Context<Editor>) {
1395        self.selected_item = if self.scroll_handle.y_flipped() {
1396            self.next_match_index()
1397        } else {
1398            self.prev_match_index()
1399        };
1400        self.scroll_handle
1401            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1402        cx.notify();
1403    }
1404
1405    fn select_next(&mut self, cx: &mut Context<Editor>) {
1406        self.selected_item = if self.scroll_handle.y_flipped() {
1407            self.prev_match_index()
1408        } else {
1409            self.next_match_index()
1410        };
1411        self.scroll_handle
1412            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1413        cx.notify();
1414    }
1415
1416    fn prev_match_index(&self) -> usize {
1417        if self.selected_item > 0 {
1418            self.selected_item - 1
1419        } else {
1420            self.actions.len() - 1
1421        }
1422    }
1423
1424    fn next_match_index(&self) -> usize {
1425        if self.selected_item + 1 < self.actions.len() {
1426            self.selected_item + 1
1427        } else {
1428            0
1429        }
1430    }
1431
1432    fn visible(&self) -> bool {
1433        !self.actions.is_empty()
1434    }
1435
1436    fn origin(&self) -> ContextMenuOrigin {
1437        match &self.deployed_from {
1438            Some(CodeActionSource::Indicator(row)) => ContextMenuOrigin::GutterIndicator(*row),
1439            Some(CodeActionSource::QuickActionBar) => ContextMenuOrigin::QuickActionBar,
1440            None => ContextMenuOrigin::Cursor,
1441        }
1442    }
1443
1444    fn render(
1445        &self,
1446        _style: &EditorStyle,
1447        max_height_in_lines: u32,
1448        window: &mut Window,
1449        cx: &mut Context<Editor>,
1450    ) -> AnyElement {
1451        let actions = self.actions.clone();
1452        let selected_item = self.selected_item;
1453        let list = uniform_list(
1454            "code_actions_menu",
1455            self.actions.len(),
1456            cx.processor(move |_this, range: Range<usize>, _, cx| {
1457                actions
1458                    .iter()
1459                    .skip(range.start)
1460                    .take(range.end - range.start)
1461                    .enumerate()
1462                    .map(|(ix, action)| {
1463                        let item_ix = range.start + ix;
1464                        let selected = item_ix == selected_item;
1465                        let colors = cx.theme().colors();
1466                        div().min_w(px(220.)).max_w(px(540.)).child(
1467                            ListItem::new(item_ix)
1468                                .inset(true)
1469                                .toggle_state(selected)
1470                                .when_some(action.as_code_action(), |this, action| {
1471                                    this.child(
1472                                        h_flex()
1473                                            .overflow_hidden()
1474                                            .child(
1475                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1476                                                action.lsp_action.title().replace("\n", ""),
1477                                            )
1478                                            .when(selected, |this| {
1479                                                this.text_color(colors.text_accent)
1480                                            }),
1481                                    )
1482                                })
1483                                .when_some(action.as_task(), |this, task| {
1484                                    this.child(
1485                                        h_flex()
1486                                            .overflow_hidden()
1487                                            .child(task.resolved_label.replace("\n", ""))
1488                                            .when(selected, |this| {
1489                                                this.text_color(colors.text_accent)
1490                                            }),
1491                                    )
1492                                })
1493                                .when_some(action.as_debug_scenario(), |this, scenario| {
1494                                    this.child(
1495                                        h_flex()
1496                                            .overflow_hidden()
1497                                            .child("debug: ")
1498                                            .child(scenario.label.clone())
1499                                            .when(selected, |this| {
1500                                                this.text_color(colors.text_accent)
1501                                            }),
1502                                    )
1503                                })
1504                                .on_click(cx.listener(move |editor, _, window, cx| {
1505                                    cx.stop_propagation();
1506                                    if let Some(task) = editor.confirm_code_action(
1507                                        &ConfirmCodeAction {
1508                                            item_ix: Some(item_ix),
1509                                        },
1510                                        window,
1511                                        cx,
1512                                    ) {
1513                                        task.detach_and_log_err(cx)
1514                                    }
1515                                })),
1516                        )
1517                    })
1518                    .collect()
1519            }),
1520        )
1521        .occlude()
1522        .max_h(max_height_in_lines as f32 * window.line_height())
1523        .track_scroll(self.scroll_handle.clone())
1524        .with_width_from_item(
1525            self.actions
1526                .iter()
1527                .enumerate()
1528                .max_by_key(|(_, action)| match action {
1529                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1530                    CodeActionsItem::CodeAction { action, .. } => {
1531                        action.lsp_action.title().chars().count()
1532                    }
1533                    CodeActionsItem::DebugScenario(scenario) => {
1534                        format!("debug: {}", scenario.label).chars().count()
1535                    }
1536                })
1537                .map(|(ix, _)| ix),
1538        )
1539        .with_sizing_behavior(ListSizingBehavior::Infer);
1540
1541        Popover::new().child(list).into_any_element()
1542    }
1543}