editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behaviour.
   15pub mod actions;
   16mod blink_manager;
   17pub mod display_map;
   18mod editor_settings;
   19mod element;
   20mod inlay_hint_cache;
   21
   22mod debounced_delay;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26mod hover_popover;
   27mod inline_completion_provider;
   28pub mod items;
   29mod mouse_context_menu;
   30pub mod movement;
   31mod persistence;
   32mod rust_analyzer_ext;
   33pub mod scroll;
   34mod selections_collection;
   35
   36#[cfg(test)]
   37mod editor_tests;
   38#[cfg(any(test, feature = "test-support"))]
   39pub mod test;
   40use ::git::diff::{DiffHunk, DiffHunkStatus};
   41use ::git::permalink::{build_permalink, BuildPermalinkParams};
   42pub(crate) use actions::*;
   43use aho_corasick::AhoCorasick;
   44use anyhow::{anyhow, Context as _, Result};
   45use blink_manager::BlinkManager;
   46use client::{Collaborator, ParticipantIndex};
   47use clock::ReplicaId;
   48use collections::{hash_map, BTreeMap, Bound, HashMap, HashSet, VecDeque};
   49use convert_case::{Case, Casing};
   50use debounced_delay::DebouncedDelay;
   51pub use display_map::DisplayPoint;
   52use display_map::*;
   53pub use editor_settings::EditorSettings;
   54use element::LineWithInvisibles;
   55pub use element::{
   56    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   57};
   58use futures::FutureExt;
   59use fuzzy::{StringMatch, StringMatchCandidate};
   60use git::blame::GitBlame;
   61use git::diff_hunk_to_display;
   62use gpui::{
   63    div, impl_actions, point, prelude::*, px, relative, rems, size, uniform_list, Action,
   64    AnyElement, AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds,
   65    ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView,
   66    FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext, Model,
   67    MouseButton, ParentElement, Pixels, Render, SharedString, Styled, StyledText, Subscription,
   68    Task, TextStyle, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   69    VisualContext, WeakView, WhiteSpace, WindowContext,
   70};
   71use highlight_matching_bracket::refresh_matching_bracket_highlights;
   72use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   73use hover_popover::{hide_hover, HoverState};
   74use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   75pub use inline_completion_provider::*;
   76pub use items::MAX_TAB_TITLE_LEN;
   77use itertools::Itertools;
   78use language::{char_kind, CharKind};
   79use language::{
   80    language_settings::{self, all_language_settings, InlayHintSettings},
   81    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CodeAction,
   82    CodeLabel, Completion, CursorShape, Diagnostic, Documentation, IndentKind, IndentSize,
   83    Language, OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
   84};
   85use lsp::{DiagnosticSeverity, LanguageServerId};
   86use mouse_context_menu::MouseContextMenu;
   87use movement::TextLayoutDetails;
   88use multi_buffer::ToOffsetUtf16;
   89pub use multi_buffer::{
   90    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
   91    ToPoint,
   92};
   93use ordered_float::OrderedFloat;
   94use parking_lot::{Mutex, RwLock};
   95use project::project_settings::{GitGutterSetting, ProjectSettings};
   96use project::{FormatTrigger, Item, Location, Project, ProjectPath, ProjectTransaction};
   97use rand::prelude::*;
   98use rpc::proto::*;
   99use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  100use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  101use serde::{Deserialize, Serialize};
  102use settings::{Settings, SettingsStore};
  103use smallvec::SmallVec;
  104use snippet::Snippet;
  105use std::ops::Not as _;
  106use std::{
  107    any::TypeId,
  108    borrow::Cow,
  109    cmp::{self, Ordering, Reverse},
  110    mem,
  111    num::NonZeroU32,
  112    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
  113    path::Path,
  114    sync::Arc,
  115    time::{Duration, Instant},
  116};
  117pub use sum_tree::Bias;
  118use text::{BufferId, OffsetUtf16, Rope};
  119use theme::{
  120    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  121    ThemeColors, ThemeSettings,
  122};
  123use ui::{
  124    h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
  125    Tooltip,
  126};
  127use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  128use workspace::Toast;
  129use workspace::{
  130    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  131};
  132
  133use crate::hover_links::find_url;
  134
  135const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  136const MAX_LINE_LEN: usize = 1024;
  137const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  138const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  139pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  140#[doc(hidden)]
  141pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  142#[doc(hidden)]
  143pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  144
  145pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  146
  147pub fn render_parsed_markdown(
  148    element_id: impl Into<ElementId>,
  149    parsed: &language::ParsedMarkdown,
  150    editor_style: &EditorStyle,
  151    workspace: Option<WeakView<Workspace>>,
  152    cx: &mut ViewContext<Editor>,
  153) -> InteractiveText {
  154    let code_span_background_color = cx
  155        .theme()
  156        .colors()
  157        .editor_document_highlight_read_background;
  158
  159    let highlights = gpui::combine_highlights(
  160        parsed.highlights.iter().filter_map(|(range, highlight)| {
  161            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  162            Some((range.clone(), highlight))
  163        }),
  164        parsed
  165            .regions
  166            .iter()
  167            .zip(&parsed.region_ranges)
  168            .filter_map(|(region, range)| {
  169                if region.code {
  170                    Some((
  171                        range.clone(),
  172                        HighlightStyle {
  173                            background_color: Some(code_span_background_color),
  174                            ..Default::default()
  175                        },
  176                    ))
  177                } else {
  178                    None
  179                }
  180            }),
  181    );
  182
  183    let mut links = Vec::new();
  184    let mut link_ranges = Vec::new();
  185    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  186        if let Some(link) = region.link.clone() {
  187            links.push(link);
  188            link_ranges.push(range.clone());
  189        }
  190    }
  191
  192    InteractiveText::new(
  193        element_id,
  194        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  195    )
  196    .on_click(link_ranges, move |clicked_range_ix, cx| {
  197        match &links[clicked_range_ix] {
  198            markdown::Link::Web { url } => cx.open_url(url),
  199            markdown::Link::Path { path } => {
  200                if let Some(workspace) = &workspace {
  201                    _ = workspace.update(cx, |workspace, cx| {
  202                        workspace.open_abs_path(path.clone(), false, cx).detach();
  203                    });
  204                }
  205            }
  206        }
  207    })
  208}
  209
  210#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  211pub(crate) enum InlayId {
  212    Suggestion(usize),
  213    Hint(usize),
  214}
  215
  216impl InlayId {
  217    fn id(&self) -> usize {
  218        match self {
  219            Self::Suggestion(id) => *id,
  220            Self::Hint(id) => *id,
  221        }
  222    }
  223}
  224
  225enum DocumentHighlightRead {}
  226enum DocumentHighlightWrite {}
  227enum InputComposition {}
  228
  229#[derive(Copy, Clone, PartialEq, Eq)]
  230pub enum Direction {
  231    Prev,
  232    Next,
  233}
  234
  235pub fn init_settings(cx: &mut AppContext) {
  236    EditorSettings::register(cx);
  237}
  238
  239pub fn init(cx: &mut AppContext) {
  240    init_settings(cx);
  241
  242    workspace::register_project_item::<Editor>(cx);
  243    workspace::register_followable_item::<Editor>(cx);
  244    workspace::register_deserializable_item::<Editor>(cx);
  245    cx.observe_new_views(
  246        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  247            workspace.register_action(Editor::new_file);
  248            workspace.register_action(Editor::new_file_in_direction);
  249        },
  250    )
  251    .detach();
  252
  253    cx.on_action(move |_: &workspace::NewFile, cx| {
  254        let app_state = workspace::AppState::global(cx);
  255        if let Some(app_state) = app_state.upgrade() {
  256            workspace::open_new(app_state, cx, |workspace, cx| {
  257                Editor::new_file(workspace, &Default::default(), cx)
  258            })
  259            .detach();
  260        }
  261    });
  262    cx.on_action(move |_: &workspace::NewWindow, cx| {
  263        let app_state = workspace::AppState::global(cx);
  264        if let Some(app_state) = app_state.upgrade() {
  265            workspace::open_new(app_state, cx, |workspace, cx| {
  266                Editor::new_file(workspace, &Default::default(), cx)
  267            })
  268            .detach();
  269        }
  270    });
  271}
  272
  273trait InvalidationRegion {
  274    fn ranges(&self) -> &[Range<Anchor>];
  275}
  276
  277#[derive(Clone, Debug, PartialEq)]
  278pub enum SelectPhase {
  279    Begin {
  280        position: DisplayPoint,
  281        add: bool,
  282        click_count: usize,
  283    },
  284    BeginColumnar {
  285        position: DisplayPoint,
  286        goal_column: u32,
  287    },
  288    Extend {
  289        position: DisplayPoint,
  290        click_count: usize,
  291    },
  292    Update {
  293        position: DisplayPoint,
  294        goal_column: u32,
  295        scroll_delta: gpui::Point<f32>,
  296    },
  297    End,
  298}
  299
  300#[derive(Clone, Debug)]
  301pub enum SelectMode {
  302    Character,
  303    Word(Range<Anchor>),
  304    Line(Range<Anchor>),
  305    All,
  306}
  307
  308#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  309pub enum EditorMode {
  310    SingleLine,
  311    AutoHeight { max_lines: usize },
  312    Full,
  313}
  314
  315#[derive(Clone, Debug)]
  316pub enum SoftWrap {
  317    None,
  318    EditorWidth,
  319    Column(u32),
  320}
  321
  322#[derive(Clone)]
  323pub struct EditorStyle {
  324    pub background: Hsla,
  325    pub local_player: PlayerColor,
  326    pub text: TextStyle,
  327    pub scrollbar_width: Pixels,
  328    pub syntax: Arc<SyntaxTheme>,
  329    pub status: StatusColors,
  330    pub inlay_hints_style: HighlightStyle,
  331    pub suggestions_style: HighlightStyle,
  332}
  333
  334impl Default for EditorStyle {
  335    fn default() -> Self {
  336        Self {
  337            background: Hsla::default(),
  338            local_player: PlayerColor::default(),
  339            text: TextStyle::default(),
  340            scrollbar_width: Pixels::default(),
  341            syntax: Default::default(),
  342            // HACK: Status colors don't have a real default.
  343            // We should look into removing the status colors from the editor
  344            // style and retrieve them directly from the theme.
  345            status: StatusColors::dark(),
  346            inlay_hints_style: HighlightStyle::default(),
  347            suggestions_style: HighlightStyle::default(),
  348        }
  349    }
  350}
  351
  352type CompletionId = usize;
  353
  354// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  355// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  356
  357type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<Range<Anchor>>);
  358
  359/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  360///
  361/// See the [module level documentation](self) for more information.
  362pub struct Editor {
  363    focus_handle: FocusHandle,
  364    /// The text buffer being edited
  365    buffer: Model<MultiBuffer>,
  366    /// Map of how text in the buffer should be displayed.
  367    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  368    pub display_map: Model<DisplayMap>,
  369    pub selections: SelectionsCollection,
  370    pub scroll_manager: ScrollManager,
  371    columnar_selection_tail: Option<Anchor>,
  372    add_selections_state: Option<AddSelectionsState>,
  373    select_next_state: Option<SelectNextState>,
  374    select_prev_state: Option<SelectNextState>,
  375    selection_history: SelectionHistory,
  376    autoclose_regions: Vec<AutocloseRegion>,
  377    snippet_stack: InvalidationStack<SnippetState>,
  378    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  379    ime_transaction: Option<TransactionId>,
  380    active_diagnostics: Option<ActiveDiagnosticGroup>,
  381    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  382    project: Option<Model<Project>>,
  383    completion_provider: Option<Box<dyn CompletionProvider>>,
  384    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  385    blink_manager: Model<BlinkManager>,
  386    show_cursor_names: bool,
  387    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  388    pub show_local_selections: bool,
  389    mode: EditorMode,
  390    show_breadcrumbs: bool,
  391    show_gutter: bool,
  392    show_wrap_guides: Option<bool>,
  393    placeholder_text: Option<Arc<str>>,
  394    highlight_order: usize,
  395    highlighted_rows: HashMap<TypeId, Vec<(usize, Range<Anchor>, Hsla)>>,
  396    background_highlights: BTreeMap<TypeId, BackgroundHighlight>,
  397    nav_history: Option<ItemNavHistory>,
  398    context_menu: RwLock<Option<ContextMenu>>,
  399    mouse_context_menu: Option<MouseContextMenu>,
  400    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  401    find_all_references_task_sources: Vec<Anchor>,
  402    next_completion_id: CompletionId,
  403    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  404    available_code_actions: Option<(Model<Buffer>, Arc<[CodeAction]>)>,
  405    code_actions_task: Option<Task<()>>,
  406    document_highlights_task: Option<Task<()>>,
  407    pending_rename: Option<RenameState>,
  408    searchable: bool,
  409    cursor_shape: CursorShape,
  410    collapse_matches: bool,
  411    autoindent_mode: Option<AutoindentMode>,
  412    workspace: Option<(WeakView<Workspace>, WorkspaceId)>,
  413    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  414    input_enabled: bool,
  415    use_modal_editing: bool,
  416    read_only: bool,
  417    leader_peer_id: Option<PeerId>,
  418    remote_id: Option<ViewId>,
  419    hover_state: HoverState,
  420    gutter_hovered: bool,
  421    hovered_link_state: Option<HoveredLinkState>,
  422    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  423    active_inline_completion: Option<Inlay>,
  424    show_inline_completions: bool,
  425    inlay_hint_cache: InlayHintCache,
  426    next_inlay_id: usize,
  427    _subscriptions: Vec<Subscription>,
  428    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  429    gutter_width: Pixels,
  430    pub vim_replace_map: HashMap<Range<usize>, String>,
  431    style: Option<EditorStyle>,
  432    editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
  433    use_autoclose: bool,
  434    auto_replace_emoji_shortcode: bool,
  435    show_git_blame: bool,
  436    blame: Option<Model<GitBlame>>,
  437    blame_subscription: Option<Subscription>,
  438    custom_context_menu: Option<
  439        Box<
  440            dyn 'static
  441                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  442        >,
  443    >,
  444}
  445
  446pub struct EditorSnapshot {
  447    pub mode: EditorMode,
  448    show_gutter: bool,
  449    show_git_blame: bool,
  450    pub display_snapshot: DisplaySnapshot,
  451    pub placeholder_text: Option<Arc<str>>,
  452    is_focused: bool,
  453    scroll_anchor: ScrollAnchor,
  454    ongoing_scroll: OngoingScroll,
  455}
  456
  457const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  458
  459pub struct GutterDimensions {
  460    pub left_padding: Pixels,
  461    pub right_padding: Pixels,
  462    pub width: Pixels,
  463    pub margin: Pixels,
  464    pub git_blame_entries_width: Option<Pixels>,
  465}
  466
  467impl Default for GutterDimensions {
  468    fn default() -> Self {
  469        Self {
  470            left_padding: Pixels::ZERO,
  471            right_padding: Pixels::ZERO,
  472            width: Pixels::ZERO,
  473            margin: Pixels::ZERO,
  474            git_blame_entries_width: None,
  475        }
  476    }
  477}
  478
  479#[derive(Debug)]
  480pub struct RemoteSelection {
  481    pub replica_id: ReplicaId,
  482    pub selection: Selection<Anchor>,
  483    pub cursor_shape: CursorShape,
  484    pub peer_id: PeerId,
  485    pub line_mode: bool,
  486    pub participant_index: Option<ParticipantIndex>,
  487    pub user_name: Option<SharedString>,
  488}
  489
  490#[derive(Clone, Debug)]
  491struct SelectionHistoryEntry {
  492    selections: Arc<[Selection<Anchor>]>,
  493    select_next_state: Option<SelectNextState>,
  494    select_prev_state: Option<SelectNextState>,
  495    add_selections_state: Option<AddSelectionsState>,
  496}
  497
  498enum SelectionHistoryMode {
  499    Normal,
  500    Undoing,
  501    Redoing,
  502}
  503
  504#[derive(Clone, PartialEq, Eq, Hash)]
  505struct HoveredCursor {
  506    replica_id: u16,
  507    selection_id: usize,
  508}
  509
  510impl Default for SelectionHistoryMode {
  511    fn default() -> Self {
  512        Self::Normal
  513    }
  514}
  515
  516#[derive(Default)]
  517struct SelectionHistory {
  518    #[allow(clippy::type_complexity)]
  519    selections_by_transaction:
  520        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  521    mode: SelectionHistoryMode,
  522    undo_stack: VecDeque<SelectionHistoryEntry>,
  523    redo_stack: VecDeque<SelectionHistoryEntry>,
  524}
  525
  526impl SelectionHistory {
  527    fn insert_transaction(
  528        &mut self,
  529        transaction_id: TransactionId,
  530        selections: Arc<[Selection<Anchor>]>,
  531    ) {
  532        self.selections_by_transaction
  533            .insert(transaction_id, (selections, None));
  534    }
  535
  536    #[allow(clippy::type_complexity)]
  537    fn transaction(
  538        &self,
  539        transaction_id: TransactionId,
  540    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  541        self.selections_by_transaction.get(&transaction_id)
  542    }
  543
  544    #[allow(clippy::type_complexity)]
  545    fn transaction_mut(
  546        &mut self,
  547        transaction_id: TransactionId,
  548    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  549        self.selections_by_transaction.get_mut(&transaction_id)
  550    }
  551
  552    fn push(&mut self, entry: SelectionHistoryEntry) {
  553        if !entry.selections.is_empty() {
  554            match self.mode {
  555                SelectionHistoryMode::Normal => {
  556                    self.push_undo(entry);
  557                    self.redo_stack.clear();
  558                }
  559                SelectionHistoryMode::Undoing => self.push_redo(entry),
  560                SelectionHistoryMode::Redoing => self.push_undo(entry),
  561            }
  562        }
  563    }
  564
  565    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  566        if self
  567            .undo_stack
  568            .back()
  569            .map_or(true, |e| e.selections != entry.selections)
  570        {
  571            self.undo_stack.push_back(entry);
  572            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  573                self.undo_stack.pop_front();
  574            }
  575        }
  576    }
  577
  578    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  579        if self
  580            .redo_stack
  581            .back()
  582            .map_or(true, |e| e.selections != entry.selections)
  583        {
  584            self.redo_stack.push_back(entry);
  585            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  586                self.redo_stack.pop_front();
  587            }
  588        }
  589    }
  590}
  591
  592#[derive(Clone, Debug)]
  593struct AddSelectionsState {
  594    above: bool,
  595    stack: Vec<usize>,
  596}
  597
  598#[derive(Clone)]
  599struct SelectNextState {
  600    query: AhoCorasick,
  601    wordwise: bool,
  602    done: bool,
  603}
  604
  605impl std::fmt::Debug for SelectNextState {
  606    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  607        f.debug_struct(std::any::type_name::<Self>())
  608            .field("wordwise", &self.wordwise)
  609            .field("done", &self.done)
  610            .finish()
  611    }
  612}
  613
  614#[derive(Debug)]
  615struct AutocloseRegion {
  616    selection_id: usize,
  617    range: Range<Anchor>,
  618    pair: BracketPair,
  619}
  620
  621#[derive(Debug)]
  622struct SnippetState {
  623    ranges: Vec<Vec<Range<Anchor>>>,
  624    active_index: usize,
  625}
  626
  627#[doc(hidden)]
  628pub struct RenameState {
  629    pub range: Range<Anchor>,
  630    pub old_name: Arc<str>,
  631    pub editor: View<Editor>,
  632    block_id: BlockId,
  633}
  634
  635struct InvalidationStack<T>(Vec<T>);
  636
  637struct RegisteredInlineCompletionProvider {
  638    provider: Arc<dyn InlineCompletionProviderHandle>,
  639    _subscription: Subscription,
  640}
  641
  642enum ContextMenu {
  643    Completions(CompletionsMenu),
  644    CodeActions(CodeActionsMenu),
  645}
  646
  647impl ContextMenu {
  648    fn select_first(
  649        &mut self,
  650        project: Option<&Model<Project>>,
  651        cx: &mut ViewContext<Editor>,
  652    ) -> bool {
  653        if self.visible() {
  654            match self {
  655                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  656                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  657            }
  658            true
  659        } else {
  660            false
  661        }
  662    }
  663
  664    fn select_prev(
  665        &mut self,
  666        project: Option<&Model<Project>>,
  667        cx: &mut ViewContext<Editor>,
  668    ) -> bool {
  669        if self.visible() {
  670            match self {
  671                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  672                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  673            }
  674            true
  675        } else {
  676            false
  677        }
  678    }
  679
  680    fn select_next(
  681        &mut self,
  682        project: Option<&Model<Project>>,
  683        cx: &mut ViewContext<Editor>,
  684    ) -> bool {
  685        if self.visible() {
  686            match self {
  687                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  688                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  689            }
  690            true
  691        } else {
  692            false
  693        }
  694    }
  695
  696    fn select_last(
  697        &mut self,
  698        project: Option<&Model<Project>>,
  699        cx: &mut ViewContext<Editor>,
  700    ) -> bool {
  701        if self.visible() {
  702            match self {
  703                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  704                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  705            }
  706            true
  707        } else {
  708            false
  709        }
  710    }
  711
  712    fn visible(&self) -> bool {
  713        match self {
  714            ContextMenu::Completions(menu) => menu.visible(),
  715            ContextMenu::CodeActions(menu) => menu.visible(),
  716        }
  717    }
  718
  719    fn render(
  720        &self,
  721        cursor_position: DisplayPoint,
  722        style: &EditorStyle,
  723        max_height: Pixels,
  724        workspace: Option<WeakView<Workspace>>,
  725        cx: &mut ViewContext<Editor>,
  726    ) -> (DisplayPoint, AnyElement) {
  727        match self {
  728            ContextMenu::Completions(menu) => (
  729                cursor_position,
  730                menu.render(style, max_height, workspace, cx),
  731            ),
  732            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  733        }
  734    }
  735}
  736
  737#[derive(Clone)]
  738struct CompletionsMenu {
  739    id: CompletionId,
  740    initial_position: Anchor,
  741    buffer: Model<Buffer>,
  742    completions: Arc<RwLock<Box<[Completion]>>>,
  743    match_candidates: Arc<[StringMatchCandidate]>,
  744    matches: Arc<[StringMatch]>,
  745    selected_item: usize,
  746    scroll_handle: UniformListScrollHandle,
  747    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  748}
  749
  750impl CompletionsMenu {
  751    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  752        self.selected_item = 0;
  753        self.scroll_handle.scroll_to_item(self.selected_item);
  754        self.attempt_resolve_selected_completion_documentation(project, cx);
  755        cx.notify();
  756    }
  757
  758    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  759        if self.selected_item > 0 {
  760            self.selected_item -= 1;
  761        } else {
  762            self.selected_item = self.matches.len() - 1;
  763        }
  764        self.scroll_handle.scroll_to_item(self.selected_item);
  765        self.attempt_resolve_selected_completion_documentation(project, cx);
  766        cx.notify();
  767    }
  768
  769    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  770        if self.selected_item + 1 < self.matches.len() {
  771            self.selected_item += 1;
  772        } else {
  773            self.selected_item = 0;
  774        }
  775        self.scroll_handle.scroll_to_item(self.selected_item);
  776        self.attempt_resolve_selected_completion_documentation(project, cx);
  777        cx.notify();
  778    }
  779
  780    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  781        self.selected_item = self.matches.len() - 1;
  782        self.scroll_handle.scroll_to_item(self.selected_item);
  783        self.attempt_resolve_selected_completion_documentation(project, cx);
  784        cx.notify();
  785    }
  786
  787    fn pre_resolve_completion_documentation(
  788        completions: Arc<RwLock<Box<[Completion]>>>,
  789        matches: Arc<[StringMatch]>,
  790        editor: &Editor,
  791        cx: &mut ViewContext<Editor>,
  792    ) -> Task<()> {
  793        let settings = EditorSettings::get_global(cx);
  794        if !settings.show_completion_documentation {
  795            return Task::ready(());
  796        }
  797
  798        let Some(provider) = editor.completion_provider.as_ref() else {
  799            return Task::ready(());
  800        };
  801
  802        let resolve_task = provider.resolve_completions(
  803            matches.iter().map(|m| m.candidate_id).collect(),
  804            completions.clone(),
  805            cx,
  806        );
  807
  808        return cx.spawn(move |this, mut cx| async move {
  809            if let Some(true) = resolve_task.await.log_err() {
  810                this.update(&mut cx, |_, cx| cx.notify()).ok();
  811            }
  812        });
  813    }
  814
  815    fn attempt_resolve_selected_completion_documentation(
  816        &mut self,
  817        project: Option<&Model<Project>>,
  818        cx: &mut ViewContext<Editor>,
  819    ) {
  820        let settings = EditorSettings::get_global(cx);
  821        if !settings.show_completion_documentation {
  822            return;
  823        }
  824
  825        let completion_index = self.matches[self.selected_item].candidate_id;
  826        let Some(project) = project else {
  827            return;
  828        };
  829
  830        let resolve_task = project.update(cx, |project, cx| {
  831            project.resolve_completions(vec![completion_index], self.completions.clone(), cx)
  832        });
  833
  834        let delay_ms =
  835            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
  836        let delay = Duration::from_millis(delay_ms);
  837
  838        self.selected_completion_documentation_resolve_debounce
  839            .lock()
  840            .fire_new(delay, cx, |_, cx| {
  841                cx.spawn(move |this, mut cx| async move {
  842                    if let Some(true) = resolve_task.await.log_err() {
  843                        this.update(&mut cx, |_, cx| cx.notify()).ok();
  844                    }
  845                })
  846            });
  847    }
  848
  849    fn visible(&self) -> bool {
  850        !self.matches.is_empty()
  851    }
  852
  853    fn render(
  854        &self,
  855        style: &EditorStyle,
  856        max_height: Pixels,
  857        workspace: Option<WeakView<Workspace>>,
  858        cx: &mut ViewContext<Editor>,
  859    ) -> AnyElement {
  860        let settings = EditorSettings::get_global(cx);
  861        let show_completion_documentation = settings.show_completion_documentation;
  862
  863        let font_size = style.text.font_size.to_pixels(cx.rem_size());
  864        let padding_width = cx.rem_size().0 / 16. * 36.;
  865
  866        let max_completion_len = px(510.);
  867        let widest_completion_pixels = self
  868            .matches
  869            .iter()
  870            .map(|mat| {
  871                let completions = self.completions.read();
  872                let completion = &completions[mat.candidate_id];
  873                let documentation = &completion.documentation;
  874
  875                let mut len = completion.label.text.chars().count() as f32;
  876                if let Ok(text_width) = cx.text_system().layout_line(
  877                    completion.label.text.as_str(),
  878                    font_size,
  879                    &[style.text.to_run(completion.label.text.as_str().len())],
  880                ) {
  881                    len = text_width.width.0;
  882                }
  883
  884                if let Some(Documentation::SingleLine(documentation_text)) = documentation {
  885                    if show_completion_documentation {
  886                        if let Ok(documentation_width) = cx.text_system().layout_line(
  887                            documentation_text.as_str(),
  888                            font_size,
  889                            &[style.text.to_run(documentation_text.as_str().len())],
  890                        ) {
  891                            len = documentation_width.width.0 + padding_width;
  892                        }
  893                    }
  894                }
  895                (len + padding_width).min(max_completion_len.0 as f32)
  896            })
  897            .fold(190_f32, |a, b| a.max(b));
  898
  899        let completions = self.completions.clone();
  900        let matches = self.matches.clone();
  901        let selected_item = self.selected_item;
  902        let style = style.clone();
  903
  904        let multiline_docs = if show_completion_documentation {
  905            let mat = &self.matches[selected_item];
  906            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
  907                Some(Documentation::MultiLinePlainText(text)) => {
  908                    Some(div().child(SharedString::from(text.clone())))
  909                }
  910                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
  911                    Some(div().child(render_parsed_markdown(
  912                        "completions_markdown",
  913                        parsed,
  914                        &style,
  915                        workspace,
  916                        cx,
  917                    )))
  918                }
  919                _ => None,
  920            };
  921            multiline_docs.map(|div| {
  922                div.id("multiline_docs")
  923                    .max_h(max_height)
  924                    .flex_1()
  925                    .px_1p5()
  926                    .py_1()
  927                    .min_w(px(260.))
  928                    .max_w(px(640.))
  929                    .w(px(500.))
  930                    .overflow_y_scroll()
  931                    .occlude()
  932            })
  933        } else {
  934            None
  935        };
  936
  937        let list = uniform_list(
  938            cx.view().clone(),
  939            "completions",
  940            matches.len(),
  941            move |_editor, range, cx| {
  942                let start_ix = range.start;
  943                let completions_guard = completions.read();
  944
  945                matches[range]
  946                    .iter()
  947                    .enumerate()
  948                    .map(|(ix, mat)| {
  949                        let item_ix = start_ix + ix;
  950                        let candidate_id = mat.candidate_id;
  951                        let completion = completions_guard[candidate_id].clone();
  952
  953                        let documentation = if show_completion_documentation {
  954                            &completion.documentation
  955                        } else {
  956                            &None
  957                        };
  958
  959                        let (_completion_width, completion_label, documentation_label) =
  960                            Self::truncate_completion(
  961                                &style,
  962                                cx,
  963                                mat,
  964                                &mut completion.clone(),
  965                                documentation,
  966                                max_completion_len,
  967                            );
  968                        div()
  969                            .min_w(px(widest_completion_pixels + padding_width))
  970                            .max_w(max_completion_len + px(padding_width))
  971                            .child(
  972                                ListItem::new(mat.candidate_id)
  973                                    .inset(true)
  974                                    .selected(item_ix == selected_item)
  975                                    .on_click(cx.listener(move |editor, _event, cx| {
  976                                        cx.stop_propagation();
  977                                        if let Some(task) = editor.confirm_completion(
  978                                            &ConfirmCompletion {
  979                                                item_ix: Some(item_ix),
  980                                            },
  981                                            cx,
  982                                        ) {
  983                                            task.detach_and_log_err(cx)
  984                                        }
  985                                    }))
  986                                    .child(h_flex().overflow_hidden().child(completion_label))
  987                                    .end_slot(documentation_label),
  988                            )
  989                    })
  990                    .collect()
  991            },
  992        )
  993        .occlude()
  994        .max_h(max_height)
  995        .track_scroll(self.scroll_handle.clone())
  996        .min_w(px(widest_completion_pixels + padding_width));
  997
  998        Popover::new()
  999            .child(list)
 1000            .when_some(multiline_docs, |popover, multiline_docs| {
 1001                popover.aside(multiline_docs)
 1002            })
 1003            .into_any_element()
 1004    }
 1005
 1006    fn truncate_completion(
 1007        style: &EditorStyle,
 1008        cx: &mut ViewContext<Editor>,
 1009        mat: &StringMatch,
 1010        completion: &mut Completion,
 1011        documentation: &Option<Documentation>,
 1012        max_completion_len: Pixels,
 1013    ) -> (Pixels, StyledText, StyledText) {
 1014        let highlights = gpui::combine_highlights(
 1015            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1016            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1017                |(range, mut highlight)| {
 1018                    // Ignore font weight for syntax highlighting, as we'll use it
 1019                    // for fuzzy matches.
 1020                    highlight.font_weight = None;
 1021                    (range, highlight)
 1022                },
 1023            ),
 1024        );
 1025
 1026        let mut inline_documentation_exists = false;
 1027
 1028        let mut documentation_text = if let Some(Documentation::SingleLine(text)) = documentation {
 1029            inline_documentation_exists = true;
 1030            text
 1031        } else {
 1032            ""
 1033        }
 1034        .to_owned();
 1035        let documentation_style = style.clone().text;
 1036
 1037        let documentation_highlight_style = HighlightStyle {
 1038            color: Some(Color::Muted.color(cx)),
 1039            ..Default::default()
 1040        };
 1041
 1042        let documentation_highlights = vec![(
 1043            Range {
 1044                start: 0,
 1045                end: documentation_text.len(),
 1046            },
 1047            documentation_highlight_style,
 1048        )];
 1049        let documentation_label = StyledText::new(documentation_text.clone())
 1050            .with_highlights(&documentation_style, documentation_highlights);
 1051
 1052        let mut completion_label =
 1053            StyledText::new(completion.label.text.clone()).with_highlights(&style.text, highlights);
 1054
 1055        let font_size = style.text.font_size.to_pixels(cx.rem_size());
 1056
 1057        let mut variable_name_end = completion.label.filter_range.end;
 1058        let mut completion_label_text = completion.label.text.clone();
 1059        let mut variable_name_length_truncated: i32 = 0;
 1060
 1061        let mut actual_width: Pixels = px(0.);
 1062        if let Ok(ellipsis_width) =
 1063            cx.text_system()
 1064                .layout_line("", font_size, &[style.text.to_run("".len())])
 1065        {
 1066            if let Ok(completion_layout_line) = completion_label.layout_line(font_size, cx) {
 1067                if let Ok(documentation_layout_line) =
 1068                    documentation_label.layout_line(font_size, cx)
 1069                {
 1070                    if inline_documentation_exists {
 1071                        if completion_layout_line.width + documentation_layout_line.width
 1072                            > max_completion_len
 1073                        {
 1074                            actual_width = max_completion_len;
 1075                            let width_of_variable_name = completion_layout_line
 1076                                .x_for_index(completion.label.filter_range.end);
 1077                            let width_of_documentation =
 1078                                documentation_layout_line.x_for_index(documentation_text.len());
 1079
 1080                            let max_width_of_variable_name =
 1081                                if width_of_documentation < max_completion_len * 0.2 {
 1082                                    max_completion_len - width_of_documentation
 1083                                } else {
 1084                                    max_completion_len * 0.8
 1085                                };
 1086
 1087                            if width_of_variable_name < max_width_of_variable_name {
 1088                                // Only truncate the second part.
 1089                                if let Some(documentation_truncation_index) =
 1090                                    documentation_layout_line.index_for_x(
 1091                                        (max_completion_len * 0.65).min(
 1092                                            max_completion_len
 1093                                                - ellipsis_width.width
 1094                                                - width_of_variable_name,
 1095                                        ),
 1096                                    )
 1097                                {
 1098                                    variable_name_end = documentation_truncation_index + 2;
 1099                                    documentation_text = documentation_text
 1100                                        .chars()
 1101                                        .take(documentation_truncation_index)
 1102                                        .collect::<String>()
 1103                                        + "";
 1104                                }
 1105                            } else {
 1106                                // Truncate the first part (and optionally the second part).
 1107                                if let Some(variable_name_truncation_index) = completion_layout_line
 1108                                    .index_for_x(max_width_of_variable_name - ellipsis_width.width)
 1109                                {
 1110                                    variable_name_end = variable_name_truncation_index + 2;
 1111                                    variable_name_length_truncated =
 1112                                        completion.label.filter_range.end as i32
 1113                                            - variable_name_end as i32
 1114                                            - 1;
 1115                                    completion_label_text = completion
 1116                                        .label
 1117                                        .text
 1118                                        .chars()
 1119                                        .take(variable_name_truncation_index)
 1120                                        .collect::<String>()
 1121                                        + "";
 1122                                    completion_label =
 1123                                        completion_label.with_text(completion_label_text.clone());
 1124                                    if let Ok(new_completion_layout_line) =
 1125                                        completion_label.layout_line(font_size, cx)
 1126                                    {
 1127                                        let combined_width = new_completion_layout_line
 1128                                            .x_for_index(completion_label_text.len())
 1129                                            + width_of_documentation;
 1130                                        if combined_width > max_completion_len {
 1131                                            if let Some(documentation_truncation_index) =
 1132                                                documentation_layout_line.index_for_x(
 1133                                                    (max_completion_len * 0.65).min(
 1134                                                        max_completion_len
 1135                                                            - ellipsis_width.width
 1136                                                            - max_width_of_variable_name,
 1137                                                    ),
 1138                                                )
 1139                                            {
 1140                                                documentation_text = documentation_text
 1141                                                    .chars()
 1142                                                    .take(documentation_truncation_index)
 1143                                                    .collect::<String>()
 1144                                                    + "";
 1145                                            }
 1146                                        }
 1147                                    }
 1148                                }
 1149                            }
 1150                        } else {
 1151                            actual_width =
 1152                                completion_layout_line.width + documentation_layout_line.width;
 1153                        }
 1154                    } else {
 1155                        if completion_layout_line.width > max_completion_len {
 1156                            actual_width = max_completion_len;
 1157                            let width_of_variable_name = completion_layout_line
 1158                                .x_for_index(completion.label.filter_range.end);
 1159                            let width_of_type_annotation =
 1160                                completion_layout_line.width - width_of_variable_name;
 1161
 1162                            let max_width_of_variable_name =
 1163                                if width_of_type_annotation < max_completion_len * 0.2 {
 1164                                    max_completion_len - width_of_type_annotation
 1165                                } else {
 1166                                    max_completion_len * 0.8
 1167                                };
 1168
 1169                            if width_of_variable_name < max_width_of_variable_name {
 1170                                // Only truncate the second part.
 1171
 1172                                if let Some(type_annotation_truncation_index) =
 1173                                    completion_layout_line
 1174                                        .index_for_x(max_completion_len - ellipsis_width.width)
 1175                                {
 1176                                    completion_label_text = completion
 1177                                        .label
 1178                                        .text
 1179                                        .chars()
 1180                                        .take(type_annotation_truncation_index)
 1181                                        .collect::<String>()
 1182                                        + "";
 1183                                }
 1184                            } else {
 1185                                // Truncate the first part (and optionally the second part).
 1186                                if let Some(variable_name_truncation_index) = completion_layout_line
 1187                                    .index_for_x(max_width_of_variable_name - ellipsis_width.width)
 1188                                {
 1189                                    variable_name_end = variable_name_truncation_index + 2;
 1190
 1191                                    variable_name_length_truncated =
 1192                                        completion.label.filter_range.end as i32
 1193                                            - variable_name_end as i32
 1194                                            - 1;
 1195
 1196                                    let second_part_text = &completion.label.text.as_str()
 1197                                        [completion.label.filter_range.end..];
 1198
 1199                                    completion_label_text = completion
 1200                                        .label
 1201                                        .text
 1202                                        .chars()
 1203                                        .take(variable_name_truncation_index)
 1204                                        .collect::<String>()
 1205                                        + ""
 1206                                        + second_part_text;
 1207                                    completion_label =
 1208                                        completion_label.with_text(completion_label_text.clone());
 1209
 1210                                    if let Ok(layout_line) =
 1211                                        completion_label.layout_line(font_size, cx)
 1212                                    {
 1213                                        let combined_width =
 1214                                            layout_line.x_for_index(completion_label_text.len());
 1215                                        if combined_width > max_completion_len {
 1216                                            if let Some(type_annotation_truncation_index) =
 1217                                                layout_line.index_for_x(
 1218                                                    max_completion_len - ellipsis_width.width,
 1219                                                )
 1220                                            {
 1221                                                completion_label_text = completion_label_text
 1222                                                    .chars()
 1223                                                    .take(type_annotation_truncation_index - 2)
 1224                                                    .collect::<String>()
 1225                                                    + "";
 1226                                            }
 1227                                        }
 1228                                    }
 1229                                }
 1230                            }
 1231                        } else {
 1232                            actual_width = completion_layout_line.width;
 1233                        }
 1234                    }
 1235                }
 1236            }
 1237        };
 1238
 1239        // Recompute syntax highlighting.
 1240        completion.label.text = completion_label_text.clone();
 1241        if inline_documentation_exists {
 1242            completion.label.filter_range.end = completion_label_text.len();
 1243            for run in completion.label.runs.iter_mut() {
 1244                if run.0.start == 0 {
 1245                    run.0.start = 0;
 1246                    run.0.end = completion_label_text.len();
 1247                }
 1248            }
 1249        } else {
 1250            completion.label.filter_range.end = variable_name_end;
 1251            for run in completion.label.runs.iter_mut() {
 1252                if run.0.start == 0 {
 1253                    run.0.start = 0;
 1254                    run.0.end = variable_name_end;
 1255                } else {
 1256                    run.0.start = (run.0.start as i32 - variable_name_length_truncated) as usize;
 1257                    run.0.end = (run.0.end as i32 - variable_name_length_truncated) as usize;
 1258                }
 1259            }
 1260        }
 1261        let highlights = gpui::combine_highlights(
 1262            mat.ranges().map(|range| (range, FontWeight::NORMAL.into())),
 1263            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1264                |(range, mut highlight)| {
 1265                    // Ignore font weight for syntax highlighting, as we'll use it
 1266                    // for fuzzy matches.
 1267                    highlight.font_weight = None;
 1268                    (range, highlight)
 1269                },
 1270            ),
 1271        );
 1272
 1273        let completion_label =
 1274            StyledText::new(completion_label_text).with_highlights(&style.text, highlights);
 1275
 1276        let documentation_style = style.clone().text;
 1277        let documentation_highlight_style = HighlightStyle {
 1278            color: Some(Color::Muted.color(cx)),
 1279            ..Default::default()
 1280        };
 1281        let documentation_highlights = vec![(
 1282            Range {
 1283                start: 0,
 1284                end: documentation_text.len(),
 1285            },
 1286            documentation_highlight_style,
 1287        )];
 1288
 1289        let documentation_label = StyledText::new(documentation_text)
 1290            .with_highlights(&documentation_style, documentation_highlights);
 1291        (actual_width, completion_label, documentation_label)
 1292    }
 1293
 1294    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1295        let mut matches = if let Some(query) = query {
 1296            fuzzy::match_strings(
 1297                &self.match_candidates,
 1298                query,
 1299                query.chars().any(|c| c.is_uppercase()),
 1300                100,
 1301                &Default::default(),
 1302                executor,
 1303            )
 1304            .await
 1305        } else {
 1306            self.match_candidates
 1307                .iter()
 1308                .enumerate()
 1309                .map(|(candidate_id, candidate)| StringMatch {
 1310                    candidate_id,
 1311                    score: Default::default(),
 1312                    positions: Default::default(),
 1313                    string: candidate.string.clone(),
 1314                })
 1315                .collect()
 1316        };
 1317
 1318        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1319        if let Some(query) = query {
 1320            if let Some(query_start) = query.chars().next() {
 1321                matches.retain(|string_match| {
 1322                    split_words(&string_match.string).any(|word| {
 1323                        // Check that the first codepoint of the word as lowercase matches the first
 1324                        // codepoint of the query as lowercase
 1325                        word.chars()
 1326                            .flat_map(|codepoint| codepoint.to_lowercase())
 1327                            .zip(query_start.to_lowercase())
 1328                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1329                    })
 1330                });
 1331            }
 1332        }
 1333
 1334        let completions = self.completions.read();
 1335        matches.sort_unstable_by_key(|mat| {
 1336            // We do want to strike a balance here between what the language server tells us
 1337            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1338            // `Creat` and there is a local variable called `CreateComponent`).
 1339            // So what we do is: we bucket all matches into two buckets
 1340            // - Strong matches
 1341            // - Weak matches
 1342            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1343            // and the Weak matches are the rest.
 1344            //
 1345            // For the strong matches, we sort by the language-servers score first and for the weak
 1346            // matches, we prefer our fuzzy finder first.
 1347            //
 1348            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1349            // us into account when it's obviously a bad match.
 1350
 1351            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1352            enum MatchScore<'a> {
 1353                Strong {
 1354                    sort_text: Option<&'a str>,
 1355                    score: Reverse<OrderedFloat<f64>>,
 1356                    sort_key: (usize, &'a str),
 1357                },
 1358                Weak {
 1359                    score: Reverse<OrderedFloat<f64>>,
 1360                    sort_text: Option<&'a str>,
 1361                    sort_key: (usize, &'a str),
 1362                },
 1363            }
 1364
 1365            let completion = &completions[mat.candidate_id];
 1366            let sort_key = completion.sort_key();
 1367            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1368            let score = Reverse(OrderedFloat(mat.score));
 1369
 1370            if mat.score >= 0.2 {
 1371                MatchScore::Strong {
 1372                    sort_text,
 1373                    score,
 1374                    sort_key,
 1375                }
 1376            } else {
 1377                MatchScore::Weak {
 1378                    score,
 1379                    sort_text,
 1380                    sort_key,
 1381                }
 1382            }
 1383        });
 1384
 1385        for mat in &mut matches {
 1386            let completion = &completions[mat.candidate_id];
 1387            mat.string = completion.label.text.clone();
 1388            for position in &mut mat.positions {
 1389                *position += completion.label.filter_range.start;
 1390            }
 1391        }
 1392        drop(completions);
 1393
 1394        self.matches = matches.into();
 1395        self.selected_item = 0;
 1396    }
 1397}
 1398
 1399#[derive(Clone)]
 1400struct CodeActionsMenu {
 1401    actions: Arc<[CodeAction]>,
 1402    buffer: Model<Buffer>,
 1403    selected_item: usize,
 1404    scroll_handle: UniformListScrollHandle,
 1405    deployed_from_indicator: bool,
 1406}
 1407
 1408impl CodeActionsMenu {
 1409    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1410        self.selected_item = 0;
 1411        self.scroll_handle.scroll_to_item(self.selected_item);
 1412        cx.notify()
 1413    }
 1414
 1415    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1416        if self.selected_item > 0 {
 1417            self.selected_item -= 1;
 1418        } else {
 1419            self.selected_item = self.actions.len() - 1;
 1420        }
 1421        self.scroll_handle.scroll_to_item(self.selected_item);
 1422        cx.notify();
 1423    }
 1424
 1425    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1426        if self.selected_item + 1 < self.actions.len() {
 1427            self.selected_item += 1;
 1428        } else {
 1429            self.selected_item = 0;
 1430        }
 1431        self.scroll_handle.scroll_to_item(self.selected_item);
 1432        cx.notify();
 1433    }
 1434
 1435    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1436        self.selected_item = self.actions.len() - 1;
 1437        self.scroll_handle.scroll_to_item(self.selected_item);
 1438        cx.notify()
 1439    }
 1440
 1441    fn visible(&self) -> bool {
 1442        !self.actions.is_empty()
 1443    }
 1444
 1445    fn render(
 1446        &self,
 1447        mut cursor_position: DisplayPoint,
 1448        _style: &EditorStyle,
 1449        max_height: Pixels,
 1450        cx: &mut ViewContext<Editor>,
 1451    ) -> (DisplayPoint, AnyElement) {
 1452        let actions = self.actions.clone();
 1453        let selected_item = self.selected_item;
 1454
 1455        let element = uniform_list(
 1456            cx.view().clone(),
 1457            "code_actions_menu",
 1458            self.actions.len(),
 1459            move |_this, range, cx| {
 1460                actions[range.clone()]
 1461                    .iter()
 1462                    .enumerate()
 1463                    .map(|(ix, action)| {
 1464                        let item_ix = range.start + ix;
 1465                        let selected = selected_item == item_ix;
 1466                        let colors = cx.theme().colors();
 1467                        div()
 1468                            .px_2()
 1469                            .text_color(colors.text)
 1470                            .when(selected, |style| {
 1471                                style
 1472                                    .bg(colors.element_active)
 1473                                    .text_color(colors.text_accent)
 1474                            })
 1475                            .hover(|style| {
 1476                                style
 1477                                    .bg(colors.element_hover)
 1478                                    .text_color(colors.text_accent)
 1479                            })
 1480                            .on_mouse_down(
 1481                                MouseButton::Left,
 1482                                cx.listener(move |editor, _, cx| {
 1483                                    cx.stop_propagation();
 1484                                    if let Some(task) = editor.confirm_code_action(
 1485                                        &ConfirmCodeAction {
 1486                                            item_ix: Some(item_ix),
 1487                                        },
 1488                                        cx,
 1489                                    ) {
 1490                                        task.detach_and_log_err(cx)
 1491                                    }
 1492                                }),
 1493                            )
 1494                            .whitespace_nowrap()
 1495                            // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1496                            .child(SharedString::from(action.lsp_action.title.clone()))
 1497                    })
 1498                    .collect()
 1499            },
 1500        )
 1501        .elevation_1(cx)
 1502        .px_2()
 1503        .py_1()
 1504        .max_h(max_height)
 1505        .occlude()
 1506        .track_scroll(self.scroll_handle.clone())
 1507        .with_width_from_item(
 1508            self.actions
 1509                .iter()
 1510                .enumerate()
 1511                .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
 1512                .map(|(ix, _)| ix),
 1513        )
 1514        .into_any_element();
 1515
 1516        if self.deployed_from_indicator {
 1517            *cursor_position.column_mut() = 0;
 1518        }
 1519
 1520        (cursor_position, element)
 1521    }
 1522}
 1523
 1524#[derive(Debug)]
 1525struct ActiveDiagnosticGroup {
 1526    primary_range: Range<Anchor>,
 1527    primary_message: String,
 1528    blocks: HashMap<BlockId, Diagnostic>,
 1529    is_valid: bool,
 1530}
 1531
 1532#[derive(Serialize, Deserialize)]
 1533pub struct ClipboardSelection {
 1534    pub len: usize,
 1535    pub is_entire_line: bool,
 1536    pub first_line_indent: u32,
 1537}
 1538
 1539#[derive(Debug)]
 1540pub(crate) struct NavigationData {
 1541    cursor_anchor: Anchor,
 1542    cursor_position: Point,
 1543    scroll_anchor: ScrollAnchor,
 1544    scroll_top_row: u32,
 1545}
 1546
 1547enum GotoDefinitionKind {
 1548    Symbol,
 1549    Type,
 1550    Implementation,
 1551}
 1552
 1553#[derive(Debug, Clone)]
 1554enum InlayHintRefreshReason {
 1555    Toggle(bool),
 1556    SettingsChange(InlayHintSettings),
 1557    NewLinesShown,
 1558    BufferEdited(HashSet<Arc<Language>>),
 1559    RefreshRequested,
 1560    ExcerptsRemoved(Vec<ExcerptId>),
 1561}
 1562
 1563impl InlayHintRefreshReason {
 1564    fn description(&self) -> &'static str {
 1565        match self {
 1566            Self::Toggle(_) => "toggle",
 1567            Self::SettingsChange(_) => "settings change",
 1568            Self::NewLinesShown => "new lines shown",
 1569            Self::BufferEdited(_) => "buffer edited",
 1570            Self::RefreshRequested => "refresh requested",
 1571            Self::ExcerptsRemoved(_) => "excerpts removed",
 1572        }
 1573    }
 1574}
 1575
 1576impl Editor {
 1577    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1578        let buffer = cx.new_model(|cx| {
 1579            Buffer::new(
 1580                0,
 1581                BufferId::new(cx.entity_id().as_u64()).unwrap(),
 1582                String::new(),
 1583            )
 1584        });
 1585        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1586        Self::new(EditorMode::SingleLine, buffer, None, cx)
 1587    }
 1588
 1589    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1590        let buffer = cx.new_model(|cx| {
 1591            Buffer::new(
 1592                0,
 1593                BufferId::new(cx.entity_id().as_u64()).unwrap(),
 1594                String::new(),
 1595            )
 1596        });
 1597        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1598        Self::new(EditorMode::Full, buffer, None, cx)
 1599    }
 1600
 1601    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1602        let buffer = cx.new_model(|cx| {
 1603            Buffer::new(
 1604                0,
 1605                BufferId::new(cx.entity_id().as_u64()).unwrap(),
 1606                String::new(),
 1607            )
 1608        });
 1609        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1610        Self::new(EditorMode::AutoHeight { max_lines }, buffer, None, cx)
 1611    }
 1612
 1613    pub fn for_buffer(
 1614        buffer: Model<Buffer>,
 1615        project: Option<Model<Project>>,
 1616        cx: &mut ViewContext<Self>,
 1617    ) -> Self {
 1618        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1619        Self::new(EditorMode::Full, buffer, project, cx)
 1620    }
 1621
 1622    pub fn for_multibuffer(
 1623        buffer: Model<MultiBuffer>,
 1624        project: Option<Model<Project>>,
 1625        cx: &mut ViewContext<Self>,
 1626    ) -> Self {
 1627        Self::new(EditorMode::Full, buffer, project, cx)
 1628    }
 1629
 1630    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1631        let mut clone = Self::new(self.mode, self.buffer.clone(), self.project.clone(), cx);
 1632        self.display_map.update(cx, |display_map, cx| {
 1633            let snapshot = display_map.snapshot(cx);
 1634            clone.display_map.update(cx, |display_map, cx| {
 1635                display_map.set_state(&snapshot, cx);
 1636            });
 1637        });
 1638        clone.selections.clone_state(&self.selections);
 1639        clone.scroll_manager.clone_state(&self.scroll_manager);
 1640        clone.searchable = self.searchable;
 1641        clone
 1642    }
 1643
 1644    fn new(
 1645        mode: EditorMode,
 1646        buffer: Model<MultiBuffer>,
 1647        project: Option<Model<Project>>,
 1648        cx: &mut ViewContext<Self>,
 1649    ) -> Self {
 1650        let style = cx.text_style();
 1651        let font_size = style.font_size.to_pixels(cx.rem_size());
 1652        let display_map = cx.new_model(|cx| {
 1653            DisplayMap::new(buffer.clone(), style.font(), font_size, None, 2, 1, cx)
 1654        });
 1655
 1656        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1657
 1658        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1659
 1660        let soft_wrap_mode_override =
 1661            (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::None);
 1662
 1663        let mut project_subscriptions = Vec::new();
 1664        if mode == EditorMode::Full {
 1665            if let Some(project) = project.as_ref() {
 1666                if buffer.read(cx).is_singleton() {
 1667                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1668                        cx.emit(EditorEvent::TitleChanged);
 1669                    }));
 1670                }
 1671                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1672                    if let project::Event::RefreshInlayHints = event {
 1673                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1674                    };
 1675                }));
 1676            }
 1677        }
 1678
 1679        let inlay_hint_settings = inlay_hint_settings(
 1680            selections.newest_anchor().head(),
 1681            &buffer.read(cx).snapshot(cx),
 1682            cx,
 1683        );
 1684
 1685        let focus_handle = cx.focus_handle();
 1686        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1687        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1688
 1689        let mut this = Self {
 1690            focus_handle,
 1691            buffer: buffer.clone(),
 1692            display_map: display_map.clone(),
 1693            selections,
 1694            scroll_manager: ScrollManager::new(cx),
 1695            columnar_selection_tail: None,
 1696            add_selections_state: None,
 1697            select_next_state: None,
 1698            select_prev_state: None,
 1699            selection_history: Default::default(),
 1700            autoclose_regions: Default::default(),
 1701            snippet_stack: Default::default(),
 1702            select_larger_syntax_node_stack: Vec::new(),
 1703            ime_transaction: Default::default(),
 1704            active_diagnostics: None,
 1705            soft_wrap_mode_override,
 1706            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1707            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1708            project,
 1709            blink_manager: blink_manager.clone(),
 1710            show_local_selections: true,
 1711            mode,
 1712            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1713            show_gutter: mode == EditorMode::Full,
 1714            show_wrap_guides: None,
 1715            placeholder_text: None,
 1716            highlight_order: 0,
 1717            highlighted_rows: HashMap::default(),
 1718            background_highlights: Default::default(),
 1719            nav_history: None,
 1720            context_menu: RwLock::new(None),
 1721            mouse_context_menu: None,
 1722            completion_tasks: Default::default(),
 1723            find_all_references_task_sources: Vec::new(),
 1724            next_completion_id: 0,
 1725            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1726            next_inlay_id: 0,
 1727            available_code_actions: Default::default(),
 1728            code_actions_task: Default::default(),
 1729            document_highlights_task: Default::default(),
 1730            pending_rename: Default::default(),
 1731            searchable: true,
 1732            cursor_shape: Default::default(),
 1733            autoindent_mode: Some(AutoindentMode::EachLine),
 1734            collapse_matches: false,
 1735            workspace: None,
 1736            keymap_context_layers: Default::default(),
 1737            input_enabled: true,
 1738            use_modal_editing: mode == EditorMode::Full,
 1739            read_only: false,
 1740            use_autoclose: true,
 1741            auto_replace_emoji_shortcode: false,
 1742            leader_peer_id: None,
 1743            remote_id: None,
 1744            hover_state: Default::default(),
 1745            hovered_link_state: Default::default(),
 1746            inline_completion_provider: None,
 1747            active_inline_completion: None,
 1748            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1749            gutter_hovered: false,
 1750            pixel_position_of_newest_cursor: None,
 1751            gutter_width: Default::default(),
 1752            style: None,
 1753            show_cursor_names: false,
 1754            hovered_cursors: Default::default(),
 1755            editor_actions: Default::default(),
 1756            vim_replace_map: Default::default(),
 1757            show_inline_completions: mode == EditorMode::Full,
 1758            custom_context_menu: None,
 1759            show_git_blame: false,
 1760            blame: None,
 1761            blame_subscription: None,
 1762            _subscriptions: vec![
 1763                cx.observe(&buffer, Self::on_buffer_changed),
 1764                cx.subscribe(&buffer, Self::on_buffer_event),
 1765                cx.observe(&display_map, Self::on_display_map_changed),
 1766                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1767                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1768                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1769                cx.observe_window_activation(|editor, cx| {
 1770                    let active = cx.is_window_active();
 1771                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1772                        if active {
 1773                            blink_manager.enable(cx);
 1774                        } else {
 1775                            blink_manager.show_cursor(cx);
 1776                            blink_manager.disable(cx);
 1777                        }
 1778                    });
 1779                }),
 1780            ],
 1781        };
 1782
 1783        this._subscriptions.extend(project_subscriptions);
 1784
 1785        this.end_selection(cx);
 1786        this.scroll_manager.show_scrollbar(cx);
 1787
 1788        if mode == EditorMode::Full {
 1789            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1790            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1791        }
 1792
 1793        this.report_editor_event("open", None, cx);
 1794        this
 1795    }
 1796
 1797    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1798        let mut key_context = KeyContext::default();
 1799        key_context.add("Editor");
 1800        let mode = match self.mode {
 1801            EditorMode::SingleLine => "single_line",
 1802            EditorMode::AutoHeight { .. } => "auto_height",
 1803            EditorMode::Full => "full",
 1804        };
 1805        key_context.set("mode", mode);
 1806        if self.pending_rename.is_some() {
 1807            key_context.add("renaming");
 1808        }
 1809        if self.context_menu_visible() {
 1810            match self.context_menu.read().as_ref() {
 1811                Some(ContextMenu::Completions(_)) => {
 1812                    key_context.add("menu");
 1813                    key_context.add("showing_completions")
 1814                }
 1815                Some(ContextMenu::CodeActions(_)) => {
 1816                    key_context.add("menu");
 1817                    key_context.add("showing_code_actions")
 1818                }
 1819                None => {}
 1820            }
 1821        }
 1822
 1823        for layer in self.keymap_context_layers.values() {
 1824            key_context.extend(layer);
 1825        }
 1826
 1827        if let Some(extension) = self
 1828            .buffer
 1829            .read(cx)
 1830            .as_singleton()
 1831            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1832        {
 1833            key_context.set("extension", extension.to_string());
 1834        }
 1835
 1836        if self.has_active_inline_completion(cx) {
 1837            key_context.add("copilot_suggestion");
 1838            key_context.add("inline_completion");
 1839        }
 1840
 1841        key_context
 1842    }
 1843
 1844    pub fn new_file(
 1845        workspace: &mut Workspace,
 1846        _: &workspace::NewFile,
 1847        cx: &mut ViewContext<Workspace>,
 1848    ) {
 1849        let project = workspace.project().clone();
 1850        if project.read(cx).is_remote() {
 1851            cx.propagate();
 1852        } else if let Some(buffer) = project
 1853            .update(cx, |project, cx| project.create_buffer("", None, cx))
 1854            .log_err()
 1855        {
 1856            workspace.add_item_to_active_pane(
 1857                Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
 1858                cx,
 1859            );
 1860        }
 1861    }
 1862
 1863    pub fn new_file_in_direction(
 1864        workspace: &mut Workspace,
 1865        action: &workspace::NewFileInDirection,
 1866        cx: &mut ViewContext<Workspace>,
 1867    ) {
 1868        let project = workspace.project().clone();
 1869        if project.read(cx).is_remote() {
 1870            cx.propagate();
 1871        } else if let Some(buffer) = project
 1872            .update(cx, |project, cx| project.create_buffer("", None, cx))
 1873            .log_err()
 1874        {
 1875            workspace.split_item(
 1876                action.0,
 1877                Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
 1878                cx,
 1879            );
 1880        }
 1881    }
 1882
 1883    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 1884        self.buffer.read(cx).replica_id()
 1885    }
 1886
 1887    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1888        self.leader_peer_id
 1889    }
 1890
 1891    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1892        &self.buffer
 1893    }
 1894
 1895    pub fn workspace(&self) -> Option<View<Workspace>> {
 1896        self.workspace.as_ref()?.0.upgrade()
 1897    }
 1898
 1899    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1900        self.buffer().read(cx).title(cx)
 1901    }
 1902
 1903    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1904        EditorSnapshot {
 1905            mode: self.mode,
 1906            show_gutter: self.show_gutter,
 1907            show_git_blame: self
 1908                .blame
 1909                .as_ref()
 1910                .map_or(false, |blame| blame.read(cx).has_generated_entries()),
 1911            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1912            scroll_anchor: self.scroll_manager.anchor(),
 1913            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1914            placeholder_text: self.placeholder_text.clone(),
 1915            is_focused: self.focus_handle.is_focused(cx),
 1916        }
 1917    }
 1918
 1919    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1920        self.buffer.read(cx).language_at(point, cx)
 1921    }
 1922
 1923    pub fn file_at<T: ToOffset>(
 1924        &self,
 1925        point: T,
 1926        cx: &AppContext,
 1927    ) -> Option<Arc<dyn language::File>> {
 1928        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1929    }
 1930
 1931    pub fn active_excerpt(
 1932        &self,
 1933        cx: &AppContext,
 1934    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1935        self.buffer
 1936            .read(cx)
 1937            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1938    }
 1939
 1940    pub fn mode(&self) -> EditorMode {
 1941        self.mode
 1942    }
 1943
 1944    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1945        self.collaboration_hub.as_deref()
 1946    }
 1947
 1948    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1949        self.collaboration_hub = Some(hub);
 1950    }
 1951
 1952    pub fn set_custom_context_menu(
 1953        &mut self,
 1954        f: impl 'static
 1955            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1956    ) {
 1957        self.custom_context_menu = Some(Box::new(f))
 1958    }
 1959
 1960    pub fn set_completion_provider(&mut self, hub: Box<dyn CompletionProvider>) {
 1961        self.completion_provider = Some(hub);
 1962    }
 1963
 1964    pub fn set_inline_completion_provider(
 1965        &mut self,
 1966        provider: Model<impl InlineCompletionProvider>,
 1967        cx: &mut ViewContext<Self>,
 1968    ) {
 1969        self.inline_completion_provider = Some(RegisteredInlineCompletionProvider {
 1970            _subscription: cx.observe(&provider, |this, _, cx| {
 1971                if this.focus_handle.is_focused(cx) {
 1972                    this.update_visible_inline_completion(cx);
 1973                }
 1974            }),
 1975            provider: Arc::new(provider),
 1976        });
 1977        self.refresh_inline_completion(false, cx);
 1978    }
 1979
 1980    pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
 1981        self.placeholder_text.as_deref()
 1982    }
 1983
 1984    pub fn set_placeholder_text(
 1985        &mut self,
 1986        placeholder_text: impl Into<Arc<str>>,
 1987        cx: &mut ViewContext<Self>,
 1988    ) {
 1989        let placeholder_text = Some(placeholder_text.into());
 1990        if self.placeholder_text != placeholder_text {
 1991            self.placeholder_text = placeholder_text;
 1992            cx.notify();
 1993        }
 1994    }
 1995
 1996    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1997        self.cursor_shape = cursor_shape;
 1998        cx.notify();
 1999    }
 2000
 2001    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2002        self.collapse_matches = collapse_matches;
 2003    }
 2004
 2005    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2006        if self.collapse_matches {
 2007            return range.start..range.start;
 2008        }
 2009        range.clone()
 2010    }
 2011
 2012    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2013        if self.display_map.read(cx).clip_at_line_ends != clip {
 2014            self.display_map
 2015                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2016        }
 2017    }
 2018
 2019    pub fn set_keymap_context_layer<Tag: 'static>(
 2020        &mut self,
 2021        context: KeyContext,
 2022        cx: &mut ViewContext<Self>,
 2023    ) {
 2024        self.keymap_context_layers
 2025            .insert(TypeId::of::<Tag>(), context);
 2026        cx.notify();
 2027    }
 2028
 2029    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2030        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2031        cx.notify();
 2032    }
 2033
 2034    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2035        self.input_enabled = input_enabled;
 2036    }
 2037
 2038    pub fn set_autoindent(&mut self, autoindent: bool) {
 2039        if autoindent {
 2040            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2041        } else {
 2042            self.autoindent_mode = None;
 2043        }
 2044    }
 2045
 2046    pub fn read_only(&self, cx: &AppContext) -> bool {
 2047        self.read_only || self.buffer.read(cx).read_only()
 2048    }
 2049
 2050    pub fn set_read_only(&mut self, read_only: bool) {
 2051        self.read_only = read_only;
 2052    }
 2053
 2054    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2055        self.use_autoclose = autoclose;
 2056    }
 2057
 2058    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2059        self.auto_replace_emoji_shortcode = auto_replace;
 2060    }
 2061
 2062    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2063        self.show_inline_completions = show_inline_completions;
 2064    }
 2065
 2066    pub fn set_use_modal_editing(&mut self, to: bool) {
 2067        self.use_modal_editing = to;
 2068    }
 2069
 2070    pub fn use_modal_editing(&self) -> bool {
 2071        self.use_modal_editing
 2072    }
 2073
 2074    fn selections_did_change(
 2075        &mut self,
 2076        local: bool,
 2077        old_cursor_position: &Anchor,
 2078        cx: &mut ViewContext<Self>,
 2079    ) {
 2080        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2081            self.buffer.update(cx, |buffer, cx| {
 2082                buffer.set_active_selections(
 2083                    &self.selections.disjoint_anchors(),
 2084                    self.selections.line_mode,
 2085                    self.cursor_shape,
 2086                    cx,
 2087                )
 2088            });
 2089        }
 2090
 2091        let display_map = self
 2092            .display_map
 2093            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2094        let buffer = &display_map.buffer_snapshot;
 2095        self.add_selections_state = None;
 2096        self.select_next_state = None;
 2097        self.select_prev_state = None;
 2098        self.select_larger_syntax_node_stack.clear();
 2099        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2100        self.snippet_stack
 2101            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2102        self.take_rename(false, cx);
 2103
 2104        let new_cursor_position = self.selections.newest_anchor().head();
 2105
 2106        self.push_to_nav_history(
 2107            *old_cursor_position,
 2108            Some(new_cursor_position.to_point(buffer)),
 2109            cx,
 2110        );
 2111
 2112        if local {
 2113            let new_cursor_position = self.selections.newest_anchor().head();
 2114            let mut context_menu = self.context_menu.write();
 2115            let completion_menu = match context_menu.as_ref() {
 2116                Some(ContextMenu::Completions(menu)) => Some(menu),
 2117
 2118                _ => {
 2119                    *context_menu = None;
 2120                    None
 2121                }
 2122            };
 2123
 2124            if let Some(completion_menu) = completion_menu {
 2125                let cursor_position = new_cursor_position.to_offset(buffer);
 2126                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2127                if kind == Some(CharKind::Word)
 2128                    && word_range.to_inclusive().contains(&cursor_position)
 2129                {
 2130                    let mut completion_menu = completion_menu.clone();
 2131                    drop(context_menu);
 2132
 2133                    let query = Self::completion_query(buffer, cursor_position);
 2134                    cx.spawn(move |this, mut cx| async move {
 2135                        completion_menu
 2136                            .filter(query.as_deref(), cx.background_executor().clone())
 2137                            .await;
 2138
 2139                        this.update(&mut cx, |this, cx| {
 2140                            let mut context_menu = this.context_menu.write();
 2141                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2142                                return;
 2143                            };
 2144
 2145                            if menu.id > completion_menu.id {
 2146                                return;
 2147                            }
 2148
 2149                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2150                            drop(context_menu);
 2151                            cx.notify();
 2152                        })
 2153                    })
 2154                    .detach();
 2155
 2156                    self.show_completions(&ShowCompletions, cx);
 2157                } else {
 2158                    drop(context_menu);
 2159                    self.hide_context_menu(cx);
 2160                }
 2161            } else {
 2162                drop(context_menu);
 2163            }
 2164
 2165            hide_hover(self, cx);
 2166
 2167            if old_cursor_position.to_display_point(&display_map).row()
 2168                != new_cursor_position.to_display_point(&display_map).row()
 2169            {
 2170                self.available_code_actions.take();
 2171            }
 2172            self.refresh_code_actions(cx);
 2173            self.refresh_document_highlights(cx);
 2174            refresh_matching_bracket_highlights(self, cx);
 2175            self.discard_inline_completion(cx);
 2176        }
 2177
 2178        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2179        cx.emit(EditorEvent::SelectionsChanged { local });
 2180
 2181        if self.selections.disjoint_anchors().len() == 1 {
 2182            cx.emit(SearchEvent::ActiveMatchChanged)
 2183        }
 2184
 2185        cx.notify();
 2186    }
 2187
 2188    pub fn change_selections<R>(
 2189        &mut self,
 2190        autoscroll: Option<Autoscroll>,
 2191        cx: &mut ViewContext<Self>,
 2192        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2193    ) -> R {
 2194        let old_cursor_position = self.selections.newest_anchor().head();
 2195        self.push_to_selection_history();
 2196
 2197        let (changed, result) = self.selections.change_with(cx, change);
 2198
 2199        if changed {
 2200            if let Some(autoscroll) = autoscroll {
 2201                self.request_autoscroll(autoscroll, cx);
 2202            }
 2203            self.selections_did_change(true, &old_cursor_position, cx);
 2204        }
 2205
 2206        result
 2207    }
 2208
 2209    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2210    where
 2211        I: IntoIterator<Item = (Range<S>, T)>,
 2212        S: ToOffset,
 2213        T: Into<Arc<str>>,
 2214    {
 2215        if self.read_only(cx) {
 2216            return;
 2217        }
 2218
 2219        self.buffer
 2220            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2221    }
 2222
 2223    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2224    where
 2225        I: IntoIterator<Item = (Range<S>, T)>,
 2226        S: ToOffset,
 2227        T: Into<Arc<str>>,
 2228    {
 2229        if self.read_only(cx) {
 2230            return;
 2231        }
 2232
 2233        self.buffer.update(cx, |buffer, cx| {
 2234            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2235        });
 2236    }
 2237
 2238    pub fn edit_with_block_indent<I, S, T>(
 2239        &mut self,
 2240        edits: I,
 2241        original_indent_columns: Vec<u32>,
 2242        cx: &mut ViewContext<Self>,
 2243    ) where
 2244        I: IntoIterator<Item = (Range<S>, T)>,
 2245        S: ToOffset,
 2246        T: Into<Arc<str>>,
 2247    {
 2248        if self.read_only(cx) {
 2249            return;
 2250        }
 2251
 2252        self.buffer.update(cx, |buffer, cx| {
 2253            buffer.edit(
 2254                edits,
 2255                Some(AutoindentMode::Block {
 2256                    original_indent_columns,
 2257                }),
 2258                cx,
 2259            )
 2260        });
 2261    }
 2262
 2263    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2264        self.hide_context_menu(cx);
 2265
 2266        match phase {
 2267            SelectPhase::Begin {
 2268                position,
 2269                add,
 2270                click_count,
 2271            } => self.begin_selection(position, add, click_count, cx),
 2272            SelectPhase::BeginColumnar {
 2273                position,
 2274                goal_column,
 2275            } => self.begin_columnar_selection(position, goal_column, cx),
 2276            SelectPhase::Extend {
 2277                position,
 2278                click_count,
 2279            } => self.extend_selection(position, click_count, cx),
 2280            SelectPhase::Update {
 2281                position,
 2282                goal_column,
 2283                scroll_delta,
 2284            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2285            SelectPhase::End => self.end_selection(cx),
 2286        }
 2287    }
 2288
 2289    fn extend_selection(
 2290        &mut self,
 2291        position: DisplayPoint,
 2292        click_count: usize,
 2293        cx: &mut ViewContext<Self>,
 2294    ) {
 2295        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2296        let tail = self.selections.newest::<usize>(cx).tail();
 2297        self.begin_selection(position, false, click_count, cx);
 2298
 2299        let position = position.to_offset(&display_map, Bias::Left);
 2300        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2301
 2302        let mut pending_selection = self
 2303            .selections
 2304            .pending_anchor()
 2305            .expect("extend_selection not called with pending selection");
 2306        if position >= tail {
 2307            pending_selection.start = tail_anchor;
 2308        } else {
 2309            pending_selection.end = tail_anchor;
 2310            pending_selection.reversed = true;
 2311        }
 2312
 2313        let mut pending_mode = self.selections.pending_mode().unwrap();
 2314        match &mut pending_mode {
 2315            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2316            _ => {}
 2317        }
 2318
 2319        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2320            s.set_pending(pending_selection, pending_mode)
 2321        });
 2322    }
 2323
 2324    fn begin_selection(
 2325        &mut self,
 2326        position: DisplayPoint,
 2327        add: bool,
 2328        click_count: usize,
 2329        cx: &mut ViewContext<Self>,
 2330    ) {
 2331        if !self.focus_handle.is_focused(cx) {
 2332            cx.focus(&self.focus_handle);
 2333        }
 2334
 2335        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2336        let buffer = &display_map.buffer_snapshot;
 2337        let newest_selection = self.selections.newest_anchor().clone();
 2338        let position = display_map.clip_point(position, Bias::Left);
 2339
 2340        let start;
 2341        let end;
 2342        let mode;
 2343        let auto_scroll;
 2344        match click_count {
 2345            1 => {
 2346                start = buffer.anchor_before(position.to_point(&display_map));
 2347                end = start;
 2348                mode = SelectMode::Character;
 2349                auto_scroll = true;
 2350            }
 2351            2 => {
 2352                let range = movement::surrounding_word(&display_map, position);
 2353                start = buffer.anchor_before(range.start.to_point(&display_map));
 2354                end = buffer.anchor_before(range.end.to_point(&display_map));
 2355                mode = SelectMode::Word(start..end);
 2356                auto_scroll = true;
 2357            }
 2358            3 => {
 2359                let position = display_map
 2360                    .clip_point(position, Bias::Left)
 2361                    .to_point(&display_map);
 2362                let line_start = display_map.prev_line_boundary(position).0;
 2363                let next_line_start = buffer.clip_point(
 2364                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2365                    Bias::Left,
 2366                );
 2367                start = buffer.anchor_before(line_start);
 2368                end = buffer.anchor_before(next_line_start);
 2369                mode = SelectMode::Line(start..end);
 2370                auto_scroll = true;
 2371            }
 2372            _ => {
 2373                start = buffer.anchor_before(0);
 2374                end = buffer.anchor_before(buffer.len());
 2375                mode = SelectMode::All;
 2376                auto_scroll = false;
 2377            }
 2378        }
 2379
 2380        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2381            if !add {
 2382                s.clear_disjoint();
 2383            } else if click_count > 1 {
 2384                s.delete(newest_selection.id)
 2385            }
 2386
 2387            s.set_pending_anchor_range(start..end, mode);
 2388        });
 2389    }
 2390
 2391    fn begin_columnar_selection(
 2392        &mut self,
 2393        position: DisplayPoint,
 2394        goal_column: u32,
 2395        cx: &mut ViewContext<Self>,
 2396    ) {
 2397        if !self.focus_handle.is_focused(cx) {
 2398            cx.focus(&self.focus_handle);
 2399        }
 2400
 2401        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2402        let tail = self.selections.newest::<Point>(cx).tail();
 2403        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2404
 2405        self.select_columns(
 2406            tail.to_display_point(&display_map),
 2407            position,
 2408            goal_column,
 2409            &display_map,
 2410            cx,
 2411        );
 2412    }
 2413
 2414    fn update_selection(
 2415        &mut self,
 2416        position: DisplayPoint,
 2417        goal_column: u32,
 2418        scroll_delta: gpui::Point<f32>,
 2419        cx: &mut ViewContext<Self>,
 2420    ) {
 2421        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2422
 2423        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2424            let tail = tail.to_display_point(&display_map);
 2425            self.select_columns(tail, position, goal_column, &display_map, cx);
 2426        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2427            let buffer = self.buffer.read(cx).snapshot(cx);
 2428            let head;
 2429            let tail;
 2430            let mode = self.selections.pending_mode().unwrap();
 2431            match &mode {
 2432                SelectMode::Character => {
 2433                    head = position.to_point(&display_map);
 2434                    tail = pending.tail().to_point(&buffer);
 2435                }
 2436                SelectMode::Word(original_range) => {
 2437                    let original_display_range = original_range.start.to_display_point(&display_map)
 2438                        ..original_range.end.to_display_point(&display_map);
 2439                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2440                        ..original_display_range.end.to_point(&display_map);
 2441                    if movement::is_inside_word(&display_map, position)
 2442                        || original_display_range.contains(&position)
 2443                    {
 2444                        let word_range = movement::surrounding_word(&display_map, position);
 2445                        if word_range.start < original_display_range.start {
 2446                            head = word_range.start.to_point(&display_map);
 2447                        } else {
 2448                            head = word_range.end.to_point(&display_map);
 2449                        }
 2450                    } else {
 2451                        head = position.to_point(&display_map);
 2452                    }
 2453
 2454                    if head <= original_buffer_range.start {
 2455                        tail = original_buffer_range.end;
 2456                    } else {
 2457                        tail = original_buffer_range.start;
 2458                    }
 2459                }
 2460                SelectMode::Line(original_range) => {
 2461                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2462
 2463                    let position = display_map
 2464                        .clip_point(position, Bias::Left)
 2465                        .to_point(&display_map);
 2466                    let line_start = display_map.prev_line_boundary(position).0;
 2467                    let next_line_start = buffer.clip_point(
 2468                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2469                        Bias::Left,
 2470                    );
 2471
 2472                    if line_start < original_range.start {
 2473                        head = line_start
 2474                    } else {
 2475                        head = next_line_start
 2476                    }
 2477
 2478                    if head <= original_range.start {
 2479                        tail = original_range.end;
 2480                    } else {
 2481                        tail = original_range.start;
 2482                    }
 2483                }
 2484                SelectMode::All => {
 2485                    return;
 2486                }
 2487            };
 2488
 2489            if head < tail {
 2490                pending.start = buffer.anchor_before(head);
 2491                pending.end = buffer.anchor_before(tail);
 2492                pending.reversed = true;
 2493            } else {
 2494                pending.start = buffer.anchor_before(tail);
 2495                pending.end = buffer.anchor_before(head);
 2496                pending.reversed = false;
 2497            }
 2498
 2499            self.change_selections(None, cx, |s| {
 2500                s.set_pending(pending, mode);
 2501            });
 2502        } else {
 2503            log::error!("update_selection dispatched with no pending selection");
 2504            return;
 2505        }
 2506
 2507        self.apply_scroll_delta(scroll_delta, cx);
 2508        cx.notify();
 2509    }
 2510
 2511    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2512        self.columnar_selection_tail.take();
 2513        if self.selections.pending_anchor().is_some() {
 2514            let selections = self.selections.all::<usize>(cx);
 2515            self.change_selections(None, cx, |s| {
 2516                s.select(selections);
 2517                s.clear_pending();
 2518            });
 2519        }
 2520    }
 2521
 2522    fn select_columns(
 2523        &mut self,
 2524        tail: DisplayPoint,
 2525        head: DisplayPoint,
 2526        goal_column: u32,
 2527        display_map: &DisplaySnapshot,
 2528        cx: &mut ViewContext<Self>,
 2529    ) {
 2530        let start_row = cmp::min(tail.row(), head.row());
 2531        let end_row = cmp::max(tail.row(), head.row());
 2532        let start_column = cmp::min(tail.column(), goal_column);
 2533        let end_column = cmp::max(tail.column(), goal_column);
 2534        let reversed = start_column < tail.column();
 2535
 2536        let selection_ranges = (start_row..=end_row)
 2537            .filter_map(|row| {
 2538                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2539                    let start = display_map
 2540                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2541                        .to_point(display_map);
 2542                    let end = display_map
 2543                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2544                        .to_point(display_map);
 2545                    if reversed {
 2546                        Some(end..start)
 2547                    } else {
 2548                        Some(start..end)
 2549                    }
 2550                } else {
 2551                    None
 2552                }
 2553            })
 2554            .collect::<Vec<_>>();
 2555
 2556        self.change_selections(None, cx, |s| {
 2557            s.select_ranges(selection_ranges);
 2558        });
 2559        cx.notify();
 2560    }
 2561
 2562    pub fn has_pending_nonempty_selection(&self) -> bool {
 2563        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2564            Some(Selection { start, end, .. }) => start != end,
 2565            None => false,
 2566        };
 2567        pending_nonempty_selection || self.columnar_selection_tail.is_some()
 2568    }
 2569
 2570    pub fn has_pending_selection(&self) -> bool {
 2571        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2572    }
 2573
 2574    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2575        if self.dismiss_menus_and_popups(cx) {
 2576            return;
 2577        }
 2578
 2579        if self.mode == EditorMode::Full {
 2580            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2581                return;
 2582            }
 2583        }
 2584
 2585        cx.propagate();
 2586    }
 2587
 2588    pub fn dismiss_menus_and_popups(&mut self, cx: &mut ViewContext<Self>) -> bool {
 2589        if self.take_rename(false, cx).is_some() {
 2590            return true;
 2591        }
 2592
 2593        if hide_hover(self, cx) {
 2594            return true;
 2595        }
 2596
 2597        if self.hide_context_menu(cx).is_some() {
 2598            return true;
 2599        }
 2600
 2601        if self.discard_inline_completion(cx) {
 2602            return true;
 2603        }
 2604
 2605        if self.snippet_stack.pop().is_some() {
 2606            return true;
 2607        }
 2608
 2609        if self.mode == EditorMode::Full {
 2610            if self.active_diagnostics.is_some() {
 2611                self.dismiss_diagnostics(cx);
 2612                return true;
 2613            }
 2614        }
 2615
 2616        false
 2617    }
 2618
 2619    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2620        let text: Arc<str> = text.into();
 2621
 2622        if self.read_only(cx) {
 2623            return;
 2624        }
 2625
 2626        let selections = self.selections.all_adjusted(cx);
 2627        let mut brace_inserted = false;
 2628        let mut edits = Vec::new();
 2629        let mut new_selections = Vec::with_capacity(selections.len());
 2630        let mut new_autoclose_regions = Vec::new();
 2631        let snapshot = self.buffer.read(cx).read(cx);
 2632
 2633        for (selection, autoclose_region) in
 2634            self.selections_with_autoclose_regions(selections, &snapshot)
 2635        {
 2636            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2637                // Determine if the inserted text matches the opening or closing
 2638                // bracket of any of this language's bracket pairs.
 2639                let mut bracket_pair = None;
 2640                let mut is_bracket_pair_start = false;
 2641                let mut is_bracket_pair_end = false;
 2642                if !text.is_empty() {
 2643                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2644                    //  and they are removing the character that triggered IME popup.
 2645                    for (pair, enabled) in scope.brackets() {
 2646                        if !pair.close {
 2647                            continue;
 2648                        }
 2649
 2650                        if enabled && pair.start.ends_with(text.as_ref()) {
 2651                            bracket_pair = Some(pair.clone());
 2652                            is_bracket_pair_start = true;
 2653                            break;
 2654                        }
 2655                        if pair.end.as_str() == text.as_ref() {
 2656                            bracket_pair = Some(pair.clone());
 2657                            is_bracket_pair_end = true;
 2658                            break;
 2659                        }
 2660                    }
 2661                }
 2662
 2663                if let Some(bracket_pair) = bracket_pair {
 2664                    if selection.is_empty() {
 2665                        if is_bracket_pair_start {
 2666                            let prefix_len = bracket_pair.start.len() - text.len();
 2667
 2668                            // If the inserted text is a suffix of an opening bracket and the
 2669                            // selection is preceded by the rest of the opening bracket, then
 2670                            // insert the closing bracket.
 2671                            let following_text_allows_autoclose = snapshot
 2672                                .chars_at(selection.start)
 2673                                .next()
 2674                                .map_or(true, |c| scope.should_autoclose_before(c));
 2675                            let preceding_text_matches_prefix = prefix_len == 0
 2676                                || (selection.start.column >= (prefix_len as u32)
 2677                                    && snapshot.contains_str_at(
 2678                                        Point::new(
 2679                                            selection.start.row,
 2680                                            selection.start.column - (prefix_len as u32),
 2681                                        ),
 2682                                        &bracket_pair.start[..prefix_len],
 2683                                    ));
 2684                            let autoclose = self.use_autoclose
 2685                                && snapshot.settings_at(selection.start, cx).use_autoclose;
 2686                            if autoclose
 2687                                && following_text_allows_autoclose
 2688                                && preceding_text_matches_prefix
 2689                            {
 2690                                let anchor = snapshot.anchor_before(selection.end);
 2691                                new_selections.push((selection.map(|_| anchor), text.len()));
 2692                                new_autoclose_regions.push((
 2693                                    anchor,
 2694                                    text.len(),
 2695                                    selection.id,
 2696                                    bracket_pair.clone(),
 2697                                ));
 2698                                edits.push((
 2699                                    selection.range(),
 2700                                    format!("{}{}", text, bracket_pair.end).into(),
 2701                                ));
 2702                                brace_inserted = true;
 2703                                continue;
 2704                            }
 2705                        }
 2706
 2707                        if let Some(region) = autoclose_region {
 2708                            // If the selection is followed by an auto-inserted closing bracket,
 2709                            // then don't insert that closing bracket again; just move the selection
 2710                            // past the closing bracket.
 2711                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2712                                && text.as_ref() == region.pair.end.as_str();
 2713                            if should_skip {
 2714                                let anchor = snapshot.anchor_after(selection.end);
 2715                                new_selections
 2716                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2717                                continue;
 2718                            }
 2719                        }
 2720
 2721                        let always_treat_brackets_as_autoclosed = snapshot
 2722                            .settings_at(selection.start, cx)
 2723                            .always_treat_brackets_as_autoclosed;
 2724                        if always_treat_brackets_as_autoclosed
 2725                            && is_bracket_pair_end
 2726                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2727                        {
 2728                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2729                            // and the inserted text is a closing bracket and the selection is followed
 2730                            // by the closing bracket then move the selection past the closing bracket.
 2731                            let anchor = snapshot.anchor_after(selection.end);
 2732                            new_selections.push((selection.map(|_| anchor), text.len()));
 2733                            continue;
 2734                        }
 2735                    }
 2736                    // If an opening bracket is 1 character long and is typed while
 2737                    // text is selected, then surround that text with the bracket pair.
 2738                    else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
 2739                        edits.push((selection.start..selection.start, text.clone()));
 2740                        edits.push((
 2741                            selection.end..selection.end,
 2742                            bracket_pair.end.as_str().into(),
 2743                        ));
 2744                        brace_inserted = true;
 2745                        new_selections.push((
 2746                            Selection {
 2747                                id: selection.id,
 2748                                start: snapshot.anchor_after(selection.start),
 2749                                end: snapshot.anchor_before(selection.end),
 2750                                reversed: selection.reversed,
 2751                                goal: selection.goal,
 2752                            },
 2753                            0,
 2754                        ));
 2755                        continue;
 2756                    }
 2757                }
 2758            }
 2759
 2760            if self.auto_replace_emoji_shortcode
 2761                && selection.is_empty()
 2762                && text.as_ref().ends_with(':')
 2763            {
 2764                if let Some(possible_emoji_short_code) =
 2765                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2766                {
 2767                    if !possible_emoji_short_code.is_empty() {
 2768                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2769                            let emoji_shortcode_start = Point::new(
 2770                                selection.start.row,
 2771                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2772                            );
 2773
 2774                            // Remove shortcode from buffer
 2775                            edits.push((
 2776                                emoji_shortcode_start..selection.start,
 2777                                "".to_string().into(),
 2778                            ));
 2779                            new_selections.push((
 2780                                Selection {
 2781                                    id: selection.id,
 2782                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2783                                    end: snapshot.anchor_before(selection.start),
 2784                                    reversed: selection.reversed,
 2785                                    goal: selection.goal,
 2786                                },
 2787                                0,
 2788                            ));
 2789
 2790                            // Insert emoji
 2791                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2792                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2793                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2794
 2795                            continue;
 2796                        }
 2797                    }
 2798                }
 2799            }
 2800
 2801            // If not handling any auto-close operation, then just replace the selected
 2802            // text with the given input and move the selection to the end of the
 2803            // newly inserted text.
 2804            let anchor = snapshot.anchor_after(selection.end);
 2805            new_selections.push((selection.map(|_| anchor), 0));
 2806            edits.push((selection.start..selection.end, text.clone()));
 2807        }
 2808
 2809        drop(snapshot);
 2810        self.transact(cx, |this, cx| {
 2811            this.buffer.update(cx, |buffer, cx| {
 2812                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2813            });
 2814
 2815            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2816            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2817            let snapshot = this.buffer.read(cx).read(cx);
 2818            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 2819                .zip(new_selection_deltas)
 2820                .map(|(selection, delta)| Selection {
 2821                    id: selection.id,
 2822                    start: selection.start + delta,
 2823                    end: selection.end + delta,
 2824                    reversed: selection.reversed,
 2825                    goal: SelectionGoal::None,
 2826                })
 2827                .collect::<Vec<_>>();
 2828
 2829            let mut i = 0;
 2830            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2831                let position = position.to_offset(&snapshot) + delta;
 2832                let start = snapshot.anchor_before(position);
 2833                let end = snapshot.anchor_after(position);
 2834                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2835                    match existing_state.range.start.cmp(&start, &snapshot) {
 2836                        Ordering::Less => i += 1,
 2837                        Ordering::Greater => break,
 2838                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 2839                            Ordering::Less => i += 1,
 2840                            Ordering::Equal => break,
 2841                            Ordering::Greater => break,
 2842                        },
 2843                    }
 2844                }
 2845                this.autoclose_regions.insert(
 2846                    i,
 2847                    AutocloseRegion {
 2848                        selection_id,
 2849                        range: start..end,
 2850                        pair,
 2851                    },
 2852                );
 2853            }
 2854
 2855            drop(snapshot);
 2856            let had_active_copilot_completion = this.has_active_inline_completion(cx);
 2857            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 2858
 2859            if brace_inserted {
 2860                // If we inserted a brace while composing text (i.e. typing `"` on a
 2861                // Brazilian keyboard), exit the composing state because most likely
 2862                // the user wanted to surround the selection.
 2863                this.unmark_text(cx);
 2864            } else if EditorSettings::get_global(cx).use_on_type_format {
 2865                if let Some(on_type_format_task) =
 2866                    this.trigger_on_type_formatting(text.to_string(), cx)
 2867                {
 2868                    on_type_format_task.detach_and_log_err(cx);
 2869                }
 2870            }
 2871
 2872            if had_active_copilot_completion {
 2873                this.refresh_inline_completion(true, cx);
 2874                if !this.has_active_inline_completion(cx) {
 2875                    this.trigger_completion_on_input(&text, cx);
 2876                }
 2877            } else {
 2878                this.trigger_completion_on_input(&text, cx);
 2879                this.refresh_inline_completion(true, cx);
 2880            }
 2881        });
 2882    }
 2883
 2884    fn find_possible_emoji_shortcode_at_position(
 2885        snapshot: &MultiBufferSnapshot,
 2886        position: Point,
 2887    ) -> Option<String> {
 2888        let mut chars = Vec::new();
 2889        let mut found_colon = false;
 2890        for char in snapshot.reversed_chars_at(position).take(100) {
 2891            // Found a possible emoji shortcode in the middle of the buffer
 2892            if found_colon {
 2893                if char.is_whitespace() {
 2894                    chars.reverse();
 2895                    return Some(chars.iter().collect());
 2896                }
 2897                // If the previous character is not a whitespace, we are in the middle of a word
 2898                // and we only want to complete the shortcode if the word is made up of other emojis
 2899                let mut containing_word = String::new();
 2900                for ch in snapshot
 2901                    .reversed_chars_at(position)
 2902                    .skip(chars.len() + 1)
 2903                    .take(100)
 2904                {
 2905                    if ch.is_whitespace() {
 2906                        break;
 2907                    }
 2908                    containing_word.push(ch);
 2909                }
 2910                let containing_word = containing_word.chars().rev().collect::<String>();
 2911                if util::word_consists_of_emojis(containing_word.as_str()) {
 2912                    chars.reverse();
 2913                    return Some(chars.iter().collect());
 2914                }
 2915            }
 2916
 2917            if char.is_whitespace() || !char.is_ascii() {
 2918                return None;
 2919            }
 2920            if char == ':' {
 2921                found_colon = true;
 2922            } else {
 2923                chars.push(char);
 2924            }
 2925        }
 2926        // Found a possible emoji shortcode at the beginning of the buffer
 2927        chars.reverse();
 2928        Some(chars.iter().collect())
 2929    }
 2930
 2931    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2932        self.transact(cx, |this, cx| {
 2933            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2934                let selections = this.selections.all::<usize>(cx);
 2935                let multi_buffer = this.buffer.read(cx);
 2936                let buffer = multi_buffer.snapshot(cx);
 2937                selections
 2938                    .iter()
 2939                    .map(|selection| {
 2940                        let start_point = selection.start.to_point(&buffer);
 2941                        let mut indent = buffer.indent_size_for_line(start_point.row);
 2942                        indent.len = cmp::min(indent.len, start_point.column);
 2943                        let start = selection.start;
 2944                        let end = selection.end;
 2945                        let is_cursor = start == end;
 2946                        let language_scope = buffer.language_scope_at(start);
 2947                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2948                            &language_scope
 2949                        {
 2950                            let leading_whitespace_len = buffer
 2951                                .reversed_chars_at(start)
 2952                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2953                                .map(|c| c.len_utf8())
 2954                                .sum::<usize>();
 2955
 2956                            let trailing_whitespace_len = buffer
 2957                                .chars_at(end)
 2958                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2959                                .map(|c| c.len_utf8())
 2960                                .sum::<usize>();
 2961
 2962                            let insert_extra_newline =
 2963                                language.brackets().any(|(pair, enabled)| {
 2964                                    let pair_start = pair.start.trim_end();
 2965                                    let pair_end = pair.end.trim_start();
 2966
 2967                                    enabled
 2968                                        && pair.newline
 2969                                        && buffer.contains_str_at(
 2970                                            end + trailing_whitespace_len,
 2971                                            pair_end,
 2972                                        )
 2973                                        && buffer.contains_str_at(
 2974                                            (start - leading_whitespace_len)
 2975                                                .saturating_sub(pair_start.len()),
 2976                                            pair_start,
 2977                                        )
 2978                                });
 2979                            // Comment extension on newline is allowed only for cursor selections
 2980                            let comment_delimiter = language.line_comment_prefixes().filter(|_| {
 2981                                let is_comment_extension_enabled =
 2982                                    multi_buffer.settings_at(0, cx).extend_comment_on_newline;
 2983                                is_cursor && is_comment_extension_enabled
 2984                            });
 2985                            let get_comment_delimiter = |delimiters: &[Arc<str>]| {
 2986                                let max_len_of_delimiter =
 2987                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2988                                let (snapshot, range) =
 2989                                    buffer.buffer_line_for_row(start_point.row)?;
 2990
 2991                                let mut index_of_first_non_whitespace = 0;
 2992                                let comment_candidate = snapshot
 2993                                    .chars_for_range(range)
 2994                                    .skip_while(|c| {
 2995                                        let should_skip = c.is_whitespace();
 2996                                        if should_skip {
 2997                                            index_of_first_non_whitespace += 1;
 2998                                        }
 2999                                        should_skip
 3000                                    })
 3001                                    .take(max_len_of_delimiter)
 3002                                    .collect::<String>();
 3003                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3004                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3005                                })?;
 3006                                let cursor_is_placed_after_comment_marker =
 3007                                    index_of_first_non_whitespace + comment_prefix.len()
 3008                                        <= start_point.column as usize;
 3009                                if cursor_is_placed_after_comment_marker {
 3010                                    Some(comment_prefix.clone())
 3011                                } else {
 3012                                    None
 3013                                }
 3014                            };
 3015                            let comment_delimiter = if let Some(delimiters) = comment_delimiter {
 3016                                get_comment_delimiter(delimiters)
 3017                            } else {
 3018                                None
 3019                            };
 3020                            (comment_delimiter, insert_extra_newline)
 3021                        } else {
 3022                            (None, false)
 3023                        };
 3024
 3025                        let capacity_for_delimiter = comment_delimiter
 3026                            .as_deref()
 3027                            .map(str::len)
 3028                            .unwrap_or_default();
 3029                        let mut new_text =
 3030                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3031                        new_text.push_str("\n");
 3032                        new_text.extend(indent.chars());
 3033                        if let Some(delimiter) = &comment_delimiter {
 3034                            new_text.push_str(&delimiter);
 3035                        }
 3036                        if insert_extra_newline {
 3037                            new_text = new_text.repeat(2);
 3038                        }
 3039
 3040                        let anchor = buffer.anchor_after(end);
 3041                        let new_selection = selection.map(|_| anchor);
 3042                        (
 3043                            (start..end, new_text),
 3044                            (insert_extra_newline, new_selection),
 3045                        )
 3046                    })
 3047                    .unzip()
 3048            };
 3049
 3050            this.edit_with_autoindent(edits, cx);
 3051            let buffer = this.buffer.read(cx).snapshot(cx);
 3052            let new_selections = selection_fixup_info
 3053                .into_iter()
 3054                .map(|(extra_newline_inserted, new_selection)| {
 3055                    let mut cursor = new_selection.end.to_point(&buffer);
 3056                    if extra_newline_inserted {
 3057                        cursor.row -= 1;
 3058                        cursor.column = buffer.line_len(cursor.row);
 3059                    }
 3060                    new_selection.map(|_| cursor)
 3061                })
 3062                .collect();
 3063
 3064            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3065            this.refresh_inline_completion(true, cx);
 3066        });
 3067    }
 3068
 3069    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3070        let buffer = self.buffer.read(cx);
 3071        let snapshot = buffer.snapshot(cx);
 3072
 3073        let mut edits = Vec::new();
 3074        let mut rows = Vec::new();
 3075
 3076        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3077            let cursor = selection.head();
 3078            let row = cursor.row;
 3079
 3080            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3081
 3082            let newline = "\n".to_string();
 3083            edits.push((start_of_line..start_of_line, newline));
 3084
 3085            rows.push(row + rows_inserted as u32);
 3086        }
 3087
 3088        self.transact(cx, |editor, cx| {
 3089            editor.edit(edits, cx);
 3090
 3091            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3092                let mut index = 0;
 3093                s.move_cursors_with(|map, _, _| {
 3094                    let row = rows[index];
 3095                    index += 1;
 3096
 3097                    let point = Point::new(row, 0);
 3098                    let boundary = map.next_line_boundary(point).1;
 3099                    let clipped = map.clip_point(boundary, Bias::Left);
 3100
 3101                    (clipped, SelectionGoal::None)
 3102                });
 3103            });
 3104
 3105            let mut indent_edits = Vec::new();
 3106            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3107            for row in rows {
 3108                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3109                for (row, indent) in indents {
 3110                    if indent.len == 0 {
 3111                        continue;
 3112                    }
 3113
 3114                    let text = match indent.kind {
 3115                        IndentKind::Space => " ".repeat(indent.len as usize),
 3116                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3117                    };
 3118                    let point = Point::new(row, 0);
 3119                    indent_edits.push((point..point, text));
 3120                }
 3121            }
 3122            editor.edit(indent_edits, cx);
 3123        });
 3124    }
 3125
 3126    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3127        let buffer = self.buffer.read(cx);
 3128        let snapshot = buffer.snapshot(cx);
 3129
 3130        let mut edits = Vec::new();
 3131        let mut rows = Vec::new();
 3132        let mut rows_inserted = 0;
 3133
 3134        for selection in self.selections.all_adjusted(cx) {
 3135            let cursor = selection.head();
 3136            let row = cursor.row;
 3137
 3138            let point = Point::new(row + 1, 0);
 3139            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3140
 3141            let newline = "\n".to_string();
 3142            edits.push((start_of_line..start_of_line, newline));
 3143
 3144            rows_inserted += 1;
 3145            rows.push(row + rows_inserted);
 3146        }
 3147
 3148        self.transact(cx, |editor, cx| {
 3149            editor.edit(edits, cx);
 3150
 3151            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3152                let mut index = 0;
 3153                s.move_cursors_with(|map, _, _| {
 3154                    let row = rows[index];
 3155                    index += 1;
 3156
 3157                    let point = Point::new(row, 0);
 3158                    let boundary = map.next_line_boundary(point).1;
 3159                    let clipped = map.clip_point(boundary, Bias::Left);
 3160
 3161                    (clipped, SelectionGoal::None)
 3162                });
 3163            });
 3164
 3165            let mut indent_edits = Vec::new();
 3166            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3167            for row in rows {
 3168                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3169                for (row, indent) in indents {
 3170                    if indent.len == 0 {
 3171                        continue;
 3172                    }
 3173
 3174                    let text = match indent.kind {
 3175                        IndentKind::Space => " ".repeat(indent.len as usize),
 3176                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3177                    };
 3178                    let point = Point::new(row, 0);
 3179                    indent_edits.push((point..point, text));
 3180                }
 3181            }
 3182            editor.edit(indent_edits, cx);
 3183        });
 3184    }
 3185
 3186    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3187        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3188            original_indent_columns: Vec::new(),
 3189        });
 3190        self.insert_with_autoindent_mode(text, autoindent, cx);
 3191    }
 3192
 3193    fn insert_with_autoindent_mode(
 3194        &mut self,
 3195        text: &str,
 3196        autoindent_mode: Option<AutoindentMode>,
 3197        cx: &mut ViewContext<Self>,
 3198    ) {
 3199        if self.read_only(cx) {
 3200            return;
 3201        }
 3202
 3203        let text: Arc<str> = text.into();
 3204        self.transact(cx, |this, cx| {
 3205            let old_selections = this.selections.all_adjusted(cx);
 3206            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3207                let anchors = {
 3208                    let snapshot = buffer.read(cx);
 3209                    old_selections
 3210                        .iter()
 3211                        .map(|s| {
 3212                            let anchor = snapshot.anchor_after(s.head());
 3213                            s.map(|_| anchor)
 3214                        })
 3215                        .collect::<Vec<_>>()
 3216                };
 3217                buffer.edit(
 3218                    old_selections
 3219                        .iter()
 3220                        .map(|s| (s.start..s.end, text.clone())),
 3221                    autoindent_mode,
 3222                    cx,
 3223                );
 3224                anchors
 3225            });
 3226
 3227            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3228                s.select_anchors(selection_anchors);
 3229            })
 3230        });
 3231    }
 3232
 3233    fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3234        if !EditorSettings::get_global(cx).show_completions_on_input {
 3235            return;
 3236        }
 3237
 3238        let selection = self.selections.newest_anchor();
 3239        if self
 3240            .buffer
 3241            .read(cx)
 3242            .is_completion_trigger(selection.head(), text, cx)
 3243        {
 3244            self.show_completions(&ShowCompletions, cx);
 3245        } else {
 3246            self.hide_context_menu(cx);
 3247        }
 3248    }
 3249
 3250    /// If any empty selections is touching the start of its innermost containing autoclose
 3251    /// region, expand it to select the brackets.
 3252    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3253        let selections = self.selections.all::<usize>(cx);
 3254        let buffer = self.buffer.read(cx).read(cx);
 3255        let new_selections = self
 3256            .selections_with_autoclose_regions(selections, &buffer)
 3257            .map(|(mut selection, region)| {
 3258                if !selection.is_empty() {
 3259                    return selection;
 3260                }
 3261
 3262                if let Some(region) = region {
 3263                    let mut range = region.range.to_offset(&buffer);
 3264                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3265                        range.start -= region.pair.start.len();
 3266                        if buffer.contains_str_at(range.start, &region.pair.start)
 3267                            && buffer.contains_str_at(range.end, &region.pair.end)
 3268                        {
 3269                            range.end += region.pair.end.len();
 3270                            selection.start = range.start;
 3271                            selection.end = range.end;
 3272
 3273                            return selection;
 3274                        }
 3275                    }
 3276                }
 3277
 3278                let always_treat_brackets_as_autoclosed = buffer
 3279                    .settings_at(selection.start, cx)
 3280                    .always_treat_brackets_as_autoclosed;
 3281
 3282                if !always_treat_brackets_as_autoclosed {
 3283                    return selection;
 3284                }
 3285
 3286                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3287                    for (pair, enabled) in scope.brackets() {
 3288                        if !enabled || !pair.close {
 3289                            continue;
 3290                        }
 3291
 3292                        if buffer.contains_str_at(selection.start, &pair.end) {
 3293                            let pair_start_len = pair.start.len();
 3294                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3295                            {
 3296                                selection.start -= pair_start_len;
 3297                                selection.end += pair.end.len();
 3298
 3299                                return selection;
 3300                            }
 3301                        }
 3302                    }
 3303                }
 3304
 3305                selection
 3306            })
 3307            .collect();
 3308
 3309        drop(buffer);
 3310        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3311    }
 3312
 3313    /// Iterate the given selections, and for each one, find the smallest surrounding
 3314    /// autoclose region. This uses the ordering of the selections and the autoclose
 3315    /// regions to avoid repeated comparisons.
 3316    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3317        &'a self,
 3318        selections: impl IntoIterator<Item = Selection<D>>,
 3319        buffer: &'a MultiBufferSnapshot,
 3320    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3321        let mut i = 0;
 3322        let mut regions = self.autoclose_regions.as_slice();
 3323        selections.into_iter().map(move |selection| {
 3324            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3325
 3326            let mut enclosing = None;
 3327            while let Some(pair_state) = regions.get(i) {
 3328                if pair_state.range.end.to_offset(buffer) < range.start {
 3329                    regions = &regions[i + 1..];
 3330                    i = 0;
 3331                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3332                    break;
 3333                } else {
 3334                    if pair_state.selection_id == selection.id {
 3335                        enclosing = Some(pair_state);
 3336                    }
 3337                    i += 1;
 3338                }
 3339            }
 3340
 3341            (selection.clone(), enclosing)
 3342        })
 3343    }
 3344
 3345    /// Remove any autoclose regions that no longer contain their selection.
 3346    fn invalidate_autoclose_regions(
 3347        &mut self,
 3348        mut selections: &[Selection<Anchor>],
 3349        buffer: &MultiBufferSnapshot,
 3350    ) {
 3351        self.autoclose_regions.retain(|state| {
 3352            let mut i = 0;
 3353            while let Some(selection) = selections.get(i) {
 3354                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3355                    selections = &selections[1..];
 3356                    continue;
 3357                }
 3358                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3359                    break;
 3360                }
 3361                if selection.id == state.selection_id {
 3362                    return true;
 3363                } else {
 3364                    i += 1;
 3365                }
 3366            }
 3367            false
 3368        });
 3369    }
 3370
 3371    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3372        let offset = position.to_offset(buffer);
 3373        let (word_range, kind) = buffer.surrounding_word(offset);
 3374        if offset > word_range.start && kind == Some(CharKind::Word) {
 3375            Some(
 3376                buffer
 3377                    .text_for_range(word_range.start..offset)
 3378                    .collect::<String>(),
 3379            )
 3380        } else {
 3381            None
 3382        }
 3383    }
 3384
 3385    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3386        self.refresh_inlay_hints(
 3387            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3388            cx,
 3389        );
 3390    }
 3391
 3392    pub fn inlay_hints_enabled(&self) -> bool {
 3393        self.inlay_hint_cache.enabled
 3394    }
 3395
 3396    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3397        if self.project.is_none() || self.mode != EditorMode::Full {
 3398            return;
 3399        }
 3400
 3401        let reason_description = reason.description();
 3402        let ignore_debounce = matches!(
 3403            reason,
 3404            InlayHintRefreshReason::SettingsChange(_)
 3405                | InlayHintRefreshReason::Toggle(_)
 3406                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3407        );
 3408        let (invalidate_cache, required_languages) = match reason {
 3409            InlayHintRefreshReason::Toggle(enabled) => {
 3410                self.inlay_hint_cache.enabled = enabled;
 3411                if enabled {
 3412                    (InvalidationStrategy::RefreshRequested, None)
 3413                } else {
 3414                    self.inlay_hint_cache.clear();
 3415                    self.splice_inlays(
 3416                        self.visible_inlay_hints(cx)
 3417                            .iter()
 3418                            .map(|inlay| inlay.id)
 3419                            .collect(),
 3420                        Vec::new(),
 3421                        cx,
 3422                    );
 3423                    return;
 3424                }
 3425            }
 3426            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3427                match self.inlay_hint_cache.update_settings(
 3428                    &self.buffer,
 3429                    new_settings,
 3430                    self.visible_inlay_hints(cx),
 3431                    cx,
 3432                ) {
 3433                    ControlFlow::Break(Some(InlaySplice {
 3434                        to_remove,
 3435                        to_insert,
 3436                    })) => {
 3437                        self.splice_inlays(to_remove, to_insert, cx);
 3438                        return;
 3439                    }
 3440                    ControlFlow::Break(None) => return,
 3441                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3442                }
 3443            }
 3444            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3445                if let Some(InlaySplice {
 3446                    to_remove,
 3447                    to_insert,
 3448                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3449                {
 3450                    self.splice_inlays(to_remove, to_insert, cx);
 3451                }
 3452                return;
 3453            }
 3454            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3455            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3456                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3457            }
 3458            InlayHintRefreshReason::RefreshRequested => {
 3459                (InvalidationStrategy::RefreshRequested, None)
 3460            }
 3461        };
 3462
 3463        if let Some(InlaySplice {
 3464            to_remove,
 3465            to_insert,
 3466        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3467            reason_description,
 3468            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3469            invalidate_cache,
 3470            ignore_debounce,
 3471            cx,
 3472        ) {
 3473            self.splice_inlays(to_remove, to_insert, cx);
 3474        }
 3475    }
 3476
 3477    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3478        self.display_map
 3479            .read(cx)
 3480            .current_inlays()
 3481            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3482            .cloned()
 3483            .collect()
 3484    }
 3485
 3486    pub fn excerpts_for_inlay_hints_query(
 3487        &self,
 3488        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3489        cx: &mut ViewContext<Editor>,
 3490    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3491        let Some(project) = self.project.as_ref() else {
 3492            return HashMap::default();
 3493        };
 3494        let project = project.read(cx);
 3495        let multi_buffer = self.buffer().read(cx);
 3496        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3497        let multi_buffer_visible_start = self
 3498            .scroll_manager
 3499            .anchor()
 3500            .anchor
 3501            .to_point(&multi_buffer_snapshot);
 3502        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3503            multi_buffer_visible_start
 3504                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3505            Bias::Left,
 3506        );
 3507        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3508        multi_buffer
 3509            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3510            .into_iter()
 3511            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3512            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3513                let buffer = buffer_handle.read(cx);
 3514                let buffer_file = project::File::from_dyn(buffer.file())?;
 3515                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3516                let worktree_entry = buffer_worktree
 3517                    .read(cx)
 3518                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3519                if worktree_entry.is_ignored {
 3520                    return None;
 3521                }
 3522
 3523                let language = buffer.language()?;
 3524                if let Some(restrict_to_languages) = restrict_to_languages {
 3525                    if !restrict_to_languages.contains(language) {
 3526                        return None;
 3527                    }
 3528                }
 3529                Some((
 3530                    excerpt_id,
 3531                    (
 3532                        buffer_handle,
 3533                        buffer.version().clone(),
 3534                        excerpt_visible_range,
 3535                    ),
 3536                ))
 3537            })
 3538            .collect()
 3539    }
 3540
 3541    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3542        TextLayoutDetails {
 3543            text_system: cx.text_system().clone(),
 3544            editor_style: self.style.clone().unwrap(),
 3545            rem_size: cx.rem_size(),
 3546            scroll_anchor: self.scroll_manager.anchor(),
 3547            visible_rows: self.visible_line_count(),
 3548            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3549        }
 3550    }
 3551
 3552    fn splice_inlays(
 3553        &self,
 3554        to_remove: Vec<InlayId>,
 3555        to_insert: Vec<Inlay>,
 3556        cx: &mut ViewContext<Self>,
 3557    ) {
 3558        self.display_map.update(cx, |display_map, cx| {
 3559            display_map.splice_inlays(to_remove, to_insert, cx);
 3560        });
 3561        cx.notify();
 3562    }
 3563
 3564    fn trigger_on_type_formatting(
 3565        &self,
 3566        input: String,
 3567        cx: &mut ViewContext<Self>,
 3568    ) -> Option<Task<Result<()>>> {
 3569        if input.len() != 1 {
 3570            return None;
 3571        }
 3572
 3573        let project = self.project.as_ref()?;
 3574        let position = self.selections.newest_anchor().head();
 3575        let (buffer, buffer_position) = self
 3576            .buffer
 3577            .read(cx)
 3578            .text_anchor_for_position(position, cx)?;
 3579
 3580        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3581        // hence we do LSP request & edit on host side only — add formats to host's history.
 3582        let push_to_lsp_host_history = true;
 3583        // If this is not the host, append its history with new edits.
 3584        let push_to_client_history = project.read(cx).is_remote();
 3585
 3586        let on_type_formatting = project.update(cx, |project, cx| {
 3587            project.on_type_format(
 3588                buffer.clone(),
 3589                buffer_position,
 3590                input,
 3591                push_to_lsp_host_history,
 3592                cx,
 3593            )
 3594        });
 3595        Some(cx.spawn(|editor, mut cx| async move {
 3596            if let Some(transaction) = on_type_formatting.await? {
 3597                if push_to_client_history {
 3598                    buffer
 3599                        .update(&mut cx, |buffer, _| {
 3600                            buffer.push_transaction(transaction, Instant::now());
 3601                        })
 3602                        .ok();
 3603                }
 3604                editor.update(&mut cx, |editor, cx| {
 3605                    editor.refresh_document_highlights(cx);
 3606                })?;
 3607            }
 3608            Ok(())
 3609        }))
 3610    }
 3611
 3612    fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3613        if self.pending_rename.is_some() {
 3614            return;
 3615        }
 3616
 3617        let Some(provider) = self.completion_provider.as_ref() else {
 3618            return;
 3619        };
 3620
 3621        let position = self.selections.newest_anchor().head();
 3622        let (buffer, buffer_position) =
 3623            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3624                output
 3625            } else {
 3626                return;
 3627            };
 3628
 3629        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3630        let completions = provider.completions(&buffer, buffer_position, cx);
 3631
 3632        let id = post_inc(&mut self.next_completion_id);
 3633        let task = cx.spawn(|this, mut cx| {
 3634            async move {
 3635                let completions = completions.await.log_err();
 3636                let menu = if let Some(completions) = completions {
 3637                    let mut menu = CompletionsMenu {
 3638                        id,
 3639                        initial_position: position,
 3640                        match_candidates: completions
 3641                            .iter()
 3642                            .enumerate()
 3643                            .map(|(id, completion)| {
 3644                                StringMatchCandidate::new(
 3645                                    id,
 3646                                    completion.label.text[completion.label.filter_range.clone()]
 3647                                        .into(),
 3648                                )
 3649                            })
 3650                            .collect(),
 3651                        buffer,
 3652                        completions: Arc::new(RwLock::new(completions.into())),
 3653                        matches: Vec::new().into(),
 3654                        selected_item: 0,
 3655                        scroll_handle: UniformListScrollHandle::new(),
 3656                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 3657                            DebouncedDelay::new(),
 3658                        )),
 3659                    };
 3660                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3661                        .await;
 3662
 3663                    if menu.matches.is_empty() {
 3664                        None
 3665                    } else {
 3666                        this.update(&mut cx, |editor, cx| {
 3667                            let completions = menu.completions.clone();
 3668                            let matches = menu.matches.clone();
 3669
 3670                            let delay_ms = EditorSettings::get_global(cx)
 3671                                .completion_documentation_secondary_query_debounce;
 3672                            let delay = Duration::from_millis(delay_ms);
 3673
 3674                            editor
 3675                                .completion_documentation_pre_resolve_debounce
 3676                                .fire_new(delay, cx, |editor, cx| {
 3677                                    CompletionsMenu::pre_resolve_completion_documentation(
 3678                                        completions,
 3679                                        matches,
 3680                                        editor,
 3681                                        cx,
 3682                                    )
 3683                                });
 3684                        })
 3685                        .ok();
 3686                        Some(menu)
 3687                    }
 3688                } else {
 3689                    None
 3690                };
 3691
 3692                this.update(&mut cx, |this, cx| {
 3693                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3694
 3695                    let mut context_menu = this.context_menu.write();
 3696                    match context_menu.as_ref() {
 3697                        None => {}
 3698
 3699                        Some(ContextMenu::Completions(prev_menu)) => {
 3700                            if prev_menu.id > id {
 3701                                return;
 3702                            }
 3703                        }
 3704
 3705                        _ => return,
 3706                    }
 3707
 3708                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 3709                        let menu = menu.unwrap();
 3710                        *context_menu = Some(ContextMenu::Completions(menu));
 3711                        drop(context_menu);
 3712                        this.discard_inline_completion(cx);
 3713                        cx.notify();
 3714                    } else if this.completion_tasks.len() <= 1 {
 3715                        // If there are no more completion tasks and the last menu was
 3716                        // empty, we should hide it. If it was already hidden, we should
 3717                        // also show the copilot completion when available.
 3718                        drop(context_menu);
 3719                        if this.hide_context_menu(cx).is_none() {
 3720                            this.update_visible_inline_completion(cx);
 3721                        }
 3722                    }
 3723                })?;
 3724
 3725                Ok::<_, anyhow::Error>(())
 3726            }
 3727            .log_err()
 3728        });
 3729
 3730        self.completion_tasks.push((id, task));
 3731    }
 3732
 3733    pub fn confirm_completion(
 3734        &mut self,
 3735        action: &ConfirmCompletion,
 3736        cx: &mut ViewContext<Self>,
 3737    ) -> Option<Task<Result<()>>> {
 3738        use language::ToOffset as _;
 3739
 3740        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3741            menu
 3742        } else {
 3743            return None;
 3744        };
 3745
 3746        let mat = completions_menu
 3747            .matches
 3748            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 3749        let buffer_handle = completions_menu.buffer;
 3750        let completions = completions_menu.completions.read();
 3751        let completion = completions.get(mat.candidate_id)?;
 3752        cx.stop_propagation();
 3753
 3754        let snippet;
 3755        let text;
 3756        if completion.is_snippet() {
 3757            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3758            text = snippet.as_ref().unwrap().text.clone();
 3759        } else {
 3760            snippet = None;
 3761            text = completion.new_text.clone();
 3762        };
 3763        let selections = self.selections.all::<usize>(cx);
 3764        let buffer = buffer_handle.read(cx);
 3765        let old_range = completion.old_range.to_offset(buffer);
 3766        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3767
 3768        let newest_selection = self.selections.newest_anchor();
 3769        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3770            return None;
 3771        }
 3772
 3773        let lookbehind = newest_selection
 3774            .start
 3775            .text_anchor
 3776            .to_offset(buffer)
 3777            .saturating_sub(old_range.start);
 3778        let lookahead = old_range
 3779            .end
 3780            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3781        let mut common_prefix_len = old_text
 3782            .bytes()
 3783            .zip(text.bytes())
 3784            .take_while(|(a, b)| a == b)
 3785            .count();
 3786
 3787        let snapshot = self.buffer.read(cx).snapshot(cx);
 3788        let mut range_to_replace: Option<Range<isize>> = None;
 3789        let mut ranges = Vec::new();
 3790        for selection in &selections {
 3791            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3792                let start = selection.start.saturating_sub(lookbehind);
 3793                let end = selection.end + lookahead;
 3794                if selection.id == newest_selection.id {
 3795                    range_to_replace = Some(
 3796                        ((start + common_prefix_len) as isize - selection.start as isize)
 3797                            ..(end as isize - selection.start as isize),
 3798                    );
 3799                }
 3800                ranges.push(start + common_prefix_len..end);
 3801            } else {
 3802                common_prefix_len = 0;
 3803                ranges.clear();
 3804                ranges.extend(selections.iter().map(|s| {
 3805                    if s.id == newest_selection.id {
 3806                        range_to_replace = Some(
 3807                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3808                                - selection.start as isize
 3809                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3810                                    - selection.start as isize,
 3811                        );
 3812                        old_range.clone()
 3813                    } else {
 3814                        s.start..s.end
 3815                    }
 3816                }));
 3817                break;
 3818            }
 3819        }
 3820        let text = &text[common_prefix_len..];
 3821
 3822        cx.emit(EditorEvent::InputHandled {
 3823            utf16_range_to_replace: range_to_replace,
 3824            text: text.into(),
 3825        });
 3826
 3827        self.transact(cx, |this, cx| {
 3828            if let Some(mut snippet) = snippet {
 3829                snippet.text = text.to_string();
 3830                for tabstop in snippet.tabstops.iter_mut().flatten() {
 3831                    tabstop.start -= common_prefix_len as isize;
 3832                    tabstop.end -= common_prefix_len as isize;
 3833                }
 3834
 3835                this.insert_snippet(&ranges, snippet, cx).log_err();
 3836            } else {
 3837                this.buffer.update(cx, |buffer, cx| {
 3838                    buffer.edit(
 3839                        ranges.iter().map(|range| (range.clone(), text)),
 3840                        this.autoindent_mode.clone(),
 3841                        cx,
 3842                    );
 3843                });
 3844            }
 3845
 3846            this.refresh_inline_completion(true, cx);
 3847        });
 3848
 3849        let provider = self.completion_provider.as_ref()?;
 3850        let apply_edits = provider.apply_additional_edits_for_completion(
 3851            buffer_handle,
 3852            completion.clone(),
 3853            true,
 3854            cx,
 3855        );
 3856        Some(cx.foreground_executor().spawn(async move {
 3857            apply_edits.await?;
 3858            Ok(())
 3859        }))
 3860    }
 3861
 3862    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3863        let mut context_menu = self.context_menu.write();
 3864        if matches!(context_menu.as_ref(), Some(ContextMenu::CodeActions(_))) {
 3865            *context_menu = None;
 3866            cx.notify();
 3867            return;
 3868        }
 3869        drop(context_menu);
 3870
 3871        let deployed_from_indicator = action.deployed_from_indicator;
 3872        let mut task = self.code_actions_task.take();
 3873        cx.spawn(|this, mut cx| async move {
 3874            while let Some(prev_task) = task {
 3875                prev_task.await;
 3876                task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3877            }
 3878
 3879            this.update(&mut cx, |this, cx| {
 3880                if this.focus_handle.is_focused(cx) {
 3881                    if let Some((buffer, actions)) = this.available_code_actions.clone() {
 3882                        this.completion_tasks.clear();
 3883                        this.discard_inline_completion(cx);
 3884                        *this.context_menu.write() =
 3885                            Some(ContextMenu::CodeActions(CodeActionsMenu {
 3886                                buffer,
 3887                                actions,
 3888                                selected_item: Default::default(),
 3889                                scroll_handle: UniformListScrollHandle::default(),
 3890                                deployed_from_indicator,
 3891                            }));
 3892                        cx.notify();
 3893                    }
 3894                }
 3895            })?;
 3896
 3897            Ok::<_, anyhow::Error>(())
 3898        })
 3899        .detach_and_log_err(cx);
 3900    }
 3901
 3902    pub fn confirm_code_action(
 3903        &mut self,
 3904        action: &ConfirmCodeAction,
 3905        cx: &mut ViewContext<Self>,
 3906    ) -> Option<Task<Result<()>>> {
 3907        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 3908            menu
 3909        } else {
 3910            return None;
 3911        };
 3912        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 3913        let action = actions_menu.actions.get(action_ix)?.clone();
 3914        let title = action.lsp_action.title.clone();
 3915        let buffer = actions_menu.buffer;
 3916        let workspace = self.workspace()?;
 3917
 3918        let apply_code_actions = workspace
 3919            .read(cx)
 3920            .project()
 3921            .clone()
 3922            .update(cx, |project, cx| {
 3923                project.apply_code_action(buffer, action, true, cx)
 3924            });
 3925        let workspace = workspace.downgrade();
 3926        Some(cx.spawn(|editor, cx| async move {
 3927            let project_transaction = apply_code_actions.await?;
 3928            Self::open_project_transaction(&editor, workspace, project_transaction, title, cx).await
 3929        }))
 3930    }
 3931
 3932    async fn open_project_transaction(
 3933        this: &WeakView<Editor>,
 3934        workspace: WeakView<Workspace>,
 3935        transaction: ProjectTransaction,
 3936        title: String,
 3937        mut cx: AsyncWindowContext,
 3938    ) -> Result<()> {
 3939        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 3940
 3941        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 3942        cx.update(|cx| {
 3943            entries.sort_unstable_by_key(|(buffer, _)| {
 3944                buffer.read(cx).file().map(|f| f.path().clone())
 3945            });
 3946        })?;
 3947
 3948        // If the project transaction's edits are all contained within this editor, then
 3949        // avoid opening a new editor to display them.
 3950
 3951        if let Some((buffer, transaction)) = entries.first() {
 3952            if entries.len() == 1 {
 3953                let excerpt = this.update(&mut cx, |editor, cx| {
 3954                    editor
 3955                        .buffer()
 3956                        .read(cx)
 3957                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 3958                })?;
 3959                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 3960                    if excerpted_buffer == *buffer {
 3961                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 3962                            let excerpt_range = excerpt_range.to_offset(buffer);
 3963                            buffer
 3964                                .edited_ranges_for_transaction::<usize>(transaction)
 3965                                .all(|range| {
 3966                                    excerpt_range.start <= range.start
 3967                                        && excerpt_range.end >= range.end
 3968                                })
 3969                        })?;
 3970
 3971                        if all_edits_within_excerpt {
 3972                            return Ok(());
 3973                        }
 3974                    }
 3975                }
 3976            }
 3977        } else {
 3978            return Ok(());
 3979        }
 3980
 3981        let mut ranges_to_highlight = Vec::new();
 3982        let excerpt_buffer = cx.new_model(|cx| {
 3983            let mut multibuffer =
 3984                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 3985            for (buffer_handle, transaction) in &entries {
 3986                let buffer = buffer_handle.read(cx);
 3987                ranges_to_highlight.extend(
 3988                    multibuffer.push_excerpts_with_context_lines(
 3989                        buffer_handle.clone(),
 3990                        buffer
 3991                            .edited_ranges_for_transaction::<usize>(transaction)
 3992                            .collect(),
 3993                        1,
 3994                        cx,
 3995                    ),
 3996                );
 3997            }
 3998            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 3999            multibuffer
 4000        })?;
 4001
 4002        workspace.update(&mut cx, |workspace, cx| {
 4003            let project = workspace.project().clone();
 4004            let editor =
 4005                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
 4006            workspace.add_item_to_active_pane(Box::new(editor.clone()), cx);
 4007            editor.update(cx, |editor, cx| {
 4008                editor.highlight_background::<Self>(
 4009                    ranges_to_highlight,
 4010                    |theme| theme.editor_highlighted_line_background,
 4011                    cx,
 4012                );
 4013            });
 4014        })?;
 4015
 4016        Ok(())
 4017    }
 4018
 4019    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4020        let project = self.project.clone()?;
 4021        let buffer = self.buffer.read(cx);
 4022        let newest_selection = self.selections.newest_anchor().clone();
 4023        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4024        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4025        if start_buffer != end_buffer {
 4026            return None;
 4027        }
 4028
 4029        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4030            cx.background_executor()
 4031                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4032                .await;
 4033
 4034            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4035                project.code_actions(&start_buffer, start..end, cx)
 4036            }) {
 4037                code_actions.await
 4038            } else {
 4039                Vec::new()
 4040            };
 4041
 4042            this.update(&mut cx, |this, cx| {
 4043                this.available_code_actions = if actions.is_empty() {
 4044                    None
 4045                } else {
 4046                    Some((start_buffer, actions.into()))
 4047                };
 4048                cx.notify();
 4049            })
 4050            .log_err();
 4051        }));
 4052        None
 4053    }
 4054
 4055    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4056        if self.pending_rename.is_some() {
 4057            return None;
 4058        }
 4059
 4060        let project = self.project.clone()?;
 4061        let buffer = self.buffer.read(cx);
 4062        let newest_selection = self.selections.newest_anchor().clone();
 4063        let cursor_position = newest_selection.head();
 4064        let (cursor_buffer, cursor_buffer_position) =
 4065            buffer.text_anchor_for_position(cursor_position, cx)?;
 4066        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4067        if cursor_buffer != tail_buffer {
 4068            return None;
 4069        }
 4070
 4071        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4072            cx.background_executor()
 4073                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4074                .await;
 4075
 4076            let highlights = if let Some(highlights) = project
 4077                .update(&mut cx, |project, cx| {
 4078                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4079                })
 4080                .log_err()
 4081            {
 4082                highlights.await.log_err()
 4083            } else {
 4084                None
 4085            };
 4086
 4087            if let Some(highlights) = highlights {
 4088                this.update(&mut cx, |this, cx| {
 4089                    if this.pending_rename.is_some() {
 4090                        return;
 4091                    }
 4092
 4093                    let buffer_id = cursor_position.buffer_id;
 4094                    let buffer = this.buffer.read(cx);
 4095                    if !buffer
 4096                        .text_anchor_for_position(cursor_position, cx)
 4097                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4098                    {
 4099                        return;
 4100                    }
 4101
 4102                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4103                    let mut write_ranges = Vec::new();
 4104                    let mut read_ranges = Vec::new();
 4105                    for highlight in highlights {
 4106                        for (excerpt_id, excerpt_range) in
 4107                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4108                        {
 4109                            let start = highlight
 4110                                .range
 4111                                .start
 4112                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4113                            let end = highlight
 4114                                .range
 4115                                .end
 4116                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4117                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4118                                continue;
 4119                            }
 4120
 4121                            let range = Anchor {
 4122                                buffer_id,
 4123                                excerpt_id: excerpt_id,
 4124                                text_anchor: start,
 4125                            }..Anchor {
 4126                                buffer_id,
 4127                                excerpt_id,
 4128                                text_anchor: end,
 4129                            };
 4130                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4131                                write_ranges.push(range);
 4132                            } else {
 4133                                read_ranges.push(range);
 4134                            }
 4135                        }
 4136                    }
 4137
 4138                    this.highlight_background::<DocumentHighlightRead>(
 4139                        read_ranges,
 4140                        |theme| theme.editor_document_highlight_read_background,
 4141                        cx,
 4142                    );
 4143                    this.highlight_background::<DocumentHighlightWrite>(
 4144                        write_ranges,
 4145                        |theme| theme.editor_document_highlight_write_background,
 4146                        cx,
 4147                    );
 4148                    cx.notify();
 4149                })
 4150                .log_err();
 4151            }
 4152        }));
 4153        None
 4154    }
 4155
 4156    fn refresh_inline_completion(
 4157        &mut self,
 4158        debounce: bool,
 4159        cx: &mut ViewContext<Self>,
 4160    ) -> Option<()> {
 4161        let provider = self.inline_completion_provider()?;
 4162        let cursor = self.selections.newest_anchor().head();
 4163        let (buffer, cursor_buffer_position) =
 4164            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4165        if !self.show_inline_completions
 4166            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4167        {
 4168            self.clear_inline_completion(cx);
 4169            return None;
 4170        }
 4171
 4172        self.update_visible_inline_completion(cx);
 4173        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4174        Some(())
 4175    }
 4176
 4177    fn cycle_inline_completion(
 4178        &mut self,
 4179        direction: Direction,
 4180        cx: &mut ViewContext<Self>,
 4181    ) -> Option<()> {
 4182        let provider = self.inline_completion_provider()?;
 4183        let cursor = self.selections.newest_anchor().head();
 4184        let (buffer, cursor_buffer_position) =
 4185            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4186        if !self.show_inline_completions
 4187            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4188        {
 4189            return None;
 4190        }
 4191
 4192        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4193        self.update_visible_inline_completion(cx);
 4194
 4195        Some(())
 4196    }
 4197
 4198    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4199        if !self.has_active_inline_completion(cx) {
 4200            self.refresh_inline_completion(false, cx);
 4201            return;
 4202        }
 4203
 4204        self.update_visible_inline_completion(cx);
 4205    }
 4206
 4207    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4208        self.show_cursor_names(cx);
 4209    }
 4210
 4211    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4212        self.show_cursor_names = true;
 4213        cx.notify();
 4214        cx.spawn(|this, mut cx| async move {
 4215            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4216            this.update(&mut cx, |this, cx| {
 4217                this.show_cursor_names = false;
 4218                cx.notify()
 4219            })
 4220            .ok()
 4221        })
 4222        .detach();
 4223    }
 4224
 4225    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4226        if self.has_active_inline_completion(cx) {
 4227            self.cycle_inline_completion(Direction::Next, cx);
 4228        } else {
 4229            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4230            if is_copilot_disabled {
 4231                cx.propagate();
 4232            }
 4233        }
 4234    }
 4235
 4236    pub fn previous_inline_completion(
 4237        &mut self,
 4238        _: &PreviousInlineCompletion,
 4239        cx: &mut ViewContext<Self>,
 4240    ) {
 4241        if self.has_active_inline_completion(cx) {
 4242            self.cycle_inline_completion(Direction::Prev, cx);
 4243        } else {
 4244            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4245            if is_copilot_disabled {
 4246                cx.propagate();
 4247            }
 4248        }
 4249    }
 4250
 4251    fn accept_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4252        if let Some(completion) = self.take_active_inline_completion(cx) {
 4253            if let Some(provider) = self.inline_completion_provider() {
 4254                provider.accept(cx);
 4255            }
 4256
 4257            cx.emit(EditorEvent::InputHandled {
 4258                utf16_range_to_replace: None,
 4259                text: completion.text.to_string().into(),
 4260            });
 4261            self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4262            cx.notify();
 4263            true
 4264        } else {
 4265            false
 4266        }
 4267    }
 4268
 4269    pub fn accept_partial_inline_completion(
 4270        &mut self,
 4271        _: &AcceptPartialInlineCompletion,
 4272        cx: &mut ViewContext<Self>,
 4273    ) {
 4274        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4275            if let Some(completion) = self.take_active_inline_completion(cx) {
 4276                let mut partial_completion = completion
 4277                    .text
 4278                    .chars()
 4279                    .by_ref()
 4280                    .take_while(|c| c.is_alphabetic())
 4281                    .collect::<String>();
 4282                if partial_completion.is_empty() {
 4283                    partial_completion = completion
 4284                        .text
 4285                        .chars()
 4286                        .by_ref()
 4287                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4288                        .collect::<String>();
 4289                }
 4290
 4291                cx.emit(EditorEvent::InputHandled {
 4292                    utf16_range_to_replace: None,
 4293                    text: partial_completion.clone().into(),
 4294                });
 4295                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4296                self.refresh_inline_completion(true, cx);
 4297                cx.notify();
 4298            }
 4299        }
 4300    }
 4301
 4302    fn discard_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4303        if let Some(provider) = self.inline_completion_provider() {
 4304            provider.discard(cx);
 4305        }
 4306
 4307        self.take_active_inline_completion(cx).is_some()
 4308    }
 4309
 4310    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4311        if let Some(completion) = self.active_inline_completion.as_ref() {
 4312            let buffer = self.buffer.read(cx).read(cx);
 4313            completion.position.is_valid(&buffer)
 4314        } else {
 4315            false
 4316        }
 4317    }
 4318
 4319    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4320        let completion = self.active_inline_completion.take()?;
 4321        self.display_map.update(cx, |map, cx| {
 4322            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4323        });
 4324        let buffer = self.buffer.read(cx).read(cx);
 4325
 4326        if completion.position.is_valid(&buffer) {
 4327            Some(completion)
 4328        } else {
 4329            None
 4330        }
 4331    }
 4332
 4333    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4334        let selection = self.selections.newest_anchor();
 4335        let cursor = selection.head();
 4336
 4337        if self.context_menu.read().is_none()
 4338            && self.completion_tasks.is_empty()
 4339            && selection.start == selection.end
 4340        {
 4341            if let Some(provider) = self.inline_completion_provider() {
 4342                if let Some((buffer, cursor_buffer_position)) =
 4343                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4344                {
 4345                    if let Some(text) =
 4346                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 4347                    {
 4348                        let text = Rope::from(text);
 4349                        let mut to_remove = Vec::new();
 4350                        if let Some(completion) = self.active_inline_completion.take() {
 4351                            to_remove.push(completion.id);
 4352                        }
 4353
 4354                        let completion_inlay =
 4355                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 4356                        self.active_inline_completion = Some(completion_inlay.clone());
 4357                        self.display_map.update(cx, move |map, cx| {
 4358                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 4359                        });
 4360                        cx.notify();
 4361                        return;
 4362                    }
 4363                }
 4364            }
 4365        }
 4366
 4367        self.discard_inline_completion(cx);
 4368    }
 4369
 4370    fn clear_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4371        if let Some(old_completion) = self.active_inline_completion.take() {
 4372            self.splice_inlays(vec![old_completion.id], Vec::new(), cx);
 4373        }
 4374        self.discard_inline_completion(cx);
 4375    }
 4376
 4377    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4378        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4379    }
 4380
 4381    pub fn render_code_actions_indicator(
 4382        &self,
 4383        _style: &EditorStyle,
 4384        is_active: bool,
 4385        cx: &mut ViewContext<Self>,
 4386    ) -> Option<IconButton> {
 4387        if self.available_code_actions.is_some() {
 4388            Some(
 4389                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4390                    .icon_size(IconSize::XSmall)
 4391                    .size(ui::ButtonSize::None)
 4392                    .icon_color(Color::Muted)
 4393                    .selected(is_active)
 4394                    .on_click(cx.listener(|editor, _e, cx| {
 4395                        editor.toggle_code_actions(
 4396                            &ToggleCodeActions {
 4397                                deployed_from_indicator: true,
 4398                            },
 4399                            cx,
 4400                        );
 4401                    })),
 4402            )
 4403        } else {
 4404            None
 4405        }
 4406    }
 4407
 4408    pub fn render_fold_indicators(
 4409        &mut self,
 4410        fold_data: Vec<Option<(FoldStatus, u32, bool)>>,
 4411        _style: &EditorStyle,
 4412        gutter_hovered: bool,
 4413        _line_height: Pixels,
 4414        _gutter_margin: Pixels,
 4415        cx: &mut ViewContext<Self>,
 4416    ) -> Vec<Option<AnyElement>> {
 4417        fold_data
 4418            .iter()
 4419            .enumerate()
 4420            .map(|(ix, fold_data)| {
 4421                fold_data
 4422                    .map(|(fold_status, buffer_row, active)| {
 4423                        (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
 4424                            IconButton::new(ix, ui::IconName::ChevronDown)
 4425                                .on_click(cx.listener(move |this, _e, cx| match fold_status {
 4426                                    FoldStatus::Folded => {
 4427                                        this.unfold_at(&UnfoldAt { buffer_row }, cx);
 4428                                    }
 4429                                    FoldStatus::Foldable => {
 4430                                        this.fold_at(&FoldAt { buffer_row }, cx);
 4431                                    }
 4432                                }))
 4433                                .icon_color(ui::Color::Muted)
 4434                                .icon_size(ui::IconSize::Small)
 4435                                .selected(fold_status == FoldStatus::Folded)
 4436                                .selected_icon(ui::IconName::ChevronRight)
 4437                                .size(ui::ButtonSize::None)
 4438                                .into_any_element()
 4439                        })
 4440                    })
 4441                    .flatten()
 4442            })
 4443            .collect()
 4444    }
 4445
 4446    pub fn context_menu_visible(&self) -> bool {
 4447        self.context_menu
 4448            .read()
 4449            .as_ref()
 4450            .map_or(false, |menu| menu.visible())
 4451    }
 4452
 4453    pub fn render_context_menu(
 4454        &self,
 4455        cursor_position: DisplayPoint,
 4456        style: &EditorStyle,
 4457        max_height: Pixels,
 4458        cx: &mut ViewContext<Editor>,
 4459    ) -> Option<(DisplayPoint, AnyElement)> {
 4460        self.context_menu.read().as_ref().map(|menu| {
 4461            menu.render(
 4462                cursor_position,
 4463                style,
 4464                max_height,
 4465                self.workspace.as_ref().map(|(w, _)| w.clone()),
 4466                cx,
 4467            )
 4468        })
 4469    }
 4470
 4471    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 4472        cx.notify();
 4473        self.completion_tasks.clear();
 4474        let context_menu = self.context_menu.write().take();
 4475        if context_menu.is_some() {
 4476            self.update_visible_inline_completion(cx);
 4477        }
 4478        context_menu
 4479    }
 4480
 4481    pub fn insert_snippet(
 4482        &mut self,
 4483        insertion_ranges: &[Range<usize>],
 4484        snippet: Snippet,
 4485        cx: &mut ViewContext<Self>,
 4486    ) -> Result<()> {
 4487        let tabstops = self.buffer.update(cx, |buffer, cx| {
 4488            let snippet_text: Arc<str> = snippet.text.clone().into();
 4489            buffer.edit(
 4490                insertion_ranges
 4491                    .iter()
 4492                    .cloned()
 4493                    .map(|range| (range, snippet_text.clone())),
 4494                Some(AutoindentMode::EachLine),
 4495                cx,
 4496            );
 4497
 4498            let snapshot = &*buffer.read(cx);
 4499            let snippet = &snippet;
 4500            snippet
 4501                .tabstops
 4502                .iter()
 4503                .map(|tabstop| {
 4504                    let mut tabstop_ranges = tabstop
 4505                        .iter()
 4506                        .flat_map(|tabstop_range| {
 4507                            let mut delta = 0_isize;
 4508                            insertion_ranges.iter().map(move |insertion_range| {
 4509                                let insertion_start = insertion_range.start as isize + delta;
 4510                                delta +=
 4511                                    snippet.text.len() as isize - insertion_range.len() as isize;
 4512
 4513                                let start = snapshot.anchor_before(
 4514                                    (insertion_start + tabstop_range.start) as usize,
 4515                                );
 4516                                let end = snapshot
 4517                                    .anchor_after((insertion_start + tabstop_range.end) as usize);
 4518                                start..end
 4519                            })
 4520                        })
 4521                        .collect::<Vec<_>>();
 4522                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 4523                    tabstop_ranges
 4524                })
 4525                .collect::<Vec<_>>()
 4526        });
 4527
 4528        if let Some(tabstop) = tabstops.first() {
 4529            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4530                s.select_ranges(tabstop.iter().cloned());
 4531            });
 4532            self.snippet_stack.push(SnippetState {
 4533                active_index: 0,
 4534                ranges: tabstops,
 4535            });
 4536
 4537            // Check whether the just-entered snippet ends with an auto-closable bracket.
 4538            if self.autoclose_regions.is_empty() {
 4539                let snapshot = self.buffer.read(cx).snapshot(cx);
 4540                for selection in &mut self.selections.all::<Point>(cx) {
 4541                    let selection_head = selection.head();
 4542                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 4543                        continue;
 4544                    };
 4545
 4546                    let mut bracket_pair = None;
 4547                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 4548                    let prev_chars = snapshot
 4549                        .reversed_chars_at(selection_head)
 4550                        .collect::<String>();
 4551                    for (pair, enabled) in scope.brackets() {
 4552                        if enabled
 4553                            && pair.close
 4554                            && prev_chars.starts_with(pair.start.as_str())
 4555                            && next_chars.starts_with(pair.end.as_str())
 4556                        {
 4557                            bracket_pair = Some(pair.clone());
 4558                            break;
 4559                        }
 4560                    }
 4561                    if let Some(pair) = bracket_pair {
 4562                        let start = snapshot.anchor_after(selection_head);
 4563                        let end = snapshot.anchor_after(selection_head);
 4564                        self.autoclose_regions.push(AutocloseRegion {
 4565                            selection_id: selection.id,
 4566                            range: start..end,
 4567                            pair,
 4568                        });
 4569                    }
 4570                }
 4571            }
 4572        }
 4573        Ok(())
 4574    }
 4575
 4576    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4577        self.move_to_snippet_tabstop(Bias::Right, cx)
 4578    }
 4579
 4580    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4581        self.move_to_snippet_tabstop(Bias::Left, cx)
 4582    }
 4583
 4584    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 4585        if let Some(mut snippet) = self.snippet_stack.pop() {
 4586            match bias {
 4587                Bias::Left => {
 4588                    if snippet.active_index > 0 {
 4589                        snippet.active_index -= 1;
 4590                    } else {
 4591                        self.snippet_stack.push(snippet);
 4592                        return false;
 4593                    }
 4594                }
 4595                Bias::Right => {
 4596                    if snippet.active_index + 1 < snippet.ranges.len() {
 4597                        snippet.active_index += 1;
 4598                    } else {
 4599                        self.snippet_stack.push(snippet);
 4600                        return false;
 4601                    }
 4602                }
 4603            }
 4604            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 4605                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4606                    s.select_anchor_ranges(current_ranges.iter().cloned())
 4607                });
 4608                // If snippet state is not at the last tabstop, push it back on the stack
 4609                if snippet.active_index + 1 < snippet.ranges.len() {
 4610                    self.snippet_stack.push(snippet);
 4611                }
 4612                return true;
 4613            }
 4614        }
 4615
 4616        false
 4617    }
 4618
 4619    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 4620        self.transact(cx, |this, cx| {
 4621            this.select_all(&SelectAll, cx);
 4622            this.insert("", cx);
 4623        });
 4624    }
 4625
 4626    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 4627        self.transact(cx, |this, cx| {
 4628            this.select_autoclose_pair(cx);
 4629            let mut selections = this.selections.all::<Point>(cx);
 4630            if !this.selections.line_mode {
 4631                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 4632                for selection in &mut selections {
 4633                    if selection.is_empty() {
 4634                        let old_head = selection.head();
 4635                        let mut new_head =
 4636                            movement::left(&display_map, old_head.to_display_point(&display_map))
 4637                                .to_point(&display_map);
 4638                        if let Some((buffer, line_buffer_range)) = display_map
 4639                            .buffer_snapshot
 4640                            .buffer_line_for_row(old_head.row)
 4641                        {
 4642                            let indent_size =
 4643                                buffer.indent_size_for_line(line_buffer_range.start.row);
 4644                            let indent_len = match indent_size.kind {
 4645                                IndentKind::Space => {
 4646                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 4647                                }
 4648                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 4649                            };
 4650                            if old_head.column <= indent_size.len && old_head.column > 0 {
 4651                                let indent_len = indent_len.get();
 4652                                new_head = cmp::min(
 4653                                    new_head,
 4654                                    Point::new(
 4655                                        old_head.row,
 4656                                        ((old_head.column - 1) / indent_len) * indent_len,
 4657                                    ),
 4658                                );
 4659                            }
 4660                        }
 4661
 4662                        selection.set_head(new_head, SelectionGoal::None);
 4663                    }
 4664                }
 4665            }
 4666
 4667            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4668            this.insert("", cx);
 4669            this.refresh_inline_completion(true, cx);
 4670        });
 4671    }
 4672
 4673    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 4674        self.transact(cx, |this, cx| {
 4675            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4676                let line_mode = s.line_mode;
 4677                s.move_with(|map, selection| {
 4678                    if selection.is_empty() && !line_mode {
 4679                        let cursor = movement::right(map, selection.head());
 4680                        selection.end = cursor;
 4681                        selection.reversed = true;
 4682                        selection.goal = SelectionGoal::None;
 4683                    }
 4684                })
 4685            });
 4686            this.insert("", cx);
 4687            this.refresh_inline_completion(true, cx);
 4688        });
 4689    }
 4690
 4691    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 4692        if self.move_to_prev_snippet_tabstop(cx) {
 4693            return;
 4694        }
 4695
 4696        self.outdent(&Outdent, cx);
 4697    }
 4698
 4699    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 4700        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 4701            return;
 4702        }
 4703
 4704        let mut selections = self.selections.all_adjusted(cx);
 4705        let buffer = self.buffer.read(cx);
 4706        let snapshot = buffer.snapshot(cx);
 4707        let rows_iter = selections.iter().map(|s| s.head().row);
 4708        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 4709
 4710        let mut edits = Vec::new();
 4711        let mut prev_edited_row = 0;
 4712        let mut row_delta = 0;
 4713        for selection in &mut selections {
 4714            if selection.start.row != prev_edited_row {
 4715                row_delta = 0;
 4716            }
 4717            prev_edited_row = selection.end.row;
 4718
 4719            // If the selection is non-empty, then increase the indentation of the selected lines.
 4720            if !selection.is_empty() {
 4721                row_delta =
 4722                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4723                continue;
 4724            }
 4725
 4726            // If the selection is empty and the cursor is in the leading whitespace before the
 4727            // suggested indentation, then auto-indent the line.
 4728            let cursor = selection.head();
 4729            let current_indent = snapshot.indent_size_for_line(cursor.row);
 4730            if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
 4731                if cursor.column < suggested_indent.len
 4732                    && cursor.column <= current_indent.len
 4733                    && current_indent.len <= suggested_indent.len
 4734                {
 4735                    selection.start = Point::new(cursor.row, suggested_indent.len);
 4736                    selection.end = selection.start;
 4737                    if row_delta == 0 {
 4738                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 4739                            cursor.row,
 4740                            current_indent,
 4741                            suggested_indent,
 4742                        ));
 4743                        row_delta = suggested_indent.len - current_indent.len;
 4744                    }
 4745                    continue;
 4746                }
 4747            }
 4748
 4749            // Accept copilot completion if there is only one selection and the cursor is not
 4750            // in the leading whitespace.
 4751            if self.selections.count() == 1
 4752                && cursor.column >= current_indent.len
 4753                && self.has_active_inline_completion(cx)
 4754            {
 4755                self.accept_inline_completion(cx);
 4756                return;
 4757            }
 4758
 4759            // Otherwise, insert a hard or soft tab.
 4760            let settings = buffer.settings_at(cursor, cx);
 4761            let tab_size = if settings.hard_tabs {
 4762                IndentSize::tab()
 4763            } else {
 4764                let tab_size = settings.tab_size.get();
 4765                let char_column = snapshot
 4766                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 4767                    .flat_map(str::chars)
 4768                    .count()
 4769                    + row_delta as usize;
 4770                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 4771                IndentSize::spaces(chars_to_next_tab_stop)
 4772            };
 4773            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 4774            selection.end = selection.start;
 4775            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 4776            row_delta += tab_size.len;
 4777        }
 4778
 4779        self.transact(cx, |this, cx| {
 4780            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4781            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4782            this.refresh_inline_completion(true, cx);
 4783        });
 4784    }
 4785
 4786    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 4787        if self.read_only(cx) {
 4788            return;
 4789        }
 4790        let mut selections = self.selections.all::<Point>(cx);
 4791        let mut prev_edited_row = 0;
 4792        let mut row_delta = 0;
 4793        let mut edits = Vec::new();
 4794        let buffer = self.buffer.read(cx);
 4795        let snapshot = buffer.snapshot(cx);
 4796        for selection in &mut selections {
 4797            if selection.start.row != prev_edited_row {
 4798                row_delta = 0;
 4799            }
 4800            prev_edited_row = selection.end.row;
 4801
 4802            row_delta =
 4803                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4804        }
 4805
 4806        self.transact(cx, |this, cx| {
 4807            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4808            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4809        });
 4810    }
 4811
 4812    fn indent_selection(
 4813        buffer: &MultiBuffer,
 4814        snapshot: &MultiBufferSnapshot,
 4815        selection: &mut Selection<Point>,
 4816        edits: &mut Vec<(Range<Point>, String)>,
 4817        delta_for_start_row: u32,
 4818        cx: &AppContext,
 4819    ) -> u32 {
 4820        let settings = buffer.settings_at(selection.start, cx);
 4821        let tab_size = settings.tab_size.get();
 4822        let indent_kind = if settings.hard_tabs {
 4823            IndentKind::Tab
 4824        } else {
 4825            IndentKind::Space
 4826        };
 4827        let mut start_row = selection.start.row;
 4828        let mut end_row = selection.end.row + 1;
 4829
 4830        // If a selection ends at the beginning of a line, don't indent
 4831        // that last line.
 4832        if selection.end.column == 0 && selection.end.row > selection.start.row {
 4833            end_row -= 1;
 4834        }
 4835
 4836        // Avoid re-indenting a row that has already been indented by a
 4837        // previous selection, but still update this selection's column
 4838        // to reflect that indentation.
 4839        if delta_for_start_row > 0 {
 4840            start_row += 1;
 4841            selection.start.column += delta_for_start_row;
 4842            if selection.end.row == selection.start.row {
 4843                selection.end.column += delta_for_start_row;
 4844            }
 4845        }
 4846
 4847        let mut delta_for_end_row = 0;
 4848        for row in start_row..end_row {
 4849            let current_indent = snapshot.indent_size_for_line(row);
 4850            let indent_delta = match (current_indent.kind, indent_kind) {
 4851                (IndentKind::Space, IndentKind::Space) => {
 4852                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 4853                    IndentSize::spaces(columns_to_next_tab_stop)
 4854                }
 4855                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 4856                (_, IndentKind::Tab) => IndentSize::tab(),
 4857            };
 4858
 4859            let row_start = Point::new(row, 0);
 4860            edits.push((
 4861                row_start..row_start,
 4862                indent_delta.chars().collect::<String>(),
 4863            ));
 4864
 4865            // Update this selection's endpoints to reflect the indentation.
 4866            if row == selection.start.row {
 4867                selection.start.column += indent_delta.len;
 4868            }
 4869            if row == selection.end.row {
 4870                selection.end.column += indent_delta.len;
 4871                delta_for_end_row = indent_delta.len;
 4872            }
 4873        }
 4874
 4875        if selection.start.row == selection.end.row {
 4876            delta_for_start_row + delta_for_end_row
 4877        } else {
 4878            delta_for_end_row
 4879        }
 4880    }
 4881
 4882    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 4883        if self.read_only(cx) {
 4884            return;
 4885        }
 4886        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4887        let selections = self.selections.all::<Point>(cx);
 4888        let mut deletion_ranges = Vec::new();
 4889        let mut last_outdent = None;
 4890        {
 4891            let buffer = self.buffer.read(cx);
 4892            let snapshot = buffer.snapshot(cx);
 4893            for selection in &selections {
 4894                let settings = buffer.settings_at(selection.start, cx);
 4895                let tab_size = settings.tab_size.get();
 4896                let mut rows = selection.spanned_rows(false, &display_map);
 4897
 4898                // Avoid re-outdenting a row that has already been outdented by a
 4899                // previous selection.
 4900                if let Some(last_row) = last_outdent {
 4901                    if last_row == rows.start {
 4902                        rows.start += 1;
 4903                    }
 4904                }
 4905
 4906                for row in rows {
 4907                    let indent_size = snapshot.indent_size_for_line(row);
 4908                    if indent_size.len > 0 {
 4909                        let deletion_len = match indent_size.kind {
 4910                            IndentKind::Space => {
 4911                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 4912                                if columns_to_prev_tab_stop == 0 {
 4913                                    tab_size
 4914                                } else {
 4915                                    columns_to_prev_tab_stop
 4916                                }
 4917                            }
 4918                            IndentKind::Tab => 1,
 4919                        };
 4920                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
 4921                        last_outdent = Some(row);
 4922                    }
 4923                }
 4924            }
 4925        }
 4926
 4927        self.transact(cx, |this, cx| {
 4928            this.buffer.update(cx, |buffer, cx| {
 4929                let empty_str: Arc<str> = "".into();
 4930                buffer.edit(
 4931                    deletion_ranges
 4932                        .into_iter()
 4933                        .map(|range| (range, empty_str.clone())),
 4934                    None,
 4935                    cx,
 4936                );
 4937            });
 4938            let selections = this.selections.all::<usize>(cx);
 4939            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4940        });
 4941    }
 4942
 4943    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 4944        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4945        let selections = self.selections.all::<Point>(cx);
 4946
 4947        let mut new_cursors = Vec::new();
 4948        let mut edit_ranges = Vec::new();
 4949        let mut selections = selections.iter().peekable();
 4950        while let Some(selection) = selections.next() {
 4951            let mut rows = selection.spanned_rows(false, &display_map);
 4952            let goal_display_column = selection.head().to_display_point(&display_map).column();
 4953
 4954            // Accumulate contiguous regions of rows that we want to delete.
 4955            while let Some(next_selection) = selections.peek() {
 4956                let next_rows = next_selection.spanned_rows(false, &display_map);
 4957                if next_rows.start <= rows.end {
 4958                    rows.end = next_rows.end;
 4959                    selections.next().unwrap();
 4960                } else {
 4961                    break;
 4962                }
 4963            }
 4964
 4965            let buffer = &display_map.buffer_snapshot;
 4966            let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
 4967            let edit_end;
 4968            let cursor_buffer_row;
 4969            if buffer.max_point().row >= rows.end {
 4970                // If there's a line after the range, delete the \n from the end of the row range
 4971                // and position the cursor on the next line.
 4972                edit_end = Point::new(rows.end, 0).to_offset(buffer);
 4973                cursor_buffer_row = rows.end;
 4974            } else {
 4975                // If there isn't a line after the range, delete the \n from the line before the
 4976                // start of the row range and position the cursor there.
 4977                edit_start = edit_start.saturating_sub(1);
 4978                edit_end = buffer.len();
 4979                cursor_buffer_row = rows.start.saturating_sub(1);
 4980            }
 4981
 4982            let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
 4983            *cursor.column_mut() =
 4984                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 4985
 4986            new_cursors.push((
 4987                selection.id,
 4988                buffer.anchor_after(cursor.to_point(&display_map)),
 4989            ));
 4990            edit_ranges.push(edit_start..edit_end);
 4991        }
 4992
 4993        self.transact(cx, |this, cx| {
 4994            let buffer = this.buffer.update(cx, |buffer, cx| {
 4995                let empty_str: Arc<str> = "".into();
 4996                buffer.edit(
 4997                    edit_ranges
 4998                        .into_iter()
 4999                        .map(|range| (range, empty_str.clone())),
 5000                    None,
 5001                    cx,
 5002                );
 5003                buffer.snapshot(cx)
 5004            });
 5005            let new_selections = new_cursors
 5006                .into_iter()
 5007                .map(|(id, cursor)| {
 5008                    let cursor = cursor.to_point(&buffer);
 5009                    Selection {
 5010                        id,
 5011                        start: cursor,
 5012                        end: cursor,
 5013                        reversed: false,
 5014                        goal: SelectionGoal::None,
 5015                    }
 5016                })
 5017                .collect();
 5018
 5019            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5020                s.select(new_selections);
 5021            });
 5022        });
 5023    }
 5024
 5025    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5026        if self.read_only(cx) {
 5027            return;
 5028        }
 5029        let mut row_ranges = Vec::<Range<u32>>::new();
 5030        for selection in self.selections.all::<Point>(cx) {
 5031            let start = selection.start.row;
 5032            let end = if selection.start.row == selection.end.row {
 5033                selection.start.row + 1
 5034            } else {
 5035                selection.end.row
 5036            };
 5037
 5038            if let Some(last_row_range) = row_ranges.last_mut() {
 5039                if start <= last_row_range.end {
 5040                    last_row_range.end = end;
 5041                    continue;
 5042                }
 5043            }
 5044            row_ranges.push(start..end);
 5045        }
 5046
 5047        let snapshot = self.buffer.read(cx).snapshot(cx);
 5048        let mut cursor_positions = Vec::new();
 5049        for row_range in &row_ranges {
 5050            let anchor = snapshot.anchor_before(Point::new(
 5051                row_range.end - 1,
 5052                snapshot.line_len(row_range.end - 1),
 5053            ));
 5054            cursor_positions.push(anchor..anchor);
 5055        }
 5056
 5057        self.transact(cx, |this, cx| {
 5058            for row_range in row_ranges.into_iter().rev() {
 5059                for row in row_range.rev() {
 5060                    let end_of_line = Point::new(row, snapshot.line_len(row));
 5061                    let indent = snapshot.indent_size_for_line(row + 1);
 5062                    let start_of_next_line = Point::new(row + 1, indent.len);
 5063
 5064                    let replace = if snapshot.line_len(row + 1) > indent.len {
 5065                        " "
 5066                    } else {
 5067                        ""
 5068                    };
 5069
 5070                    this.buffer.update(cx, |buffer, cx| {
 5071                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5072                    });
 5073                }
 5074            }
 5075
 5076            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5077                s.select_anchor_ranges(cursor_positions)
 5078            });
 5079        });
 5080    }
 5081
 5082    pub fn sort_lines_case_sensitive(
 5083        &mut self,
 5084        _: &SortLinesCaseSensitive,
 5085        cx: &mut ViewContext<Self>,
 5086    ) {
 5087        self.manipulate_lines(cx, |lines| lines.sort())
 5088    }
 5089
 5090    pub fn sort_lines_case_insensitive(
 5091        &mut self,
 5092        _: &SortLinesCaseInsensitive,
 5093        cx: &mut ViewContext<Self>,
 5094    ) {
 5095        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5096    }
 5097
 5098    pub fn unique_lines_case_insensitive(
 5099        &mut self,
 5100        _: &UniqueLinesCaseInsensitive,
 5101        cx: &mut ViewContext<Self>,
 5102    ) {
 5103        self.manipulate_lines(cx, |lines| {
 5104            let mut seen = HashSet::default();
 5105            lines.retain(|line| seen.insert(line.to_lowercase()));
 5106        })
 5107    }
 5108
 5109    pub fn unique_lines_case_sensitive(
 5110        &mut self,
 5111        _: &UniqueLinesCaseSensitive,
 5112        cx: &mut ViewContext<Self>,
 5113    ) {
 5114        self.manipulate_lines(cx, |lines| {
 5115            let mut seen = HashSet::default();
 5116            lines.retain(|line| seen.insert(*line));
 5117        })
 5118    }
 5119
 5120    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5121        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5122        if !revert_changes.is_empty() {
 5123            self.transact(cx, |editor, cx| {
 5124                editor.buffer().update(cx, |multi_buffer, cx| {
 5125                    for (buffer_id, buffer_revert_ranges) in revert_changes {
 5126                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5127                            buffer.update(cx, |buffer, cx| {
 5128                                buffer.edit(buffer_revert_ranges, None, cx);
 5129                            });
 5130                        }
 5131                    }
 5132                });
 5133                editor.change_selections(None, cx, |selections| selections.refresh());
 5134            });
 5135        }
 5136    }
 5137
 5138    fn gather_revert_changes(
 5139        &mut self,
 5140        selections: &[Selection<Anchor>],
 5141        cx: &mut ViewContext<'_, Editor>,
 5142    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Arc<str>)>> {
 5143        let mut revert_changes = HashMap::default();
 5144        self.buffer.update(cx, |multi_buffer, cx| {
 5145            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5146            let selected_multi_buffer_rows = selections.iter().map(|selection| {
 5147                let head = selection.head();
 5148                let tail = selection.tail();
 5149                let start = tail.to_point(&multi_buffer_snapshot).row;
 5150                let end = head.to_point(&multi_buffer_snapshot).row;
 5151                if start > end {
 5152                    end..start
 5153                } else {
 5154                    start..end
 5155                }
 5156            });
 5157
 5158            let mut processed_buffer_rows =
 5159                HashMap::<BufferId, HashSet<Range<text::Anchor>>>::default();
 5160            for selected_multi_buffer_rows in selected_multi_buffer_rows {
 5161                let query_rows =
 5162                    selected_multi_buffer_rows.start..selected_multi_buffer_rows.end + 1;
 5163                for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
 5164                    // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
 5165                    // when the caret is just above or just below the deleted hunk.
 5166                    let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
 5167                    let related_to_selection = if allow_adjacent {
 5168                        hunk.associated_range.overlaps(&query_rows)
 5169                            || hunk.associated_range.start == query_rows.end
 5170                            || hunk.associated_range.end == query_rows.start
 5171                    } else {
 5172                        // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
 5173                        // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
 5174                        hunk.associated_range.overlaps(&selected_multi_buffer_rows)
 5175                            || selected_multi_buffer_rows.end == hunk.associated_range.start
 5176                    };
 5177                    if related_to_selection {
 5178                        if !processed_buffer_rows
 5179                            .entry(hunk.buffer_id)
 5180                            .or_default()
 5181                            .insert(hunk.buffer_range.start..hunk.buffer_range.end)
 5182                        {
 5183                            continue;
 5184                        }
 5185                        Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5186                    }
 5187                }
 5188            }
 5189        });
 5190        revert_changes
 5191    }
 5192
 5193    fn prepare_revert_change(
 5194        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Arc<str>)>>,
 5195        multi_buffer: &MultiBuffer,
 5196        hunk: &DiffHunk<u32>,
 5197        cx: &mut AppContext,
 5198    ) -> Option<()> {
 5199        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5200        let buffer = buffer.read(cx);
 5201        let original_text = buffer.diff_base()?.get(hunk.diff_base_byte_range.clone())?;
 5202        let buffer_snapshot = buffer.snapshot();
 5203        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5204        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5205            probe
 5206                .0
 5207                .start
 5208                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5209                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5210                .then(probe.1.as_ref().cmp(original_text))
 5211        }) {
 5212            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), Arc::from(original_text)));
 5213            Some(())
 5214        } else {
 5215            None
 5216        }
 5217    }
 5218
 5219    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5220        self.manipulate_lines(cx, |lines| lines.reverse())
 5221    }
 5222
 5223    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5224        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5225    }
 5226
 5227    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5228    where
 5229        Fn: FnMut(&mut Vec<&str>),
 5230    {
 5231        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5232        let buffer = self.buffer.read(cx).snapshot(cx);
 5233
 5234        let mut edits = Vec::new();
 5235
 5236        let selections = self.selections.all::<Point>(cx);
 5237        let mut selections = selections.iter().peekable();
 5238        let mut contiguous_row_selections = Vec::new();
 5239        let mut new_selections = Vec::new();
 5240        let mut added_lines = 0;
 5241        let mut removed_lines = 0;
 5242
 5243        while let Some(selection) = selections.next() {
 5244            let (start_row, end_row) = consume_contiguous_rows(
 5245                &mut contiguous_row_selections,
 5246                selection,
 5247                &display_map,
 5248                &mut selections,
 5249            );
 5250
 5251            let start_point = Point::new(start_row, 0);
 5252            let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
 5253            let text = buffer
 5254                .text_for_range(start_point..end_point)
 5255                .collect::<String>();
 5256
 5257            let mut lines = text.split('\n').collect_vec();
 5258
 5259            let lines_before = lines.len();
 5260            callback(&mut lines);
 5261            let lines_after = lines.len();
 5262
 5263            edits.push((start_point..end_point, lines.join("\n")));
 5264
 5265            // Selections must change based on added and removed line count
 5266            let start_row = start_point.row + added_lines as u32 - removed_lines as u32;
 5267            let end_row = start_row + lines_after.saturating_sub(1) as u32;
 5268            new_selections.push(Selection {
 5269                id: selection.id,
 5270                start: start_row,
 5271                end: end_row,
 5272                goal: SelectionGoal::None,
 5273                reversed: selection.reversed,
 5274            });
 5275
 5276            if lines_after > lines_before {
 5277                added_lines += lines_after - lines_before;
 5278            } else if lines_before > lines_after {
 5279                removed_lines += lines_before - lines_after;
 5280            }
 5281        }
 5282
 5283        self.transact(cx, |this, cx| {
 5284            let buffer = this.buffer.update(cx, |buffer, cx| {
 5285                buffer.edit(edits, None, cx);
 5286                buffer.snapshot(cx)
 5287            });
 5288
 5289            // Recalculate offsets on newly edited buffer
 5290            let new_selections = new_selections
 5291                .iter()
 5292                .map(|s| {
 5293                    let start_point = Point::new(s.start, 0);
 5294                    let end_point = Point::new(s.end, buffer.line_len(s.end));
 5295                    Selection {
 5296                        id: s.id,
 5297                        start: buffer.point_to_offset(start_point),
 5298                        end: buffer.point_to_offset(end_point),
 5299                        goal: s.goal,
 5300                        reversed: s.reversed,
 5301                    }
 5302                })
 5303                .collect();
 5304
 5305            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5306                s.select(new_selections);
 5307            });
 5308
 5309            this.request_autoscroll(Autoscroll::fit(), cx);
 5310        });
 5311    }
 5312
 5313    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5314        self.manipulate_text(cx, |text| text.to_uppercase())
 5315    }
 5316
 5317    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5318        self.manipulate_text(cx, |text| text.to_lowercase())
 5319    }
 5320
 5321    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5322        self.manipulate_text(cx, |text| {
 5323            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5324            // https://github.com/rutrum/convert-case/issues/16
 5325            text.split('\n')
 5326                .map(|line| line.to_case(Case::Title))
 5327                .join("\n")
 5328        })
 5329    }
 5330
 5331    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 5332        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 5333    }
 5334
 5335    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 5336        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 5337    }
 5338
 5339    pub fn convert_to_upper_camel_case(
 5340        &mut self,
 5341        _: &ConvertToUpperCamelCase,
 5342        cx: &mut ViewContext<Self>,
 5343    ) {
 5344        self.manipulate_text(cx, |text| {
 5345            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5346            // https://github.com/rutrum/convert-case/issues/16
 5347            text.split('\n')
 5348                .map(|line| line.to_case(Case::UpperCamel))
 5349                .join("\n")
 5350        })
 5351    }
 5352
 5353    pub fn convert_to_lower_camel_case(
 5354        &mut self,
 5355        _: &ConvertToLowerCamelCase,
 5356        cx: &mut ViewContext<Self>,
 5357    ) {
 5358        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 5359    }
 5360
 5361    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5362    where
 5363        Fn: FnMut(&str) -> String,
 5364    {
 5365        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5366        let buffer = self.buffer.read(cx).snapshot(cx);
 5367
 5368        let mut new_selections = Vec::new();
 5369        let mut edits = Vec::new();
 5370        let mut selection_adjustment = 0i32;
 5371
 5372        for selection in self.selections.all::<usize>(cx) {
 5373            let selection_is_empty = selection.is_empty();
 5374
 5375            let (start, end) = if selection_is_empty {
 5376                let word_range = movement::surrounding_word(
 5377                    &display_map,
 5378                    selection.start.to_display_point(&display_map),
 5379                );
 5380                let start = word_range.start.to_offset(&display_map, Bias::Left);
 5381                let end = word_range.end.to_offset(&display_map, Bias::Left);
 5382                (start, end)
 5383            } else {
 5384                (selection.start, selection.end)
 5385            };
 5386
 5387            let text = buffer.text_for_range(start..end).collect::<String>();
 5388            let old_length = text.len() as i32;
 5389            let text = callback(&text);
 5390
 5391            new_selections.push(Selection {
 5392                start: (start as i32 - selection_adjustment) as usize,
 5393                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 5394                goal: SelectionGoal::None,
 5395                ..selection
 5396            });
 5397
 5398            selection_adjustment += old_length - text.len() as i32;
 5399
 5400            edits.push((start..end, text));
 5401        }
 5402
 5403        self.transact(cx, |this, cx| {
 5404            this.buffer.update(cx, |buffer, cx| {
 5405                buffer.edit(edits, None, cx);
 5406            });
 5407
 5408            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5409                s.select(new_selections);
 5410            });
 5411
 5412            this.request_autoscroll(Autoscroll::fit(), cx);
 5413        });
 5414    }
 5415
 5416    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 5417        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5418        let buffer = &display_map.buffer_snapshot;
 5419        let selections = self.selections.all::<Point>(cx);
 5420
 5421        let mut edits = Vec::new();
 5422        let mut selections_iter = selections.iter().peekable();
 5423        while let Some(selection) = selections_iter.next() {
 5424            // Avoid duplicating the same lines twice.
 5425            let mut rows = selection.spanned_rows(false, &display_map);
 5426
 5427            while let Some(next_selection) = selections_iter.peek() {
 5428                let next_rows = next_selection.spanned_rows(false, &display_map);
 5429                if next_rows.start < rows.end {
 5430                    rows.end = next_rows.end;
 5431                    selections_iter.next().unwrap();
 5432                } else {
 5433                    break;
 5434                }
 5435            }
 5436
 5437            // Copy the text from the selected row region and splice it either at the start
 5438            // or end of the region.
 5439            let start = Point::new(rows.start, 0);
 5440            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
 5441            let text = buffer
 5442                .text_for_range(start..end)
 5443                .chain(Some("\n"))
 5444                .collect::<String>();
 5445            let insert_location = if upwards {
 5446                Point::new(rows.end, 0)
 5447            } else {
 5448                start
 5449            };
 5450            edits.push((insert_location..insert_location, text));
 5451        }
 5452
 5453        self.transact(cx, |this, cx| {
 5454            this.buffer.update(cx, |buffer, cx| {
 5455                buffer.edit(edits, None, cx);
 5456            });
 5457
 5458            this.request_autoscroll(Autoscroll::fit(), cx);
 5459        });
 5460    }
 5461
 5462    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 5463        self.duplicate_line(true, cx);
 5464    }
 5465
 5466    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 5467        self.duplicate_line(false, cx);
 5468    }
 5469
 5470    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 5471        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5472        let buffer = self.buffer.read(cx).snapshot(cx);
 5473
 5474        let mut edits = Vec::new();
 5475        let mut unfold_ranges = Vec::new();
 5476        let mut refold_ranges = Vec::new();
 5477
 5478        let selections = self.selections.all::<Point>(cx);
 5479        let mut selections = selections.iter().peekable();
 5480        let mut contiguous_row_selections = Vec::new();
 5481        let mut new_selections = Vec::new();
 5482
 5483        while let Some(selection) = selections.next() {
 5484            // Find all the selections that span a contiguous row range
 5485            let (start_row, end_row) = consume_contiguous_rows(
 5486                &mut contiguous_row_selections,
 5487                selection,
 5488                &display_map,
 5489                &mut selections,
 5490            );
 5491
 5492            // Move the text spanned by the row range to be before the line preceding the row range
 5493            if start_row > 0 {
 5494                let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
 5495                    ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
 5496                let insertion_point = display_map
 5497                    .prev_line_boundary(Point::new(start_row - 1, 0))
 5498                    .0;
 5499
 5500                // Don't move lines across excerpts
 5501                if buffer
 5502                    .excerpt_boundaries_in_range((
 5503                        Bound::Excluded(insertion_point),
 5504                        Bound::Included(range_to_move.end),
 5505                    ))
 5506                    .next()
 5507                    .is_none()
 5508                {
 5509                    let text = buffer
 5510                        .text_for_range(range_to_move.clone())
 5511                        .flat_map(|s| s.chars())
 5512                        .skip(1)
 5513                        .chain(['\n'])
 5514                        .collect::<String>();
 5515
 5516                    edits.push((
 5517                        buffer.anchor_after(range_to_move.start)
 5518                            ..buffer.anchor_before(range_to_move.end),
 5519                        String::new(),
 5520                    ));
 5521                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5522                    edits.push((insertion_anchor..insertion_anchor, text));
 5523
 5524                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 5525
 5526                    // Move selections up
 5527                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5528                        |mut selection| {
 5529                            selection.start.row -= row_delta;
 5530                            selection.end.row -= row_delta;
 5531                            selection
 5532                        },
 5533                    ));
 5534
 5535                    // Move folds up
 5536                    unfold_ranges.push(range_to_move.clone());
 5537                    for fold in display_map.folds_in_range(
 5538                        buffer.anchor_before(range_to_move.start)
 5539                            ..buffer.anchor_after(range_to_move.end),
 5540                    ) {
 5541                        let mut start = fold.range.start.to_point(&buffer);
 5542                        let mut end = fold.range.end.to_point(&buffer);
 5543                        start.row -= row_delta;
 5544                        end.row -= row_delta;
 5545                        refold_ranges.push(start..end);
 5546                    }
 5547                }
 5548            }
 5549
 5550            // If we didn't move line(s), preserve the existing selections
 5551            new_selections.append(&mut contiguous_row_selections);
 5552        }
 5553
 5554        self.transact(cx, |this, cx| {
 5555            this.unfold_ranges(unfold_ranges, true, true, cx);
 5556            this.buffer.update(cx, |buffer, cx| {
 5557                for (range, text) in edits {
 5558                    buffer.edit([(range, text)], None, cx);
 5559                }
 5560            });
 5561            this.fold_ranges(refold_ranges, true, cx);
 5562            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5563                s.select(new_selections);
 5564            })
 5565        });
 5566    }
 5567
 5568    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 5569        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5570        let buffer = self.buffer.read(cx).snapshot(cx);
 5571
 5572        let mut edits = Vec::new();
 5573        let mut unfold_ranges = Vec::new();
 5574        let mut refold_ranges = Vec::new();
 5575
 5576        let selections = self.selections.all::<Point>(cx);
 5577        let mut selections = selections.iter().peekable();
 5578        let mut contiguous_row_selections = Vec::new();
 5579        let mut new_selections = Vec::new();
 5580
 5581        while let Some(selection) = selections.next() {
 5582            // Find all the selections that span a contiguous row range
 5583            let (start_row, end_row) = consume_contiguous_rows(
 5584                &mut contiguous_row_selections,
 5585                selection,
 5586                &display_map,
 5587                &mut selections,
 5588            );
 5589
 5590            // Move the text spanned by the row range to be after the last line of the row range
 5591            if end_row <= buffer.max_point().row {
 5592                let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
 5593                let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
 5594
 5595                // Don't move lines across excerpt boundaries
 5596                if buffer
 5597                    .excerpt_boundaries_in_range((
 5598                        Bound::Excluded(range_to_move.start),
 5599                        Bound::Included(insertion_point),
 5600                    ))
 5601                    .next()
 5602                    .is_none()
 5603                {
 5604                    let mut text = String::from("\n");
 5605                    text.extend(buffer.text_for_range(range_to_move.clone()));
 5606                    text.pop(); // Drop trailing newline
 5607                    edits.push((
 5608                        buffer.anchor_after(range_to_move.start)
 5609                            ..buffer.anchor_before(range_to_move.end),
 5610                        String::new(),
 5611                    ));
 5612                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5613                    edits.push((insertion_anchor..insertion_anchor, text));
 5614
 5615                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 5616
 5617                    // Move selections down
 5618                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5619                        |mut selection| {
 5620                            selection.start.row += row_delta;
 5621                            selection.end.row += row_delta;
 5622                            selection
 5623                        },
 5624                    ));
 5625
 5626                    // Move folds down
 5627                    unfold_ranges.push(range_to_move.clone());
 5628                    for fold in display_map.folds_in_range(
 5629                        buffer.anchor_before(range_to_move.start)
 5630                            ..buffer.anchor_after(range_to_move.end),
 5631                    ) {
 5632                        let mut start = fold.range.start.to_point(&buffer);
 5633                        let mut end = fold.range.end.to_point(&buffer);
 5634                        start.row += row_delta;
 5635                        end.row += row_delta;
 5636                        refold_ranges.push(start..end);
 5637                    }
 5638                }
 5639            }
 5640
 5641            // If we didn't move line(s), preserve the existing selections
 5642            new_selections.append(&mut contiguous_row_selections);
 5643        }
 5644
 5645        self.transact(cx, |this, cx| {
 5646            this.unfold_ranges(unfold_ranges, true, true, cx);
 5647            this.buffer.update(cx, |buffer, cx| {
 5648                for (range, text) in edits {
 5649                    buffer.edit([(range, text)], None, cx);
 5650                }
 5651            });
 5652            this.fold_ranges(refold_ranges, true, cx);
 5653            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 5654        });
 5655    }
 5656
 5657    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 5658        let text_layout_details = &self.text_layout_details(cx);
 5659        self.transact(cx, |this, cx| {
 5660            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5661                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 5662                let line_mode = s.line_mode;
 5663                s.move_with(|display_map, selection| {
 5664                    if !selection.is_empty() || line_mode {
 5665                        return;
 5666                    }
 5667
 5668                    let mut head = selection.head();
 5669                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 5670                    if head.column() == display_map.line_len(head.row()) {
 5671                        transpose_offset = display_map
 5672                            .buffer_snapshot
 5673                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5674                    }
 5675
 5676                    if transpose_offset == 0 {
 5677                        return;
 5678                    }
 5679
 5680                    *head.column_mut() += 1;
 5681                    head = display_map.clip_point(head, Bias::Right);
 5682                    let goal = SelectionGoal::HorizontalPosition(
 5683                        display_map
 5684                            .x_for_display_point(head, &text_layout_details)
 5685                            .into(),
 5686                    );
 5687                    selection.collapse_to(head, goal);
 5688
 5689                    let transpose_start = display_map
 5690                        .buffer_snapshot
 5691                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5692                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 5693                        let transpose_end = display_map
 5694                            .buffer_snapshot
 5695                            .clip_offset(transpose_offset + 1, Bias::Right);
 5696                        if let Some(ch) =
 5697                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 5698                        {
 5699                            edits.push((transpose_start..transpose_offset, String::new()));
 5700                            edits.push((transpose_end..transpose_end, ch.to_string()));
 5701                        }
 5702                    }
 5703                });
 5704                edits
 5705            });
 5706            this.buffer
 5707                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 5708            let selections = this.selections.all::<usize>(cx);
 5709            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5710                s.select(selections);
 5711            });
 5712        });
 5713    }
 5714
 5715    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 5716        let mut text = String::new();
 5717        let buffer = self.buffer.read(cx).snapshot(cx);
 5718        let mut selections = self.selections.all::<Point>(cx);
 5719        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5720        {
 5721            let max_point = buffer.max_point();
 5722            let mut is_first = true;
 5723            for selection in &mut selections {
 5724                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5725                if is_entire_line {
 5726                    selection.start = Point::new(selection.start.row, 0);
 5727                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 5728                    selection.goal = SelectionGoal::None;
 5729                }
 5730                if is_first {
 5731                    is_first = false;
 5732                } else {
 5733                    text += "\n";
 5734                }
 5735                let mut len = 0;
 5736                for chunk in buffer.text_for_range(selection.start..selection.end) {
 5737                    text.push_str(chunk);
 5738                    len += chunk.len();
 5739                }
 5740                clipboard_selections.push(ClipboardSelection {
 5741                    len,
 5742                    is_entire_line,
 5743                    first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
 5744                });
 5745            }
 5746        }
 5747
 5748        self.transact(cx, |this, cx| {
 5749            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5750                s.select(selections);
 5751            });
 5752            this.insert("", cx);
 5753            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5754        });
 5755    }
 5756
 5757    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 5758        let selections = self.selections.all::<Point>(cx);
 5759        let buffer = self.buffer.read(cx).read(cx);
 5760        let mut text = String::new();
 5761
 5762        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5763        {
 5764            let max_point = buffer.max_point();
 5765            let mut is_first = true;
 5766            for selection in selections.iter() {
 5767                let mut start = selection.start;
 5768                let mut end = selection.end;
 5769                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5770                if is_entire_line {
 5771                    start = Point::new(start.row, 0);
 5772                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5773                }
 5774                if is_first {
 5775                    is_first = false;
 5776                } else {
 5777                    text += "\n";
 5778                }
 5779                let mut len = 0;
 5780                for chunk in buffer.text_for_range(start..end) {
 5781                    text.push_str(chunk);
 5782                    len += chunk.len();
 5783                }
 5784                clipboard_selections.push(ClipboardSelection {
 5785                    len,
 5786                    is_entire_line,
 5787                    first_line_indent: buffer.indent_size_for_line(start.row).len,
 5788                });
 5789            }
 5790        }
 5791
 5792        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5793    }
 5794
 5795    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 5796        if self.read_only(cx) {
 5797            return;
 5798        }
 5799
 5800        self.transact(cx, |this, cx| {
 5801            if let Some(item) = cx.read_from_clipboard() {
 5802                let clipboard_text = Cow::Borrowed(item.text());
 5803                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
 5804                    let old_selections = this.selections.all::<usize>(cx);
 5805                    let all_selections_were_entire_line =
 5806                        clipboard_selections.iter().all(|s| s.is_entire_line);
 5807                    let first_selection_indent_column =
 5808                        clipboard_selections.first().map(|s| s.first_line_indent);
 5809                    if clipboard_selections.len() != old_selections.len() {
 5810                        clipboard_selections.drain(..);
 5811                    }
 5812
 5813                    this.buffer.update(cx, |buffer, cx| {
 5814                        let snapshot = buffer.read(cx);
 5815                        let mut start_offset = 0;
 5816                        let mut edits = Vec::new();
 5817                        let mut original_indent_columns = Vec::new();
 5818                        let line_mode = this.selections.line_mode;
 5819                        for (ix, selection) in old_selections.iter().enumerate() {
 5820                            let to_insert;
 5821                            let entire_line;
 5822                            let original_indent_column;
 5823                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 5824                                let end_offset = start_offset + clipboard_selection.len;
 5825                                to_insert = &clipboard_text[start_offset..end_offset];
 5826                                entire_line = clipboard_selection.is_entire_line;
 5827                                start_offset = end_offset + 1;
 5828                                original_indent_column =
 5829                                    Some(clipboard_selection.first_line_indent);
 5830                            } else {
 5831                                to_insert = clipboard_text.as_str();
 5832                                entire_line = all_selections_were_entire_line;
 5833                                original_indent_column = first_selection_indent_column
 5834                            }
 5835
 5836                            // If the corresponding selection was empty when this slice of the
 5837                            // clipboard text was written, then the entire line containing the
 5838                            // selection was copied. If this selection is also currently empty,
 5839                            // then paste the line before the current line of the buffer.
 5840                            let range = if selection.is_empty() && !line_mode && entire_line {
 5841                                let column = selection.start.to_point(&snapshot).column as usize;
 5842                                let line_start = selection.start - column;
 5843                                line_start..line_start
 5844                            } else {
 5845                                selection.range()
 5846                            };
 5847
 5848                            edits.push((range, to_insert));
 5849                            original_indent_columns.extend(original_indent_column);
 5850                        }
 5851                        drop(snapshot);
 5852
 5853                        buffer.edit(
 5854                            edits,
 5855                            Some(AutoindentMode::Block {
 5856                                original_indent_columns,
 5857                            }),
 5858                            cx,
 5859                        );
 5860                    });
 5861
 5862                    let selections = this.selections.all::<usize>(cx);
 5863                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5864                } else {
 5865                    this.insert(&clipboard_text, cx);
 5866                }
 5867            }
 5868        });
 5869    }
 5870
 5871    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 5872        if self.read_only(cx) {
 5873            return;
 5874        }
 5875
 5876        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 5877            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
 5878                self.change_selections(None, cx, |s| {
 5879                    s.select_anchors(selections.to_vec());
 5880                });
 5881            }
 5882            self.request_autoscroll(Autoscroll::fit(), cx);
 5883            self.unmark_text(cx);
 5884            self.refresh_inline_completion(true, cx);
 5885            cx.emit(EditorEvent::Edited);
 5886            cx.emit(EditorEvent::TransactionUndone {
 5887                transaction_id: tx_id,
 5888            });
 5889        }
 5890    }
 5891
 5892    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 5893        if self.read_only(cx) {
 5894            return;
 5895        }
 5896
 5897        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 5898            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
 5899            {
 5900                self.change_selections(None, cx, |s| {
 5901                    s.select_anchors(selections.to_vec());
 5902                });
 5903            }
 5904            self.request_autoscroll(Autoscroll::fit(), cx);
 5905            self.unmark_text(cx);
 5906            self.refresh_inline_completion(true, cx);
 5907            cx.emit(EditorEvent::Edited);
 5908        }
 5909    }
 5910
 5911    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 5912        self.buffer
 5913            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 5914    }
 5915
 5916    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 5917        self.buffer
 5918            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 5919    }
 5920
 5921    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 5922        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5923            let line_mode = s.line_mode;
 5924            s.move_with(|map, selection| {
 5925                let cursor = if selection.is_empty() && !line_mode {
 5926                    movement::left(map, selection.start)
 5927                } else {
 5928                    selection.start
 5929                };
 5930                selection.collapse_to(cursor, SelectionGoal::None);
 5931            });
 5932        })
 5933    }
 5934
 5935    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 5936        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5937            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 5938        })
 5939    }
 5940
 5941    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 5942        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5943            let line_mode = s.line_mode;
 5944            s.move_with(|map, selection| {
 5945                let cursor = if selection.is_empty() && !line_mode {
 5946                    movement::right(map, selection.end)
 5947                } else {
 5948                    selection.end
 5949                };
 5950                selection.collapse_to(cursor, SelectionGoal::None)
 5951            });
 5952        })
 5953    }
 5954
 5955    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 5956        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5957            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 5958        })
 5959    }
 5960
 5961    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 5962        if self.take_rename(true, cx).is_some() {
 5963            return;
 5964        }
 5965
 5966        if matches!(self.mode, EditorMode::SingleLine) {
 5967            cx.propagate();
 5968            return;
 5969        }
 5970
 5971        let text_layout_details = &self.text_layout_details(cx);
 5972
 5973        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5974            let line_mode = s.line_mode;
 5975            s.move_with(|map, selection| {
 5976                if !selection.is_empty() && !line_mode {
 5977                    selection.goal = SelectionGoal::None;
 5978                }
 5979                let (cursor, goal) = movement::up(
 5980                    map,
 5981                    selection.start,
 5982                    selection.goal,
 5983                    false,
 5984                    &text_layout_details,
 5985                );
 5986                selection.collapse_to(cursor, goal);
 5987            });
 5988        })
 5989    }
 5990
 5991    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 5992        if self.take_rename(true, cx).is_some() {
 5993            return;
 5994        }
 5995
 5996        if matches!(self.mode, EditorMode::SingleLine) {
 5997            cx.propagate();
 5998            return;
 5999        }
 6000
 6001        let text_layout_details = &self.text_layout_details(cx);
 6002
 6003        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6004            let line_mode = s.line_mode;
 6005            s.move_with(|map, selection| {
 6006                if !selection.is_empty() && !line_mode {
 6007                    selection.goal = SelectionGoal::None;
 6008                }
 6009                let (cursor, goal) = movement::up_by_rows(
 6010                    map,
 6011                    selection.start,
 6012                    action.lines,
 6013                    selection.goal,
 6014                    false,
 6015                    &text_layout_details,
 6016                );
 6017                selection.collapse_to(cursor, goal);
 6018            });
 6019        })
 6020    }
 6021
 6022    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6023        if self.take_rename(true, cx).is_some() {
 6024            return;
 6025        }
 6026
 6027        if matches!(self.mode, EditorMode::SingleLine) {
 6028            cx.propagate();
 6029            return;
 6030        }
 6031
 6032        let text_layout_details = &self.text_layout_details(cx);
 6033
 6034        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6035            let line_mode = s.line_mode;
 6036            s.move_with(|map, selection| {
 6037                if !selection.is_empty() && !line_mode {
 6038                    selection.goal = SelectionGoal::None;
 6039                }
 6040                let (cursor, goal) = movement::down_by_rows(
 6041                    map,
 6042                    selection.start,
 6043                    action.lines,
 6044                    selection.goal,
 6045                    false,
 6046                    &text_layout_details,
 6047                );
 6048                selection.collapse_to(cursor, goal);
 6049            });
 6050        })
 6051    }
 6052
 6053    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6054        let text_layout_details = &self.text_layout_details(cx);
 6055        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6056            s.move_heads_with(|map, head, goal| {
 6057                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6058            })
 6059        })
 6060    }
 6061
 6062    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6063        let text_layout_details = &self.text_layout_details(cx);
 6064        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6065            s.move_heads_with(|map, head, goal| {
 6066                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6067            })
 6068        })
 6069    }
 6070
 6071    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6072        if self.take_rename(true, cx).is_some() {
 6073            return;
 6074        }
 6075
 6076        if matches!(self.mode, EditorMode::SingleLine) {
 6077            cx.propagate();
 6078            return;
 6079        }
 6080
 6081        let row_count = if let Some(row_count) = self.visible_line_count() {
 6082            row_count as u32 - 1
 6083        } else {
 6084            return;
 6085        };
 6086
 6087        let autoscroll = if action.center_cursor {
 6088            Autoscroll::center()
 6089        } else {
 6090            Autoscroll::fit()
 6091        };
 6092
 6093        let text_layout_details = &self.text_layout_details(cx);
 6094
 6095        self.change_selections(Some(autoscroll), cx, |s| {
 6096            let line_mode = s.line_mode;
 6097            s.move_with(|map, selection| {
 6098                if !selection.is_empty() && !line_mode {
 6099                    selection.goal = SelectionGoal::None;
 6100                }
 6101                let (cursor, goal) = movement::up_by_rows(
 6102                    map,
 6103                    selection.end,
 6104                    row_count,
 6105                    selection.goal,
 6106                    false,
 6107                    &text_layout_details,
 6108                );
 6109                selection.collapse_to(cursor, goal);
 6110            });
 6111        });
 6112    }
 6113
 6114    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6115        let text_layout_details = &self.text_layout_details(cx);
 6116        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6117            s.move_heads_with(|map, head, goal| {
 6118                movement::up(map, head, goal, false, &text_layout_details)
 6119            })
 6120        })
 6121    }
 6122
 6123    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6124        self.take_rename(true, cx);
 6125
 6126        if self.mode == EditorMode::SingleLine {
 6127            cx.propagate();
 6128            return;
 6129        }
 6130
 6131        let text_layout_details = &self.text_layout_details(cx);
 6132        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6133            let line_mode = s.line_mode;
 6134            s.move_with(|map, selection| {
 6135                if !selection.is_empty() && !line_mode {
 6136                    selection.goal = SelectionGoal::None;
 6137                }
 6138                let (cursor, goal) = movement::down(
 6139                    map,
 6140                    selection.end,
 6141                    selection.goal,
 6142                    false,
 6143                    &text_layout_details,
 6144                );
 6145                selection.collapse_to(cursor, goal);
 6146            });
 6147        });
 6148    }
 6149
 6150    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6151        if self.take_rename(true, cx).is_some() {
 6152            return;
 6153        }
 6154
 6155        if self
 6156            .context_menu
 6157            .write()
 6158            .as_mut()
 6159            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6160            .unwrap_or(false)
 6161        {
 6162            return;
 6163        }
 6164
 6165        if matches!(self.mode, EditorMode::SingleLine) {
 6166            cx.propagate();
 6167            return;
 6168        }
 6169
 6170        let row_count = if let Some(row_count) = self.visible_line_count() {
 6171            row_count as u32 - 1
 6172        } else {
 6173            return;
 6174        };
 6175
 6176        let autoscroll = if action.center_cursor {
 6177            Autoscroll::center()
 6178        } else {
 6179            Autoscroll::fit()
 6180        };
 6181
 6182        let text_layout_details = &self.text_layout_details(cx);
 6183        self.change_selections(Some(autoscroll), cx, |s| {
 6184            let line_mode = s.line_mode;
 6185            s.move_with(|map, selection| {
 6186                if !selection.is_empty() && !line_mode {
 6187                    selection.goal = SelectionGoal::None;
 6188                }
 6189                let (cursor, goal) = movement::down_by_rows(
 6190                    map,
 6191                    selection.end,
 6192                    row_count,
 6193                    selection.goal,
 6194                    false,
 6195                    &text_layout_details,
 6196                );
 6197                selection.collapse_to(cursor, goal);
 6198            });
 6199        });
 6200    }
 6201
 6202    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6203        let text_layout_details = &self.text_layout_details(cx);
 6204        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6205            s.move_heads_with(|map, head, goal| {
 6206                movement::down(map, head, goal, false, &text_layout_details)
 6207            })
 6208        });
 6209    }
 6210
 6211    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6212        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6213            context_menu.select_first(self.project.as_ref(), cx);
 6214        }
 6215    }
 6216
 6217    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6218        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6219            context_menu.select_prev(self.project.as_ref(), cx);
 6220        }
 6221    }
 6222
 6223    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6224        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6225            context_menu.select_next(self.project.as_ref(), cx);
 6226        }
 6227    }
 6228
 6229    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6230        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6231            context_menu.select_last(self.project.as_ref(), cx);
 6232        }
 6233    }
 6234
 6235    pub fn move_to_previous_word_start(
 6236        &mut self,
 6237        _: &MoveToPreviousWordStart,
 6238        cx: &mut ViewContext<Self>,
 6239    ) {
 6240        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6241            s.move_cursors_with(|map, head, _| {
 6242                (
 6243                    movement::previous_word_start(map, head),
 6244                    SelectionGoal::None,
 6245                )
 6246            });
 6247        })
 6248    }
 6249
 6250    pub fn move_to_previous_subword_start(
 6251        &mut self,
 6252        _: &MoveToPreviousSubwordStart,
 6253        cx: &mut ViewContext<Self>,
 6254    ) {
 6255        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6256            s.move_cursors_with(|map, head, _| {
 6257                (
 6258                    movement::previous_subword_start(map, head),
 6259                    SelectionGoal::None,
 6260                )
 6261            });
 6262        })
 6263    }
 6264
 6265    pub fn select_to_previous_word_start(
 6266        &mut self,
 6267        _: &SelectToPreviousWordStart,
 6268        cx: &mut ViewContext<Self>,
 6269    ) {
 6270        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6271            s.move_heads_with(|map, head, _| {
 6272                (
 6273                    movement::previous_word_start(map, head),
 6274                    SelectionGoal::None,
 6275                )
 6276            });
 6277        })
 6278    }
 6279
 6280    pub fn select_to_previous_subword_start(
 6281        &mut self,
 6282        _: &SelectToPreviousSubwordStart,
 6283        cx: &mut ViewContext<Self>,
 6284    ) {
 6285        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6286            s.move_heads_with(|map, head, _| {
 6287                (
 6288                    movement::previous_subword_start(map, head),
 6289                    SelectionGoal::None,
 6290                )
 6291            });
 6292        })
 6293    }
 6294
 6295    pub fn delete_to_previous_word_start(
 6296        &mut self,
 6297        _: &DeleteToPreviousWordStart,
 6298        cx: &mut ViewContext<Self>,
 6299    ) {
 6300        self.transact(cx, |this, cx| {
 6301            this.select_autoclose_pair(cx);
 6302            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6303                let line_mode = s.line_mode;
 6304                s.move_with(|map, selection| {
 6305                    if selection.is_empty() && !line_mode {
 6306                        let cursor = movement::previous_word_start(map, selection.head());
 6307                        selection.set_head(cursor, SelectionGoal::None);
 6308                    }
 6309                });
 6310            });
 6311            this.insert("", cx);
 6312        });
 6313    }
 6314
 6315    pub fn delete_to_previous_subword_start(
 6316        &mut self,
 6317        _: &DeleteToPreviousSubwordStart,
 6318        cx: &mut ViewContext<Self>,
 6319    ) {
 6320        self.transact(cx, |this, cx| {
 6321            this.select_autoclose_pair(cx);
 6322            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6323                let line_mode = s.line_mode;
 6324                s.move_with(|map, selection| {
 6325                    if selection.is_empty() && !line_mode {
 6326                        let cursor = movement::previous_subword_start(map, selection.head());
 6327                        selection.set_head(cursor, SelectionGoal::None);
 6328                    }
 6329                });
 6330            });
 6331            this.insert("", cx);
 6332        });
 6333    }
 6334
 6335    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 6336        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6337            s.move_cursors_with(|map, head, _| {
 6338                (movement::next_word_end(map, head), SelectionGoal::None)
 6339            });
 6340        })
 6341    }
 6342
 6343    pub fn move_to_next_subword_end(
 6344        &mut self,
 6345        _: &MoveToNextSubwordEnd,
 6346        cx: &mut ViewContext<Self>,
 6347    ) {
 6348        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6349            s.move_cursors_with(|map, head, _| {
 6350                (movement::next_subword_end(map, head), SelectionGoal::None)
 6351            });
 6352        })
 6353    }
 6354
 6355    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 6356        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6357            s.move_heads_with(|map, head, _| {
 6358                (movement::next_word_end(map, head), SelectionGoal::None)
 6359            });
 6360        })
 6361    }
 6362
 6363    pub fn select_to_next_subword_end(
 6364        &mut self,
 6365        _: &SelectToNextSubwordEnd,
 6366        cx: &mut ViewContext<Self>,
 6367    ) {
 6368        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6369            s.move_heads_with(|map, head, _| {
 6370                (movement::next_subword_end(map, head), SelectionGoal::None)
 6371            });
 6372        })
 6373    }
 6374
 6375    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 6376        self.transact(cx, |this, cx| {
 6377            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6378                let line_mode = s.line_mode;
 6379                s.move_with(|map, selection| {
 6380                    if selection.is_empty() && !line_mode {
 6381                        let cursor = movement::next_word_end(map, selection.head());
 6382                        selection.set_head(cursor, SelectionGoal::None);
 6383                    }
 6384                });
 6385            });
 6386            this.insert("", cx);
 6387        });
 6388    }
 6389
 6390    pub fn delete_to_next_subword_end(
 6391        &mut self,
 6392        _: &DeleteToNextSubwordEnd,
 6393        cx: &mut ViewContext<Self>,
 6394    ) {
 6395        self.transact(cx, |this, cx| {
 6396            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6397                s.move_with(|map, selection| {
 6398                    if selection.is_empty() {
 6399                        let cursor = movement::next_subword_end(map, selection.head());
 6400                        selection.set_head(cursor, SelectionGoal::None);
 6401                    }
 6402                });
 6403            });
 6404            this.insert("", cx);
 6405        });
 6406    }
 6407
 6408    pub fn move_to_beginning_of_line(
 6409        &mut self,
 6410        _: &MoveToBeginningOfLine,
 6411        cx: &mut ViewContext<Self>,
 6412    ) {
 6413        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6414            s.move_cursors_with(|map, head, _| {
 6415                (
 6416                    movement::indented_line_beginning(map, head, true),
 6417                    SelectionGoal::None,
 6418                )
 6419            });
 6420        })
 6421    }
 6422
 6423    pub fn select_to_beginning_of_line(
 6424        &mut self,
 6425        action: &SelectToBeginningOfLine,
 6426        cx: &mut ViewContext<Self>,
 6427    ) {
 6428        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6429            s.move_heads_with(|map, head, _| {
 6430                (
 6431                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6432                    SelectionGoal::None,
 6433                )
 6434            });
 6435        });
 6436    }
 6437
 6438    pub fn delete_to_beginning_of_line(
 6439        &mut self,
 6440        _: &DeleteToBeginningOfLine,
 6441        cx: &mut ViewContext<Self>,
 6442    ) {
 6443        self.transact(cx, |this, cx| {
 6444            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6445                s.move_with(|_, selection| {
 6446                    selection.reversed = true;
 6447                });
 6448            });
 6449
 6450            this.select_to_beginning_of_line(
 6451                &SelectToBeginningOfLine {
 6452                    stop_at_soft_wraps: false,
 6453                },
 6454                cx,
 6455            );
 6456            this.backspace(&Backspace, cx);
 6457        });
 6458    }
 6459
 6460    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 6461        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6462            s.move_cursors_with(|map, head, _| {
 6463                (movement::line_end(map, head, true), SelectionGoal::None)
 6464            });
 6465        })
 6466    }
 6467
 6468    pub fn select_to_end_of_line(
 6469        &mut self,
 6470        action: &SelectToEndOfLine,
 6471        cx: &mut ViewContext<Self>,
 6472    ) {
 6473        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6474            s.move_heads_with(|map, head, _| {
 6475                (
 6476                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6477                    SelectionGoal::None,
 6478                )
 6479            });
 6480        })
 6481    }
 6482
 6483    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 6484        self.transact(cx, |this, cx| {
 6485            this.select_to_end_of_line(
 6486                &SelectToEndOfLine {
 6487                    stop_at_soft_wraps: false,
 6488                },
 6489                cx,
 6490            );
 6491            this.delete(&Delete, cx);
 6492        });
 6493    }
 6494
 6495    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 6496        self.transact(cx, |this, cx| {
 6497            this.select_to_end_of_line(
 6498                &SelectToEndOfLine {
 6499                    stop_at_soft_wraps: false,
 6500                },
 6501                cx,
 6502            );
 6503            this.cut(&Cut, cx);
 6504        });
 6505    }
 6506
 6507    pub fn move_to_start_of_paragraph(
 6508        &mut self,
 6509        _: &MoveToStartOfParagraph,
 6510        cx: &mut ViewContext<Self>,
 6511    ) {
 6512        if matches!(self.mode, EditorMode::SingleLine) {
 6513            cx.propagate();
 6514            return;
 6515        }
 6516
 6517        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6518            s.move_with(|map, selection| {
 6519                selection.collapse_to(
 6520                    movement::start_of_paragraph(map, selection.head(), 1),
 6521                    SelectionGoal::None,
 6522                )
 6523            });
 6524        })
 6525    }
 6526
 6527    pub fn move_to_end_of_paragraph(
 6528        &mut self,
 6529        _: &MoveToEndOfParagraph,
 6530        cx: &mut ViewContext<Self>,
 6531    ) {
 6532        if matches!(self.mode, EditorMode::SingleLine) {
 6533            cx.propagate();
 6534            return;
 6535        }
 6536
 6537        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6538            s.move_with(|map, selection| {
 6539                selection.collapse_to(
 6540                    movement::end_of_paragraph(map, selection.head(), 1),
 6541                    SelectionGoal::None,
 6542                )
 6543            });
 6544        })
 6545    }
 6546
 6547    pub fn select_to_start_of_paragraph(
 6548        &mut self,
 6549        _: &SelectToStartOfParagraph,
 6550        cx: &mut ViewContext<Self>,
 6551    ) {
 6552        if matches!(self.mode, EditorMode::SingleLine) {
 6553            cx.propagate();
 6554            return;
 6555        }
 6556
 6557        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6558            s.move_heads_with(|map, head, _| {
 6559                (
 6560                    movement::start_of_paragraph(map, head, 1),
 6561                    SelectionGoal::None,
 6562                )
 6563            });
 6564        })
 6565    }
 6566
 6567    pub fn select_to_end_of_paragraph(
 6568        &mut self,
 6569        _: &SelectToEndOfParagraph,
 6570        cx: &mut ViewContext<Self>,
 6571    ) {
 6572        if matches!(self.mode, EditorMode::SingleLine) {
 6573            cx.propagate();
 6574            return;
 6575        }
 6576
 6577        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6578            s.move_heads_with(|map, head, _| {
 6579                (
 6580                    movement::end_of_paragraph(map, head, 1),
 6581                    SelectionGoal::None,
 6582                )
 6583            });
 6584        })
 6585    }
 6586
 6587    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 6588        if matches!(self.mode, EditorMode::SingleLine) {
 6589            cx.propagate();
 6590            return;
 6591        }
 6592
 6593        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6594            s.select_ranges(vec![0..0]);
 6595        });
 6596    }
 6597
 6598    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 6599        let mut selection = self.selections.last::<Point>(cx);
 6600        selection.set_head(Point::zero(), SelectionGoal::None);
 6601
 6602        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6603            s.select(vec![selection]);
 6604        });
 6605    }
 6606
 6607    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 6608        if matches!(self.mode, EditorMode::SingleLine) {
 6609            cx.propagate();
 6610            return;
 6611        }
 6612
 6613        let cursor = self.buffer.read(cx).read(cx).len();
 6614        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6615            s.select_ranges(vec![cursor..cursor])
 6616        });
 6617    }
 6618
 6619    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 6620        self.nav_history = nav_history;
 6621    }
 6622
 6623    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 6624        self.nav_history.as_ref()
 6625    }
 6626
 6627    fn push_to_nav_history(
 6628        &mut self,
 6629        cursor_anchor: Anchor,
 6630        new_position: Option<Point>,
 6631        cx: &mut ViewContext<Self>,
 6632    ) {
 6633        if let Some(nav_history) = self.nav_history.as_mut() {
 6634            let buffer = self.buffer.read(cx).read(cx);
 6635            let cursor_position = cursor_anchor.to_point(&buffer);
 6636            let scroll_state = self.scroll_manager.anchor();
 6637            let scroll_top_row = scroll_state.top_row(&buffer);
 6638            drop(buffer);
 6639
 6640            if let Some(new_position) = new_position {
 6641                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 6642                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 6643                    return;
 6644                }
 6645            }
 6646
 6647            nav_history.push(
 6648                Some(NavigationData {
 6649                    cursor_anchor,
 6650                    cursor_position,
 6651                    scroll_anchor: scroll_state,
 6652                    scroll_top_row,
 6653                }),
 6654                cx,
 6655            );
 6656        }
 6657    }
 6658
 6659    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 6660        let buffer = self.buffer.read(cx).snapshot(cx);
 6661        let mut selection = self.selections.first::<usize>(cx);
 6662        selection.set_head(buffer.len(), SelectionGoal::None);
 6663        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6664            s.select(vec![selection]);
 6665        });
 6666    }
 6667
 6668    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 6669        let end = self.buffer.read(cx).read(cx).len();
 6670        self.change_selections(None, cx, |s| {
 6671            s.select_ranges(vec![0..end]);
 6672        });
 6673    }
 6674
 6675    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 6676        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6677        let mut selections = self.selections.all::<Point>(cx);
 6678        let max_point = display_map.buffer_snapshot.max_point();
 6679        for selection in &mut selections {
 6680            let rows = selection.spanned_rows(true, &display_map);
 6681            selection.start = Point::new(rows.start, 0);
 6682            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
 6683            selection.reversed = false;
 6684        }
 6685        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6686            s.select(selections);
 6687        });
 6688    }
 6689
 6690    pub fn split_selection_into_lines(
 6691        &mut self,
 6692        _: &SplitSelectionIntoLines,
 6693        cx: &mut ViewContext<Self>,
 6694    ) {
 6695        let mut to_unfold = Vec::new();
 6696        let mut new_selection_ranges = Vec::new();
 6697        {
 6698            let selections = self.selections.all::<Point>(cx);
 6699            let buffer = self.buffer.read(cx).read(cx);
 6700            for selection in selections {
 6701                for row in selection.start.row..selection.end.row {
 6702                    let cursor = Point::new(row, buffer.line_len(row));
 6703                    new_selection_ranges.push(cursor..cursor);
 6704                }
 6705                new_selection_ranges.push(selection.end..selection.end);
 6706                to_unfold.push(selection.start..selection.end);
 6707            }
 6708        }
 6709        self.unfold_ranges(to_unfold, true, true, cx);
 6710        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6711            s.select_ranges(new_selection_ranges);
 6712        });
 6713    }
 6714
 6715    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 6716        self.add_selection(true, cx);
 6717    }
 6718
 6719    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 6720        self.add_selection(false, cx);
 6721    }
 6722
 6723    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 6724        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6725        let mut selections = self.selections.all::<Point>(cx);
 6726        let text_layout_details = self.text_layout_details(cx);
 6727        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 6728            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 6729            let range = oldest_selection.display_range(&display_map).sorted();
 6730
 6731            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 6732            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 6733            let positions = start_x.min(end_x)..start_x.max(end_x);
 6734
 6735            selections.clear();
 6736            let mut stack = Vec::new();
 6737            for row in range.start.row()..=range.end.row() {
 6738                if let Some(selection) = self.selections.build_columnar_selection(
 6739                    &display_map,
 6740                    row,
 6741                    &positions,
 6742                    oldest_selection.reversed,
 6743                    &text_layout_details,
 6744                ) {
 6745                    stack.push(selection.id);
 6746                    selections.push(selection);
 6747                }
 6748            }
 6749
 6750            if above {
 6751                stack.reverse();
 6752            }
 6753
 6754            AddSelectionsState { above, stack }
 6755        });
 6756
 6757        let last_added_selection = *state.stack.last().unwrap();
 6758        let mut new_selections = Vec::new();
 6759        if above == state.above {
 6760            let end_row = if above {
 6761                0
 6762            } else {
 6763                display_map.max_point().row()
 6764            };
 6765
 6766            'outer: for selection in selections {
 6767                if selection.id == last_added_selection {
 6768                    let range = selection.display_range(&display_map).sorted();
 6769                    debug_assert_eq!(range.start.row(), range.end.row());
 6770                    let mut row = range.start.row();
 6771                    let positions =
 6772                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 6773                            px(start)..px(end)
 6774                        } else {
 6775                            let start_x =
 6776                                display_map.x_for_display_point(range.start, &text_layout_details);
 6777                            let end_x =
 6778                                display_map.x_for_display_point(range.end, &text_layout_details);
 6779                            start_x.min(end_x)..start_x.max(end_x)
 6780                        };
 6781
 6782                    while row != end_row {
 6783                        if above {
 6784                            row -= 1;
 6785                        } else {
 6786                            row += 1;
 6787                        }
 6788
 6789                        if let Some(new_selection) = self.selections.build_columnar_selection(
 6790                            &display_map,
 6791                            row,
 6792                            &positions,
 6793                            selection.reversed,
 6794                            &text_layout_details,
 6795                        ) {
 6796                            state.stack.push(new_selection.id);
 6797                            if above {
 6798                                new_selections.push(new_selection);
 6799                                new_selections.push(selection);
 6800                            } else {
 6801                                new_selections.push(selection);
 6802                                new_selections.push(new_selection);
 6803                            }
 6804
 6805                            continue 'outer;
 6806                        }
 6807                    }
 6808                }
 6809
 6810                new_selections.push(selection);
 6811            }
 6812        } else {
 6813            new_selections = selections;
 6814            new_selections.retain(|s| s.id != last_added_selection);
 6815            state.stack.pop();
 6816        }
 6817
 6818        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6819            s.select(new_selections);
 6820        });
 6821        if state.stack.len() > 1 {
 6822            self.add_selections_state = Some(state);
 6823        }
 6824    }
 6825
 6826    pub fn select_next_match_internal(
 6827        &mut self,
 6828        display_map: &DisplaySnapshot,
 6829        replace_newest: bool,
 6830        autoscroll: Option<Autoscroll>,
 6831        cx: &mut ViewContext<Self>,
 6832    ) -> Result<()> {
 6833        fn select_next_match_ranges(
 6834            this: &mut Editor,
 6835            range: Range<usize>,
 6836            replace_newest: bool,
 6837            auto_scroll: Option<Autoscroll>,
 6838            cx: &mut ViewContext<Editor>,
 6839        ) {
 6840            this.unfold_ranges([range.clone()], false, true, cx);
 6841            this.change_selections(auto_scroll, cx, |s| {
 6842                if replace_newest {
 6843                    s.delete(s.newest_anchor().id);
 6844                }
 6845                s.insert_range(range.clone());
 6846            });
 6847        }
 6848
 6849        let buffer = &display_map.buffer_snapshot;
 6850        let mut selections = self.selections.all::<usize>(cx);
 6851        if let Some(mut select_next_state) = self.select_next_state.take() {
 6852            let query = &select_next_state.query;
 6853            if !select_next_state.done {
 6854                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 6855                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 6856                let mut next_selected_range = None;
 6857
 6858                let bytes_after_last_selection =
 6859                    buffer.bytes_in_range(last_selection.end..buffer.len());
 6860                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 6861                let query_matches = query
 6862                    .stream_find_iter(bytes_after_last_selection)
 6863                    .map(|result| (last_selection.end, result))
 6864                    .chain(
 6865                        query
 6866                            .stream_find_iter(bytes_before_first_selection)
 6867                            .map(|result| (0, result)),
 6868                    );
 6869
 6870                for (start_offset, query_match) in query_matches {
 6871                    let query_match = query_match.unwrap(); // can only fail due to I/O
 6872                    let offset_range =
 6873                        start_offset + query_match.start()..start_offset + query_match.end();
 6874                    let display_range = offset_range.start.to_display_point(&display_map)
 6875                        ..offset_range.end.to_display_point(&display_map);
 6876
 6877                    if !select_next_state.wordwise
 6878                        || (!movement::is_inside_word(&display_map, display_range.start)
 6879                            && !movement::is_inside_word(&display_map, display_range.end))
 6880                    {
 6881                        // TODO: This is n^2, because we might check all the selections
 6882                        if !selections
 6883                            .iter()
 6884                            .any(|selection| selection.range().overlaps(&offset_range))
 6885                        {
 6886                            next_selected_range = Some(offset_range);
 6887                            break;
 6888                        }
 6889                    }
 6890                }
 6891
 6892                if let Some(next_selected_range) = next_selected_range {
 6893                    select_next_match_ranges(
 6894                        self,
 6895                        next_selected_range,
 6896                        replace_newest,
 6897                        autoscroll,
 6898                        cx,
 6899                    );
 6900                } else {
 6901                    select_next_state.done = true;
 6902                }
 6903            }
 6904
 6905            self.select_next_state = Some(select_next_state);
 6906        } else {
 6907            let mut only_carets = true;
 6908            let mut same_text_selected = true;
 6909            let mut selected_text = None;
 6910
 6911            let mut selections_iter = selections.iter().peekable();
 6912            while let Some(selection) = selections_iter.next() {
 6913                if selection.start != selection.end {
 6914                    only_carets = false;
 6915                }
 6916
 6917                if same_text_selected {
 6918                    if selected_text.is_none() {
 6919                        selected_text =
 6920                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 6921                    }
 6922
 6923                    if let Some(next_selection) = selections_iter.peek() {
 6924                        if next_selection.range().len() == selection.range().len() {
 6925                            let next_selected_text = buffer
 6926                                .text_for_range(next_selection.range())
 6927                                .collect::<String>();
 6928                            if Some(next_selected_text) != selected_text {
 6929                                same_text_selected = false;
 6930                                selected_text = None;
 6931                            }
 6932                        } else {
 6933                            same_text_selected = false;
 6934                            selected_text = None;
 6935                        }
 6936                    }
 6937                }
 6938            }
 6939
 6940            if only_carets {
 6941                for selection in &mut selections {
 6942                    let word_range = movement::surrounding_word(
 6943                        &display_map,
 6944                        selection.start.to_display_point(&display_map),
 6945                    );
 6946                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 6947                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 6948                    selection.goal = SelectionGoal::None;
 6949                    selection.reversed = false;
 6950                    select_next_match_ranges(
 6951                        self,
 6952                        selection.start..selection.end,
 6953                        replace_newest,
 6954                        autoscroll,
 6955                        cx,
 6956                    );
 6957                }
 6958
 6959                if selections.len() == 1 {
 6960                    let selection = selections
 6961                        .last()
 6962                        .expect("ensured that there's only one selection");
 6963                    let query = buffer
 6964                        .text_for_range(selection.start..selection.end)
 6965                        .collect::<String>();
 6966                    let is_empty = query.is_empty();
 6967                    let select_state = SelectNextState {
 6968                        query: AhoCorasick::new(&[query])?,
 6969                        wordwise: true,
 6970                        done: is_empty,
 6971                    };
 6972                    self.select_next_state = Some(select_state);
 6973                } else {
 6974                    self.select_next_state = None;
 6975                }
 6976            } else if let Some(selected_text) = selected_text {
 6977                self.select_next_state = Some(SelectNextState {
 6978                    query: AhoCorasick::new(&[selected_text])?,
 6979                    wordwise: false,
 6980                    done: false,
 6981                });
 6982                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 6983            }
 6984        }
 6985        Ok(())
 6986    }
 6987
 6988    pub fn select_all_matches(
 6989        &mut self,
 6990        _action: &SelectAllMatches,
 6991        cx: &mut ViewContext<Self>,
 6992    ) -> Result<()> {
 6993        self.push_to_selection_history();
 6994        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6995
 6996        self.select_next_match_internal(&display_map, false, None, cx)?;
 6997        let Some(select_next_state) = self.select_next_state.as_mut() else {
 6998            return Ok(());
 6999        };
 7000        if select_next_state.done {
 7001            return Ok(());
 7002        }
 7003
 7004        let mut new_selections = self.selections.all::<usize>(cx);
 7005
 7006        let buffer = &display_map.buffer_snapshot;
 7007        let query_matches = select_next_state
 7008            .query
 7009            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7010
 7011        for query_match in query_matches {
 7012            let query_match = query_match.unwrap(); // can only fail due to I/O
 7013            let offset_range = query_match.start()..query_match.end();
 7014            let display_range = offset_range.start.to_display_point(&display_map)
 7015                ..offset_range.end.to_display_point(&display_map);
 7016
 7017            if !select_next_state.wordwise
 7018                || (!movement::is_inside_word(&display_map, display_range.start)
 7019                    && !movement::is_inside_word(&display_map, display_range.end))
 7020            {
 7021                self.selections.change_with(cx, |selections| {
 7022                    new_selections.push(Selection {
 7023                        id: selections.new_selection_id(),
 7024                        start: offset_range.start,
 7025                        end: offset_range.end,
 7026                        reversed: false,
 7027                        goal: SelectionGoal::None,
 7028                    });
 7029                });
 7030            }
 7031        }
 7032
 7033        new_selections.sort_by_key(|selection| selection.start);
 7034        let mut ix = 0;
 7035        while ix + 1 < new_selections.len() {
 7036            let current_selection = &new_selections[ix];
 7037            let next_selection = &new_selections[ix + 1];
 7038            if current_selection.range().overlaps(&next_selection.range()) {
 7039                if current_selection.id < next_selection.id {
 7040                    new_selections.remove(ix + 1);
 7041                } else {
 7042                    new_selections.remove(ix);
 7043                }
 7044            } else {
 7045                ix += 1;
 7046            }
 7047        }
 7048
 7049        select_next_state.done = true;
 7050        self.unfold_ranges(
 7051            new_selections.iter().map(|selection| selection.range()),
 7052            false,
 7053            false,
 7054            cx,
 7055        );
 7056        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7057            selections.select(new_selections)
 7058        });
 7059
 7060        Ok(())
 7061    }
 7062
 7063    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7064        self.push_to_selection_history();
 7065        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7066        self.select_next_match_internal(
 7067            &display_map,
 7068            action.replace_newest,
 7069            Some(Autoscroll::newest()),
 7070            cx,
 7071        )?;
 7072        Ok(())
 7073    }
 7074
 7075    pub fn select_previous(
 7076        &mut self,
 7077        action: &SelectPrevious,
 7078        cx: &mut ViewContext<Self>,
 7079    ) -> Result<()> {
 7080        self.push_to_selection_history();
 7081        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7082        let buffer = &display_map.buffer_snapshot;
 7083        let mut selections = self.selections.all::<usize>(cx);
 7084        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7085            let query = &select_prev_state.query;
 7086            if !select_prev_state.done {
 7087                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7088                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7089                let mut next_selected_range = None;
 7090                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7091                let bytes_before_last_selection =
 7092                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7093                let bytes_after_first_selection =
 7094                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7095                let query_matches = query
 7096                    .stream_find_iter(bytes_before_last_selection)
 7097                    .map(|result| (last_selection.start, result))
 7098                    .chain(
 7099                        query
 7100                            .stream_find_iter(bytes_after_first_selection)
 7101                            .map(|result| (buffer.len(), result)),
 7102                    );
 7103                for (end_offset, query_match) in query_matches {
 7104                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7105                    let offset_range =
 7106                        end_offset - query_match.end()..end_offset - query_match.start();
 7107                    let display_range = offset_range.start.to_display_point(&display_map)
 7108                        ..offset_range.end.to_display_point(&display_map);
 7109
 7110                    if !select_prev_state.wordwise
 7111                        || (!movement::is_inside_word(&display_map, display_range.start)
 7112                            && !movement::is_inside_word(&display_map, display_range.end))
 7113                    {
 7114                        next_selected_range = Some(offset_range);
 7115                        break;
 7116                    }
 7117                }
 7118
 7119                if let Some(next_selected_range) = next_selected_range {
 7120                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7121                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7122                        if action.replace_newest {
 7123                            s.delete(s.newest_anchor().id);
 7124                        }
 7125                        s.insert_range(next_selected_range);
 7126                    });
 7127                } else {
 7128                    select_prev_state.done = true;
 7129                }
 7130            }
 7131
 7132            self.select_prev_state = Some(select_prev_state);
 7133        } else {
 7134            let mut only_carets = true;
 7135            let mut same_text_selected = true;
 7136            let mut selected_text = None;
 7137
 7138            let mut selections_iter = selections.iter().peekable();
 7139            while let Some(selection) = selections_iter.next() {
 7140                if selection.start != selection.end {
 7141                    only_carets = false;
 7142                }
 7143
 7144                if same_text_selected {
 7145                    if selected_text.is_none() {
 7146                        selected_text =
 7147                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7148                    }
 7149
 7150                    if let Some(next_selection) = selections_iter.peek() {
 7151                        if next_selection.range().len() == selection.range().len() {
 7152                            let next_selected_text = buffer
 7153                                .text_for_range(next_selection.range())
 7154                                .collect::<String>();
 7155                            if Some(next_selected_text) != selected_text {
 7156                                same_text_selected = false;
 7157                                selected_text = None;
 7158                            }
 7159                        } else {
 7160                            same_text_selected = false;
 7161                            selected_text = None;
 7162                        }
 7163                    }
 7164                }
 7165            }
 7166
 7167            if only_carets {
 7168                for selection in &mut selections {
 7169                    let word_range = movement::surrounding_word(
 7170                        &display_map,
 7171                        selection.start.to_display_point(&display_map),
 7172                    );
 7173                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7174                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7175                    selection.goal = SelectionGoal::None;
 7176                    selection.reversed = false;
 7177                }
 7178                if selections.len() == 1 {
 7179                    let selection = selections
 7180                        .last()
 7181                        .expect("ensured that there's only one selection");
 7182                    let query = buffer
 7183                        .text_for_range(selection.start..selection.end)
 7184                        .collect::<String>();
 7185                    let is_empty = query.is_empty();
 7186                    let select_state = SelectNextState {
 7187                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7188                        wordwise: true,
 7189                        done: is_empty,
 7190                    };
 7191                    self.select_prev_state = Some(select_state);
 7192                } else {
 7193                    self.select_prev_state = None;
 7194                }
 7195
 7196                self.unfold_ranges(
 7197                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7198                    false,
 7199                    true,
 7200                    cx,
 7201                );
 7202                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7203                    s.select(selections);
 7204                });
 7205            } else if let Some(selected_text) = selected_text {
 7206                self.select_prev_state = Some(SelectNextState {
 7207                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7208                    wordwise: false,
 7209                    done: false,
 7210                });
 7211                self.select_previous(action, cx)?;
 7212            }
 7213        }
 7214        Ok(())
 7215    }
 7216
 7217    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7218        let text_layout_details = &self.text_layout_details(cx);
 7219        self.transact(cx, |this, cx| {
 7220            let mut selections = this.selections.all::<Point>(cx);
 7221            let mut edits = Vec::new();
 7222            let mut selection_edit_ranges = Vec::new();
 7223            let mut last_toggled_row = None;
 7224            let snapshot = this.buffer.read(cx).read(cx);
 7225            let empty_str: Arc<str> = "".into();
 7226            let mut suffixes_inserted = Vec::new();
 7227
 7228            fn comment_prefix_range(
 7229                snapshot: &MultiBufferSnapshot,
 7230                row: u32,
 7231                comment_prefix: &str,
 7232                comment_prefix_whitespace: &str,
 7233            ) -> Range<Point> {
 7234                let start = Point::new(row, snapshot.indent_size_for_line(row).len);
 7235
 7236                let mut line_bytes = snapshot
 7237                    .bytes_in_range(start..snapshot.max_point())
 7238                    .flatten()
 7239                    .copied();
 7240
 7241                // If this line currently begins with the line comment prefix, then record
 7242                // the range containing the prefix.
 7243                if line_bytes
 7244                    .by_ref()
 7245                    .take(comment_prefix.len())
 7246                    .eq(comment_prefix.bytes())
 7247                {
 7248                    // Include any whitespace that matches the comment prefix.
 7249                    let matching_whitespace_len = line_bytes
 7250                        .zip(comment_prefix_whitespace.bytes())
 7251                        .take_while(|(a, b)| a == b)
 7252                        .count() as u32;
 7253                    let end = Point::new(
 7254                        start.row,
 7255                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 7256                    );
 7257                    start..end
 7258                } else {
 7259                    start..start
 7260                }
 7261            }
 7262
 7263            fn comment_suffix_range(
 7264                snapshot: &MultiBufferSnapshot,
 7265                row: u32,
 7266                comment_suffix: &str,
 7267                comment_suffix_has_leading_space: bool,
 7268            ) -> Range<Point> {
 7269                let end = Point::new(row, snapshot.line_len(row));
 7270                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 7271
 7272                let mut line_end_bytes = snapshot
 7273                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 7274                    .flatten()
 7275                    .copied();
 7276
 7277                let leading_space_len = if suffix_start_column > 0
 7278                    && line_end_bytes.next() == Some(b' ')
 7279                    && comment_suffix_has_leading_space
 7280                {
 7281                    1
 7282                } else {
 7283                    0
 7284                };
 7285
 7286                // If this line currently begins with the line comment prefix, then record
 7287                // the range containing the prefix.
 7288                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 7289                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 7290                    start..end
 7291                } else {
 7292                    end..end
 7293                }
 7294            }
 7295
 7296            // TODO: Handle selections that cross excerpts
 7297            for selection in &mut selections {
 7298                let start_column = snapshot.indent_size_for_line(selection.start.row).len;
 7299                let language = if let Some(language) =
 7300                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 7301                {
 7302                    language
 7303                } else {
 7304                    continue;
 7305                };
 7306
 7307                selection_edit_ranges.clear();
 7308
 7309                // If multiple selections contain a given row, avoid processing that
 7310                // row more than once.
 7311                let mut start_row = selection.start.row;
 7312                if last_toggled_row == Some(start_row) {
 7313                    start_row += 1;
 7314                }
 7315                let end_row =
 7316                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 7317                        selection.end.row - 1
 7318                    } else {
 7319                        selection.end.row
 7320                    };
 7321                last_toggled_row = Some(end_row);
 7322
 7323                if start_row > end_row {
 7324                    continue;
 7325                }
 7326
 7327                // If the language has line comments, toggle those.
 7328                if let Some(full_comment_prefix) = language
 7329                    .line_comment_prefixes()
 7330                    .and_then(|prefixes| prefixes.first())
 7331                {
 7332                    // Split the comment prefix's trailing whitespace into a separate string,
 7333                    // as that portion won't be used for detecting if a line is a comment.
 7334                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7335                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7336                    let mut all_selection_lines_are_comments = true;
 7337
 7338                    for row in start_row..=end_row {
 7339                        if start_row < end_row && snapshot.is_line_blank(row) {
 7340                            continue;
 7341                        }
 7342
 7343                        let prefix_range = comment_prefix_range(
 7344                            snapshot.deref(),
 7345                            row,
 7346                            comment_prefix,
 7347                            comment_prefix_whitespace,
 7348                        );
 7349                        if prefix_range.is_empty() {
 7350                            all_selection_lines_are_comments = false;
 7351                        }
 7352                        selection_edit_ranges.push(prefix_range);
 7353                    }
 7354
 7355                    if all_selection_lines_are_comments {
 7356                        edits.extend(
 7357                            selection_edit_ranges
 7358                                .iter()
 7359                                .cloned()
 7360                                .map(|range| (range, empty_str.clone())),
 7361                        );
 7362                    } else {
 7363                        let min_column = selection_edit_ranges
 7364                            .iter()
 7365                            .map(|r| r.start.column)
 7366                            .min()
 7367                            .unwrap_or(0);
 7368                        edits.extend(selection_edit_ranges.iter().map(|range| {
 7369                            let position = Point::new(range.start.row, min_column);
 7370                            (position..position, full_comment_prefix.clone())
 7371                        }));
 7372                    }
 7373                } else if let Some((full_comment_prefix, comment_suffix)) =
 7374                    language.block_comment_delimiters()
 7375                {
 7376                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7377                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7378                    let prefix_range = comment_prefix_range(
 7379                        snapshot.deref(),
 7380                        start_row,
 7381                        comment_prefix,
 7382                        comment_prefix_whitespace,
 7383                    );
 7384                    let suffix_range = comment_suffix_range(
 7385                        snapshot.deref(),
 7386                        end_row,
 7387                        comment_suffix.trim_start_matches(' '),
 7388                        comment_suffix.starts_with(' '),
 7389                    );
 7390
 7391                    if prefix_range.is_empty() || suffix_range.is_empty() {
 7392                        edits.push((
 7393                            prefix_range.start..prefix_range.start,
 7394                            full_comment_prefix.clone(),
 7395                        ));
 7396                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 7397                        suffixes_inserted.push((end_row, comment_suffix.len()));
 7398                    } else {
 7399                        edits.push((prefix_range, empty_str.clone()));
 7400                        edits.push((suffix_range, empty_str.clone()));
 7401                    }
 7402                } else {
 7403                    continue;
 7404                }
 7405            }
 7406
 7407            drop(snapshot);
 7408            this.buffer.update(cx, |buffer, cx| {
 7409                buffer.edit(edits, None, cx);
 7410            });
 7411
 7412            // Adjust selections so that they end before any comment suffixes that
 7413            // were inserted.
 7414            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 7415            let mut selections = this.selections.all::<Point>(cx);
 7416            let snapshot = this.buffer.read(cx).read(cx);
 7417            for selection in &mut selections {
 7418                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 7419                    match row.cmp(&selection.end.row) {
 7420                        Ordering::Less => {
 7421                            suffixes_inserted.next();
 7422                            continue;
 7423                        }
 7424                        Ordering::Greater => break,
 7425                        Ordering::Equal => {
 7426                            if selection.end.column == snapshot.line_len(row) {
 7427                                if selection.is_empty() {
 7428                                    selection.start.column -= suffix_len as u32;
 7429                                }
 7430                                selection.end.column -= suffix_len as u32;
 7431                            }
 7432                            break;
 7433                        }
 7434                    }
 7435                }
 7436            }
 7437
 7438            drop(snapshot);
 7439            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7440
 7441            let selections = this.selections.all::<Point>(cx);
 7442            let selections_on_single_row = selections.windows(2).all(|selections| {
 7443                selections[0].start.row == selections[1].start.row
 7444                    && selections[0].end.row == selections[1].end.row
 7445                    && selections[0].start.row == selections[0].end.row
 7446            });
 7447            let selections_selecting = selections
 7448                .iter()
 7449                .any(|selection| selection.start != selection.end);
 7450            let advance_downwards = action.advance_downwards
 7451                && selections_on_single_row
 7452                && !selections_selecting
 7453                && this.mode != EditorMode::SingleLine;
 7454
 7455            if advance_downwards {
 7456                let snapshot = this.buffer.read(cx).snapshot(cx);
 7457
 7458                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7459                    s.move_cursors_with(|display_snapshot, display_point, _| {
 7460                        let mut point = display_point.to_point(display_snapshot);
 7461                        point.row += 1;
 7462                        point = snapshot.clip_point(point, Bias::Left);
 7463                        let display_point = point.to_display_point(display_snapshot);
 7464                        let goal = SelectionGoal::HorizontalPosition(
 7465                            display_snapshot
 7466                                .x_for_display_point(display_point, &text_layout_details)
 7467                                .into(),
 7468                        );
 7469                        (display_point, goal)
 7470                    })
 7471                });
 7472            }
 7473        });
 7474    }
 7475
 7476    pub fn select_larger_syntax_node(
 7477        &mut self,
 7478        _: &SelectLargerSyntaxNode,
 7479        cx: &mut ViewContext<Self>,
 7480    ) {
 7481        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7482        let buffer = self.buffer.read(cx).snapshot(cx);
 7483        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 7484
 7485        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7486        let mut selected_larger_node = false;
 7487        let new_selections = old_selections
 7488            .iter()
 7489            .map(|selection| {
 7490                let old_range = selection.start..selection.end;
 7491                let mut new_range = old_range.clone();
 7492                while let Some(containing_range) =
 7493                    buffer.range_for_syntax_ancestor(new_range.clone())
 7494                {
 7495                    new_range = containing_range;
 7496                    if !display_map.intersects_fold(new_range.start)
 7497                        && !display_map.intersects_fold(new_range.end)
 7498                    {
 7499                        break;
 7500                    }
 7501                }
 7502
 7503                selected_larger_node |= new_range != old_range;
 7504                Selection {
 7505                    id: selection.id,
 7506                    start: new_range.start,
 7507                    end: new_range.end,
 7508                    goal: SelectionGoal::None,
 7509                    reversed: selection.reversed,
 7510                }
 7511            })
 7512            .collect::<Vec<_>>();
 7513
 7514        if selected_larger_node {
 7515            stack.push(old_selections);
 7516            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7517                s.select(new_selections);
 7518            });
 7519        }
 7520        self.select_larger_syntax_node_stack = stack;
 7521    }
 7522
 7523    pub fn select_smaller_syntax_node(
 7524        &mut self,
 7525        _: &SelectSmallerSyntaxNode,
 7526        cx: &mut ViewContext<Self>,
 7527    ) {
 7528        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7529        if let Some(selections) = stack.pop() {
 7530            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7531                s.select(selections.to_vec());
 7532            });
 7533        }
 7534        self.select_larger_syntax_node_stack = stack;
 7535    }
 7536
 7537    pub fn move_to_enclosing_bracket(
 7538        &mut self,
 7539        _: &MoveToEnclosingBracket,
 7540        cx: &mut ViewContext<Self>,
 7541    ) {
 7542        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7543            s.move_offsets_with(|snapshot, selection| {
 7544                let Some(enclosing_bracket_ranges) =
 7545                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 7546                else {
 7547                    return;
 7548                };
 7549
 7550                let mut best_length = usize::MAX;
 7551                let mut best_inside = false;
 7552                let mut best_in_bracket_range = false;
 7553                let mut best_destination = None;
 7554                for (open, close) in enclosing_bracket_ranges {
 7555                    let close = close.to_inclusive();
 7556                    let length = close.end() - open.start;
 7557                    let inside = selection.start >= open.end && selection.end <= *close.start();
 7558                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 7559                        || close.contains(&selection.head());
 7560
 7561                    // If best is next to a bracket and current isn't, skip
 7562                    if !in_bracket_range && best_in_bracket_range {
 7563                        continue;
 7564                    }
 7565
 7566                    // Prefer smaller lengths unless best is inside and current isn't
 7567                    if length > best_length && (best_inside || !inside) {
 7568                        continue;
 7569                    }
 7570
 7571                    best_length = length;
 7572                    best_inside = inside;
 7573                    best_in_bracket_range = in_bracket_range;
 7574                    best_destination = Some(
 7575                        if close.contains(&selection.start) && close.contains(&selection.end) {
 7576                            if inside {
 7577                                open.end
 7578                            } else {
 7579                                open.start
 7580                            }
 7581                        } else {
 7582                            if inside {
 7583                                *close.start()
 7584                            } else {
 7585                                *close.end()
 7586                            }
 7587                        },
 7588                    );
 7589                }
 7590
 7591                if let Some(destination) = best_destination {
 7592                    selection.collapse_to(destination, SelectionGoal::None);
 7593                }
 7594            })
 7595        });
 7596    }
 7597
 7598    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 7599        self.end_selection(cx);
 7600        self.selection_history.mode = SelectionHistoryMode::Undoing;
 7601        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 7602            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7603            self.select_next_state = entry.select_next_state;
 7604            self.select_prev_state = entry.select_prev_state;
 7605            self.add_selections_state = entry.add_selections_state;
 7606            self.request_autoscroll(Autoscroll::newest(), cx);
 7607        }
 7608        self.selection_history.mode = SelectionHistoryMode::Normal;
 7609    }
 7610
 7611    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 7612        self.end_selection(cx);
 7613        self.selection_history.mode = SelectionHistoryMode::Redoing;
 7614        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 7615            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7616            self.select_next_state = entry.select_next_state;
 7617            self.select_prev_state = entry.select_prev_state;
 7618            self.add_selections_state = entry.add_selections_state;
 7619            self.request_autoscroll(Autoscroll::newest(), cx);
 7620        }
 7621        self.selection_history.mode = SelectionHistoryMode::Normal;
 7622    }
 7623
 7624    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 7625        self.go_to_diagnostic_impl(Direction::Next, cx)
 7626    }
 7627
 7628    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 7629        self.go_to_diagnostic_impl(Direction::Prev, cx)
 7630    }
 7631
 7632    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 7633        let buffer = self.buffer.read(cx).snapshot(cx);
 7634        let selection = self.selections.newest::<usize>(cx);
 7635
 7636        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 7637        if direction == Direction::Next {
 7638            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 7639                let (group_id, jump_to) = popover.activation_info();
 7640                if self.activate_diagnostics(group_id, cx) {
 7641                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7642                        let mut new_selection = s.newest_anchor().clone();
 7643                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 7644                        s.select_anchors(vec![new_selection.clone()]);
 7645                    });
 7646                }
 7647                return;
 7648            }
 7649        }
 7650
 7651        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 7652            active_diagnostics
 7653                .primary_range
 7654                .to_offset(&buffer)
 7655                .to_inclusive()
 7656        });
 7657        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 7658            if active_primary_range.contains(&selection.head()) {
 7659                *active_primary_range.end()
 7660            } else {
 7661                selection.head()
 7662            }
 7663        } else {
 7664            selection.head()
 7665        };
 7666
 7667        loop {
 7668            let mut diagnostics = if direction == Direction::Prev {
 7669                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 7670            } else {
 7671                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 7672            };
 7673            let group = diagnostics.find_map(|entry| {
 7674                if entry.diagnostic.is_primary
 7675                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 7676                    && !entry.range.is_empty()
 7677                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
 7678                    && !entry.range.contains(&search_start)
 7679                {
 7680                    Some((entry.range, entry.diagnostic.group_id))
 7681                } else {
 7682                    None
 7683                }
 7684            });
 7685
 7686            if let Some((primary_range, group_id)) = group {
 7687                if self.activate_diagnostics(group_id, cx) {
 7688                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7689                        s.select(vec![Selection {
 7690                            id: selection.id,
 7691                            start: primary_range.start,
 7692                            end: primary_range.start,
 7693                            reversed: false,
 7694                            goal: SelectionGoal::None,
 7695                        }]);
 7696                    });
 7697                }
 7698                break;
 7699            } else {
 7700                // Cycle around to the start of the buffer, potentially moving back to the start of
 7701                // the currently active diagnostic.
 7702                active_primary_range.take();
 7703                if direction == Direction::Prev {
 7704                    if search_start == buffer.len() {
 7705                        break;
 7706                    } else {
 7707                        search_start = buffer.len();
 7708                    }
 7709                } else if search_start == 0 {
 7710                    break;
 7711                } else {
 7712                    search_start = 0;
 7713                }
 7714            }
 7715        }
 7716    }
 7717
 7718    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 7719        let snapshot = self
 7720            .display_map
 7721            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7722        let selection = self.selections.newest::<Point>(cx);
 7723
 7724        if !self.seek_in_direction(
 7725            &snapshot,
 7726            selection.head(),
 7727            false,
 7728            snapshot
 7729                .buffer_snapshot
 7730                .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
 7731            cx,
 7732        ) {
 7733            let wrapped_point = Point::zero();
 7734            self.seek_in_direction(
 7735                &snapshot,
 7736                wrapped_point,
 7737                true,
 7738                snapshot
 7739                    .buffer_snapshot
 7740                    .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
 7741                cx,
 7742            );
 7743        }
 7744    }
 7745
 7746    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 7747        let snapshot = self
 7748            .display_map
 7749            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7750        let selection = self.selections.newest::<Point>(cx);
 7751
 7752        if !self.seek_in_direction(
 7753            &snapshot,
 7754            selection.head(),
 7755            false,
 7756            snapshot
 7757                .buffer_snapshot
 7758                .git_diff_hunks_in_range_rev(0..selection.head().row),
 7759            cx,
 7760        ) {
 7761            let wrapped_point = snapshot.buffer_snapshot.max_point();
 7762            self.seek_in_direction(
 7763                &snapshot,
 7764                wrapped_point,
 7765                true,
 7766                snapshot
 7767                    .buffer_snapshot
 7768                    .git_diff_hunks_in_range_rev(0..wrapped_point.row),
 7769                cx,
 7770            );
 7771        }
 7772    }
 7773
 7774    fn seek_in_direction(
 7775        &mut self,
 7776        snapshot: &DisplaySnapshot,
 7777        initial_point: Point,
 7778        is_wrapped: bool,
 7779        hunks: impl Iterator<Item = DiffHunk<u32>>,
 7780        cx: &mut ViewContext<Editor>,
 7781    ) -> bool {
 7782        let display_point = initial_point.to_display_point(snapshot);
 7783        let mut hunks = hunks
 7784            .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
 7785            .filter(|hunk| {
 7786                if is_wrapped {
 7787                    true
 7788                } else {
 7789                    !hunk.contains_display_row(display_point.row())
 7790                }
 7791            })
 7792            .dedup();
 7793
 7794        if let Some(hunk) = hunks.next() {
 7795            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7796                let row = hunk.start_display_row();
 7797                let point = DisplayPoint::new(row, 0);
 7798                s.select_display_ranges([point..point]);
 7799            });
 7800
 7801            true
 7802        } else {
 7803            false
 7804        }
 7805    }
 7806
 7807    pub fn go_to_definition(
 7808        &mut self,
 7809        _: &GoToDefinition,
 7810        cx: &mut ViewContext<Self>,
 7811    ) -> Task<Result<bool>> {
 7812        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 7813    }
 7814
 7815    pub fn go_to_implementation(
 7816        &mut self,
 7817        _: &GoToImplementation,
 7818        cx: &mut ViewContext<Self>,
 7819    ) -> Task<Result<bool>> {
 7820        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 7821    }
 7822
 7823    pub fn go_to_implementation_split(
 7824        &mut self,
 7825        _: &GoToImplementationSplit,
 7826        cx: &mut ViewContext<Self>,
 7827    ) -> Task<Result<bool>> {
 7828        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 7829    }
 7830
 7831    pub fn go_to_type_definition(
 7832        &mut self,
 7833        _: &GoToTypeDefinition,
 7834        cx: &mut ViewContext<Self>,
 7835    ) -> Task<Result<bool>> {
 7836        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 7837    }
 7838
 7839    pub fn go_to_definition_split(
 7840        &mut self,
 7841        _: &GoToDefinitionSplit,
 7842        cx: &mut ViewContext<Self>,
 7843    ) -> Task<Result<bool>> {
 7844        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 7845    }
 7846
 7847    pub fn go_to_type_definition_split(
 7848        &mut self,
 7849        _: &GoToTypeDefinitionSplit,
 7850        cx: &mut ViewContext<Self>,
 7851    ) -> Task<Result<bool>> {
 7852        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 7853    }
 7854
 7855    fn go_to_definition_of_kind(
 7856        &mut self,
 7857        kind: GotoDefinitionKind,
 7858        split: bool,
 7859        cx: &mut ViewContext<Self>,
 7860    ) -> Task<Result<bool>> {
 7861        let Some(workspace) = self.workspace() else {
 7862            return Task::ready(Ok(false));
 7863        };
 7864        let buffer = self.buffer.read(cx);
 7865        let head = self.selections.newest::<usize>(cx).head();
 7866        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 7867            text_anchor
 7868        } else {
 7869            return Task::ready(Ok(false));
 7870        };
 7871
 7872        let project = workspace.read(cx).project().clone();
 7873        let definitions = project.update(cx, |project, cx| match kind {
 7874            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 7875            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 7876            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 7877        });
 7878
 7879        cx.spawn(|editor, mut cx| async move {
 7880            let definitions = definitions.await?;
 7881            let navigated = editor
 7882                .update(&mut cx, |editor, cx| {
 7883                    editor.navigate_to_hover_links(
 7884                        Some(kind),
 7885                        definitions.into_iter().map(HoverLink::Text).collect(),
 7886                        split,
 7887                        cx,
 7888                    )
 7889                })?
 7890                .await?;
 7891            anyhow::Ok(navigated)
 7892        })
 7893    }
 7894
 7895    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 7896        let position = self.selections.newest_anchor().head();
 7897        let Some((buffer, buffer_position)) =
 7898            self.buffer.read(cx).text_anchor_for_position(position, cx)
 7899        else {
 7900            return;
 7901        };
 7902
 7903        cx.spawn(|editor, mut cx| async move {
 7904            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 7905                editor.update(&mut cx, |_, cx| {
 7906                    cx.open_url(&url);
 7907                })
 7908            } else {
 7909                Ok(())
 7910            }
 7911        })
 7912        .detach();
 7913    }
 7914
 7915    pub(crate) fn navigate_to_hover_links(
 7916        &mut self,
 7917        kind: Option<GotoDefinitionKind>,
 7918        mut definitions: Vec<HoverLink>,
 7919        split: bool,
 7920        cx: &mut ViewContext<Editor>,
 7921    ) -> Task<Result<bool>> {
 7922        // If there is one definition, just open it directly
 7923        if definitions.len() == 1 {
 7924            let definition = definitions.pop().unwrap();
 7925            let target_task = match definition {
 7926                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7927                HoverLink::InlayHint(lsp_location, server_id) => {
 7928                    self.compute_target_location(lsp_location, server_id, cx)
 7929                }
 7930                HoverLink::Url(url) => {
 7931                    cx.open_url(&url);
 7932                    Task::ready(Ok(None))
 7933                }
 7934            };
 7935            cx.spawn(|editor, mut cx| async move {
 7936                let target = target_task.await.context("target resolution task")?;
 7937                if let Some(target) = target {
 7938                    editor.update(&mut cx, |editor, cx| {
 7939                        let Some(workspace) = editor.workspace() else {
 7940                            return false;
 7941                        };
 7942                        let pane = workspace.read(cx).active_pane().clone();
 7943
 7944                        let range = target.range.to_offset(target.buffer.read(cx));
 7945                        let range = editor.range_for_match(&range);
 7946                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 7947                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 7948                                s.select_ranges([range]);
 7949                            });
 7950                        } else {
 7951                            cx.window_context().defer(move |cx| {
 7952                                let target_editor: View<Self> =
 7953                                    workspace.update(cx, |workspace, cx| {
 7954                                        let pane = if split {
 7955                                            workspace.adjacent_pane(cx)
 7956                                        } else {
 7957                                            workspace.active_pane().clone()
 7958                                        };
 7959
 7960                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 7961                                    });
 7962                                target_editor.update(cx, |target_editor, cx| {
 7963                                    // When selecting a definition in a different buffer, disable the nav history
 7964                                    // to avoid creating a history entry at the previous cursor location.
 7965                                    pane.update(cx, |pane, _| pane.disable_history());
 7966                                    target_editor.change_selections(
 7967                                        Some(Autoscroll::focused()),
 7968                                        cx,
 7969                                        |s| {
 7970                                            s.select_ranges([range]);
 7971                                        },
 7972                                    );
 7973                                    pane.update(cx, |pane, _| pane.enable_history());
 7974                                });
 7975                            });
 7976                        }
 7977                        true
 7978                    })
 7979                } else {
 7980                    Ok(false)
 7981                }
 7982            })
 7983        } else if !definitions.is_empty() {
 7984            let replica_id = self.replica_id(cx);
 7985            cx.spawn(|editor, mut cx| async move {
 7986                let (title, location_tasks, workspace) = editor
 7987                    .update(&mut cx, |editor, cx| {
 7988                        let tab_kind = match kind {
 7989                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 7990                            _ => "Definitions",
 7991                        };
 7992                        let title = definitions
 7993                            .iter()
 7994                            .find_map(|definition| match definition {
 7995                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 7996                                    let buffer = origin.buffer.read(cx);
 7997                                    format!(
 7998                                        "{} for {}",
 7999                                        tab_kind,
 8000                                        buffer
 8001                                            .text_for_range(origin.range.clone())
 8002                                            .collect::<String>()
 8003                                    )
 8004                                }),
 8005                                HoverLink::InlayHint(_, _) => None,
 8006                                HoverLink::Url(_) => None,
 8007                            })
 8008                            .unwrap_or(tab_kind.to_string());
 8009                        let location_tasks = definitions
 8010                            .into_iter()
 8011                            .map(|definition| match definition {
 8012                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8013                                HoverLink::InlayHint(lsp_location, server_id) => {
 8014                                    editor.compute_target_location(lsp_location, server_id, cx)
 8015                                }
 8016                                HoverLink::Url(_) => Task::ready(Ok(None)),
 8017                            })
 8018                            .collect::<Vec<_>>();
 8019                        (title, location_tasks, editor.workspace().clone())
 8020                    })
 8021                    .context("location tasks preparation")?;
 8022
 8023                let locations = futures::future::join_all(location_tasks)
 8024                    .await
 8025                    .into_iter()
 8026                    .filter_map(|location| location.transpose())
 8027                    .collect::<Result<_>>()
 8028                    .context("location tasks")?;
 8029
 8030                let Some(workspace) = workspace else {
 8031                    return Ok(false);
 8032                };
 8033                let opened = workspace
 8034                    .update(&mut cx, |workspace, cx| {
 8035                        Self::open_locations_in_multibuffer(
 8036                            workspace, locations, replica_id, title, split, cx,
 8037                        )
 8038                    })
 8039                    .ok();
 8040
 8041                anyhow::Ok(opened.is_some())
 8042            })
 8043        } else {
 8044            Task::ready(Ok(false))
 8045        }
 8046    }
 8047
 8048    fn compute_target_location(
 8049        &self,
 8050        lsp_location: lsp::Location,
 8051        server_id: LanguageServerId,
 8052        cx: &mut ViewContext<Editor>,
 8053    ) -> Task<anyhow::Result<Option<Location>>> {
 8054        let Some(project) = self.project.clone() else {
 8055            return Task::Ready(Some(Ok(None)));
 8056        };
 8057
 8058        cx.spawn(move |editor, mut cx| async move {
 8059            let location_task = editor.update(&mut cx, |editor, cx| {
 8060                project.update(cx, |project, cx| {
 8061                    let language_server_name =
 8062                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 8063                            project
 8064                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 8065                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 8066                        });
 8067                    language_server_name.map(|language_server_name| {
 8068                        project.open_local_buffer_via_lsp(
 8069                            lsp_location.uri.clone(),
 8070                            server_id,
 8071                            language_server_name,
 8072                            cx,
 8073                        )
 8074                    })
 8075                })
 8076            })?;
 8077            let location = match location_task {
 8078                Some(task) => Some({
 8079                    let target_buffer_handle = task.await.context("open local buffer")?;
 8080                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 8081                        let target_start = target_buffer
 8082                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 8083                        let target_end = target_buffer
 8084                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 8085                        target_buffer.anchor_after(target_start)
 8086                            ..target_buffer.anchor_before(target_end)
 8087                    })?;
 8088                    Location {
 8089                        buffer: target_buffer_handle,
 8090                        range,
 8091                    }
 8092                }),
 8093                None => None,
 8094            };
 8095            Ok(location)
 8096        })
 8097    }
 8098
 8099    pub fn find_all_references(
 8100        &mut self,
 8101        _: &FindAllReferences,
 8102        cx: &mut ViewContext<Self>,
 8103    ) -> Option<Task<Result<()>>> {
 8104        let multi_buffer = self.buffer.read(cx);
 8105        let selection = self.selections.newest::<usize>(cx);
 8106        let head = selection.head();
 8107
 8108        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 8109        let head_anchor = multi_buffer_snapshot.anchor_at(
 8110            head,
 8111            if head < selection.tail() {
 8112                Bias::Right
 8113            } else {
 8114                Bias::Left
 8115            },
 8116        );
 8117        match self
 8118            .find_all_references_task_sources
 8119            .binary_search_by(|task_anchor| task_anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 8120        {
 8121            Ok(_) => {
 8122                log::info!(
 8123                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 8124                );
 8125                return None;
 8126            }
 8127            Err(i) => {
 8128                self.find_all_references_task_sources.insert(i, head_anchor);
 8129            }
 8130        }
 8131
 8132        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 8133        let replica_id = self.replica_id(cx);
 8134        let workspace = self.workspace()?;
 8135        let project = workspace.read(cx).project().clone();
 8136        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 8137        let open_task = cx.spawn(|editor, mut cx| async move {
 8138            let mut locations = references.await?;
 8139            let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
 8140            let head_offset = text::ToOffset::to_offset(&head, &snapshot);
 8141
 8142            // LSP may return references that contain the item itself we requested `find_all_references` for (eg. rust-analyzer)
 8143            // So we will remove it from locations
 8144            // If there is only one reference, we will not do this filter cause it may make locations empty
 8145            if locations.len() > 1 {
 8146                cx.update(|cx| {
 8147                    locations.retain(|location| {
 8148                        // fn foo(x : i64) {
 8149                        //         ^
 8150                        //  println!(x);
 8151                        // }
 8152                        // It is ok to find reference when caret being at ^ (the end of the word)
 8153                        // So we turn offset into inclusive to include the end of the word
 8154                        !location
 8155                            .range
 8156                            .to_offset(location.buffer.read(cx))
 8157                            .to_inclusive()
 8158                            .contains(&head_offset)
 8159                    });
 8160                })?;
 8161            }
 8162
 8163            if locations.is_empty() {
 8164                return Ok(());
 8165            }
 8166
 8167            // If there is one reference, just open it directly
 8168            if locations.len() == 1 {
 8169                let target = locations.pop().unwrap();
 8170
 8171                return editor.update(&mut cx, |editor, cx| {
 8172                    let range = target.range.to_offset(target.buffer.read(cx));
 8173                    let range = editor.range_for_match(&range);
 8174
 8175                    if Some(&target.buffer) == editor.buffer().read(cx).as_singleton().as_ref() {
 8176                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8177                            s.select_ranges([range]);
 8178                        });
 8179                    } else {
 8180                        cx.window_context().defer(move |cx| {
 8181                            let target_editor: View<Self> =
 8182                                workspace.update(cx, |workspace, cx| {
 8183                                    workspace.open_project_item(
 8184                                        workspace.active_pane().clone(),
 8185                                        target.buffer.clone(),
 8186                                        cx,
 8187                                    )
 8188                                });
 8189                            target_editor.update(cx, |target_editor, cx| {
 8190                                target_editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8191                                    s.select_ranges([range]);
 8192                                })
 8193                            })
 8194                        })
 8195                    }
 8196                });
 8197            }
 8198
 8199            workspace.update(&mut cx, |workspace, cx| {
 8200                let title = locations
 8201                    .first()
 8202                    .as_ref()
 8203                    .map(|location| {
 8204                        let buffer = location.buffer.read(cx);
 8205                        format!(
 8206                            "References to `{}`",
 8207                            buffer
 8208                                .text_for_range(location.range.clone())
 8209                                .collect::<String>()
 8210                        )
 8211                    })
 8212                    .unwrap();
 8213                Self::open_locations_in_multibuffer(
 8214                    workspace, locations, replica_id, title, false, cx,
 8215                );
 8216            })?;
 8217
 8218            Ok(())
 8219        });
 8220        Some(cx.spawn(|editor, mut cx| async move {
 8221            open_task.await?;
 8222            editor.update(&mut cx, |editor, _| {
 8223                if let Ok(i) =
 8224                    editor
 8225                        .find_all_references_task_sources
 8226                        .binary_search_by(|task_anchor| {
 8227                            task_anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 8228                        })
 8229                {
 8230                    editor.find_all_references_task_sources.remove(i);
 8231                }
 8232            })?;
 8233            anyhow::Ok(())
 8234        }))
 8235    }
 8236
 8237    /// Opens a multibuffer with the given project locations in it
 8238    pub fn open_locations_in_multibuffer(
 8239        workspace: &mut Workspace,
 8240        mut locations: Vec<Location>,
 8241        replica_id: ReplicaId,
 8242        title: String,
 8243        split: bool,
 8244        cx: &mut ViewContext<Workspace>,
 8245    ) {
 8246        // If there are multiple definitions, open them in a multibuffer
 8247        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 8248        let mut locations = locations.into_iter().peekable();
 8249        let mut ranges_to_highlight = Vec::new();
 8250        let capability = workspace.project().read(cx).capability();
 8251
 8252        let excerpt_buffer = cx.new_model(|cx| {
 8253            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 8254            while let Some(location) = locations.next() {
 8255                let buffer = location.buffer.read(cx);
 8256                let mut ranges_for_buffer = Vec::new();
 8257                let range = location.range.to_offset(buffer);
 8258                ranges_for_buffer.push(range.clone());
 8259
 8260                while let Some(next_location) = locations.peek() {
 8261                    if next_location.buffer == location.buffer {
 8262                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 8263                        locations.next();
 8264                    } else {
 8265                        break;
 8266                    }
 8267                }
 8268
 8269                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 8270                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 8271                    location.buffer.clone(),
 8272                    ranges_for_buffer,
 8273                    1,
 8274                    cx,
 8275                ))
 8276            }
 8277
 8278            multibuffer.with_title(title)
 8279        });
 8280
 8281        let editor = cx.new_view(|cx| {
 8282            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
 8283        });
 8284        editor.update(cx, |editor, cx| {
 8285            editor.highlight_background::<Self>(
 8286                ranges_to_highlight,
 8287                |theme| theme.editor_highlighted_line_background,
 8288                cx,
 8289            );
 8290        });
 8291        if split {
 8292            workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
 8293        } else {
 8294            workspace.add_item_to_active_pane(Box::new(editor), cx);
 8295        }
 8296    }
 8297
 8298    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8299        use language::ToOffset as _;
 8300
 8301        let project = self.project.clone()?;
 8302        let selection = self.selections.newest_anchor().clone();
 8303        let (cursor_buffer, cursor_buffer_position) = self
 8304            .buffer
 8305            .read(cx)
 8306            .text_anchor_for_position(selection.head(), cx)?;
 8307        let (tail_buffer, _) = self
 8308            .buffer
 8309            .read(cx)
 8310            .text_anchor_for_position(selection.tail(), cx)?;
 8311        if tail_buffer != cursor_buffer {
 8312            return None;
 8313        }
 8314
 8315        let snapshot = cursor_buffer.read(cx).snapshot();
 8316        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 8317        let prepare_rename = project.update(cx, |project, cx| {
 8318            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 8319        });
 8320        drop(snapshot);
 8321
 8322        Some(cx.spawn(|this, mut cx| async move {
 8323            let rename_range = if let Some(range) = prepare_rename.await? {
 8324                Some(range)
 8325            } else {
 8326                this.update(&mut cx, |this, cx| {
 8327                    let buffer = this.buffer.read(cx).snapshot(cx);
 8328                    let mut buffer_highlights = this
 8329                        .document_highlights_for_position(selection.head(), &buffer)
 8330                        .filter(|highlight| {
 8331                            highlight.start.excerpt_id == selection.head().excerpt_id
 8332                                && highlight.end.excerpt_id == selection.head().excerpt_id
 8333                        });
 8334                    buffer_highlights
 8335                        .next()
 8336                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 8337                })?
 8338            };
 8339            if let Some(rename_range) = rename_range {
 8340                this.update(&mut cx, |this, cx| {
 8341                    let snapshot = cursor_buffer.read(cx).snapshot();
 8342                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 8343                    let cursor_offset_in_rename_range =
 8344                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 8345
 8346                    this.take_rename(false, cx);
 8347                    let buffer = this.buffer.read(cx).read(cx);
 8348                    let cursor_offset = selection.head().to_offset(&buffer);
 8349                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 8350                    let rename_end = rename_start + rename_buffer_range.len();
 8351                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 8352                    let mut old_highlight_id = None;
 8353                    let old_name: Arc<str> = buffer
 8354                        .chunks(rename_start..rename_end, true)
 8355                        .map(|chunk| {
 8356                            if old_highlight_id.is_none() {
 8357                                old_highlight_id = chunk.syntax_highlight_id;
 8358                            }
 8359                            chunk.text
 8360                        })
 8361                        .collect::<String>()
 8362                        .into();
 8363
 8364                    drop(buffer);
 8365
 8366                    // Position the selection in the rename editor so that it matches the current selection.
 8367                    this.show_local_selections = false;
 8368                    let rename_editor = cx.new_view(|cx| {
 8369                        let mut editor = Editor::single_line(cx);
 8370                        editor.buffer.update(cx, |buffer, cx| {
 8371                            buffer.edit([(0..0, old_name.clone())], None, cx)
 8372                        });
 8373                        editor.select_all(&SelectAll, cx);
 8374                        editor
 8375                    });
 8376
 8377                    let ranges = this
 8378                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
 8379                        .into_iter()
 8380                        .flat_map(|(_, ranges)| ranges.into_iter())
 8381                        .chain(
 8382                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
 8383                                .into_iter()
 8384                                .flat_map(|(_, ranges)| ranges.into_iter()),
 8385                        )
 8386                        .collect();
 8387
 8388                    this.highlight_text::<Rename>(
 8389                        ranges,
 8390                        HighlightStyle {
 8391                            fade_out: Some(0.6),
 8392                            ..Default::default()
 8393                        },
 8394                        cx,
 8395                    );
 8396                    let rename_focus_handle = rename_editor.focus_handle(cx);
 8397                    cx.focus(&rename_focus_handle);
 8398                    let block_id = this.insert_blocks(
 8399                        [BlockProperties {
 8400                            style: BlockStyle::Flex,
 8401                            position: range.start,
 8402                            height: 1,
 8403                            render: Arc::new({
 8404                                let rename_editor = rename_editor.clone();
 8405                                move |cx: &mut BlockContext| {
 8406                                    let mut text_style = cx.editor_style.text.clone();
 8407                                    if let Some(highlight_style) = old_highlight_id
 8408                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 8409                                    {
 8410                                        text_style = text_style.highlight(highlight_style);
 8411                                    }
 8412                                    div()
 8413                                        .pl(cx.anchor_x)
 8414                                        .child(EditorElement::new(
 8415                                            &rename_editor,
 8416                                            EditorStyle {
 8417                                                background: cx.theme().system().transparent,
 8418                                                local_player: cx.editor_style.local_player,
 8419                                                text: text_style,
 8420                                                scrollbar_width: cx.editor_style.scrollbar_width,
 8421                                                syntax: cx.editor_style.syntax.clone(),
 8422                                                status: cx.editor_style.status.clone(),
 8423                                                inlay_hints_style: HighlightStyle {
 8424                                                    color: Some(cx.theme().status().hint),
 8425                                                    font_weight: Some(FontWeight::BOLD),
 8426                                                    ..HighlightStyle::default()
 8427                                                },
 8428                                                suggestions_style: HighlightStyle {
 8429                                                    color: Some(cx.theme().status().predictive),
 8430                                                    ..HighlightStyle::default()
 8431                                                },
 8432                                            },
 8433                                        ))
 8434                                        .into_any_element()
 8435                                }
 8436                            }),
 8437                            disposition: BlockDisposition::Below,
 8438                        }],
 8439                        Some(Autoscroll::fit()),
 8440                        cx,
 8441                    )[0];
 8442                    this.pending_rename = Some(RenameState {
 8443                        range,
 8444                        old_name,
 8445                        editor: rename_editor,
 8446                        block_id,
 8447                    });
 8448                })?;
 8449            }
 8450
 8451            Ok(())
 8452        }))
 8453    }
 8454
 8455    pub fn confirm_rename(
 8456        &mut self,
 8457        _: &ConfirmRename,
 8458        cx: &mut ViewContext<Self>,
 8459    ) -> Option<Task<Result<()>>> {
 8460        let rename = self.take_rename(false, cx)?;
 8461        let workspace = self.workspace()?;
 8462        let (start_buffer, start) = self
 8463            .buffer
 8464            .read(cx)
 8465            .text_anchor_for_position(rename.range.start, cx)?;
 8466        let (end_buffer, end) = self
 8467            .buffer
 8468            .read(cx)
 8469            .text_anchor_for_position(rename.range.end, cx)?;
 8470        if start_buffer != end_buffer {
 8471            return None;
 8472        }
 8473
 8474        let buffer = start_buffer;
 8475        let range = start..end;
 8476        let old_name = rename.old_name;
 8477        let new_name = rename.editor.read(cx).text(cx);
 8478
 8479        let rename = workspace
 8480            .read(cx)
 8481            .project()
 8482            .clone()
 8483            .update(cx, |project, cx| {
 8484                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 8485            });
 8486        let workspace = workspace.downgrade();
 8487
 8488        Some(cx.spawn(|editor, mut cx| async move {
 8489            let project_transaction = rename.await?;
 8490            Self::open_project_transaction(
 8491                &editor,
 8492                workspace,
 8493                project_transaction,
 8494                format!("Rename: {}{}", old_name, new_name),
 8495                cx.clone(),
 8496            )
 8497            .await?;
 8498
 8499            editor.update(&mut cx, |editor, cx| {
 8500                editor.refresh_document_highlights(cx);
 8501            })?;
 8502            Ok(())
 8503        }))
 8504    }
 8505
 8506    fn take_rename(
 8507        &mut self,
 8508        moving_cursor: bool,
 8509        cx: &mut ViewContext<Self>,
 8510    ) -> Option<RenameState> {
 8511        let rename = self.pending_rename.take()?;
 8512        if rename.editor.focus_handle(cx).is_focused(cx) {
 8513            cx.focus(&self.focus_handle);
 8514        }
 8515
 8516        self.remove_blocks(
 8517            [rename.block_id].into_iter().collect(),
 8518            Some(Autoscroll::fit()),
 8519            cx,
 8520        );
 8521        self.clear_highlights::<Rename>(cx);
 8522        self.show_local_selections = true;
 8523
 8524        if moving_cursor {
 8525            let rename_editor = rename.editor.read(cx);
 8526            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 8527
 8528            // Update the selection to match the position of the selection inside
 8529            // the rename editor.
 8530            let snapshot = self.buffer.read(cx).read(cx);
 8531            let rename_range = rename.range.to_offset(&snapshot);
 8532            let cursor_in_editor = snapshot
 8533                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 8534                .min(rename_range.end);
 8535            drop(snapshot);
 8536
 8537            self.change_selections(None, cx, |s| {
 8538                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 8539            });
 8540        } else {
 8541            self.refresh_document_highlights(cx);
 8542        }
 8543
 8544        Some(rename)
 8545    }
 8546
 8547    pub fn pending_rename(&self) -> Option<&RenameState> {
 8548        self.pending_rename.as_ref()
 8549    }
 8550
 8551    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8552        let project = match &self.project {
 8553            Some(project) => project.clone(),
 8554            None => return None,
 8555        };
 8556
 8557        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 8558    }
 8559
 8560    fn perform_format(
 8561        &mut self,
 8562        project: Model<Project>,
 8563        trigger: FormatTrigger,
 8564        cx: &mut ViewContext<Self>,
 8565    ) -> Task<Result<()>> {
 8566        let buffer = self.buffer().clone();
 8567        let mut buffers = buffer.read(cx).all_buffers();
 8568        if trigger == FormatTrigger::Save {
 8569            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 8570        }
 8571
 8572        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 8573        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 8574
 8575        cx.spawn(|_, mut cx| async move {
 8576            let transaction = futures::select_biased! {
 8577                () = timeout => {
 8578                    log::warn!("timed out waiting for formatting");
 8579                    None
 8580                }
 8581                transaction = format.log_err().fuse() => transaction,
 8582            };
 8583
 8584            buffer
 8585                .update(&mut cx, |buffer, cx| {
 8586                    if let Some(transaction) = transaction {
 8587                        if !buffer.is_singleton() {
 8588                            buffer.push_transaction(&transaction.0, cx);
 8589                        }
 8590                    }
 8591
 8592                    cx.notify();
 8593                })
 8594                .ok();
 8595
 8596            Ok(())
 8597        })
 8598    }
 8599
 8600    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 8601        if let Some(project) = self.project.clone() {
 8602            self.buffer.update(cx, |multi_buffer, cx| {
 8603                project.update(cx, |project, cx| {
 8604                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 8605                });
 8606            })
 8607        }
 8608    }
 8609
 8610    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 8611        cx.show_character_palette();
 8612    }
 8613
 8614    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 8615        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 8616            let buffer = self.buffer.read(cx).snapshot(cx);
 8617            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 8618            let is_valid = buffer
 8619                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 8620                .any(|entry| {
 8621                    entry.diagnostic.is_primary
 8622                        && !entry.range.is_empty()
 8623                        && entry.range.start == primary_range_start
 8624                        && entry.diagnostic.message == active_diagnostics.primary_message
 8625                });
 8626
 8627            if is_valid != active_diagnostics.is_valid {
 8628                active_diagnostics.is_valid = is_valid;
 8629                let mut new_styles = HashMap::default();
 8630                for (block_id, diagnostic) in &active_diagnostics.blocks {
 8631                    new_styles.insert(
 8632                        *block_id,
 8633                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
 8634                    );
 8635                }
 8636                self.display_map
 8637                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
 8638            }
 8639        }
 8640    }
 8641
 8642    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 8643        self.dismiss_diagnostics(cx);
 8644        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 8645            let buffer = self.buffer.read(cx).snapshot(cx);
 8646
 8647            let mut primary_range = None;
 8648            let mut primary_message = None;
 8649            let mut group_end = Point::zero();
 8650            let diagnostic_group = buffer
 8651                .diagnostic_group::<Point>(group_id)
 8652                .map(|entry| {
 8653                    if entry.range.end > group_end {
 8654                        group_end = entry.range.end;
 8655                    }
 8656                    if entry.diagnostic.is_primary {
 8657                        primary_range = Some(entry.range.clone());
 8658                        primary_message = Some(entry.diagnostic.message.clone());
 8659                    }
 8660                    entry
 8661                })
 8662                .collect::<Vec<_>>();
 8663            let primary_range = primary_range?;
 8664            let primary_message = primary_message?;
 8665            let primary_range =
 8666                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 8667
 8668            let blocks = display_map
 8669                .insert_blocks(
 8670                    diagnostic_group.iter().map(|entry| {
 8671                        let diagnostic = entry.diagnostic.clone();
 8672                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 8673                        BlockProperties {
 8674                            style: BlockStyle::Fixed,
 8675                            position: buffer.anchor_after(entry.range.start),
 8676                            height: message_height,
 8677                            render: diagnostic_block_renderer(diagnostic, true),
 8678                            disposition: BlockDisposition::Below,
 8679                        }
 8680                    }),
 8681                    cx,
 8682                )
 8683                .into_iter()
 8684                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 8685                .collect();
 8686
 8687            Some(ActiveDiagnosticGroup {
 8688                primary_range,
 8689                primary_message,
 8690                blocks,
 8691                is_valid: true,
 8692            })
 8693        });
 8694        self.active_diagnostics.is_some()
 8695    }
 8696
 8697    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 8698        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 8699            self.display_map.update(cx, |display_map, cx| {
 8700                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 8701            });
 8702            cx.notify();
 8703        }
 8704    }
 8705
 8706    pub fn set_selections_from_remote(
 8707        &mut self,
 8708        selections: Vec<Selection<Anchor>>,
 8709        pending_selection: Option<Selection<Anchor>>,
 8710        cx: &mut ViewContext<Self>,
 8711    ) {
 8712        let old_cursor_position = self.selections.newest_anchor().head();
 8713        self.selections.change_with(cx, |s| {
 8714            s.select_anchors(selections);
 8715            if let Some(pending_selection) = pending_selection {
 8716                s.set_pending(pending_selection, SelectMode::Character);
 8717            } else {
 8718                s.clear_pending();
 8719            }
 8720        });
 8721        self.selections_did_change(false, &old_cursor_position, cx);
 8722    }
 8723
 8724    fn push_to_selection_history(&mut self) {
 8725        self.selection_history.push(SelectionHistoryEntry {
 8726            selections: self.selections.disjoint_anchors(),
 8727            select_next_state: self.select_next_state.clone(),
 8728            select_prev_state: self.select_prev_state.clone(),
 8729            add_selections_state: self.add_selections_state.clone(),
 8730        });
 8731    }
 8732
 8733    pub fn transact(
 8734        &mut self,
 8735        cx: &mut ViewContext<Self>,
 8736        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 8737    ) -> Option<TransactionId> {
 8738        self.start_transaction_at(Instant::now(), cx);
 8739        update(self, cx);
 8740        self.end_transaction_at(Instant::now(), cx)
 8741    }
 8742
 8743    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 8744        self.end_selection(cx);
 8745        if let Some(tx_id) = self
 8746            .buffer
 8747            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 8748        {
 8749            self.selection_history
 8750                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 8751            cx.emit(EditorEvent::TransactionBegun {
 8752                transaction_id: tx_id,
 8753            })
 8754        }
 8755    }
 8756
 8757    fn end_transaction_at(
 8758        &mut self,
 8759        now: Instant,
 8760        cx: &mut ViewContext<Self>,
 8761    ) -> Option<TransactionId> {
 8762        if let Some(tx_id) = self
 8763            .buffer
 8764            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 8765        {
 8766            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 8767                *end_selections = Some(self.selections.disjoint_anchors());
 8768            } else {
 8769                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 8770            }
 8771
 8772            cx.emit(EditorEvent::Edited);
 8773            Some(tx_id)
 8774        } else {
 8775            None
 8776        }
 8777    }
 8778
 8779    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 8780        let mut fold_ranges = Vec::new();
 8781
 8782        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8783
 8784        let selections = self.selections.all_adjusted(cx);
 8785        for selection in selections {
 8786            let range = selection.range().sorted();
 8787            let buffer_start_row = range.start.row;
 8788
 8789            for row in (0..=range.end.row).rev() {
 8790                let fold_range = display_map.foldable_range(row);
 8791
 8792                if let Some(fold_range) = fold_range {
 8793                    if fold_range.end.row >= buffer_start_row {
 8794                        fold_ranges.push(fold_range);
 8795                        if row <= range.start.row {
 8796                            break;
 8797                        }
 8798                    }
 8799                }
 8800            }
 8801        }
 8802
 8803        self.fold_ranges(fold_ranges, true, cx);
 8804    }
 8805
 8806    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 8807        let buffer_row = fold_at.buffer_row;
 8808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8809
 8810        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
 8811            let autoscroll = self
 8812                .selections
 8813                .all::<Point>(cx)
 8814                .iter()
 8815                .any(|selection| fold_range.overlaps(&selection.range()));
 8816
 8817            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
 8818        }
 8819    }
 8820
 8821    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 8822        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8823        let buffer = &display_map.buffer_snapshot;
 8824        let selections = self.selections.all::<Point>(cx);
 8825        let ranges = selections
 8826            .iter()
 8827            .map(|s| {
 8828                let range = s.display_range(&display_map).sorted();
 8829                let mut start = range.start.to_point(&display_map);
 8830                let mut end = range.end.to_point(&display_map);
 8831                start.column = 0;
 8832                end.column = buffer.line_len(end.row);
 8833                start..end
 8834            })
 8835            .collect::<Vec<_>>();
 8836
 8837        self.unfold_ranges(ranges, true, true, cx);
 8838    }
 8839
 8840    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 8841        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8842
 8843        let intersection_range = Point::new(unfold_at.buffer_row, 0)
 8844            ..Point::new(
 8845                unfold_at.buffer_row,
 8846                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 8847            );
 8848
 8849        let autoscroll = self
 8850            .selections
 8851            .all::<Point>(cx)
 8852            .iter()
 8853            .any(|selection| selection.range().overlaps(&intersection_range));
 8854
 8855        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 8856    }
 8857
 8858    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 8859        let selections = self.selections.all::<Point>(cx);
 8860        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8861        let line_mode = self.selections.line_mode;
 8862        let ranges = selections.into_iter().map(|s| {
 8863            if line_mode {
 8864                let start = Point::new(s.start.row, 0);
 8865                let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
 8866                start..end
 8867            } else {
 8868                s.start..s.end
 8869            }
 8870        });
 8871        self.fold_ranges(ranges, true, cx);
 8872    }
 8873
 8874    pub fn fold_ranges<T: ToOffset + Clone>(
 8875        &mut self,
 8876        ranges: impl IntoIterator<Item = Range<T>>,
 8877        auto_scroll: bool,
 8878        cx: &mut ViewContext<Self>,
 8879    ) {
 8880        let mut ranges = ranges.into_iter().peekable();
 8881        if ranges.peek().is_some() {
 8882            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 8883
 8884            if auto_scroll {
 8885                self.request_autoscroll(Autoscroll::fit(), cx);
 8886            }
 8887
 8888            cx.notify();
 8889        }
 8890    }
 8891
 8892    pub fn unfold_ranges<T: ToOffset + Clone>(
 8893        &mut self,
 8894        ranges: impl IntoIterator<Item = Range<T>>,
 8895        inclusive: bool,
 8896        auto_scroll: bool,
 8897        cx: &mut ViewContext<Self>,
 8898    ) {
 8899        let mut ranges = ranges.into_iter().peekable();
 8900        if ranges.peek().is_some() {
 8901            self.display_map
 8902                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 8903            if auto_scroll {
 8904                self.request_autoscroll(Autoscroll::fit(), cx);
 8905            }
 8906
 8907            cx.notify();
 8908        }
 8909    }
 8910
 8911    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 8912        if hovered != self.gutter_hovered {
 8913            self.gutter_hovered = hovered;
 8914            cx.notify();
 8915        }
 8916    }
 8917
 8918    pub fn insert_blocks(
 8919        &mut self,
 8920        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 8921        autoscroll: Option<Autoscroll>,
 8922        cx: &mut ViewContext<Self>,
 8923    ) -> Vec<BlockId> {
 8924        let blocks = self
 8925            .display_map
 8926            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 8927        if let Some(autoscroll) = autoscroll {
 8928            self.request_autoscroll(autoscroll, cx);
 8929        }
 8930        blocks
 8931    }
 8932
 8933    pub fn replace_blocks(
 8934        &mut self,
 8935        blocks: HashMap<BlockId, RenderBlock>,
 8936        autoscroll: Option<Autoscroll>,
 8937        cx: &mut ViewContext<Self>,
 8938    ) {
 8939        self.display_map
 8940            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
 8941        if let Some(autoscroll) = autoscroll {
 8942            self.request_autoscroll(autoscroll, cx);
 8943        }
 8944    }
 8945
 8946    pub fn remove_blocks(
 8947        &mut self,
 8948        block_ids: HashSet<BlockId>,
 8949        autoscroll: Option<Autoscroll>,
 8950        cx: &mut ViewContext<Self>,
 8951    ) {
 8952        self.display_map.update(cx, |display_map, cx| {
 8953            display_map.remove_blocks(block_ids, cx)
 8954        });
 8955        if let Some(autoscroll) = autoscroll {
 8956            self.request_autoscroll(autoscroll, cx);
 8957        }
 8958    }
 8959
 8960    pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
 8961        self.display_map
 8962            .update(cx, |map, cx| map.snapshot(cx))
 8963            .longest_row()
 8964    }
 8965
 8966    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 8967        self.display_map
 8968            .update(cx, |map, cx| map.snapshot(cx))
 8969            .max_point()
 8970    }
 8971
 8972    pub fn text(&self, cx: &AppContext) -> String {
 8973        self.buffer.read(cx).read(cx).text()
 8974    }
 8975
 8976    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 8977        let text = self.text(cx);
 8978        let text = text.trim();
 8979
 8980        if text.is_empty() {
 8981            return None;
 8982        }
 8983
 8984        Some(text.to_string())
 8985    }
 8986
 8987    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 8988        self.transact(cx, |this, cx| {
 8989            this.buffer
 8990                .read(cx)
 8991                .as_singleton()
 8992                .expect("you can only call set_text on editors for singleton buffers")
 8993                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 8994        });
 8995    }
 8996
 8997    pub fn display_text(&self, cx: &mut AppContext) -> String {
 8998        self.display_map
 8999            .update(cx, |map, cx| map.snapshot(cx))
 9000            .text()
 9001    }
 9002
 9003    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 9004        let mut wrap_guides = smallvec::smallvec![];
 9005
 9006        if self.show_wrap_guides == Some(false) {
 9007            return wrap_guides;
 9008        }
 9009
 9010        let settings = self.buffer.read(cx).settings_at(0, cx);
 9011        if settings.show_wrap_guides {
 9012            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 9013                wrap_guides.push((soft_wrap as usize, true));
 9014            }
 9015            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 9016        }
 9017
 9018        wrap_guides
 9019    }
 9020
 9021    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 9022        let settings = self.buffer.read(cx).settings_at(0, cx);
 9023        let mode = self
 9024            .soft_wrap_mode_override
 9025            .unwrap_or_else(|| settings.soft_wrap);
 9026        match mode {
 9027            language_settings::SoftWrap::None => SoftWrap::None,
 9028            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 9029            language_settings::SoftWrap::PreferredLineLength => {
 9030                SoftWrap::Column(settings.preferred_line_length)
 9031            }
 9032        }
 9033    }
 9034
 9035    pub fn set_soft_wrap_mode(
 9036        &mut self,
 9037        mode: language_settings::SoftWrap,
 9038        cx: &mut ViewContext<Self>,
 9039    ) {
 9040        self.soft_wrap_mode_override = Some(mode);
 9041        cx.notify();
 9042    }
 9043
 9044    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 9045        let rem_size = cx.rem_size();
 9046        self.display_map.update(cx, |map, cx| {
 9047            map.set_font(
 9048                style.text.font(),
 9049                style.text.font_size.to_pixels(rem_size),
 9050                cx,
 9051            )
 9052        });
 9053        self.style = Some(style);
 9054    }
 9055
 9056    #[cfg(any(test, feature = "test-support"))]
 9057    pub fn style(&self) -> Option<&EditorStyle> {
 9058        self.style.as_ref()
 9059    }
 9060
 9061    // Called by the element. This method is not designed to be called outside of the editor
 9062    // element's layout code because it does not notify when rewrapping is computed synchronously.
 9063    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 9064        self.display_map
 9065            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 9066    }
 9067
 9068    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 9069        if self.soft_wrap_mode_override.is_some() {
 9070            self.soft_wrap_mode_override.take();
 9071        } else {
 9072            let soft_wrap = match self.soft_wrap_mode(cx) {
 9073                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
 9074                SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
 9075            };
 9076            self.soft_wrap_mode_override = Some(soft_wrap);
 9077        }
 9078        cx.notify();
 9079    }
 9080
 9081    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
 9082        let mut editor_settings = EditorSettings::get_global(cx).clone();
 9083        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
 9084        EditorSettings::override_global(editor_settings, cx);
 9085    }
 9086
 9087    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9088        self.show_gutter = show_gutter;
 9089        cx.notify();
 9090    }
 9091
 9092    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9093        self.show_wrap_guides = Some(show_gutter);
 9094        cx.notify();
 9095    }
 9096
 9097    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 9098        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9099            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9100                cx.reveal_path(&file.abs_path(cx));
 9101            }
 9102        }
 9103    }
 9104
 9105    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 9106        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9107            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9108                if let Some(path) = file.abs_path(cx).to_str() {
 9109                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9110                }
 9111            }
 9112        }
 9113    }
 9114
 9115    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 9116        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9117            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9118                if let Some(path) = file.path().to_str() {
 9119                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9120                }
 9121            }
 9122        }
 9123    }
 9124
 9125    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
 9126        if !self.show_git_blame {
 9127            if let Err(error) = self.show_git_blame_internal(cx) {
 9128                log::error!("failed to toggle on 'git blame': {}", error);
 9129                return;
 9130            }
 9131            self.show_git_blame = true
 9132        } else {
 9133            self.blame_subscription.take();
 9134            self.blame.take();
 9135            self.show_git_blame = false
 9136        }
 9137
 9138        cx.notify();
 9139    }
 9140
 9141    fn show_git_blame_internal(&mut self, cx: &mut ViewContext<Self>) -> Result<()> {
 9142        if let Some(project) = self.project.as_ref() {
 9143            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
 9144                anyhow::bail!("git blame not available in multi buffers")
 9145            };
 9146
 9147            let project = project.clone();
 9148            let blame = cx.new_model(|cx| GitBlame::new(buffer, project, cx));
 9149            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
 9150            self.blame = Some(blame);
 9151        }
 9152
 9153        Ok(())
 9154    }
 9155
 9156    pub fn blame(&self) -> Option<&Model<GitBlame>> {
 9157        self.blame.as_ref()
 9158    }
 9159
 9160    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
 9161        let (path, repo) = maybe!({
 9162            let project_handle = self.project.as_ref()?.clone();
 9163            let project = project_handle.read(cx);
 9164            let buffer = self.buffer().read(cx).as_singleton()?;
 9165            let path = buffer
 9166                .read(cx)
 9167                .file()?
 9168                .as_local()?
 9169                .path()
 9170                .to_str()?
 9171                .to_string();
 9172            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
 9173            Some((path, repo))
 9174        })
 9175        .ok_or_else(|| anyhow!("unable to open git repository"))?;
 9176
 9177        const REMOTE_NAME: &str = "origin";
 9178        let origin_url = repo
 9179            .lock()
 9180            .remote_url(REMOTE_NAME)
 9181            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
 9182        let sha = repo
 9183            .lock()
 9184            .head_sha()
 9185            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
 9186        let selections = self.selections.all::<Point>(cx);
 9187        let selection = selections.iter().peekable().next();
 9188
 9189        build_permalink(BuildPermalinkParams {
 9190            remote_url: &origin_url,
 9191            sha: &sha,
 9192            path: &path,
 9193            selection: selection.map(|selection| {
 9194                let range = selection.range();
 9195                let start = range.start.row;
 9196                let end = range.end.row;
 9197                start..end
 9198            }),
 9199        })
 9200    }
 9201
 9202    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
 9203        let permalink = self.get_permalink_to_line(cx);
 9204
 9205        match permalink {
 9206            Ok(permalink) => {
 9207                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
 9208            }
 9209            Err(err) => {
 9210                let message = format!("Failed to copy permalink: {err}");
 9211
 9212                Err::<(), anyhow::Error>(err).log_err();
 9213
 9214                if let Some(workspace) = self.workspace() {
 9215                    workspace.update(cx, |workspace, cx| {
 9216                        workspace.show_toast(Toast::new(0x156a5f9ee, message), cx)
 9217                    })
 9218                }
 9219            }
 9220        }
 9221    }
 9222
 9223    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
 9224        let permalink = self.get_permalink_to_line(cx);
 9225
 9226        match permalink {
 9227            Ok(permalink) => {
 9228                cx.open_url(permalink.as_ref());
 9229            }
 9230            Err(err) => {
 9231                let message = format!("Failed to open permalink: {err}");
 9232
 9233                Err::<(), anyhow::Error>(err).log_err();
 9234
 9235                if let Some(workspace) = self.workspace() {
 9236                    workspace.update(cx, |workspace, cx| {
 9237                        workspace.show_toast(Toast::new(0x45a8978, message), cx)
 9238                    })
 9239                }
 9240            }
 9241        }
 9242    }
 9243
 9244    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
 9245    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
 9246    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
 9247    pub fn highlight_rows<T: 'static>(
 9248        &mut self,
 9249        rows: Range<Anchor>,
 9250        color: Option<Hsla>,
 9251        cx: &mut ViewContext<Self>,
 9252    ) {
 9253        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 9254        match self.highlighted_rows.entry(TypeId::of::<T>()) {
 9255            hash_map::Entry::Occupied(o) => {
 9256                let row_highlights = o.into_mut();
 9257                let existing_highlight_index =
 9258                    row_highlights.binary_search_by(|(_, highlight_range, _)| {
 9259                        highlight_range
 9260                            .start
 9261                            .cmp(&rows.start, &multi_buffer_snapshot)
 9262                            .then(highlight_range.end.cmp(&rows.end, &multi_buffer_snapshot))
 9263                    });
 9264                match color {
 9265                    Some(color) => {
 9266                        let insert_index = match existing_highlight_index {
 9267                            Ok(i) => i,
 9268                            Err(i) => i,
 9269                        };
 9270                        row_highlights.insert(
 9271                            insert_index,
 9272                            (post_inc(&mut self.highlight_order), rows, color),
 9273                        );
 9274                    }
 9275                    None => {
 9276                        if let Ok(i) = existing_highlight_index {
 9277                            row_highlights.remove(i);
 9278                        }
 9279                    }
 9280                }
 9281            }
 9282            hash_map::Entry::Vacant(v) => {
 9283                if let Some(color) = color {
 9284                    v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
 9285                }
 9286            }
 9287        }
 9288    }
 9289
 9290    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
 9291    pub fn clear_row_highlights<T: 'static>(&mut self) {
 9292        self.highlighted_rows.remove(&TypeId::of::<T>());
 9293    }
 9294
 9295    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
 9296    pub fn highlighted_rows<T: 'static>(
 9297        &self,
 9298    ) -> Option<impl Iterator<Item = (&Range<Anchor>, &Hsla)>> {
 9299        Some(
 9300            self.highlighted_rows
 9301                .get(&TypeId::of::<T>())?
 9302                .iter()
 9303                .map(|(_, range, color)| (range, color)),
 9304        )
 9305    }
 9306
 9307    // Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
 9308    // Rerturns a map of display rows that are highlighted and their corresponding highlight color.
 9309    pub fn highlighted_display_rows(&mut self, cx: &mut WindowContext) -> BTreeMap<u32, Hsla> {
 9310        let snapshot = self.snapshot(cx);
 9311        let mut used_highlight_orders = HashMap::default();
 9312        self.highlighted_rows
 9313            .iter()
 9314            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
 9315            .fold(
 9316                BTreeMap::<u32, Hsla>::new(),
 9317                |mut unique_rows, (highlight_order, anchor_range, hsla)| {
 9318                    let start_row = anchor_range.start.to_display_point(&snapshot).row();
 9319                    let end_row = anchor_range.end.to_display_point(&snapshot).row();
 9320                    for row in start_row..=end_row {
 9321                        let used_index =
 9322                            used_highlight_orders.entry(row).or_insert(*highlight_order);
 9323                        if highlight_order >= used_index {
 9324                            *used_index = *highlight_order;
 9325                            unique_rows.insert(row, *hsla);
 9326                        }
 9327                    }
 9328                    unique_rows
 9329                },
 9330            )
 9331    }
 9332
 9333    pub fn highlight_background<T: 'static>(
 9334        &mut self,
 9335        ranges: Vec<Range<Anchor>>,
 9336        color_fetcher: fn(&ThemeColors) -> Hsla,
 9337        cx: &mut ViewContext<Self>,
 9338    ) {
 9339        let snapshot = self.snapshot(cx);
 9340        // this is to try and catch a panic sooner
 9341        for range in &ranges {
 9342            snapshot
 9343                .buffer_snapshot
 9344                .summary_for_anchor::<usize>(&range.start);
 9345            snapshot
 9346                .buffer_snapshot
 9347                .summary_for_anchor::<usize>(&range.end);
 9348        }
 9349
 9350        self.background_highlights
 9351            .insert(TypeId::of::<T>(), (color_fetcher, ranges));
 9352        cx.notify();
 9353    }
 9354
 9355    pub fn clear_background_highlights<T: 'static>(
 9356        &mut self,
 9357        _cx: &mut ViewContext<Self>,
 9358    ) -> Option<BackgroundHighlight> {
 9359        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
 9360        text_highlights
 9361    }
 9362
 9363    #[cfg(feature = "test-support")]
 9364    pub fn all_text_background_highlights(
 9365        &mut self,
 9366        cx: &mut ViewContext<Self>,
 9367    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9368        let snapshot = self.snapshot(cx);
 9369        let buffer = &snapshot.buffer_snapshot;
 9370        let start = buffer.anchor_before(0);
 9371        let end = buffer.anchor_after(buffer.len());
 9372        let theme = cx.theme().colors();
 9373        self.background_highlights_in_range(start..end, &snapshot, theme)
 9374    }
 9375
 9376    fn document_highlights_for_position<'a>(
 9377        &'a self,
 9378        position: Anchor,
 9379        buffer: &'a MultiBufferSnapshot,
 9380    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
 9381        let read_highlights = self
 9382            .background_highlights
 9383            .get(&TypeId::of::<DocumentHighlightRead>())
 9384            .map(|h| &h.1);
 9385        let write_highlights = self
 9386            .background_highlights
 9387            .get(&TypeId::of::<DocumentHighlightWrite>())
 9388            .map(|h| &h.1);
 9389        let left_position = position.bias_left(buffer);
 9390        let right_position = position.bias_right(buffer);
 9391        read_highlights
 9392            .into_iter()
 9393            .chain(write_highlights)
 9394            .flat_map(move |ranges| {
 9395                let start_ix = match ranges.binary_search_by(|probe| {
 9396                    let cmp = probe.end.cmp(&left_position, buffer);
 9397                    if cmp.is_ge() {
 9398                        Ordering::Greater
 9399                    } else {
 9400                        Ordering::Less
 9401                    }
 9402                }) {
 9403                    Ok(i) | Err(i) => i,
 9404                };
 9405
 9406                ranges[start_ix..]
 9407                    .iter()
 9408                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
 9409            })
 9410    }
 9411
 9412    pub fn has_background_highlights<T: 'static>(&self) -> bool {
 9413        self.background_highlights
 9414            .get(&TypeId::of::<T>())
 9415            .map_or(false, |(_, highlights)| !highlights.is_empty())
 9416    }
 9417
 9418    pub fn background_highlights_in_range(
 9419        &self,
 9420        search_range: Range<Anchor>,
 9421        display_snapshot: &DisplaySnapshot,
 9422        theme: &ThemeColors,
 9423    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9424        let mut results = Vec::new();
 9425        for (color_fetcher, ranges) in self.background_highlights.values() {
 9426            let color = color_fetcher(theme);
 9427            let start_ix = match ranges.binary_search_by(|probe| {
 9428                let cmp = probe
 9429                    .end
 9430                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9431                if cmp.is_gt() {
 9432                    Ordering::Greater
 9433                } else {
 9434                    Ordering::Less
 9435                }
 9436            }) {
 9437                Ok(i) | Err(i) => i,
 9438            };
 9439            for range in &ranges[start_ix..] {
 9440                if range
 9441                    .start
 9442                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9443                    .is_ge()
 9444                {
 9445                    break;
 9446                }
 9447
 9448                let start = range.start.to_display_point(&display_snapshot);
 9449                let end = range.end.to_display_point(&display_snapshot);
 9450                results.push((start..end, color))
 9451            }
 9452        }
 9453        results
 9454    }
 9455
 9456    pub fn background_highlight_row_ranges<T: 'static>(
 9457        &self,
 9458        search_range: Range<Anchor>,
 9459        display_snapshot: &DisplaySnapshot,
 9460        count: usize,
 9461    ) -> Vec<RangeInclusive<DisplayPoint>> {
 9462        let mut results = Vec::new();
 9463        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
 9464            return vec![];
 9465        };
 9466
 9467        let start_ix = match ranges.binary_search_by(|probe| {
 9468            let cmp = probe
 9469                .end
 9470                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9471            if cmp.is_gt() {
 9472                Ordering::Greater
 9473            } else {
 9474                Ordering::Less
 9475            }
 9476        }) {
 9477            Ok(i) | Err(i) => i,
 9478        };
 9479        let mut push_region = |start: Option<Point>, end: Option<Point>| {
 9480            if let (Some(start_display), Some(end_display)) = (start, end) {
 9481                results.push(
 9482                    start_display.to_display_point(display_snapshot)
 9483                        ..=end_display.to_display_point(display_snapshot),
 9484                );
 9485            }
 9486        };
 9487        let mut start_row: Option<Point> = None;
 9488        let mut end_row: Option<Point> = None;
 9489        if ranges.len() > count {
 9490            return Vec::new();
 9491        }
 9492        for range in &ranges[start_ix..] {
 9493            if range
 9494                .start
 9495                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9496                .is_ge()
 9497            {
 9498                break;
 9499            }
 9500            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
 9501            if let Some(current_row) = &end_row {
 9502                if end.row == current_row.row {
 9503                    continue;
 9504                }
 9505            }
 9506            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
 9507            if start_row.is_none() {
 9508                assert_eq!(end_row, None);
 9509                start_row = Some(start);
 9510                end_row = Some(end);
 9511                continue;
 9512            }
 9513            if let Some(current_end) = end_row.as_mut() {
 9514                if start.row > current_end.row + 1 {
 9515                    push_region(start_row, end_row);
 9516                    start_row = Some(start);
 9517                    end_row = Some(end);
 9518                } else {
 9519                    // Merge two hunks.
 9520                    *current_end = end;
 9521                }
 9522            } else {
 9523                unreachable!();
 9524            }
 9525        }
 9526        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
 9527        push_region(start_row, end_row);
 9528        results
 9529    }
 9530
 9531    /// Get the text ranges corresponding to the redaction query
 9532    pub fn redacted_ranges(
 9533        &self,
 9534        search_range: Range<Anchor>,
 9535        display_snapshot: &DisplaySnapshot,
 9536        cx: &WindowContext,
 9537    ) -> Vec<Range<DisplayPoint>> {
 9538        display_snapshot
 9539            .buffer_snapshot
 9540            .redacted_ranges(search_range, |file| {
 9541                if let Some(file) = file {
 9542                    file.is_private()
 9543                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
 9544                } else {
 9545                    false
 9546                }
 9547            })
 9548            .map(|range| {
 9549                range.start.to_display_point(display_snapshot)
 9550                    ..range.end.to_display_point(display_snapshot)
 9551            })
 9552            .collect()
 9553    }
 9554
 9555    pub fn highlight_text<T: 'static>(
 9556        &mut self,
 9557        ranges: Vec<Range<Anchor>>,
 9558        style: HighlightStyle,
 9559        cx: &mut ViewContext<Self>,
 9560    ) {
 9561        self.display_map.update(cx, |map, _| {
 9562            map.highlight_text(TypeId::of::<T>(), ranges, style)
 9563        });
 9564        cx.notify();
 9565    }
 9566
 9567    pub(crate) fn highlight_inlays<T: 'static>(
 9568        &mut self,
 9569        highlights: Vec<InlayHighlight>,
 9570        style: HighlightStyle,
 9571        cx: &mut ViewContext<Self>,
 9572    ) {
 9573        self.display_map.update(cx, |map, _| {
 9574            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
 9575        });
 9576        cx.notify();
 9577    }
 9578
 9579    pub fn text_highlights<'a, T: 'static>(
 9580        &'a self,
 9581        cx: &'a AppContext,
 9582    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
 9583        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
 9584    }
 9585
 9586    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 9587        let cleared = self
 9588            .display_map
 9589            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
 9590        if cleared {
 9591            cx.notify();
 9592        }
 9593    }
 9594
 9595    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
 9596        (self.read_only(cx) || self.blink_manager.read(cx).visible())
 9597            && self.focus_handle.is_focused(cx)
 9598    }
 9599
 9600    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
 9601        cx.notify();
 9602    }
 9603
 9604    fn on_buffer_event(
 9605        &mut self,
 9606        multibuffer: Model<MultiBuffer>,
 9607        event: &multi_buffer::Event,
 9608        cx: &mut ViewContext<Self>,
 9609    ) {
 9610        match event {
 9611            multi_buffer::Event::Edited {
 9612                singleton_buffer_edited,
 9613            } => {
 9614                self.refresh_active_diagnostics(cx);
 9615                self.refresh_code_actions(cx);
 9616                if self.has_active_inline_completion(cx) {
 9617                    self.update_visible_inline_completion(cx);
 9618                }
 9619                cx.emit(EditorEvent::BufferEdited);
 9620                cx.emit(SearchEvent::MatchesInvalidated);
 9621
 9622                if *singleton_buffer_edited {
 9623                    if let Some(project) = &self.project {
 9624                        let project = project.read(cx);
 9625                        let languages_affected = multibuffer
 9626                            .read(cx)
 9627                            .all_buffers()
 9628                            .into_iter()
 9629                            .filter_map(|buffer| {
 9630                                let buffer = buffer.read(cx);
 9631                                let language = buffer.language()?;
 9632                                if project.is_local()
 9633                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
 9634                                {
 9635                                    None
 9636                                } else {
 9637                                    Some(language)
 9638                                }
 9639                            })
 9640                            .cloned()
 9641                            .collect::<HashSet<_>>();
 9642                        if !languages_affected.is_empty() {
 9643                            self.refresh_inlay_hints(
 9644                                InlayHintRefreshReason::BufferEdited(languages_affected),
 9645                                cx,
 9646                            );
 9647                        }
 9648                    }
 9649                }
 9650
 9651                let Some(project) = &self.project else {
 9652                    return;
 9653                };
 9654                let telemetry = project.read(cx).client().telemetry().clone();
 9655                telemetry.log_edit_event("editor");
 9656            }
 9657            multi_buffer::Event::ExcerptsAdded {
 9658                buffer,
 9659                predecessor,
 9660                excerpts,
 9661            } => {
 9662                cx.emit(EditorEvent::ExcerptsAdded {
 9663                    buffer: buffer.clone(),
 9664                    predecessor: *predecessor,
 9665                    excerpts: excerpts.clone(),
 9666                });
 9667                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
 9668            }
 9669            multi_buffer::Event::ExcerptsRemoved { ids } => {
 9670                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
 9671                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
 9672            }
 9673            multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
 9674            multi_buffer::Event::LanguageChanged => {
 9675                cx.emit(EditorEvent::Reparsed);
 9676                cx.notify();
 9677            }
 9678            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
 9679            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
 9680            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
 9681                cx.emit(EditorEvent::TitleChanged)
 9682            }
 9683            multi_buffer::Event::DiffBaseChanged => cx.emit(EditorEvent::DiffBaseChanged),
 9684            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
 9685            multi_buffer::Event::DiagnosticsUpdated => {
 9686                self.refresh_active_diagnostics(cx);
 9687            }
 9688            _ => {}
 9689        };
 9690    }
 9691
 9692    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
 9693        cx.notify();
 9694    }
 9695
 9696    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
 9697        self.refresh_inline_completion(true, cx);
 9698        self.refresh_inlay_hints(
 9699            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
 9700                self.selections.newest_anchor().head(),
 9701                &self.buffer.read(cx).snapshot(cx),
 9702                cx,
 9703            )),
 9704            cx,
 9705        );
 9706        let editor_settings = EditorSettings::get_global(cx);
 9707        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
 9708        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
 9709        cx.notify();
 9710    }
 9711
 9712    pub fn set_searchable(&mut self, searchable: bool) {
 9713        self.searchable = searchable;
 9714    }
 9715
 9716    pub fn searchable(&self) -> bool {
 9717        self.searchable
 9718    }
 9719
 9720    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
 9721        self.open_excerpts_common(true, cx)
 9722    }
 9723
 9724    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
 9725        self.open_excerpts_common(false, cx)
 9726    }
 9727
 9728    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
 9729        let buffer = self.buffer.read(cx);
 9730        if buffer.is_singleton() {
 9731            cx.propagate();
 9732            return;
 9733        }
 9734
 9735        let Some(workspace) = self.workspace() else {
 9736            cx.propagate();
 9737            return;
 9738        };
 9739
 9740        let mut new_selections_by_buffer = HashMap::default();
 9741        for selection in self.selections.all::<usize>(cx) {
 9742            for (buffer, mut range, _) in
 9743                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
 9744            {
 9745                if selection.reversed {
 9746                    mem::swap(&mut range.start, &mut range.end);
 9747                }
 9748                new_selections_by_buffer
 9749                    .entry(buffer)
 9750                    .or_insert(Vec::new())
 9751                    .push(range)
 9752            }
 9753        }
 9754
 9755        // We defer the pane interaction because we ourselves are a workspace item
 9756        // and activating a new item causes the pane to call a method on us reentrantly,
 9757        // which panics if we're on the stack.
 9758        cx.window_context().defer(move |cx| {
 9759            workspace.update(cx, |workspace, cx| {
 9760                let pane = if split {
 9761                    workspace.adjacent_pane(cx)
 9762                } else {
 9763                    workspace.active_pane().clone()
 9764                };
 9765
 9766                for (buffer, ranges) in new_selections_by_buffer {
 9767                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
 9768                    editor.update(cx, |editor, cx| {
 9769                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 9770                            s.select_ranges(ranges);
 9771                        });
 9772                    });
 9773                }
 9774            })
 9775        });
 9776    }
 9777
 9778    fn jump(
 9779        &mut self,
 9780        path: ProjectPath,
 9781        position: Point,
 9782        anchor: language::Anchor,
 9783        offset_from_top: u32,
 9784        cx: &mut ViewContext<Self>,
 9785    ) {
 9786        let workspace = self.workspace();
 9787        cx.spawn(|_, mut cx| async move {
 9788            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
 9789            let editor = workspace.update(&mut cx, |workspace, cx| {
 9790                workspace.open_path(path, None, true, cx)
 9791            })?;
 9792            let editor = editor
 9793                .await?
 9794                .downcast::<Editor>()
 9795                .ok_or_else(|| anyhow!("opened item was not an editor"))?
 9796                .downgrade();
 9797            editor.update(&mut cx, |editor, cx| {
 9798                let buffer = editor
 9799                    .buffer()
 9800                    .read(cx)
 9801                    .as_singleton()
 9802                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
 9803                let buffer = buffer.read(cx);
 9804                let cursor = if buffer.can_resolve(&anchor) {
 9805                    language::ToPoint::to_point(&anchor, buffer)
 9806                } else {
 9807                    buffer.clip_point(position, Bias::Left)
 9808                };
 9809
 9810                let nav_history = editor.nav_history.take();
 9811                editor.change_selections(
 9812                    Some(Autoscroll::top_relative(offset_from_top as usize)),
 9813                    cx,
 9814                    |s| {
 9815                        s.select_ranges([cursor..cursor]);
 9816                    },
 9817                );
 9818                editor.nav_history = nav_history;
 9819
 9820                anyhow::Ok(())
 9821            })??;
 9822
 9823            anyhow::Ok(())
 9824        })
 9825        .detach_and_log_err(cx);
 9826    }
 9827
 9828    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
 9829        let snapshot = self.buffer.read(cx).read(cx);
 9830        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
 9831        Some(
 9832            ranges
 9833                .iter()
 9834                .map(move |range| {
 9835                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
 9836                })
 9837                .collect(),
 9838        )
 9839    }
 9840
 9841    fn selection_replacement_ranges(
 9842        &self,
 9843        range: Range<OffsetUtf16>,
 9844        cx: &AppContext,
 9845    ) -> Vec<Range<OffsetUtf16>> {
 9846        let selections = self.selections.all::<OffsetUtf16>(cx);
 9847        let newest_selection = selections
 9848            .iter()
 9849            .max_by_key(|selection| selection.id)
 9850            .unwrap();
 9851        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
 9852        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
 9853        let snapshot = self.buffer.read(cx).read(cx);
 9854        selections
 9855            .into_iter()
 9856            .map(|mut selection| {
 9857                selection.start.0 =
 9858                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
 9859                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
 9860                snapshot.clip_offset_utf16(selection.start, Bias::Left)
 9861                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
 9862            })
 9863            .collect()
 9864    }
 9865
 9866    fn report_editor_event(
 9867        &self,
 9868        operation: &'static str,
 9869        file_extension: Option<String>,
 9870        cx: &AppContext,
 9871    ) {
 9872        if cfg!(any(test, feature = "test-support")) {
 9873            return;
 9874        }
 9875
 9876        let Some(project) = &self.project else { return };
 9877
 9878        // If None, we are in a file without an extension
 9879        let file = self
 9880            .buffer
 9881            .read(cx)
 9882            .as_singleton()
 9883            .and_then(|b| b.read(cx).file());
 9884        let file_extension = file_extension.or(file
 9885            .as_ref()
 9886            .and_then(|file| Path::new(file.file_name(cx)).extension())
 9887            .and_then(|e| e.to_str())
 9888            .map(|a| a.to_string()));
 9889
 9890        let vim_mode = cx
 9891            .global::<SettingsStore>()
 9892            .raw_user_settings()
 9893            .get("vim_mode")
 9894            == Some(&serde_json::Value::Bool(true));
 9895        let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
 9896        let copilot_enabled_for_language = self
 9897            .buffer
 9898            .read(cx)
 9899            .settings_at(0, cx)
 9900            .show_copilot_suggestions;
 9901
 9902        let telemetry = project.read(cx).client().telemetry().clone();
 9903        telemetry.report_editor_event(
 9904            file_extension,
 9905            vim_mode,
 9906            operation,
 9907            copilot_enabled,
 9908            copilot_enabled_for_language,
 9909        )
 9910    }
 9911
 9912    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
 9913    /// with each line being an array of {text, highlight} objects.
 9914    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
 9915        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
 9916            return;
 9917        };
 9918
 9919        #[derive(Serialize)]
 9920        struct Chunk<'a> {
 9921            text: String,
 9922            highlight: Option<&'a str>,
 9923        }
 9924
 9925        let snapshot = buffer.read(cx).snapshot();
 9926        let range = self
 9927            .selected_text_range(cx)
 9928            .and_then(|selected_range| {
 9929                if selected_range.is_empty() {
 9930                    None
 9931                } else {
 9932                    Some(selected_range)
 9933                }
 9934            })
 9935            .unwrap_or_else(|| 0..snapshot.len());
 9936
 9937        let chunks = snapshot.chunks(range, true);
 9938        let mut lines = Vec::new();
 9939        let mut line: VecDeque<Chunk> = VecDeque::new();
 9940
 9941        let Some(style) = self.style.as_ref() else {
 9942            return;
 9943        };
 9944
 9945        for chunk in chunks {
 9946            let highlight = chunk
 9947                .syntax_highlight_id
 9948                .and_then(|id| id.name(&style.syntax));
 9949            let mut chunk_lines = chunk.text.split('\n').peekable();
 9950            while let Some(text) = chunk_lines.next() {
 9951                let mut merged_with_last_token = false;
 9952                if let Some(last_token) = line.back_mut() {
 9953                    if last_token.highlight == highlight {
 9954                        last_token.text.push_str(text);
 9955                        merged_with_last_token = true;
 9956                    }
 9957                }
 9958
 9959                if !merged_with_last_token {
 9960                    line.push_back(Chunk {
 9961                        text: text.into(),
 9962                        highlight,
 9963                    });
 9964                }
 9965
 9966                if chunk_lines.peek().is_some() {
 9967                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
 9968                        line.pop_front();
 9969                    }
 9970                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
 9971                        line.pop_back();
 9972                    }
 9973
 9974                    lines.push(mem::take(&mut line));
 9975                }
 9976            }
 9977        }
 9978
 9979        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
 9980            return;
 9981        };
 9982        cx.write_to_clipboard(ClipboardItem::new(lines));
 9983    }
 9984
 9985    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
 9986        &self.inlay_hint_cache
 9987    }
 9988
 9989    pub fn replay_insert_event(
 9990        &mut self,
 9991        text: &str,
 9992        relative_utf16_range: Option<Range<isize>>,
 9993        cx: &mut ViewContext<Self>,
 9994    ) {
 9995        if !self.input_enabled {
 9996            cx.emit(EditorEvent::InputIgnored { text: text.into() });
 9997            return;
 9998        }
 9999        if let Some(relative_utf16_range) = relative_utf16_range {
10000            let selections = self.selections.all::<OffsetUtf16>(cx);
10001            self.change_selections(None, cx, |s| {
10002                let new_ranges = selections.into_iter().map(|range| {
10003                    let start = OffsetUtf16(
10004                        range
10005                            .head()
10006                            .0
10007                            .saturating_add_signed(relative_utf16_range.start),
10008                    );
10009                    let end = OffsetUtf16(
10010                        range
10011                            .head()
10012                            .0
10013                            .saturating_add_signed(relative_utf16_range.end),
10014                    );
10015                    start..end
10016                });
10017                s.select_ranges(new_ranges);
10018            });
10019        }
10020
10021        self.handle_input(text, cx);
10022    }
10023
10024    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10025        let Some(project) = self.project.as_ref() else {
10026            return false;
10027        };
10028        let project = project.read(cx);
10029
10030        let mut supports = false;
10031        self.buffer().read(cx).for_each_buffer(|buffer| {
10032            if !supports {
10033                supports = project
10034                    .language_servers_for_buffer(buffer.read(cx), cx)
10035                    .any(
10036                        |(_, server)| match server.capabilities().inlay_hint_provider {
10037                            Some(lsp::OneOf::Left(enabled)) => enabled,
10038                            Some(lsp::OneOf::Right(_)) => true,
10039                            None => false,
10040                        },
10041                    )
10042            }
10043        });
10044        supports
10045    }
10046
10047    pub fn focus(&self, cx: &mut WindowContext) {
10048        cx.focus(&self.focus_handle)
10049    }
10050
10051    pub fn is_focused(&self, cx: &WindowContext) -> bool {
10052        self.focus_handle.is_focused(cx)
10053    }
10054
10055    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
10056        cx.emit(EditorEvent::Focused);
10057
10058        if let Some(rename) = self.pending_rename.as_ref() {
10059            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
10060            cx.focus(&rename_editor_focus_handle);
10061        } else {
10062            self.blink_manager.update(cx, BlinkManager::enable);
10063            self.show_cursor_names(cx);
10064            self.buffer.update(cx, |buffer, cx| {
10065                buffer.finalize_last_transaction(cx);
10066                if self.leader_peer_id.is_none() {
10067                    buffer.set_active_selections(
10068                        &self.selections.disjoint_anchors(),
10069                        self.selections.line_mode,
10070                        self.cursor_shape,
10071                        cx,
10072                    );
10073                }
10074            });
10075        }
10076    }
10077
10078    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
10079        self.blink_manager.update(cx, BlinkManager::disable);
10080        self.buffer
10081            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
10082        self.hide_context_menu(cx);
10083        hide_hover(self, cx);
10084        cx.emit(EditorEvent::Blurred);
10085        cx.notify();
10086    }
10087
10088    pub fn register_action<A: Action>(
10089        &mut self,
10090        listener: impl Fn(&A, &mut WindowContext) + 'static,
10091    ) -> &mut Self {
10092        let listener = Arc::new(listener);
10093
10094        self.editor_actions.push(Box::new(move |cx| {
10095            let _view = cx.view().clone();
10096            let cx = cx.window_context();
10097            let listener = listener.clone();
10098            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
10099                let action = action.downcast_ref().unwrap();
10100                if phase == DispatchPhase::Bubble {
10101                    listener(action, cx)
10102                }
10103            })
10104        }));
10105        self
10106    }
10107}
10108
10109pub trait CollaborationHub {
10110    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
10111    fn user_participant_indices<'a>(
10112        &self,
10113        cx: &'a AppContext,
10114    ) -> &'a HashMap<u64, ParticipantIndex>;
10115    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
10116}
10117
10118impl CollaborationHub for Model<Project> {
10119    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
10120        self.read(cx).collaborators()
10121    }
10122
10123    fn user_participant_indices<'a>(
10124        &self,
10125        cx: &'a AppContext,
10126    ) -> &'a HashMap<u64, ParticipantIndex> {
10127        self.read(cx).user_store().read(cx).participant_indices()
10128    }
10129
10130    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
10131        let this = self.read(cx);
10132        let user_ids = this.collaborators().values().map(|c| c.user_id);
10133        this.user_store().read_with(cx, |user_store, cx| {
10134            user_store.participant_names(user_ids, cx)
10135        })
10136    }
10137}
10138
10139pub trait CompletionProvider {
10140    fn completions(
10141        &self,
10142        buffer: &Model<Buffer>,
10143        buffer_position: text::Anchor,
10144        cx: &mut ViewContext<Editor>,
10145    ) -> Task<Result<Vec<Completion>>>;
10146
10147    fn resolve_completions(
10148        &self,
10149        completion_indices: Vec<usize>,
10150        completions: Arc<RwLock<Box<[Completion]>>>,
10151        cx: &mut ViewContext<Editor>,
10152    ) -> Task<Result<bool>>;
10153
10154    fn apply_additional_edits_for_completion(
10155        &self,
10156        buffer: Model<Buffer>,
10157        completion: Completion,
10158        push_to_history: bool,
10159        cx: &mut ViewContext<Editor>,
10160    ) -> Task<Result<Option<language::Transaction>>>;
10161}
10162
10163impl CompletionProvider for Model<Project> {
10164    fn completions(
10165        &self,
10166        buffer: &Model<Buffer>,
10167        buffer_position: text::Anchor,
10168        cx: &mut ViewContext<Editor>,
10169    ) -> Task<Result<Vec<Completion>>> {
10170        self.update(cx, |project, cx| {
10171            project.completions(&buffer, buffer_position, cx)
10172        })
10173    }
10174
10175    fn resolve_completions(
10176        &self,
10177        completion_indices: Vec<usize>,
10178        completions: Arc<RwLock<Box<[Completion]>>>,
10179        cx: &mut ViewContext<Editor>,
10180    ) -> Task<Result<bool>> {
10181        self.update(cx, |project, cx| {
10182            project.resolve_completions(completion_indices, completions, cx)
10183        })
10184    }
10185
10186    fn apply_additional_edits_for_completion(
10187        &self,
10188        buffer: Model<Buffer>,
10189        completion: Completion,
10190        push_to_history: bool,
10191        cx: &mut ViewContext<Editor>,
10192    ) -> Task<Result<Option<language::Transaction>>> {
10193        self.update(cx, |project, cx| {
10194            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
10195        })
10196    }
10197}
10198
10199fn inlay_hint_settings(
10200    location: Anchor,
10201    snapshot: &MultiBufferSnapshot,
10202    cx: &mut ViewContext<'_, Editor>,
10203) -> InlayHintSettings {
10204    let file = snapshot.file_at(location);
10205    let language = snapshot.language_at(location);
10206    let settings = all_language_settings(file, cx);
10207    settings
10208        .language(language.map(|l| l.name()).as_deref())
10209        .inlay_hints
10210}
10211
10212fn consume_contiguous_rows(
10213    contiguous_row_selections: &mut Vec<Selection<Point>>,
10214    selection: &Selection<Point>,
10215    display_map: &DisplaySnapshot,
10216    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
10217) -> (u32, u32) {
10218    contiguous_row_selections.push(selection.clone());
10219    let start_row = selection.start.row;
10220    let mut end_row = ending_row(selection, display_map);
10221
10222    while let Some(next_selection) = selections.peek() {
10223        if next_selection.start.row <= end_row {
10224            end_row = ending_row(next_selection, display_map);
10225            contiguous_row_selections.push(selections.next().unwrap().clone());
10226        } else {
10227            break;
10228        }
10229    }
10230    (start_row, end_row)
10231}
10232
10233fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
10234    if next_selection.end.column > 0 || next_selection.is_empty() {
10235        display_map.next_line_boundary(next_selection.end).0.row + 1
10236    } else {
10237        next_selection.end.row
10238    }
10239}
10240
10241impl EditorSnapshot {
10242    pub fn remote_selections_in_range<'a>(
10243        &'a self,
10244        range: &'a Range<Anchor>,
10245        collaboration_hub: &dyn CollaborationHub,
10246        cx: &'a AppContext,
10247    ) -> impl 'a + Iterator<Item = RemoteSelection> {
10248        let participant_names = collaboration_hub.user_names(cx);
10249        let participant_indices = collaboration_hub.user_participant_indices(cx);
10250        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
10251        let collaborators_by_replica_id = collaborators_by_peer_id
10252            .iter()
10253            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
10254            .collect::<HashMap<_, _>>();
10255        self.buffer_snapshot
10256            .remote_selections_in_range(range)
10257            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10258                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10259                let participant_index = participant_indices.get(&collaborator.user_id).copied();
10260                let user_name = participant_names.get(&collaborator.user_id).cloned();
10261                Some(RemoteSelection {
10262                    replica_id,
10263                    selection,
10264                    cursor_shape,
10265                    line_mode,
10266                    participant_index,
10267                    peer_id: collaborator.peer_id,
10268                    user_name,
10269                })
10270            })
10271    }
10272
10273    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10274        self.display_snapshot.buffer_snapshot.language_at(position)
10275    }
10276
10277    pub fn is_focused(&self) -> bool {
10278        self.is_focused
10279    }
10280
10281    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10282        self.placeholder_text.as_ref()
10283    }
10284
10285    pub fn scroll_position(&self) -> gpui::Point<f32> {
10286        self.scroll_anchor.scroll_position(&self.display_snapshot)
10287    }
10288
10289    pub fn gutter_dimensions(
10290        &self,
10291        font_id: FontId,
10292        font_size: Pixels,
10293        em_width: Pixels,
10294        max_line_number_width: Pixels,
10295        cx: &AppContext,
10296    ) -> GutterDimensions {
10297        if !self.show_gutter {
10298            return GutterDimensions::default();
10299        }
10300        let descent = cx.text_system().descent(font_id, font_size);
10301
10302        let show_git_gutter = matches!(
10303            ProjectSettings::get_global(cx).git.git_gutter,
10304            Some(GitGutterSetting::TrackedFiles)
10305        );
10306        let gutter_settings = EditorSettings::get_global(cx).gutter;
10307
10308        let line_gutter_width = if gutter_settings.line_numbers {
10309            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10310            let min_width_for_number_on_gutter = em_width * 4.0;
10311            max_line_number_width.max(min_width_for_number_on_gutter)
10312        } else {
10313            0.0.into()
10314        };
10315
10316        let git_blame_entries_width = self
10317            .show_git_blame
10318            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
10319
10320        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
10321        left_padding += if gutter_settings.code_actions {
10322            em_width * 3.0
10323        } else if show_git_gutter && gutter_settings.line_numbers {
10324            em_width * 2.0
10325        } else if show_git_gutter || gutter_settings.line_numbers {
10326            em_width
10327        } else {
10328            px(0.)
10329        };
10330
10331        let right_padding = if gutter_settings.folds && gutter_settings.line_numbers {
10332            em_width * 4.0
10333        } else if gutter_settings.folds {
10334            em_width * 3.0
10335        } else if gutter_settings.line_numbers {
10336            em_width
10337        } else {
10338            px(0.)
10339        };
10340
10341        GutterDimensions {
10342            left_padding,
10343            right_padding,
10344            width: line_gutter_width + left_padding + right_padding,
10345            margin: -descent,
10346            git_blame_entries_width,
10347        }
10348    }
10349}
10350
10351impl Deref for EditorSnapshot {
10352    type Target = DisplaySnapshot;
10353
10354    fn deref(&self) -> &Self::Target {
10355        &self.display_snapshot
10356    }
10357}
10358
10359#[derive(Clone, Debug, PartialEq, Eq)]
10360pub enum EditorEvent {
10361    InputIgnored {
10362        text: Arc<str>,
10363    },
10364    InputHandled {
10365        utf16_range_to_replace: Option<Range<isize>>,
10366        text: Arc<str>,
10367    },
10368    ExcerptsAdded {
10369        buffer: Model<Buffer>,
10370        predecessor: ExcerptId,
10371        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
10372    },
10373    ExcerptsRemoved {
10374        ids: Vec<ExcerptId>,
10375    },
10376    BufferEdited,
10377    Edited,
10378    Reparsed,
10379    Focused,
10380    Blurred,
10381    DirtyChanged,
10382    Saved,
10383    TitleChanged,
10384    DiffBaseChanged,
10385    SelectionsChanged {
10386        local: bool,
10387    },
10388    ScrollPositionChanged {
10389        local: bool,
10390        autoscroll: bool,
10391    },
10392    Closed,
10393    TransactionUndone {
10394        transaction_id: clock::Lamport,
10395    },
10396    TransactionBegun {
10397        transaction_id: clock::Lamport,
10398    },
10399}
10400
10401impl EventEmitter<EditorEvent> for Editor {}
10402
10403impl FocusableView for Editor {
10404    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
10405        self.focus_handle.clone()
10406    }
10407}
10408
10409impl Render for Editor {
10410    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
10411        let settings = ThemeSettings::get_global(cx);
10412        let text_style = match self.mode {
10413            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
10414                color: cx.theme().colors().editor_foreground,
10415                font_family: settings.ui_font.family.clone(),
10416                font_features: settings.ui_font.features,
10417                font_size: rems(0.875).into(),
10418                font_weight: FontWeight::NORMAL,
10419                font_style: FontStyle::Normal,
10420                line_height: relative(settings.buffer_line_height.value()),
10421                background_color: None,
10422                underline: None,
10423                strikethrough: None,
10424                white_space: WhiteSpace::Normal,
10425            },
10426
10427            EditorMode::Full => TextStyle {
10428                color: cx.theme().colors().editor_foreground,
10429                font_family: settings.buffer_font.family.clone(),
10430                font_features: settings.buffer_font.features,
10431                font_size: settings.buffer_font_size(cx).into(),
10432                font_weight: FontWeight::NORMAL,
10433                font_style: FontStyle::Normal,
10434                line_height: relative(settings.buffer_line_height.value()),
10435                background_color: None,
10436                underline: None,
10437                strikethrough: None,
10438                white_space: WhiteSpace::Normal,
10439            },
10440        };
10441
10442        let background = match self.mode {
10443            EditorMode::SingleLine => cx.theme().system().transparent,
10444            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
10445            EditorMode::Full => cx.theme().colors().editor_background,
10446        };
10447
10448        EditorElement::new(
10449            cx.view(),
10450            EditorStyle {
10451                background,
10452                local_player: cx.theme().players().local(),
10453                text: text_style,
10454                scrollbar_width: px(12.),
10455                syntax: cx.theme().syntax().clone(),
10456                status: cx.theme().status().clone(),
10457                inlay_hints_style: HighlightStyle {
10458                    color: Some(cx.theme().status().hint),
10459                    ..HighlightStyle::default()
10460                },
10461                suggestions_style: HighlightStyle {
10462                    color: Some(cx.theme().status().predictive),
10463                    ..HighlightStyle::default()
10464                },
10465            },
10466        )
10467    }
10468}
10469
10470impl ViewInputHandler for Editor {
10471    fn text_for_range(
10472        &mut self,
10473        range_utf16: Range<usize>,
10474        cx: &mut ViewContext<Self>,
10475    ) -> Option<String> {
10476        Some(
10477            self.buffer
10478                .read(cx)
10479                .read(cx)
10480                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
10481                .collect(),
10482        )
10483    }
10484
10485    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10486        // Prevent the IME menu from appearing when holding down an alphabetic key
10487        // while input is disabled.
10488        if !self.input_enabled {
10489            return None;
10490        }
10491
10492        let range = self.selections.newest::<OffsetUtf16>(cx).range();
10493        Some(range.start.0..range.end.0)
10494    }
10495
10496    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10497        let snapshot = self.buffer.read(cx).read(cx);
10498        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
10499        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
10500    }
10501
10502    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
10503        self.clear_highlights::<InputComposition>(cx);
10504        self.ime_transaction.take();
10505    }
10506
10507    fn replace_text_in_range(
10508        &mut self,
10509        range_utf16: Option<Range<usize>>,
10510        text: &str,
10511        cx: &mut ViewContext<Self>,
10512    ) {
10513        if !self.input_enabled {
10514            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10515            return;
10516        }
10517
10518        self.transact(cx, |this, cx| {
10519            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
10520                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10521                Some(this.selection_replacement_ranges(range_utf16, cx))
10522            } else {
10523                this.marked_text_ranges(cx)
10524            };
10525
10526            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
10527                let newest_selection_id = this.selections.newest_anchor().id;
10528                this.selections
10529                    .all::<OffsetUtf16>(cx)
10530                    .iter()
10531                    .zip(ranges_to_replace.iter())
10532                    .find_map(|(selection, range)| {
10533                        if selection.id == newest_selection_id {
10534                            Some(
10535                                (range.start.0 as isize - selection.head().0 as isize)
10536                                    ..(range.end.0 as isize - selection.head().0 as isize),
10537                            )
10538                        } else {
10539                            None
10540                        }
10541                    })
10542            });
10543
10544            cx.emit(EditorEvent::InputHandled {
10545                utf16_range_to_replace: range_to_replace,
10546                text: text.into(),
10547            });
10548
10549            if let Some(new_selected_ranges) = new_selected_ranges {
10550                this.change_selections(None, cx, |selections| {
10551                    selections.select_ranges(new_selected_ranges)
10552                });
10553                this.backspace(&Default::default(), cx);
10554            }
10555
10556            this.handle_input(text, cx);
10557        });
10558
10559        if let Some(transaction) = self.ime_transaction {
10560            self.buffer.update(cx, |buffer, cx| {
10561                buffer.group_until_transaction(transaction, cx);
10562            });
10563        }
10564
10565        self.unmark_text(cx);
10566    }
10567
10568    fn replace_and_mark_text_in_range(
10569        &mut self,
10570        range_utf16: Option<Range<usize>>,
10571        text: &str,
10572        new_selected_range_utf16: Option<Range<usize>>,
10573        cx: &mut ViewContext<Self>,
10574    ) {
10575        if !self.input_enabled {
10576            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10577            return;
10578        }
10579
10580        let transaction = self.transact(cx, |this, cx| {
10581            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
10582                let snapshot = this.buffer.read(cx).read(cx);
10583                if let Some(relative_range_utf16) = range_utf16.as_ref() {
10584                    for marked_range in &mut marked_ranges {
10585                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
10586                        marked_range.start.0 += relative_range_utf16.start;
10587                        marked_range.start =
10588                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
10589                        marked_range.end =
10590                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
10591                    }
10592                }
10593                Some(marked_ranges)
10594            } else if let Some(range_utf16) = range_utf16 {
10595                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10596                Some(this.selection_replacement_ranges(range_utf16, cx))
10597            } else {
10598                None
10599            };
10600
10601            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
10602                let newest_selection_id = this.selections.newest_anchor().id;
10603                this.selections
10604                    .all::<OffsetUtf16>(cx)
10605                    .iter()
10606                    .zip(ranges_to_replace.iter())
10607                    .find_map(|(selection, range)| {
10608                        if selection.id == newest_selection_id {
10609                            Some(
10610                                (range.start.0 as isize - selection.head().0 as isize)
10611                                    ..(range.end.0 as isize - selection.head().0 as isize),
10612                            )
10613                        } else {
10614                            None
10615                        }
10616                    })
10617            });
10618
10619            cx.emit(EditorEvent::InputHandled {
10620                utf16_range_to_replace: range_to_replace,
10621                text: text.into(),
10622            });
10623
10624            if let Some(ranges) = ranges_to_replace {
10625                this.change_selections(None, cx, |s| s.select_ranges(ranges));
10626            }
10627
10628            let marked_ranges = {
10629                let snapshot = this.buffer.read(cx).read(cx);
10630                this.selections
10631                    .disjoint_anchors()
10632                    .iter()
10633                    .map(|selection| {
10634                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
10635                    })
10636                    .collect::<Vec<_>>()
10637            };
10638
10639            if text.is_empty() {
10640                this.unmark_text(cx);
10641            } else {
10642                this.highlight_text::<InputComposition>(
10643                    marked_ranges.clone(),
10644                    HighlightStyle {
10645                        underline: Some(UnderlineStyle {
10646                            thickness: px(1.),
10647                            color: None,
10648                            wavy: false,
10649                        }),
10650                        ..Default::default()
10651                    },
10652                    cx,
10653                );
10654            }
10655
10656            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
10657            let use_autoclose = this.use_autoclose;
10658            this.set_use_autoclose(false);
10659            this.handle_input(text, cx);
10660            this.set_use_autoclose(use_autoclose);
10661
10662            if let Some(new_selected_range) = new_selected_range_utf16 {
10663                let snapshot = this.buffer.read(cx).read(cx);
10664                let new_selected_ranges = marked_ranges
10665                    .into_iter()
10666                    .map(|marked_range| {
10667                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
10668                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
10669                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
10670                        snapshot.clip_offset_utf16(new_start, Bias::Left)
10671                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
10672                    })
10673                    .collect::<Vec<_>>();
10674
10675                drop(snapshot);
10676                this.change_selections(None, cx, |selections| {
10677                    selections.select_ranges(new_selected_ranges)
10678                });
10679            }
10680        });
10681
10682        self.ime_transaction = self.ime_transaction.or(transaction);
10683        if let Some(transaction) = self.ime_transaction {
10684            self.buffer.update(cx, |buffer, cx| {
10685                buffer.group_until_transaction(transaction, cx);
10686            });
10687        }
10688
10689        if self.text_highlights::<InputComposition>(cx).is_none() {
10690            self.ime_transaction.take();
10691        }
10692    }
10693
10694    fn bounds_for_range(
10695        &mut self,
10696        range_utf16: Range<usize>,
10697        element_bounds: gpui::Bounds<Pixels>,
10698        cx: &mut ViewContext<Self>,
10699    ) -> Option<gpui::Bounds<Pixels>> {
10700        let text_layout_details = self.text_layout_details(cx);
10701        let style = &text_layout_details.editor_style;
10702        let font_id = cx.text_system().resolve_font(&style.text.font());
10703        let font_size = style.text.font_size.to_pixels(cx.rem_size());
10704        let line_height = style.text.line_height_in_pixels(cx.rem_size());
10705        let em_width = cx
10706            .text_system()
10707            .typographic_bounds(font_id, font_size, 'm')
10708            .unwrap()
10709            .size
10710            .width;
10711
10712        let snapshot = self.snapshot(cx);
10713        let scroll_position = snapshot.scroll_position();
10714        let scroll_left = scroll_position.x * em_width;
10715
10716        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
10717        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
10718            + self.gutter_width;
10719        let y = line_height * (start.row() as f32 - scroll_position.y);
10720
10721        Some(Bounds {
10722            origin: element_bounds.origin + point(x, y),
10723            size: size(em_width, line_height),
10724        })
10725    }
10726}
10727
10728trait SelectionExt {
10729    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
10730    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
10731    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
10732    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
10733        -> Range<u32>;
10734}
10735
10736impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
10737    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
10738        let start = self.start.to_point(buffer);
10739        let end = self.end.to_point(buffer);
10740        if self.reversed {
10741            end..start
10742        } else {
10743            start..end
10744        }
10745    }
10746
10747    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
10748        let start = self.start.to_offset(buffer);
10749        let end = self.end.to_offset(buffer);
10750        if self.reversed {
10751            end..start
10752        } else {
10753            start..end
10754        }
10755    }
10756
10757    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
10758        let start = self
10759            .start
10760            .to_point(&map.buffer_snapshot)
10761            .to_display_point(map);
10762        let end = self
10763            .end
10764            .to_point(&map.buffer_snapshot)
10765            .to_display_point(map);
10766        if self.reversed {
10767            end..start
10768        } else {
10769            start..end
10770        }
10771    }
10772
10773    fn spanned_rows(
10774        &self,
10775        include_end_if_at_line_start: bool,
10776        map: &DisplaySnapshot,
10777    ) -> Range<u32> {
10778        let start = self.start.to_point(&map.buffer_snapshot);
10779        let mut end = self.end.to_point(&map.buffer_snapshot);
10780        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
10781            end.row -= 1;
10782        }
10783
10784        let buffer_start = map.prev_line_boundary(start).0;
10785        let buffer_end = map.next_line_boundary(end).0;
10786        buffer_start.row..buffer_end.row + 1
10787    }
10788}
10789
10790impl<T: InvalidationRegion> InvalidationStack<T> {
10791    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
10792    where
10793        S: Clone + ToOffset,
10794    {
10795        while let Some(region) = self.last() {
10796            let all_selections_inside_invalidation_ranges =
10797                if selections.len() == region.ranges().len() {
10798                    selections
10799                        .iter()
10800                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
10801                        .all(|(selection, invalidation_range)| {
10802                            let head = selection.head().to_offset(buffer);
10803                            invalidation_range.start <= head && invalidation_range.end >= head
10804                        })
10805                } else {
10806                    false
10807                };
10808
10809            if all_selections_inside_invalidation_ranges {
10810                break;
10811            } else {
10812                self.pop();
10813            }
10814        }
10815    }
10816}
10817
10818impl<T> Default for InvalidationStack<T> {
10819    fn default() -> Self {
10820        Self(Default::default())
10821    }
10822}
10823
10824impl<T> Deref for InvalidationStack<T> {
10825    type Target = Vec<T>;
10826
10827    fn deref(&self) -> &Self::Target {
10828        &self.0
10829    }
10830}
10831
10832impl<T> DerefMut for InvalidationStack<T> {
10833    fn deref_mut(&mut self) -> &mut Self::Target {
10834        &mut self.0
10835    }
10836}
10837
10838impl InvalidationRegion for SnippetState {
10839    fn ranges(&self) -> &[Range<Anchor>] {
10840        &self.ranges[self.active_index]
10841    }
10842}
10843
10844pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
10845    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
10846
10847    Arc::new(move |cx: &mut BlockContext| {
10848        let group_id: SharedString = cx.block_id.to_string().into();
10849
10850        let mut text_style = cx.text_style().clone();
10851        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
10852
10853        let multi_line_diagnostic = diagnostic.message.contains('\n');
10854
10855        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
10856            if multi_line_diagnostic {
10857                v_flex()
10858            } else {
10859                h_flex()
10860            }
10861            .children(diagnostic.is_primary.then(|| {
10862                IconButton::new(("close-block", block_id), IconName::XCircle)
10863                    .icon_color(Color::Muted)
10864                    .size(ButtonSize::Compact)
10865                    .style(ButtonStyle::Transparent)
10866                    .visible_on_hover(group_id.clone())
10867                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
10868                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
10869            }))
10870            .child(
10871                IconButton::new(("copy-block", block_id), IconName::Copy)
10872                    .icon_color(Color::Muted)
10873                    .size(ButtonSize::Compact)
10874                    .style(ButtonStyle::Transparent)
10875                    .visible_on_hover(group_id.clone())
10876                    .on_click({
10877                        let message = diagnostic.message.clone();
10878                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
10879                    })
10880                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
10881            )
10882        };
10883
10884        let icon_size = buttons(&diagnostic, cx.block_id)
10885            .into_any_element()
10886            .measure(AvailableSpace::min_size(), cx);
10887
10888        h_flex()
10889            .id(cx.block_id)
10890            .group(group_id.clone())
10891            .relative()
10892            .size_full()
10893            .pl(cx.gutter_dimensions.width)
10894            .w(cx.max_width + cx.gutter_dimensions.width)
10895            .child(
10896                div()
10897                    .flex()
10898                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
10899                    .flex_shrink(),
10900            )
10901            .child(buttons(&diagnostic, cx.block_id))
10902            .child(div().flex().flex_shrink_0().child(
10903                StyledText::new(text_without_backticks.clone()).with_highlights(
10904                    &text_style,
10905                    code_ranges.iter().map(|range| {
10906                        (
10907                            range.clone(),
10908                            HighlightStyle {
10909                                font_weight: Some(FontWeight::BOLD),
10910                                ..Default::default()
10911                            },
10912                        )
10913                    }),
10914                ),
10915            ))
10916            .into_any_element()
10917    })
10918}
10919
10920pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
10921    let mut text_without_backticks = String::new();
10922    let mut code_ranges = Vec::new();
10923
10924    if let Some(source) = &diagnostic.source {
10925        text_without_backticks.push_str(&source);
10926        code_ranges.push(0..source.len());
10927        text_without_backticks.push_str(": ");
10928    }
10929
10930    let mut prev_offset = 0;
10931    let mut in_code_block = false;
10932    for (ix, _) in diagnostic
10933        .message
10934        .match_indices('`')
10935        .chain([(diagnostic.message.len(), "")])
10936    {
10937        let prev_len = text_without_backticks.len();
10938        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
10939        prev_offset = ix + 1;
10940        if in_code_block {
10941            code_ranges.push(prev_len..text_without_backticks.len());
10942            in_code_block = false;
10943        } else {
10944            in_code_block = true;
10945        }
10946    }
10947
10948    (text_without_backticks.into(), code_ranges)
10949}
10950
10951fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
10952    match (severity, valid) {
10953        (DiagnosticSeverity::ERROR, true) => colors.error,
10954        (DiagnosticSeverity::ERROR, false) => colors.error,
10955        (DiagnosticSeverity::WARNING, true) => colors.warning,
10956        (DiagnosticSeverity::WARNING, false) => colors.warning,
10957        (DiagnosticSeverity::INFORMATION, true) => colors.info,
10958        (DiagnosticSeverity::INFORMATION, false) => colors.info,
10959        (DiagnosticSeverity::HINT, true) => colors.info,
10960        (DiagnosticSeverity::HINT, false) => colors.info,
10961        _ => colors.ignored,
10962    }
10963}
10964
10965pub fn styled_runs_for_code_label<'a>(
10966    label: &'a CodeLabel,
10967    syntax_theme: &'a theme::SyntaxTheme,
10968) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
10969    let fade_out = HighlightStyle {
10970        fade_out: Some(0.35),
10971        ..Default::default()
10972    };
10973
10974    let mut prev_end = label.filter_range.end;
10975    label
10976        .runs
10977        .iter()
10978        .enumerate()
10979        .flat_map(move |(ix, (range, highlight_id))| {
10980            let style = if let Some(style) = highlight_id.style(syntax_theme) {
10981                style
10982            } else {
10983                return Default::default();
10984            };
10985            let mut muted_style = style;
10986            muted_style.highlight(fade_out);
10987
10988            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
10989            if range.start >= label.filter_range.end {
10990                if range.start > prev_end {
10991                    runs.push((prev_end..range.start, fade_out));
10992                }
10993                runs.push((range.clone(), muted_style));
10994            } else if range.end <= label.filter_range.end {
10995                runs.push((range.clone(), style));
10996            } else {
10997                runs.push((range.start..label.filter_range.end, style));
10998                runs.push((label.filter_range.end..range.end, muted_style));
10999            }
11000            prev_end = cmp::max(prev_end, range.end);
11001
11002            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
11003                runs.push((prev_end..label.text.len(), fade_out));
11004            }
11005
11006            runs
11007        })
11008}
11009
11010pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
11011    let mut prev_index = 0;
11012    let mut prev_codepoint: Option<char> = None;
11013    text.char_indices()
11014        .chain([(text.len(), '\0')])
11015        .filter_map(move |(index, codepoint)| {
11016            let prev_codepoint = prev_codepoint.replace(codepoint)?;
11017            let is_boundary = index == text.len()
11018                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
11019                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
11020            if is_boundary {
11021                let chunk = &text[prev_index..index];
11022                prev_index = index;
11023                Some(chunk)
11024            } else {
11025                None
11026            }
11027        })
11028}
11029
11030trait RangeToAnchorExt {
11031    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
11032}
11033
11034impl<T: ToOffset> RangeToAnchorExt for Range<T> {
11035    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
11036        snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
11037    }
11038}