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        let has_multiple_rows = start_row + 1 != end_row;
 4849        for row in start_row..end_row {
 4850            let current_indent = snapshot.indent_size_for_line(row);
 4851            let indent_delta = match (current_indent.kind, indent_kind) {
 4852                (IndentKind::Space, IndentKind::Space) => {
 4853                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 4854                    IndentSize::spaces(columns_to_next_tab_stop)
 4855                }
 4856                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 4857                (_, IndentKind::Tab) => IndentSize::tab(),
 4858            };
 4859
 4860            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 4861                0
 4862            } else {
 4863                selection.start.column
 4864            };
 4865            let row_start = Point::new(row, start);
 4866            edits.push((
 4867                row_start..row_start,
 4868                indent_delta.chars().collect::<String>(),
 4869            ));
 4870
 4871            // Update this selection's endpoints to reflect the indentation.
 4872            if row == selection.start.row {
 4873                selection.start.column += indent_delta.len;
 4874            }
 4875            if row == selection.end.row {
 4876                selection.end.column += indent_delta.len;
 4877                delta_for_end_row = indent_delta.len;
 4878            }
 4879        }
 4880
 4881        if selection.start.row == selection.end.row {
 4882            delta_for_start_row + delta_for_end_row
 4883        } else {
 4884            delta_for_end_row
 4885        }
 4886    }
 4887
 4888    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 4889        if self.read_only(cx) {
 4890            return;
 4891        }
 4892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4893        let selections = self.selections.all::<Point>(cx);
 4894        let mut deletion_ranges = Vec::new();
 4895        let mut last_outdent = None;
 4896        {
 4897            let buffer = self.buffer.read(cx);
 4898            let snapshot = buffer.snapshot(cx);
 4899            for selection in &selections {
 4900                let settings = buffer.settings_at(selection.start, cx);
 4901                let tab_size = settings.tab_size.get();
 4902                let mut rows = selection.spanned_rows(false, &display_map);
 4903
 4904                // Avoid re-outdenting a row that has already been outdented by a
 4905                // previous selection.
 4906                if let Some(last_row) = last_outdent {
 4907                    if last_row == rows.start {
 4908                        rows.start += 1;
 4909                    }
 4910                }
 4911                let has_multiple_rows = rows.len() > 1;
 4912                for row in rows {
 4913                    let indent_size = snapshot.indent_size_for_line(row);
 4914                    if indent_size.len > 0 {
 4915                        let deletion_len = match indent_size.kind {
 4916                            IndentKind::Space => {
 4917                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 4918                                if columns_to_prev_tab_stop == 0 {
 4919                                    tab_size
 4920                                } else {
 4921                                    columns_to_prev_tab_stop
 4922                                }
 4923                            }
 4924                            IndentKind::Tab => 1,
 4925                        };
 4926                        let start = if has_multiple_rows
 4927                            || deletion_len > selection.start.column
 4928                            || indent_size.len < selection.start.column
 4929                        {
 4930                            0
 4931                        } else {
 4932                            selection.start.column - deletion_len
 4933                        };
 4934                        deletion_ranges
 4935                            .push(Point::new(row, start)..Point::new(row, start + deletion_len));
 4936                        last_outdent = Some(row);
 4937                    }
 4938                }
 4939            }
 4940        }
 4941
 4942        self.transact(cx, |this, cx| {
 4943            this.buffer.update(cx, |buffer, cx| {
 4944                let empty_str: Arc<str> = "".into();
 4945                buffer.edit(
 4946                    deletion_ranges
 4947                        .into_iter()
 4948                        .map(|range| (range, empty_str.clone())),
 4949                    None,
 4950                    cx,
 4951                );
 4952            });
 4953            let selections = this.selections.all::<usize>(cx);
 4954            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4955        });
 4956    }
 4957
 4958    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 4959        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4960        let selections = self.selections.all::<Point>(cx);
 4961
 4962        let mut new_cursors = Vec::new();
 4963        let mut edit_ranges = Vec::new();
 4964        let mut selections = selections.iter().peekable();
 4965        while let Some(selection) = selections.next() {
 4966            let mut rows = selection.spanned_rows(false, &display_map);
 4967            let goal_display_column = selection.head().to_display_point(&display_map).column();
 4968
 4969            // Accumulate contiguous regions of rows that we want to delete.
 4970            while let Some(next_selection) = selections.peek() {
 4971                let next_rows = next_selection.spanned_rows(false, &display_map);
 4972                if next_rows.start <= rows.end {
 4973                    rows.end = next_rows.end;
 4974                    selections.next().unwrap();
 4975                } else {
 4976                    break;
 4977                }
 4978            }
 4979
 4980            let buffer = &display_map.buffer_snapshot;
 4981            let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
 4982            let edit_end;
 4983            let cursor_buffer_row;
 4984            if buffer.max_point().row >= rows.end {
 4985                // If there's a line after the range, delete the \n from the end of the row range
 4986                // and position the cursor on the next line.
 4987                edit_end = Point::new(rows.end, 0).to_offset(buffer);
 4988                cursor_buffer_row = rows.end;
 4989            } else {
 4990                // If there isn't a line after the range, delete the \n from the line before the
 4991                // start of the row range and position the cursor there.
 4992                edit_start = edit_start.saturating_sub(1);
 4993                edit_end = buffer.len();
 4994                cursor_buffer_row = rows.start.saturating_sub(1);
 4995            }
 4996
 4997            let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
 4998            *cursor.column_mut() =
 4999                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5000
 5001            new_cursors.push((
 5002                selection.id,
 5003                buffer.anchor_after(cursor.to_point(&display_map)),
 5004            ));
 5005            edit_ranges.push(edit_start..edit_end);
 5006        }
 5007
 5008        self.transact(cx, |this, cx| {
 5009            let buffer = this.buffer.update(cx, |buffer, cx| {
 5010                let empty_str: Arc<str> = "".into();
 5011                buffer.edit(
 5012                    edit_ranges
 5013                        .into_iter()
 5014                        .map(|range| (range, empty_str.clone())),
 5015                    None,
 5016                    cx,
 5017                );
 5018                buffer.snapshot(cx)
 5019            });
 5020            let new_selections = new_cursors
 5021                .into_iter()
 5022                .map(|(id, cursor)| {
 5023                    let cursor = cursor.to_point(&buffer);
 5024                    Selection {
 5025                        id,
 5026                        start: cursor,
 5027                        end: cursor,
 5028                        reversed: false,
 5029                        goal: SelectionGoal::None,
 5030                    }
 5031                })
 5032                .collect();
 5033
 5034            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5035                s.select(new_selections);
 5036            });
 5037        });
 5038    }
 5039
 5040    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5041        if self.read_only(cx) {
 5042            return;
 5043        }
 5044        let mut row_ranges = Vec::<Range<u32>>::new();
 5045        for selection in self.selections.all::<Point>(cx) {
 5046            let start = selection.start.row;
 5047            let end = if selection.start.row == selection.end.row {
 5048                selection.start.row + 1
 5049            } else {
 5050                selection.end.row
 5051            };
 5052
 5053            if let Some(last_row_range) = row_ranges.last_mut() {
 5054                if start <= last_row_range.end {
 5055                    last_row_range.end = end;
 5056                    continue;
 5057                }
 5058            }
 5059            row_ranges.push(start..end);
 5060        }
 5061
 5062        let snapshot = self.buffer.read(cx).snapshot(cx);
 5063        let mut cursor_positions = Vec::new();
 5064        for row_range in &row_ranges {
 5065            let anchor = snapshot.anchor_before(Point::new(
 5066                row_range.end - 1,
 5067                snapshot.line_len(row_range.end - 1),
 5068            ));
 5069            cursor_positions.push(anchor..anchor);
 5070        }
 5071
 5072        self.transact(cx, |this, cx| {
 5073            for row_range in row_ranges.into_iter().rev() {
 5074                for row in row_range.rev() {
 5075                    let end_of_line = Point::new(row, snapshot.line_len(row));
 5076                    let indent = snapshot.indent_size_for_line(row + 1);
 5077                    let start_of_next_line = Point::new(row + 1, indent.len);
 5078
 5079                    let replace = if snapshot.line_len(row + 1) > indent.len {
 5080                        " "
 5081                    } else {
 5082                        ""
 5083                    };
 5084
 5085                    this.buffer.update(cx, |buffer, cx| {
 5086                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5087                    });
 5088                }
 5089            }
 5090
 5091            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5092                s.select_anchor_ranges(cursor_positions)
 5093            });
 5094        });
 5095    }
 5096
 5097    pub fn sort_lines_case_sensitive(
 5098        &mut self,
 5099        _: &SortLinesCaseSensitive,
 5100        cx: &mut ViewContext<Self>,
 5101    ) {
 5102        self.manipulate_lines(cx, |lines| lines.sort())
 5103    }
 5104
 5105    pub fn sort_lines_case_insensitive(
 5106        &mut self,
 5107        _: &SortLinesCaseInsensitive,
 5108        cx: &mut ViewContext<Self>,
 5109    ) {
 5110        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5111    }
 5112
 5113    pub fn unique_lines_case_insensitive(
 5114        &mut self,
 5115        _: &UniqueLinesCaseInsensitive,
 5116        cx: &mut ViewContext<Self>,
 5117    ) {
 5118        self.manipulate_lines(cx, |lines| {
 5119            let mut seen = HashSet::default();
 5120            lines.retain(|line| seen.insert(line.to_lowercase()));
 5121        })
 5122    }
 5123
 5124    pub fn unique_lines_case_sensitive(
 5125        &mut self,
 5126        _: &UniqueLinesCaseSensitive,
 5127        cx: &mut ViewContext<Self>,
 5128    ) {
 5129        self.manipulate_lines(cx, |lines| {
 5130            let mut seen = HashSet::default();
 5131            lines.retain(|line| seen.insert(*line));
 5132        })
 5133    }
 5134
 5135    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5136        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5137        if !revert_changes.is_empty() {
 5138            self.transact(cx, |editor, cx| {
 5139                editor.buffer().update(cx, |multi_buffer, cx| {
 5140                    for (buffer_id, buffer_revert_ranges) in revert_changes {
 5141                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5142                            buffer.update(cx, |buffer, cx| {
 5143                                buffer.edit(buffer_revert_ranges, None, cx);
 5144                            });
 5145                        }
 5146                    }
 5147                });
 5148                editor.change_selections(None, cx, |selections| selections.refresh());
 5149            });
 5150        }
 5151    }
 5152
 5153    fn gather_revert_changes(
 5154        &mut self,
 5155        selections: &[Selection<Anchor>],
 5156        cx: &mut ViewContext<'_, Editor>,
 5157    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Arc<str>)>> {
 5158        let mut revert_changes = HashMap::default();
 5159        self.buffer.update(cx, |multi_buffer, cx| {
 5160            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5161            let selected_multi_buffer_rows = selections.iter().map(|selection| {
 5162                let head = selection.head();
 5163                let tail = selection.tail();
 5164                let start = tail.to_point(&multi_buffer_snapshot).row;
 5165                let end = head.to_point(&multi_buffer_snapshot).row;
 5166                if start > end {
 5167                    end..start
 5168                } else {
 5169                    start..end
 5170                }
 5171            });
 5172
 5173            let mut processed_buffer_rows =
 5174                HashMap::<BufferId, HashSet<Range<text::Anchor>>>::default();
 5175            for selected_multi_buffer_rows in selected_multi_buffer_rows {
 5176                let query_rows =
 5177                    selected_multi_buffer_rows.start..selected_multi_buffer_rows.end + 1;
 5178                for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
 5179                    // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
 5180                    // when the caret is just above or just below the deleted hunk.
 5181                    let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
 5182                    let related_to_selection = if allow_adjacent {
 5183                        hunk.associated_range.overlaps(&query_rows)
 5184                            || hunk.associated_range.start == query_rows.end
 5185                            || hunk.associated_range.end == query_rows.start
 5186                    } else {
 5187                        // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
 5188                        // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
 5189                        hunk.associated_range.overlaps(&selected_multi_buffer_rows)
 5190                            || selected_multi_buffer_rows.end == hunk.associated_range.start
 5191                    };
 5192                    if related_to_selection {
 5193                        if !processed_buffer_rows
 5194                            .entry(hunk.buffer_id)
 5195                            .or_default()
 5196                            .insert(hunk.buffer_range.start..hunk.buffer_range.end)
 5197                        {
 5198                            continue;
 5199                        }
 5200                        Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5201                    }
 5202                }
 5203            }
 5204        });
 5205        revert_changes
 5206    }
 5207
 5208    fn prepare_revert_change(
 5209        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Arc<str>)>>,
 5210        multi_buffer: &MultiBuffer,
 5211        hunk: &DiffHunk<u32>,
 5212        cx: &mut AppContext,
 5213    ) -> Option<()> {
 5214        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5215        let buffer = buffer.read(cx);
 5216        let original_text = buffer.diff_base()?.get(hunk.diff_base_byte_range.clone())?;
 5217        let buffer_snapshot = buffer.snapshot();
 5218        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5219        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5220            probe
 5221                .0
 5222                .start
 5223                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5224                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5225                .then(probe.1.as_ref().cmp(original_text))
 5226        }) {
 5227            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), Arc::from(original_text)));
 5228            Some(())
 5229        } else {
 5230            None
 5231        }
 5232    }
 5233
 5234    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5235        self.manipulate_lines(cx, |lines| lines.reverse())
 5236    }
 5237
 5238    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5239        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5240    }
 5241
 5242    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5243    where
 5244        Fn: FnMut(&mut Vec<&str>),
 5245    {
 5246        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5247        let buffer = self.buffer.read(cx).snapshot(cx);
 5248
 5249        let mut edits = Vec::new();
 5250
 5251        let selections = self.selections.all::<Point>(cx);
 5252        let mut selections = selections.iter().peekable();
 5253        let mut contiguous_row_selections = Vec::new();
 5254        let mut new_selections = Vec::new();
 5255        let mut added_lines = 0;
 5256        let mut removed_lines = 0;
 5257
 5258        while let Some(selection) = selections.next() {
 5259            let (start_row, end_row) = consume_contiguous_rows(
 5260                &mut contiguous_row_selections,
 5261                selection,
 5262                &display_map,
 5263                &mut selections,
 5264            );
 5265
 5266            let start_point = Point::new(start_row, 0);
 5267            let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
 5268            let text = buffer
 5269                .text_for_range(start_point..end_point)
 5270                .collect::<String>();
 5271
 5272            let mut lines = text.split('\n').collect_vec();
 5273
 5274            let lines_before = lines.len();
 5275            callback(&mut lines);
 5276            let lines_after = lines.len();
 5277
 5278            edits.push((start_point..end_point, lines.join("\n")));
 5279
 5280            // Selections must change based on added and removed line count
 5281            let start_row = start_point.row + added_lines as u32 - removed_lines as u32;
 5282            let end_row = start_row + lines_after.saturating_sub(1) as u32;
 5283            new_selections.push(Selection {
 5284                id: selection.id,
 5285                start: start_row,
 5286                end: end_row,
 5287                goal: SelectionGoal::None,
 5288                reversed: selection.reversed,
 5289            });
 5290
 5291            if lines_after > lines_before {
 5292                added_lines += lines_after - lines_before;
 5293            } else if lines_before > lines_after {
 5294                removed_lines += lines_before - lines_after;
 5295            }
 5296        }
 5297
 5298        self.transact(cx, |this, cx| {
 5299            let buffer = this.buffer.update(cx, |buffer, cx| {
 5300                buffer.edit(edits, None, cx);
 5301                buffer.snapshot(cx)
 5302            });
 5303
 5304            // Recalculate offsets on newly edited buffer
 5305            let new_selections = new_selections
 5306                .iter()
 5307                .map(|s| {
 5308                    let start_point = Point::new(s.start, 0);
 5309                    let end_point = Point::new(s.end, buffer.line_len(s.end));
 5310                    Selection {
 5311                        id: s.id,
 5312                        start: buffer.point_to_offset(start_point),
 5313                        end: buffer.point_to_offset(end_point),
 5314                        goal: s.goal,
 5315                        reversed: s.reversed,
 5316                    }
 5317                })
 5318                .collect();
 5319
 5320            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5321                s.select(new_selections);
 5322            });
 5323
 5324            this.request_autoscroll(Autoscroll::fit(), cx);
 5325        });
 5326    }
 5327
 5328    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5329        self.manipulate_text(cx, |text| text.to_uppercase())
 5330    }
 5331
 5332    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5333        self.manipulate_text(cx, |text| text.to_lowercase())
 5334    }
 5335
 5336    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5337        self.manipulate_text(cx, |text| {
 5338            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5339            // https://github.com/rutrum/convert-case/issues/16
 5340            text.split('\n')
 5341                .map(|line| line.to_case(Case::Title))
 5342                .join("\n")
 5343        })
 5344    }
 5345
 5346    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 5347        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 5348    }
 5349
 5350    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 5351        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 5352    }
 5353
 5354    pub fn convert_to_upper_camel_case(
 5355        &mut self,
 5356        _: &ConvertToUpperCamelCase,
 5357        cx: &mut ViewContext<Self>,
 5358    ) {
 5359        self.manipulate_text(cx, |text| {
 5360            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5361            // https://github.com/rutrum/convert-case/issues/16
 5362            text.split('\n')
 5363                .map(|line| line.to_case(Case::UpperCamel))
 5364                .join("\n")
 5365        })
 5366    }
 5367
 5368    pub fn convert_to_lower_camel_case(
 5369        &mut self,
 5370        _: &ConvertToLowerCamelCase,
 5371        cx: &mut ViewContext<Self>,
 5372    ) {
 5373        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 5374    }
 5375
 5376    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5377    where
 5378        Fn: FnMut(&str) -> String,
 5379    {
 5380        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5381        let buffer = self.buffer.read(cx).snapshot(cx);
 5382
 5383        let mut new_selections = Vec::new();
 5384        let mut edits = Vec::new();
 5385        let mut selection_adjustment = 0i32;
 5386
 5387        for selection in self.selections.all::<usize>(cx) {
 5388            let selection_is_empty = selection.is_empty();
 5389
 5390            let (start, end) = if selection_is_empty {
 5391                let word_range = movement::surrounding_word(
 5392                    &display_map,
 5393                    selection.start.to_display_point(&display_map),
 5394                );
 5395                let start = word_range.start.to_offset(&display_map, Bias::Left);
 5396                let end = word_range.end.to_offset(&display_map, Bias::Left);
 5397                (start, end)
 5398            } else {
 5399                (selection.start, selection.end)
 5400            };
 5401
 5402            let text = buffer.text_for_range(start..end).collect::<String>();
 5403            let old_length = text.len() as i32;
 5404            let text = callback(&text);
 5405
 5406            new_selections.push(Selection {
 5407                start: (start as i32 - selection_adjustment) as usize,
 5408                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 5409                goal: SelectionGoal::None,
 5410                ..selection
 5411            });
 5412
 5413            selection_adjustment += old_length - text.len() as i32;
 5414
 5415            edits.push((start..end, text));
 5416        }
 5417
 5418        self.transact(cx, |this, cx| {
 5419            this.buffer.update(cx, |buffer, cx| {
 5420                buffer.edit(edits, None, cx);
 5421            });
 5422
 5423            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5424                s.select(new_selections);
 5425            });
 5426
 5427            this.request_autoscroll(Autoscroll::fit(), cx);
 5428        });
 5429    }
 5430
 5431    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 5432        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5433        let buffer = &display_map.buffer_snapshot;
 5434        let selections = self.selections.all::<Point>(cx);
 5435
 5436        let mut edits = Vec::new();
 5437        let mut selections_iter = selections.iter().peekable();
 5438        while let Some(selection) = selections_iter.next() {
 5439            // Avoid duplicating the same lines twice.
 5440            let mut rows = selection.spanned_rows(false, &display_map);
 5441
 5442            while let Some(next_selection) = selections_iter.peek() {
 5443                let next_rows = next_selection.spanned_rows(false, &display_map);
 5444                if next_rows.start < rows.end {
 5445                    rows.end = next_rows.end;
 5446                    selections_iter.next().unwrap();
 5447                } else {
 5448                    break;
 5449                }
 5450            }
 5451
 5452            // Copy the text from the selected row region and splice it either at the start
 5453            // or end of the region.
 5454            let start = Point::new(rows.start, 0);
 5455            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
 5456            let text = buffer
 5457                .text_for_range(start..end)
 5458                .chain(Some("\n"))
 5459                .collect::<String>();
 5460            let insert_location = if upwards {
 5461                Point::new(rows.end, 0)
 5462            } else {
 5463                start
 5464            };
 5465            edits.push((insert_location..insert_location, text));
 5466        }
 5467
 5468        self.transact(cx, |this, cx| {
 5469            this.buffer.update(cx, |buffer, cx| {
 5470                buffer.edit(edits, None, cx);
 5471            });
 5472
 5473            this.request_autoscroll(Autoscroll::fit(), cx);
 5474        });
 5475    }
 5476
 5477    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 5478        self.duplicate_line(true, cx);
 5479    }
 5480
 5481    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 5482        self.duplicate_line(false, cx);
 5483    }
 5484
 5485    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 5486        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5487        let buffer = self.buffer.read(cx).snapshot(cx);
 5488
 5489        let mut edits = Vec::new();
 5490        let mut unfold_ranges = Vec::new();
 5491        let mut refold_ranges = Vec::new();
 5492
 5493        let selections = self.selections.all::<Point>(cx);
 5494        let mut selections = selections.iter().peekable();
 5495        let mut contiguous_row_selections = Vec::new();
 5496        let mut new_selections = Vec::new();
 5497
 5498        while let Some(selection) = selections.next() {
 5499            // Find all the selections that span a contiguous row range
 5500            let (start_row, end_row) = consume_contiguous_rows(
 5501                &mut contiguous_row_selections,
 5502                selection,
 5503                &display_map,
 5504                &mut selections,
 5505            );
 5506
 5507            // Move the text spanned by the row range to be before the line preceding the row range
 5508            if start_row > 0 {
 5509                let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
 5510                    ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
 5511                let insertion_point = display_map
 5512                    .prev_line_boundary(Point::new(start_row - 1, 0))
 5513                    .0;
 5514
 5515                // Don't move lines across excerpts
 5516                if buffer
 5517                    .excerpt_boundaries_in_range((
 5518                        Bound::Excluded(insertion_point),
 5519                        Bound::Included(range_to_move.end),
 5520                    ))
 5521                    .next()
 5522                    .is_none()
 5523                {
 5524                    let text = buffer
 5525                        .text_for_range(range_to_move.clone())
 5526                        .flat_map(|s| s.chars())
 5527                        .skip(1)
 5528                        .chain(['\n'])
 5529                        .collect::<String>();
 5530
 5531                    edits.push((
 5532                        buffer.anchor_after(range_to_move.start)
 5533                            ..buffer.anchor_before(range_to_move.end),
 5534                        String::new(),
 5535                    ));
 5536                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5537                    edits.push((insertion_anchor..insertion_anchor, text));
 5538
 5539                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 5540
 5541                    // Move selections up
 5542                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5543                        |mut selection| {
 5544                            selection.start.row -= row_delta;
 5545                            selection.end.row -= row_delta;
 5546                            selection
 5547                        },
 5548                    ));
 5549
 5550                    // Move folds up
 5551                    unfold_ranges.push(range_to_move.clone());
 5552                    for fold in display_map.folds_in_range(
 5553                        buffer.anchor_before(range_to_move.start)
 5554                            ..buffer.anchor_after(range_to_move.end),
 5555                    ) {
 5556                        let mut start = fold.range.start.to_point(&buffer);
 5557                        let mut end = fold.range.end.to_point(&buffer);
 5558                        start.row -= row_delta;
 5559                        end.row -= row_delta;
 5560                        refold_ranges.push(start..end);
 5561                    }
 5562                }
 5563            }
 5564
 5565            // If we didn't move line(s), preserve the existing selections
 5566            new_selections.append(&mut contiguous_row_selections);
 5567        }
 5568
 5569        self.transact(cx, |this, cx| {
 5570            this.unfold_ranges(unfold_ranges, true, true, cx);
 5571            this.buffer.update(cx, |buffer, cx| {
 5572                for (range, text) in edits {
 5573                    buffer.edit([(range, text)], None, cx);
 5574                }
 5575            });
 5576            this.fold_ranges(refold_ranges, true, cx);
 5577            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5578                s.select(new_selections);
 5579            })
 5580        });
 5581    }
 5582
 5583    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 5584        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5585        let buffer = self.buffer.read(cx).snapshot(cx);
 5586
 5587        let mut edits = Vec::new();
 5588        let mut unfold_ranges = Vec::new();
 5589        let mut refold_ranges = Vec::new();
 5590
 5591        let selections = self.selections.all::<Point>(cx);
 5592        let mut selections = selections.iter().peekable();
 5593        let mut contiguous_row_selections = Vec::new();
 5594        let mut new_selections = Vec::new();
 5595
 5596        while let Some(selection) = selections.next() {
 5597            // Find all the selections that span a contiguous row range
 5598            let (start_row, end_row) = consume_contiguous_rows(
 5599                &mut contiguous_row_selections,
 5600                selection,
 5601                &display_map,
 5602                &mut selections,
 5603            );
 5604
 5605            // Move the text spanned by the row range to be after the last line of the row range
 5606            if end_row <= buffer.max_point().row {
 5607                let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
 5608                let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
 5609
 5610                // Don't move lines across excerpt boundaries
 5611                if buffer
 5612                    .excerpt_boundaries_in_range((
 5613                        Bound::Excluded(range_to_move.start),
 5614                        Bound::Included(insertion_point),
 5615                    ))
 5616                    .next()
 5617                    .is_none()
 5618                {
 5619                    let mut text = String::from("\n");
 5620                    text.extend(buffer.text_for_range(range_to_move.clone()));
 5621                    text.pop(); // Drop trailing newline
 5622                    edits.push((
 5623                        buffer.anchor_after(range_to_move.start)
 5624                            ..buffer.anchor_before(range_to_move.end),
 5625                        String::new(),
 5626                    ));
 5627                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5628                    edits.push((insertion_anchor..insertion_anchor, text));
 5629
 5630                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 5631
 5632                    // Move selections down
 5633                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5634                        |mut selection| {
 5635                            selection.start.row += row_delta;
 5636                            selection.end.row += row_delta;
 5637                            selection
 5638                        },
 5639                    ));
 5640
 5641                    // Move folds down
 5642                    unfold_ranges.push(range_to_move.clone());
 5643                    for fold in display_map.folds_in_range(
 5644                        buffer.anchor_before(range_to_move.start)
 5645                            ..buffer.anchor_after(range_to_move.end),
 5646                    ) {
 5647                        let mut start = fold.range.start.to_point(&buffer);
 5648                        let mut end = fold.range.end.to_point(&buffer);
 5649                        start.row += row_delta;
 5650                        end.row += row_delta;
 5651                        refold_ranges.push(start..end);
 5652                    }
 5653                }
 5654            }
 5655
 5656            // If we didn't move line(s), preserve the existing selections
 5657            new_selections.append(&mut contiguous_row_selections);
 5658        }
 5659
 5660        self.transact(cx, |this, cx| {
 5661            this.unfold_ranges(unfold_ranges, true, true, cx);
 5662            this.buffer.update(cx, |buffer, cx| {
 5663                for (range, text) in edits {
 5664                    buffer.edit([(range, text)], None, cx);
 5665                }
 5666            });
 5667            this.fold_ranges(refold_ranges, true, cx);
 5668            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 5669        });
 5670    }
 5671
 5672    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 5673        let text_layout_details = &self.text_layout_details(cx);
 5674        self.transact(cx, |this, cx| {
 5675            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5676                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 5677                let line_mode = s.line_mode;
 5678                s.move_with(|display_map, selection| {
 5679                    if !selection.is_empty() || line_mode {
 5680                        return;
 5681                    }
 5682
 5683                    let mut head = selection.head();
 5684                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 5685                    if head.column() == display_map.line_len(head.row()) {
 5686                        transpose_offset = display_map
 5687                            .buffer_snapshot
 5688                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5689                    }
 5690
 5691                    if transpose_offset == 0 {
 5692                        return;
 5693                    }
 5694
 5695                    *head.column_mut() += 1;
 5696                    head = display_map.clip_point(head, Bias::Right);
 5697                    let goal = SelectionGoal::HorizontalPosition(
 5698                        display_map
 5699                            .x_for_display_point(head, &text_layout_details)
 5700                            .into(),
 5701                    );
 5702                    selection.collapse_to(head, goal);
 5703
 5704                    let transpose_start = display_map
 5705                        .buffer_snapshot
 5706                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5707                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 5708                        let transpose_end = display_map
 5709                            .buffer_snapshot
 5710                            .clip_offset(transpose_offset + 1, Bias::Right);
 5711                        if let Some(ch) =
 5712                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 5713                        {
 5714                            edits.push((transpose_start..transpose_offset, String::new()));
 5715                            edits.push((transpose_end..transpose_end, ch.to_string()));
 5716                        }
 5717                    }
 5718                });
 5719                edits
 5720            });
 5721            this.buffer
 5722                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 5723            let selections = this.selections.all::<usize>(cx);
 5724            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5725                s.select(selections);
 5726            });
 5727        });
 5728    }
 5729
 5730    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 5731        let mut text = String::new();
 5732        let buffer = self.buffer.read(cx).snapshot(cx);
 5733        let mut selections = self.selections.all::<Point>(cx);
 5734        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5735        {
 5736            let max_point = buffer.max_point();
 5737            let mut is_first = true;
 5738            for selection in &mut selections {
 5739                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5740                if is_entire_line {
 5741                    selection.start = Point::new(selection.start.row, 0);
 5742                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 5743                    selection.goal = SelectionGoal::None;
 5744                }
 5745                if is_first {
 5746                    is_first = false;
 5747                } else {
 5748                    text += "\n";
 5749                }
 5750                let mut len = 0;
 5751                for chunk in buffer.text_for_range(selection.start..selection.end) {
 5752                    text.push_str(chunk);
 5753                    len += chunk.len();
 5754                }
 5755                clipboard_selections.push(ClipboardSelection {
 5756                    len,
 5757                    is_entire_line,
 5758                    first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
 5759                });
 5760            }
 5761        }
 5762
 5763        self.transact(cx, |this, cx| {
 5764            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5765                s.select(selections);
 5766            });
 5767            this.insert("", cx);
 5768            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5769        });
 5770    }
 5771
 5772    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 5773        let selections = self.selections.all::<Point>(cx);
 5774        let buffer = self.buffer.read(cx).read(cx);
 5775        let mut text = String::new();
 5776
 5777        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5778        {
 5779            let max_point = buffer.max_point();
 5780            let mut is_first = true;
 5781            for selection in selections.iter() {
 5782                let mut start = selection.start;
 5783                let mut end = selection.end;
 5784                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5785                if is_entire_line {
 5786                    start = Point::new(start.row, 0);
 5787                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5788                }
 5789                if is_first {
 5790                    is_first = false;
 5791                } else {
 5792                    text += "\n";
 5793                }
 5794                let mut len = 0;
 5795                for chunk in buffer.text_for_range(start..end) {
 5796                    text.push_str(chunk);
 5797                    len += chunk.len();
 5798                }
 5799                clipboard_selections.push(ClipboardSelection {
 5800                    len,
 5801                    is_entire_line,
 5802                    first_line_indent: buffer.indent_size_for_line(start.row).len,
 5803                });
 5804            }
 5805        }
 5806
 5807        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5808    }
 5809
 5810    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 5811        if self.read_only(cx) {
 5812            return;
 5813        }
 5814
 5815        self.transact(cx, |this, cx| {
 5816            if let Some(item) = cx.read_from_clipboard() {
 5817                let clipboard_text = Cow::Borrowed(item.text());
 5818                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
 5819                    let old_selections = this.selections.all::<usize>(cx);
 5820                    let all_selections_were_entire_line =
 5821                        clipboard_selections.iter().all(|s| s.is_entire_line);
 5822                    let first_selection_indent_column =
 5823                        clipboard_selections.first().map(|s| s.first_line_indent);
 5824                    if clipboard_selections.len() != old_selections.len() {
 5825                        clipboard_selections.drain(..);
 5826                    }
 5827
 5828                    this.buffer.update(cx, |buffer, cx| {
 5829                        let snapshot = buffer.read(cx);
 5830                        let mut start_offset = 0;
 5831                        let mut edits = Vec::new();
 5832                        let mut original_indent_columns = Vec::new();
 5833                        let line_mode = this.selections.line_mode;
 5834                        for (ix, selection) in old_selections.iter().enumerate() {
 5835                            let to_insert;
 5836                            let entire_line;
 5837                            let original_indent_column;
 5838                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 5839                                let end_offset = start_offset + clipboard_selection.len;
 5840                                to_insert = &clipboard_text[start_offset..end_offset];
 5841                                entire_line = clipboard_selection.is_entire_line;
 5842                                start_offset = end_offset + 1;
 5843                                original_indent_column =
 5844                                    Some(clipboard_selection.first_line_indent);
 5845                            } else {
 5846                                to_insert = clipboard_text.as_str();
 5847                                entire_line = all_selections_were_entire_line;
 5848                                original_indent_column = first_selection_indent_column
 5849                            }
 5850
 5851                            // If the corresponding selection was empty when this slice of the
 5852                            // clipboard text was written, then the entire line containing the
 5853                            // selection was copied. If this selection is also currently empty,
 5854                            // then paste the line before the current line of the buffer.
 5855                            let range = if selection.is_empty() && !line_mode && entire_line {
 5856                                let column = selection.start.to_point(&snapshot).column as usize;
 5857                                let line_start = selection.start - column;
 5858                                line_start..line_start
 5859                            } else {
 5860                                selection.range()
 5861                            };
 5862
 5863                            edits.push((range, to_insert));
 5864                            original_indent_columns.extend(original_indent_column);
 5865                        }
 5866                        drop(snapshot);
 5867
 5868                        buffer.edit(
 5869                            edits,
 5870                            Some(AutoindentMode::Block {
 5871                                original_indent_columns,
 5872                            }),
 5873                            cx,
 5874                        );
 5875                    });
 5876
 5877                    let selections = this.selections.all::<usize>(cx);
 5878                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5879                } else {
 5880                    this.insert(&clipboard_text, cx);
 5881                }
 5882            }
 5883        });
 5884    }
 5885
 5886    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 5887        if self.read_only(cx) {
 5888            return;
 5889        }
 5890
 5891        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 5892            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
 5893                self.change_selections(None, cx, |s| {
 5894                    s.select_anchors(selections.to_vec());
 5895                });
 5896            }
 5897            self.request_autoscroll(Autoscroll::fit(), cx);
 5898            self.unmark_text(cx);
 5899            self.refresh_inline_completion(true, cx);
 5900            cx.emit(EditorEvent::Edited);
 5901            cx.emit(EditorEvent::TransactionUndone {
 5902                transaction_id: tx_id,
 5903            });
 5904        }
 5905    }
 5906
 5907    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 5908        if self.read_only(cx) {
 5909            return;
 5910        }
 5911
 5912        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 5913            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
 5914            {
 5915                self.change_selections(None, cx, |s| {
 5916                    s.select_anchors(selections.to_vec());
 5917                });
 5918            }
 5919            self.request_autoscroll(Autoscroll::fit(), cx);
 5920            self.unmark_text(cx);
 5921            self.refresh_inline_completion(true, cx);
 5922            cx.emit(EditorEvent::Edited);
 5923        }
 5924    }
 5925
 5926    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 5927        self.buffer
 5928            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 5929    }
 5930
 5931    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 5932        self.buffer
 5933            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 5934    }
 5935
 5936    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 5937        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5938            let line_mode = s.line_mode;
 5939            s.move_with(|map, selection| {
 5940                let cursor = if selection.is_empty() && !line_mode {
 5941                    movement::left(map, selection.start)
 5942                } else {
 5943                    selection.start
 5944                };
 5945                selection.collapse_to(cursor, SelectionGoal::None);
 5946            });
 5947        })
 5948    }
 5949
 5950    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 5951        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5952            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 5953        })
 5954    }
 5955
 5956    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 5957        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5958            let line_mode = s.line_mode;
 5959            s.move_with(|map, selection| {
 5960                let cursor = if selection.is_empty() && !line_mode {
 5961                    movement::right(map, selection.end)
 5962                } else {
 5963                    selection.end
 5964                };
 5965                selection.collapse_to(cursor, SelectionGoal::None)
 5966            });
 5967        })
 5968    }
 5969
 5970    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 5971        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5972            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 5973        })
 5974    }
 5975
 5976    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 5977        if self.take_rename(true, cx).is_some() {
 5978            return;
 5979        }
 5980
 5981        if matches!(self.mode, EditorMode::SingleLine) {
 5982            cx.propagate();
 5983            return;
 5984        }
 5985
 5986        let text_layout_details = &self.text_layout_details(cx);
 5987
 5988        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5989            let line_mode = s.line_mode;
 5990            s.move_with(|map, selection| {
 5991                if !selection.is_empty() && !line_mode {
 5992                    selection.goal = SelectionGoal::None;
 5993                }
 5994                let (cursor, goal) = movement::up(
 5995                    map,
 5996                    selection.start,
 5997                    selection.goal,
 5998                    false,
 5999                    &text_layout_details,
 6000                );
 6001                selection.collapse_to(cursor, goal);
 6002            });
 6003        })
 6004    }
 6005
 6006    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6007        if self.take_rename(true, cx).is_some() {
 6008            return;
 6009        }
 6010
 6011        if matches!(self.mode, EditorMode::SingleLine) {
 6012            cx.propagate();
 6013            return;
 6014        }
 6015
 6016        let text_layout_details = &self.text_layout_details(cx);
 6017
 6018        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6019            let line_mode = s.line_mode;
 6020            s.move_with(|map, selection| {
 6021                if !selection.is_empty() && !line_mode {
 6022                    selection.goal = SelectionGoal::None;
 6023                }
 6024                let (cursor, goal) = movement::up_by_rows(
 6025                    map,
 6026                    selection.start,
 6027                    action.lines,
 6028                    selection.goal,
 6029                    false,
 6030                    &text_layout_details,
 6031                );
 6032                selection.collapse_to(cursor, goal);
 6033            });
 6034        })
 6035    }
 6036
 6037    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6038        if self.take_rename(true, cx).is_some() {
 6039            return;
 6040        }
 6041
 6042        if matches!(self.mode, EditorMode::SingleLine) {
 6043            cx.propagate();
 6044            return;
 6045        }
 6046
 6047        let text_layout_details = &self.text_layout_details(cx);
 6048
 6049        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6050            let line_mode = s.line_mode;
 6051            s.move_with(|map, selection| {
 6052                if !selection.is_empty() && !line_mode {
 6053                    selection.goal = SelectionGoal::None;
 6054                }
 6055                let (cursor, goal) = movement::down_by_rows(
 6056                    map,
 6057                    selection.start,
 6058                    action.lines,
 6059                    selection.goal,
 6060                    false,
 6061                    &text_layout_details,
 6062                );
 6063                selection.collapse_to(cursor, goal);
 6064            });
 6065        })
 6066    }
 6067
 6068    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6069        let text_layout_details = &self.text_layout_details(cx);
 6070        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6071            s.move_heads_with(|map, head, goal| {
 6072                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6073            })
 6074        })
 6075    }
 6076
 6077    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6078        let text_layout_details = &self.text_layout_details(cx);
 6079        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6080            s.move_heads_with(|map, head, goal| {
 6081                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6082            })
 6083        })
 6084    }
 6085
 6086    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6087        if self.take_rename(true, cx).is_some() {
 6088            return;
 6089        }
 6090
 6091        if matches!(self.mode, EditorMode::SingleLine) {
 6092            cx.propagate();
 6093            return;
 6094        }
 6095
 6096        let row_count = if let Some(row_count) = self.visible_line_count() {
 6097            row_count as u32 - 1
 6098        } else {
 6099            return;
 6100        };
 6101
 6102        let autoscroll = if action.center_cursor {
 6103            Autoscroll::center()
 6104        } else {
 6105            Autoscroll::fit()
 6106        };
 6107
 6108        let text_layout_details = &self.text_layout_details(cx);
 6109
 6110        self.change_selections(Some(autoscroll), cx, |s| {
 6111            let line_mode = s.line_mode;
 6112            s.move_with(|map, selection| {
 6113                if !selection.is_empty() && !line_mode {
 6114                    selection.goal = SelectionGoal::None;
 6115                }
 6116                let (cursor, goal) = movement::up_by_rows(
 6117                    map,
 6118                    selection.end,
 6119                    row_count,
 6120                    selection.goal,
 6121                    false,
 6122                    &text_layout_details,
 6123                );
 6124                selection.collapse_to(cursor, goal);
 6125            });
 6126        });
 6127    }
 6128
 6129    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6130        let text_layout_details = &self.text_layout_details(cx);
 6131        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6132            s.move_heads_with(|map, head, goal| {
 6133                movement::up(map, head, goal, false, &text_layout_details)
 6134            })
 6135        })
 6136    }
 6137
 6138    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6139        self.take_rename(true, cx);
 6140
 6141        if self.mode == EditorMode::SingleLine {
 6142            cx.propagate();
 6143            return;
 6144        }
 6145
 6146        let text_layout_details = &self.text_layout_details(cx);
 6147        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6148            let line_mode = s.line_mode;
 6149            s.move_with(|map, selection| {
 6150                if !selection.is_empty() && !line_mode {
 6151                    selection.goal = SelectionGoal::None;
 6152                }
 6153                let (cursor, goal) = movement::down(
 6154                    map,
 6155                    selection.end,
 6156                    selection.goal,
 6157                    false,
 6158                    &text_layout_details,
 6159                );
 6160                selection.collapse_to(cursor, goal);
 6161            });
 6162        });
 6163    }
 6164
 6165    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6166        if self.take_rename(true, cx).is_some() {
 6167            return;
 6168        }
 6169
 6170        if self
 6171            .context_menu
 6172            .write()
 6173            .as_mut()
 6174            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6175            .unwrap_or(false)
 6176        {
 6177            return;
 6178        }
 6179
 6180        if matches!(self.mode, EditorMode::SingleLine) {
 6181            cx.propagate();
 6182            return;
 6183        }
 6184
 6185        let row_count = if let Some(row_count) = self.visible_line_count() {
 6186            row_count as u32 - 1
 6187        } else {
 6188            return;
 6189        };
 6190
 6191        let autoscroll = if action.center_cursor {
 6192            Autoscroll::center()
 6193        } else {
 6194            Autoscroll::fit()
 6195        };
 6196
 6197        let text_layout_details = &self.text_layout_details(cx);
 6198        self.change_selections(Some(autoscroll), cx, |s| {
 6199            let line_mode = s.line_mode;
 6200            s.move_with(|map, selection| {
 6201                if !selection.is_empty() && !line_mode {
 6202                    selection.goal = SelectionGoal::None;
 6203                }
 6204                let (cursor, goal) = movement::down_by_rows(
 6205                    map,
 6206                    selection.end,
 6207                    row_count,
 6208                    selection.goal,
 6209                    false,
 6210                    &text_layout_details,
 6211                );
 6212                selection.collapse_to(cursor, goal);
 6213            });
 6214        });
 6215    }
 6216
 6217    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6218        let text_layout_details = &self.text_layout_details(cx);
 6219        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6220            s.move_heads_with(|map, head, goal| {
 6221                movement::down(map, head, goal, false, &text_layout_details)
 6222            })
 6223        });
 6224    }
 6225
 6226    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6227        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6228            context_menu.select_first(self.project.as_ref(), cx);
 6229        }
 6230    }
 6231
 6232    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6233        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6234            context_menu.select_prev(self.project.as_ref(), cx);
 6235        }
 6236    }
 6237
 6238    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6239        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6240            context_menu.select_next(self.project.as_ref(), cx);
 6241        }
 6242    }
 6243
 6244    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6245        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6246            context_menu.select_last(self.project.as_ref(), cx);
 6247        }
 6248    }
 6249
 6250    pub fn move_to_previous_word_start(
 6251        &mut self,
 6252        _: &MoveToPreviousWordStart,
 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_word_start(map, head),
 6259                    SelectionGoal::None,
 6260                )
 6261            });
 6262        })
 6263    }
 6264
 6265    pub fn move_to_previous_subword_start(
 6266        &mut self,
 6267        _: &MoveToPreviousSubwordStart,
 6268        cx: &mut ViewContext<Self>,
 6269    ) {
 6270        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6271            s.move_cursors_with(|map, head, _| {
 6272                (
 6273                    movement::previous_subword_start(map, head),
 6274                    SelectionGoal::None,
 6275                )
 6276            });
 6277        })
 6278    }
 6279
 6280    pub fn select_to_previous_word_start(
 6281        &mut self,
 6282        _: &SelectToPreviousWordStart,
 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_word_start(map, head),
 6289                    SelectionGoal::None,
 6290                )
 6291            });
 6292        })
 6293    }
 6294
 6295    pub fn select_to_previous_subword_start(
 6296        &mut self,
 6297        _: &SelectToPreviousSubwordStart,
 6298        cx: &mut ViewContext<Self>,
 6299    ) {
 6300        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6301            s.move_heads_with(|map, head, _| {
 6302                (
 6303                    movement::previous_subword_start(map, head),
 6304                    SelectionGoal::None,
 6305                )
 6306            });
 6307        })
 6308    }
 6309
 6310    pub fn delete_to_previous_word_start(
 6311        &mut self,
 6312        _: &DeleteToPreviousWordStart,
 6313        cx: &mut ViewContext<Self>,
 6314    ) {
 6315        self.transact(cx, |this, cx| {
 6316            this.select_autoclose_pair(cx);
 6317            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6318                let line_mode = s.line_mode;
 6319                s.move_with(|map, selection| {
 6320                    if selection.is_empty() && !line_mode {
 6321                        let cursor = movement::previous_word_start(map, selection.head());
 6322                        selection.set_head(cursor, SelectionGoal::None);
 6323                    }
 6324                });
 6325            });
 6326            this.insert("", cx);
 6327        });
 6328    }
 6329
 6330    pub fn delete_to_previous_subword_start(
 6331        &mut self,
 6332        _: &DeleteToPreviousSubwordStart,
 6333        cx: &mut ViewContext<Self>,
 6334    ) {
 6335        self.transact(cx, |this, cx| {
 6336            this.select_autoclose_pair(cx);
 6337            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6338                let line_mode = s.line_mode;
 6339                s.move_with(|map, selection| {
 6340                    if selection.is_empty() && !line_mode {
 6341                        let cursor = movement::previous_subword_start(map, selection.head());
 6342                        selection.set_head(cursor, SelectionGoal::None);
 6343                    }
 6344                });
 6345            });
 6346            this.insert("", cx);
 6347        });
 6348    }
 6349
 6350    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 6351        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6352            s.move_cursors_with(|map, head, _| {
 6353                (movement::next_word_end(map, head), SelectionGoal::None)
 6354            });
 6355        })
 6356    }
 6357
 6358    pub fn move_to_next_subword_end(
 6359        &mut self,
 6360        _: &MoveToNextSubwordEnd,
 6361        cx: &mut ViewContext<Self>,
 6362    ) {
 6363        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6364            s.move_cursors_with(|map, head, _| {
 6365                (movement::next_subword_end(map, head), SelectionGoal::None)
 6366            });
 6367        })
 6368    }
 6369
 6370    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 6371        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6372            s.move_heads_with(|map, head, _| {
 6373                (movement::next_word_end(map, head), SelectionGoal::None)
 6374            });
 6375        })
 6376    }
 6377
 6378    pub fn select_to_next_subword_end(
 6379        &mut self,
 6380        _: &SelectToNextSubwordEnd,
 6381        cx: &mut ViewContext<Self>,
 6382    ) {
 6383        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6384            s.move_heads_with(|map, head, _| {
 6385                (movement::next_subword_end(map, head), SelectionGoal::None)
 6386            });
 6387        })
 6388    }
 6389
 6390    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 6391        self.transact(cx, |this, cx| {
 6392            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6393                let line_mode = s.line_mode;
 6394                s.move_with(|map, selection| {
 6395                    if selection.is_empty() && !line_mode {
 6396                        let cursor = movement::next_word_end(map, selection.head());
 6397                        selection.set_head(cursor, SelectionGoal::None);
 6398                    }
 6399                });
 6400            });
 6401            this.insert("", cx);
 6402        });
 6403    }
 6404
 6405    pub fn delete_to_next_subword_end(
 6406        &mut self,
 6407        _: &DeleteToNextSubwordEnd,
 6408        cx: &mut ViewContext<Self>,
 6409    ) {
 6410        self.transact(cx, |this, cx| {
 6411            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6412                s.move_with(|map, selection| {
 6413                    if selection.is_empty() {
 6414                        let cursor = movement::next_subword_end(map, selection.head());
 6415                        selection.set_head(cursor, SelectionGoal::None);
 6416                    }
 6417                });
 6418            });
 6419            this.insert("", cx);
 6420        });
 6421    }
 6422
 6423    pub fn move_to_beginning_of_line(
 6424        &mut self,
 6425        _: &MoveToBeginningOfLine,
 6426        cx: &mut ViewContext<Self>,
 6427    ) {
 6428        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6429            s.move_cursors_with(|map, head, _| {
 6430                (
 6431                    movement::indented_line_beginning(map, head, true),
 6432                    SelectionGoal::None,
 6433                )
 6434            });
 6435        })
 6436    }
 6437
 6438    pub fn select_to_beginning_of_line(
 6439        &mut self,
 6440        action: &SelectToBeginningOfLine,
 6441        cx: &mut ViewContext<Self>,
 6442    ) {
 6443        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6444            s.move_heads_with(|map, head, _| {
 6445                (
 6446                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6447                    SelectionGoal::None,
 6448                )
 6449            });
 6450        });
 6451    }
 6452
 6453    pub fn delete_to_beginning_of_line(
 6454        &mut self,
 6455        _: &DeleteToBeginningOfLine,
 6456        cx: &mut ViewContext<Self>,
 6457    ) {
 6458        self.transact(cx, |this, cx| {
 6459            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6460                s.move_with(|_, selection| {
 6461                    selection.reversed = true;
 6462                });
 6463            });
 6464
 6465            this.select_to_beginning_of_line(
 6466                &SelectToBeginningOfLine {
 6467                    stop_at_soft_wraps: false,
 6468                },
 6469                cx,
 6470            );
 6471            this.backspace(&Backspace, cx);
 6472        });
 6473    }
 6474
 6475    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 6476        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6477            s.move_cursors_with(|map, head, _| {
 6478                (movement::line_end(map, head, true), SelectionGoal::None)
 6479            });
 6480        })
 6481    }
 6482
 6483    pub fn select_to_end_of_line(
 6484        &mut self,
 6485        action: &SelectToEndOfLine,
 6486        cx: &mut ViewContext<Self>,
 6487    ) {
 6488        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6489            s.move_heads_with(|map, head, _| {
 6490                (
 6491                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6492                    SelectionGoal::None,
 6493                )
 6494            });
 6495        })
 6496    }
 6497
 6498    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 6499        self.transact(cx, |this, cx| {
 6500            this.select_to_end_of_line(
 6501                &SelectToEndOfLine {
 6502                    stop_at_soft_wraps: false,
 6503                },
 6504                cx,
 6505            );
 6506            this.delete(&Delete, cx);
 6507        });
 6508    }
 6509
 6510    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 6511        self.transact(cx, |this, cx| {
 6512            this.select_to_end_of_line(
 6513                &SelectToEndOfLine {
 6514                    stop_at_soft_wraps: false,
 6515                },
 6516                cx,
 6517            );
 6518            this.cut(&Cut, cx);
 6519        });
 6520    }
 6521
 6522    pub fn move_to_start_of_paragraph(
 6523        &mut self,
 6524        _: &MoveToStartOfParagraph,
 6525        cx: &mut ViewContext<Self>,
 6526    ) {
 6527        if matches!(self.mode, EditorMode::SingleLine) {
 6528            cx.propagate();
 6529            return;
 6530        }
 6531
 6532        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6533            s.move_with(|map, selection| {
 6534                selection.collapse_to(
 6535                    movement::start_of_paragraph(map, selection.head(), 1),
 6536                    SelectionGoal::None,
 6537                )
 6538            });
 6539        })
 6540    }
 6541
 6542    pub fn move_to_end_of_paragraph(
 6543        &mut self,
 6544        _: &MoveToEndOfParagraph,
 6545        cx: &mut ViewContext<Self>,
 6546    ) {
 6547        if matches!(self.mode, EditorMode::SingleLine) {
 6548            cx.propagate();
 6549            return;
 6550        }
 6551
 6552        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6553            s.move_with(|map, selection| {
 6554                selection.collapse_to(
 6555                    movement::end_of_paragraph(map, selection.head(), 1),
 6556                    SelectionGoal::None,
 6557                )
 6558            });
 6559        })
 6560    }
 6561
 6562    pub fn select_to_start_of_paragraph(
 6563        &mut self,
 6564        _: &SelectToStartOfParagraph,
 6565        cx: &mut ViewContext<Self>,
 6566    ) {
 6567        if matches!(self.mode, EditorMode::SingleLine) {
 6568            cx.propagate();
 6569            return;
 6570        }
 6571
 6572        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6573            s.move_heads_with(|map, head, _| {
 6574                (
 6575                    movement::start_of_paragraph(map, head, 1),
 6576                    SelectionGoal::None,
 6577                )
 6578            });
 6579        })
 6580    }
 6581
 6582    pub fn select_to_end_of_paragraph(
 6583        &mut self,
 6584        _: &SelectToEndOfParagraph,
 6585        cx: &mut ViewContext<Self>,
 6586    ) {
 6587        if matches!(self.mode, EditorMode::SingleLine) {
 6588            cx.propagate();
 6589            return;
 6590        }
 6591
 6592        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6593            s.move_heads_with(|map, head, _| {
 6594                (
 6595                    movement::end_of_paragraph(map, head, 1),
 6596                    SelectionGoal::None,
 6597                )
 6598            });
 6599        })
 6600    }
 6601
 6602    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 6603        if matches!(self.mode, EditorMode::SingleLine) {
 6604            cx.propagate();
 6605            return;
 6606        }
 6607
 6608        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6609            s.select_ranges(vec![0..0]);
 6610        });
 6611    }
 6612
 6613    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 6614        let mut selection = self.selections.last::<Point>(cx);
 6615        selection.set_head(Point::zero(), SelectionGoal::None);
 6616
 6617        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6618            s.select(vec![selection]);
 6619        });
 6620    }
 6621
 6622    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 6623        if matches!(self.mode, EditorMode::SingleLine) {
 6624            cx.propagate();
 6625            return;
 6626        }
 6627
 6628        let cursor = self.buffer.read(cx).read(cx).len();
 6629        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6630            s.select_ranges(vec![cursor..cursor])
 6631        });
 6632    }
 6633
 6634    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 6635        self.nav_history = nav_history;
 6636    }
 6637
 6638    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 6639        self.nav_history.as_ref()
 6640    }
 6641
 6642    fn push_to_nav_history(
 6643        &mut self,
 6644        cursor_anchor: Anchor,
 6645        new_position: Option<Point>,
 6646        cx: &mut ViewContext<Self>,
 6647    ) {
 6648        if let Some(nav_history) = self.nav_history.as_mut() {
 6649            let buffer = self.buffer.read(cx).read(cx);
 6650            let cursor_position = cursor_anchor.to_point(&buffer);
 6651            let scroll_state = self.scroll_manager.anchor();
 6652            let scroll_top_row = scroll_state.top_row(&buffer);
 6653            drop(buffer);
 6654
 6655            if let Some(new_position) = new_position {
 6656                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 6657                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 6658                    return;
 6659                }
 6660            }
 6661
 6662            nav_history.push(
 6663                Some(NavigationData {
 6664                    cursor_anchor,
 6665                    cursor_position,
 6666                    scroll_anchor: scroll_state,
 6667                    scroll_top_row,
 6668                }),
 6669                cx,
 6670            );
 6671        }
 6672    }
 6673
 6674    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 6675        let buffer = self.buffer.read(cx).snapshot(cx);
 6676        let mut selection = self.selections.first::<usize>(cx);
 6677        selection.set_head(buffer.len(), SelectionGoal::None);
 6678        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6679            s.select(vec![selection]);
 6680        });
 6681    }
 6682
 6683    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 6684        let end = self.buffer.read(cx).read(cx).len();
 6685        self.change_selections(None, cx, |s| {
 6686            s.select_ranges(vec![0..end]);
 6687        });
 6688    }
 6689
 6690    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 6691        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6692        let mut selections = self.selections.all::<Point>(cx);
 6693        let max_point = display_map.buffer_snapshot.max_point();
 6694        for selection in &mut selections {
 6695            let rows = selection.spanned_rows(true, &display_map);
 6696            selection.start = Point::new(rows.start, 0);
 6697            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
 6698            selection.reversed = false;
 6699        }
 6700        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6701            s.select(selections);
 6702        });
 6703    }
 6704
 6705    pub fn split_selection_into_lines(
 6706        &mut self,
 6707        _: &SplitSelectionIntoLines,
 6708        cx: &mut ViewContext<Self>,
 6709    ) {
 6710        let mut to_unfold = Vec::new();
 6711        let mut new_selection_ranges = Vec::new();
 6712        {
 6713            let selections = self.selections.all::<Point>(cx);
 6714            let buffer = self.buffer.read(cx).read(cx);
 6715            for selection in selections {
 6716                for row in selection.start.row..selection.end.row {
 6717                    let cursor = Point::new(row, buffer.line_len(row));
 6718                    new_selection_ranges.push(cursor..cursor);
 6719                }
 6720                new_selection_ranges.push(selection.end..selection.end);
 6721                to_unfold.push(selection.start..selection.end);
 6722            }
 6723        }
 6724        self.unfold_ranges(to_unfold, true, true, cx);
 6725        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6726            s.select_ranges(new_selection_ranges);
 6727        });
 6728    }
 6729
 6730    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 6731        self.add_selection(true, cx);
 6732    }
 6733
 6734    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 6735        self.add_selection(false, cx);
 6736    }
 6737
 6738    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 6739        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6740        let mut selections = self.selections.all::<Point>(cx);
 6741        let text_layout_details = self.text_layout_details(cx);
 6742        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 6743            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 6744            let range = oldest_selection.display_range(&display_map).sorted();
 6745
 6746            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 6747            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 6748            let positions = start_x.min(end_x)..start_x.max(end_x);
 6749
 6750            selections.clear();
 6751            let mut stack = Vec::new();
 6752            for row in range.start.row()..=range.end.row() {
 6753                if let Some(selection) = self.selections.build_columnar_selection(
 6754                    &display_map,
 6755                    row,
 6756                    &positions,
 6757                    oldest_selection.reversed,
 6758                    &text_layout_details,
 6759                ) {
 6760                    stack.push(selection.id);
 6761                    selections.push(selection);
 6762                }
 6763            }
 6764
 6765            if above {
 6766                stack.reverse();
 6767            }
 6768
 6769            AddSelectionsState { above, stack }
 6770        });
 6771
 6772        let last_added_selection = *state.stack.last().unwrap();
 6773        let mut new_selections = Vec::new();
 6774        if above == state.above {
 6775            let end_row = if above {
 6776                0
 6777            } else {
 6778                display_map.max_point().row()
 6779            };
 6780
 6781            'outer: for selection in selections {
 6782                if selection.id == last_added_selection {
 6783                    let range = selection.display_range(&display_map).sorted();
 6784                    debug_assert_eq!(range.start.row(), range.end.row());
 6785                    let mut row = range.start.row();
 6786                    let positions =
 6787                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 6788                            px(start)..px(end)
 6789                        } else {
 6790                            let start_x =
 6791                                display_map.x_for_display_point(range.start, &text_layout_details);
 6792                            let end_x =
 6793                                display_map.x_for_display_point(range.end, &text_layout_details);
 6794                            start_x.min(end_x)..start_x.max(end_x)
 6795                        };
 6796
 6797                    while row != end_row {
 6798                        if above {
 6799                            row -= 1;
 6800                        } else {
 6801                            row += 1;
 6802                        }
 6803
 6804                        if let Some(new_selection) = self.selections.build_columnar_selection(
 6805                            &display_map,
 6806                            row,
 6807                            &positions,
 6808                            selection.reversed,
 6809                            &text_layout_details,
 6810                        ) {
 6811                            state.stack.push(new_selection.id);
 6812                            if above {
 6813                                new_selections.push(new_selection);
 6814                                new_selections.push(selection);
 6815                            } else {
 6816                                new_selections.push(selection);
 6817                                new_selections.push(new_selection);
 6818                            }
 6819
 6820                            continue 'outer;
 6821                        }
 6822                    }
 6823                }
 6824
 6825                new_selections.push(selection);
 6826            }
 6827        } else {
 6828            new_selections = selections;
 6829            new_selections.retain(|s| s.id != last_added_selection);
 6830            state.stack.pop();
 6831        }
 6832
 6833        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6834            s.select(new_selections);
 6835        });
 6836        if state.stack.len() > 1 {
 6837            self.add_selections_state = Some(state);
 6838        }
 6839    }
 6840
 6841    pub fn select_next_match_internal(
 6842        &mut self,
 6843        display_map: &DisplaySnapshot,
 6844        replace_newest: bool,
 6845        autoscroll: Option<Autoscroll>,
 6846        cx: &mut ViewContext<Self>,
 6847    ) -> Result<()> {
 6848        fn select_next_match_ranges(
 6849            this: &mut Editor,
 6850            range: Range<usize>,
 6851            replace_newest: bool,
 6852            auto_scroll: Option<Autoscroll>,
 6853            cx: &mut ViewContext<Editor>,
 6854        ) {
 6855            this.unfold_ranges([range.clone()], false, true, cx);
 6856            this.change_selections(auto_scroll, cx, |s| {
 6857                if replace_newest {
 6858                    s.delete(s.newest_anchor().id);
 6859                }
 6860                s.insert_range(range.clone());
 6861            });
 6862        }
 6863
 6864        let buffer = &display_map.buffer_snapshot;
 6865        let mut selections = self.selections.all::<usize>(cx);
 6866        if let Some(mut select_next_state) = self.select_next_state.take() {
 6867            let query = &select_next_state.query;
 6868            if !select_next_state.done {
 6869                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 6870                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 6871                let mut next_selected_range = None;
 6872
 6873                let bytes_after_last_selection =
 6874                    buffer.bytes_in_range(last_selection.end..buffer.len());
 6875                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 6876                let query_matches = query
 6877                    .stream_find_iter(bytes_after_last_selection)
 6878                    .map(|result| (last_selection.end, result))
 6879                    .chain(
 6880                        query
 6881                            .stream_find_iter(bytes_before_first_selection)
 6882                            .map(|result| (0, result)),
 6883                    );
 6884
 6885                for (start_offset, query_match) in query_matches {
 6886                    let query_match = query_match.unwrap(); // can only fail due to I/O
 6887                    let offset_range =
 6888                        start_offset + query_match.start()..start_offset + query_match.end();
 6889                    let display_range = offset_range.start.to_display_point(&display_map)
 6890                        ..offset_range.end.to_display_point(&display_map);
 6891
 6892                    if !select_next_state.wordwise
 6893                        || (!movement::is_inside_word(&display_map, display_range.start)
 6894                            && !movement::is_inside_word(&display_map, display_range.end))
 6895                    {
 6896                        // TODO: This is n^2, because we might check all the selections
 6897                        if !selections
 6898                            .iter()
 6899                            .any(|selection| selection.range().overlaps(&offset_range))
 6900                        {
 6901                            next_selected_range = Some(offset_range);
 6902                            break;
 6903                        }
 6904                    }
 6905                }
 6906
 6907                if let Some(next_selected_range) = next_selected_range {
 6908                    select_next_match_ranges(
 6909                        self,
 6910                        next_selected_range,
 6911                        replace_newest,
 6912                        autoscroll,
 6913                        cx,
 6914                    );
 6915                } else {
 6916                    select_next_state.done = true;
 6917                }
 6918            }
 6919
 6920            self.select_next_state = Some(select_next_state);
 6921        } else {
 6922            let mut only_carets = true;
 6923            let mut same_text_selected = true;
 6924            let mut selected_text = None;
 6925
 6926            let mut selections_iter = selections.iter().peekable();
 6927            while let Some(selection) = selections_iter.next() {
 6928                if selection.start != selection.end {
 6929                    only_carets = false;
 6930                }
 6931
 6932                if same_text_selected {
 6933                    if selected_text.is_none() {
 6934                        selected_text =
 6935                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 6936                    }
 6937
 6938                    if let Some(next_selection) = selections_iter.peek() {
 6939                        if next_selection.range().len() == selection.range().len() {
 6940                            let next_selected_text = buffer
 6941                                .text_for_range(next_selection.range())
 6942                                .collect::<String>();
 6943                            if Some(next_selected_text) != selected_text {
 6944                                same_text_selected = false;
 6945                                selected_text = None;
 6946                            }
 6947                        } else {
 6948                            same_text_selected = false;
 6949                            selected_text = None;
 6950                        }
 6951                    }
 6952                }
 6953            }
 6954
 6955            if only_carets {
 6956                for selection in &mut selections {
 6957                    let word_range = movement::surrounding_word(
 6958                        &display_map,
 6959                        selection.start.to_display_point(&display_map),
 6960                    );
 6961                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 6962                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 6963                    selection.goal = SelectionGoal::None;
 6964                    selection.reversed = false;
 6965                    select_next_match_ranges(
 6966                        self,
 6967                        selection.start..selection.end,
 6968                        replace_newest,
 6969                        autoscroll,
 6970                        cx,
 6971                    );
 6972                }
 6973
 6974                if selections.len() == 1 {
 6975                    let selection = selections
 6976                        .last()
 6977                        .expect("ensured that there's only one selection");
 6978                    let query = buffer
 6979                        .text_for_range(selection.start..selection.end)
 6980                        .collect::<String>();
 6981                    let is_empty = query.is_empty();
 6982                    let select_state = SelectNextState {
 6983                        query: AhoCorasick::new(&[query])?,
 6984                        wordwise: true,
 6985                        done: is_empty,
 6986                    };
 6987                    self.select_next_state = Some(select_state);
 6988                } else {
 6989                    self.select_next_state = None;
 6990                }
 6991            } else if let Some(selected_text) = selected_text {
 6992                self.select_next_state = Some(SelectNextState {
 6993                    query: AhoCorasick::new(&[selected_text])?,
 6994                    wordwise: false,
 6995                    done: false,
 6996                });
 6997                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 6998            }
 6999        }
 7000        Ok(())
 7001    }
 7002
 7003    pub fn select_all_matches(
 7004        &mut self,
 7005        _action: &SelectAllMatches,
 7006        cx: &mut ViewContext<Self>,
 7007    ) -> Result<()> {
 7008        self.push_to_selection_history();
 7009        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7010
 7011        self.select_next_match_internal(&display_map, false, None, cx)?;
 7012        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7013            return Ok(());
 7014        };
 7015        if select_next_state.done {
 7016            return Ok(());
 7017        }
 7018
 7019        let mut new_selections = self.selections.all::<usize>(cx);
 7020
 7021        let buffer = &display_map.buffer_snapshot;
 7022        let query_matches = select_next_state
 7023            .query
 7024            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7025
 7026        for query_match in query_matches {
 7027            let query_match = query_match.unwrap(); // can only fail due to I/O
 7028            let offset_range = query_match.start()..query_match.end();
 7029            let display_range = offset_range.start.to_display_point(&display_map)
 7030                ..offset_range.end.to_display_point(&display_map);
 7031
 7032            if !select_next_state.wordwise
 7033                || (!movement::is_inside_word(&display_map, display_range.start)
 7034                    && !movement::is_inside_word(&display_map, display_range.end))
 7035            {
 7036                self.selections.change_with(cx, |selections| {
 7037                    new_selections.push(Selection {
 7038                        id: selections.new_selection_id(),
 7039                        start: offset_range.start,
 7040                        end: offset_range.end,
 7041                        reversed: false,
 7042                        goal: SelectionGoal::None,
 7043                    });
 7044                });
 7045            }
 7046        }
 7047
 7048        new_selections.sort_by_key(|selection| selection.start);
 7049        let mut ix = 0;
 7050        while ix + 1 < new_selections.len() {
 7051            let current_selection = &new_selections[ix];
 7052            let next_selection = &new_selections[ix + 1];
 7053            if current_selection.range().overlaps(&next_selection.range()) {
 7054                if current_selection.id < next_selection.id {
 7055                    new_selections.remove(ix + 1);
 7056                } else {
 7057                    new_selections.remove(ix);
 7058                }
 7059            } else {
 7060                ix += 1;
 7061            }
 7062        }
 7063
 7064        select_next_state.done = true;
 7065        self.unfold_ranges(
 7066            new_selections.iter().map(|selection| selection.range()),
 7067            false,
 7068            false,
 7069            cx,
 7070        );
 7071        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7072            selections.select(new_selections)
 7073        });
 7074
 7075        Ok(())
 7076    }
 7077
 7078    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7079        self.push_to_selection_history();
 7080        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7081        self.select_next_match_internal(
 7082            &display_map,
 7083            action.replace_newest,
 7084            Some(Autoscroll::newest()),
 7085            cx,
 7086        )?;
 7087        Ok(())
 7088    }
 7089
 7090    pub fn select_previous(
 7091        &mut self,
 7092        action: &SelectPrevious,
 7093        cx: &mut ViewContext<Self>,
 7094    ) -> Result<()> {
 7095        self.push_to_selection_history();
 7096        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7097        let buffer = &display_map.buffer_snapshot;
 7098        let mut selections = self.selections.all::<usize>(cx);
 7099        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7100            let query = &select_prev_state.query;
 7101            if !select_prev_state.done {
 7102                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7103                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7104                let mut next_selected_range = None;
 7105                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7106                let bytes_before_last_selection =
 7107                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7108                let bytes_after_first_selection =
 7109                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7110                let query_matches = query
 7111                    .stream_find_iter(bytes_before_last_selection)
 7112                    .map(|result| (last_selection.start, result))
 7113                    .chain(
 7114                        query
 7115                            .stream_find_iter(bytes_after_first_selection)
 7116                            .map(|result| (buffer.len(), result)),
 7117                    );
 7118                for (end_offset, query_match) in query_matches {
 7119                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7120                    let offset_range =
 7121                        end_offset - query_match.end()..end_offset - query_match.start();
 7122                    let display_range = offset_range.start.to_display_point(&display_map)
 7123                        ..offset_range.end.to_display_point(&display_map);
 7124
 7125                    if !select_prev_state.wordwise
 7126                        || (!movement::is_inside_word(&display_map, display_range.start)
 7127                            && !movement::is_inside_word(&display_map, display_range.end))
 7128                    {
 7129                        next_selected_range = Some(offset_range);
 7130                        break;
 7131                    }
 7132                }
 7133
 7134                if let Some(next_selected_range) = next_selected_range {
 7135                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7136                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7137                        if action.replace_newest {
 7138                            s.delete(s.newest_anchor().id);
 7139                        }
 7140                        s.insert_range(next_selected_range);
 7141                    });
 7142                } else {
 7143                    select_prev_state.done = true;
 7144                }
 7145            }
 7146
 7147            self.select_prev_state = Some(select_prev_state);
 7148        } else {
 7149            let mut only_carets = true;
 7150            let mut same_text_selected = true;
 7151            let mut selected_text = None;
 7152
 7153            let mut selections_iter = selections.iter().peekable();
 7154            while let Some(selection) = selections_iter.next() {
 7155                if selection.start != selection.end {
 7156                    only_carets = false;
 7157                }
 7158
 7159                if same_text_selected {
 7160                    if selected_text.is_none() {
 7161                        selected_text =
 7162                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7163                    }
 7164
 7165                    if let Some(next_selection) = selections_iter.peek() {
 7166                        if next_selection.range().len() == selection.range().len() {
 7167                            let next_selected_text = buffer
 7168                                .text_for_range(next_selection.range())
 7169                                .collect::<String>();
 7170                            if Some(next_selected_text) != selected_text {
 7171                                same_text_selected = false;
 7172                                selected_text = None;
 7173                            }
 7174                        } else {
 7175                            same_text_selected = false;
 7176                            selected_text = None;
 7177                        }
 7178                    }
 7179                }
 7180            }
 7181
 7182            if only_carets {
 7183                for selection in &mut selections {
 7184                    let word_range = movement::surrounding_word(
 7185                        &display_map,
 7186                        selection.start.to_display_point(&display_map),
 7187                    );
 7188                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7189                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7190                    selection.goal = SelectionGoal::None;
 7191                    selection.reversed = false;
 7192                }
 7193                if selections.len() == 1 {
 7194                    let selection = selections
 7195                        .last()
 7196                        .expect("ensured that there's only one selection");
 7197                    let query = buffer
 7198                        .text_for_range(selection.start..selection.end)
 7199                        .collect::<String>();
 7200                    let is_empty = query.is_empty();
 7201                    let select_state = SelectNextState {
 7202                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7203                        wordwise: true,
 7204                        done: is_empty,
 7205                    };
 7206                    self.select_prev_state = Some(select_state);
 7207                } else {
 7208                    self.select_prev_state = None;
 7209                }
 7210
 7211                self.unfold_ranges(
 7212                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7213                    false,
 7214                    true,
 7215                    cx,
 7216                );
 7217                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7218                    s.select(selections);
 7219                });
 7220            } else if let Some(selected_text) = selected_text {
 7221                self.select_prev_state = Some(SelectNextState {
 7222                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7223                    wordwise: false,
 7224                    done: false,
 7225                });
 7226                self.select_previous(action, cx)?;
 7227            }
 7228        }
 7229        Ok(())
 7230    }
 7231
 7232    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7233        let text_layout_details = &self.text_layout_details(cx);
 7234        self.transact(cx, |this, cx| {
 7235            let mut selections = this.selections.all::<Point>(cx);
 7236            let mut edits = Vec::new();
 7237            let mut selection_edit_ranges = Vec::new();
 7238            let mut last_toggled_row = None;
 7239            let snapshot = this.buffer.read(cx).read(cx);
 7240            let empty_str: Arc<str> = "".into();
 7241            let mut suffixes_inserted = Vec::new();
 7242
 7243            fn comment_prefix_range(
 7244                snapshot: &MultiBufferSnapshot,
 7245                row: u32,
 7246                comment_prefix: &str,
 7247                comment_prefix_whitespace: &str,
 7248            ) -> Range<Point> {
 7249                let start = Point::new(row, snapshot.indent_size_for_line(row).len);
 7250
 7251                let mut line_bytes = snapshot
 7252                    .bytes_in_range(start..snapshot.max_point())
 7253                    .flatten()
 7254                    .copied();
 7255
 7256                // If this line currently begins with the line comment prefix, then record
 7257                // the range containing the prefix.
 7258                if line_bytes
 7259                    .by_ref()
 7260                    .take(comment_prefix.len())
 7261                    .eq(comment_prefix.bytes())
 7262                {
 7263                    // Include any whitespace that matches the comment prefix.
 7264                    let matching_whitespace_len = line_bytes
 7265                        .zip(comment_prefix_whitespace.bytes())
 7266                        .take_while(|(a, b)| a == b)
 7267                        .count() as u32;
 7268                    let end = Point::new(
 7269                        start.row,
 7270                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 7271                    );
 7272                    start..end
 7273                } else {
 7274                    start..start
 7275                }
 7276            }
 7277
 7278            fn comment_suffix_range(
 7279                snapshot: &MultiBufferSnapshot,
 7280                row: u32,
 7281                comment_suffix: &str,
 7282                comment_suffix_has_leading_space: bool,
 7283            ) -> Range<Point> {
 7284                let end = Point::new(row, snapshot.line_len(row));
 7285                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 7286
 7287                let mut line_end_bytes = snapshot
 7288                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 7289                    .flatten()
 7290                    .copied();
 7291
 7292                let leading_space_len = if suffix_start_column > 0
 7293                    && line_end_bytes.next() == Some(b' ')
 7294                    && comment_suffix_has_leading_space
 7295                {
 7296                    1
 7297                } else {
 7298                    0
 7299                };
 7300
 7301                // If this line currently begins with the line comment prefix, then record
 7302                // the range containing the prefix.
 7303                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 7304                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 7305                    start..end
 7306                } else {
 7307                    end..end
 7308                }
 7309            }
 7310
 7311            // TODO: Handle selections that cross excerpts
 7312            for selection in &mut selections {
 7313                let start_column = snapshot.indent_size_for_line(selection.start.row).len;
 7314                let language = if let Some(language) =
 7315                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 7316                {
 7317                    language
 7318                } else {
 7319                    continue;
 7320                };
 7321
 7322                selection_edit_ranges.clear();
 7323
 7324                // If multiple selections contain a given row, avoid processing that
 7325                // row more than once.
 7326                let mut start_row = selection.start.row;
 7327                if last_toggled_row == Some(start_row) {
 7328                    start_row += 1;
 7329                }
 7330                let end_row =
 7331                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 7332                        selection.end.row - 1
 7333                    } else {
 7334                        selection.end.row
 7335                    };
 7336                last_toggled_row = Some(end_row);
 7337
 7338                if start_row > end_row {
 7339                    continue;
 7340                }
 7341
 7342                // If the language has line comments, toggle those.
 7343                if let Some(full_comment_prefix) = language
 7344                    .line_comment_prefixes()
 7345                    .and_then(|prefixes| prefixes.first())
 7346                {
 7347                    // Split the comment prefix's trailing whitespace into a separate string,
 7348                    // as that portion won't be used for detecting if a line is a comment.
 7349                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7350                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7351                    let mut all_selection_lines_are_comments = true;
 7352
 7353                    for row in start_row..=end_row {
 7354                        if start_row < end_row && snapshot.is_line_blank(row) {
 7355                            continue;
 7356                        }
 7357
 7358                        let prefix_range = comment_prefix_range(
 7359                            snapshot.deref(),
 7360                            row,
 7361                            comment_prefix,
 7362                            comment_prefix_whitespace,
 7363                        );
 7364                        if prefix_range.is_empty() {
 7365                            all_selection_lines_are_comments = false;
 7366                        }
 7367                        selection_edit_ranges.push(prefix_range);
 7368                    }
 7369
 7370                    if all_selection_lines_are_comments {
 7371                        edits.extend(
 7372                            selection_edit_ranges
 7373                                .iter()
 7374                                .cloned()
 7375                                .map(|range| (range, empty_str.clone())),
 7376                        );
 7377                    } else {
 7378                        let min_column = selection_edit_ranges
 7379                            .iter()
 7380                            .map(|r| r.start.column)
 7381                            .min()
 7382                            .unwrap_or(0);
 7383                        edits.extend(selection_edit_ranges.iter().map(|range| {
 7384                            let position = Point::new(range.start.row, min_column);
 7385                            (position..position, full_comment_prefix.clone())
 7386                        }));
 7387                    }
 7388                } else if let Some((full_comment_prefix, comment_suffix)) =
 7389                    language.block_comment_delimiters()
 7390                {
 7391                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7392                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7393                    let prefix_range = comment_prefix_range(
 7394                        snapshot.deref(),
 7395                        start_row,
 7396                        comment_prefix,
 7397                        comment_prefix_whitespace,
 7398                    );
 7399                    let suffix_range = comment_suffix_range(
 7400                        snapshot.deref(),
 7401                        end_row,
 7402                        comment_suffix.trim_start_matches(' '),
 7403                        comment_suffix.starts_with(' '),
 7404                    );
 7405
 7406                    if prefix_range.is_empty() || suffix_range.is_empty() {
 7407                        edits.push((
 7408                            prefix_range.start..prefix_range.start,
 7409                            full_comment_prefix.clone(),
 7410                        ));
 7411                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 7412                        suffixes_inserted.push((end_row, comment_suffix.len()));
 7413                    } else {
 7414                        edits.push((prefix_range, empty_str.clone()));
 7415                        edits.push((suffix_range, empty_str.clone()));
 7416                    }
 7417                } else {
 7418                    continue;
 7419                }
 7420            }
 7421
 7422            drop(snapshot);
 7423            this.buffer.update(cx, |buffer, cx| {
 7424                buffer.edit(edits, None, cx);
 7425            });
 7426
 7427            // Adjust selections so that they end before any comment suffixes that
 7428            // were inserted.
 7429            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 7430            let mut selections = this.selections.all::<Point>(cx);
 7431            let snapshot = this.buffer.read(cx).read(cx);
 7432            for selection in &mut selections {
 7433                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 7434                    match row.cmp(&selection.end.row) {
 7435                        Ordering::Less => {
 7436                            suffixes_inserted.next();
 7437                            continue;
 7438                        }
 7439                        Ordering::Greater => break,
 7440                        Ordering::Equal => {
 7441                            if selection.end.column == snapshot.line_len(row) {
 7442                                if selection.is_empty() {
 7443                                    selection.start.column -= suffix_len as u32;
 7444                                }
 7445                                selection.end.column -= suffix_len as u32;
 7446                            }
 7447                            break;
 7448                        }
 7449                    }
 7450                }
 7451            }
 7452
 7453            drop(snapshot);
 7454            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7455
 7456            let selections = this.selections.all::<Point>(cx);
 7457            let selections_on_single_row = selections.windows(2).all(|selections| {
 7458                selections[0].start.row == selections[1].start.row
 7459                    && selections[0].end.row == selections[1].end.row
 7460                    && selections[0].start.row == selections[0].end.row
 7461            });
 7462            let selections_selecting = selections
 7463                .iter()
 7464                .any(|selection| selection.start != selection.end);
 7465            let advance_downwards = action.advance_downwards
 7466                && selections_on_single_row
 7467                && !selections_selecting
 7468                && this.mode != EditorMode::SingleLine;
 7469
 7470            if advance_downwards {
 7471                let snapshot = this.buffer.read(cx).snapshot(cx);
 7472
 7473                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7474                    s.move_cursors_with(|display_snapshot, display_point, _| {
 7475                        let mut point = display_point.to_point(display_snapshot);
 7476                        point.row += 1;
 7477                        point = snapshot.clip_point(point, Bias::Left);
 7478                        let display_point = point.to_display_point(display_snapshot);
 7479                        let goal = SelectionGoal::HorizontalPosition(
 7480                            display_snapshot
 7481                                .x_for_display_point(display_point, &text_layout_details)
 7482                                .into(),
 7483                        );
 7484                        (display_point, goal)
 7485                    })
 7486                });
 7487            }
 7488        });
 7489    }
 7490
 7491    pub fn select_larger_syntax_node(
 7492        &mut self,
 7493        _: &SelectLargerSyntaxNode,
 7494        cx: &mut ViewContext<Self>,
 7495    ) {
 7496        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7497        let buffer = self.buffer.read(cx).snapshot(cx);
 7498        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 7499
 7500        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7501        let mut selected_larger_node = false;
 7502        let new_selections = old_selections
 7503            .iter()
 7504            .map(|selection| {
 7505                let old_range = selection.start..selection.end;
 7506                let mut new_range = old_range.clone();
 7507                while let Some(containing_range) =
 7508                    buffer.range_for_syntax_ancestor(new_range.clone())
 7509                {
 7510                    new_range = containing_range;
 7511                    if !display_map.intersects_fold(new_range.start)
 7512                        && !display_map.intersects_fold(new_range.end)
 7513                    {
 7514                        break;
 7515                    }
 7516                }
 7517
 7518                selected_larger_node |= new_range != old_range;
 7519                Selection {
 7520                    id: selection.id,
 7521                    start: new_range.start,
 7522                    end: new_range.end,
 7523                    goal: SelectionGoal::None,
 7524                    reversed: selection.reversed,
 7525                }
 7526            })
 7527            .collect::<Vec<_>>();
 7528
 7529        if selected_larger_node {
 7530            stack.push(old_selections);
 7531            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7532                s.select(new_selections);
 7533            });
 7534        }
 7535        self.select_larger_syntax_node_stack = stack;
 7536    }
 7537
 7538    pub fn select_smaller_syntax_node(
 7539        &mut self,
 7540        _: &SelectSmallerSyntaxNode,
 7541        cx: &mut ViewContext<Self>,
 7542    ) {
 7543        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7544        if let Some(selections) = stack.pop() {
 7545            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7546                s.select(selections.to_vec());
 7547            });
 7548        }
 7549        self.select_larger_syntax_node_stack = stack;
 7550    }
 7551
 7552    pub fn move_to_enclosing_bracket(
 7553        &mut self,
 7554        _: &MoveToEnclosingBracket,
 7555        cx: &mut ViewContext<Self>,
 7556    ) {
 7557        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7558            s.move_offsets_with(|snapshot, selection| {
 7559                let Some(enclosing_bracket_ranges) =
 7560                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 7561                else {
 7562                    return;
 7563                };
 7564
 7565                let mut best_length = usize::MAX;
 7566                let mut best_inside = false;
 7567                let mut best_in_bracket_range = false;
 7568                let mut best_destination = None;
 7569                for (open, close) in enclosing_bracket_ranges {
 7570                    let close = close.to_inclusive();
 7571                    let length = close.end() - open.start;
 7572                    let inside = selection.start >= open.end && selection.end <= *close.start();
 7573                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 7574                        || close.contains(&selection.head());
 7575
 7576                    // If best is next to a bracket and current isn't, skip
 7577                    if !in_bracket_range && best_in_bracket_range {
 7578                        continue;
 7579                    }
 7580
 7581                    // Prefer smaller lengths unless best is inside and current isn't
 7582                    if length > best_length && (best_inside || !inside) {
 7583                        continue;
 7584                    }
 7585
 7586                    best_length = length;
 7587                    best_inside = inside;
 7588                    best_in_bracket_range = in_bracket_range;
 7589                    best_destination = Some(
 7590                        if close.contains(&selection.start) && close.contains(&selection.end) {
 7591                            if inside {
 7592                                open.end
 7593                            } else {
 7594                                open.start
 7595                            }
 7596                        } else {
 7597                            if inside {
 7598                                *close.start()
 7599                            } else {
 7600                                *close.end()
 7601                            }
 7602                        },
 7603                    );
 7604                }
 7605
 7606                if let Some(destination) = best_destination {
 7607                    selection.collapse_to(destination, SelectionGoal::None);
 7608                }
 7609            })
 7610        });
 7611    }
 7612
 7613    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 7614        self.end_selection(cx);
 7615        self.selection_history.mode = SelectionHistoryMode::Undoing;
 7616        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 7617            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7618            self.select_next_state = entry.select_next_state;
 7619            self.select_prev_state = entry.select_prev_state;
 7620            self.add_selections_state = entry.add_selections_state;
 7621            self.request_autoscroll(Autoscroll::newest(), cx);
 7622        }
 7623        self.selection_history.mode = SelectionHistoryMode::Normal;
 7624    }
 7625
 7626    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 7627        self.end_selection(cx);
 7628        self.selection_history.mode = SelectionHistoryMode::Redoing;
 7629        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 7630            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7631            self.select_next_state = entry.select_next_state;
 7632            self.select_prev_state = entry.select_prev_state;
 7633            self.add_selections_state = entry.add_selections_state;
 7634            self.request_autoscroll(Autoscroll::newest(), cx);
 7635        }
 7636        self.selection_history.mode = SelectionHistoryMode::Normal;
 7637    }
 7638
 7639    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 7640        self.go_to_diagnostic_impl(Direction::Next, cx)
 7641    }
 7642
 7643    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 7644        self.go_to_diagnostic_impl(Direction::Prev, cx)
 7645    }
 7646
 7647    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 7648        let buffer = self.buffer.read(cx).snapshot(cx);
 7649        let selection = self.selections.newest::<usize>(cx);
 7650
 7651        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 7652        if direction == Direction::Next {
 7653            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 7654                let (group_id, jump_to) = popover.activation_info();
 7655                if self.activate_diagnostics(group_id, cx) {
 7656                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7657                        let mut new_selection = s.newest_anchor().clone();
 7658                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 7659                        s.select_anchors(vec![new_selection.clone()]);
 7660                    });
 7661                }
 7662                return;
 7663            }
 7664        }
 7665
 7666        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 7667            active_diagnostics
 7668                .primary_range
 7669                .to_offset(&buffer)
 7670                .to_inclusive()
 7671        });
 7672        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 7673            if active_primary_range.contains(&selection.head()) {
 7674                *active_primary_range.end()
 7675            } else {
 7676                selection.head()
 7677            }
 7678        } else {
 7679            selection.head()
 7680        };
 7681
 7682        loop {
 7683            let mut diagnostics = if direction == Direction::Prev {
 7684                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 7685            } else {
 7686                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 7687            };
 7688            let group = diagnostics.find_map(|entry| {
 7689                if entry.diagnostic.is_primary
 7690                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 7691                    && !entry.range.is_empty()
 7692                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
 7693                    && !entry.range.contains(&search_start)
 7694                {
 7695                    Some((entry.range, entry.diagnostic.group_id))
 7696                } else {
 7697                    None
 7698                }
 7699            });
 7700
 7701            if let Some((primary_range, group_id)) = group {
 7702                if self.activate_diagnostics(group_id, cx) {
 7703                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7704                        s.select(vec![Selection {
 7705                            id: selection.id,
 7706                            start: primary_range.start,
 7707                            end: primary_range.start,
 7708                            reversed: false,
 7709                            goal: SelectionGoal::None,
 7710                        }]);
 7711                    });
 7712                }
 7713                break;
 7714            } else {
 7715                // Cycle around to the start of the buffer, potentially moving back to the start of
 7716                // the currently active diagnostic.
 7717                active_primary_range.take();
 7718                if direction == Direction::Prev {
 7719                    if search_start == buffer.len() {
 7720                        break;
 7721                    } else {
 7722                        search_start = buffer.len();
 7723                    }
 7724                } else if search_start == 0 {
 7725                    break;
 7726                } else {
 7727                    search_start = 0;
 7728                }
 7729            }
 7730        }
 7731    }
 7732
 7733    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 7734        let snapshot = self
 7735            .display_map
 7736            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7737        let selection = self.selections.newest::<Point>(cx);
 7738
 7739        if !self.seek_in_direction(
 7740            &snapshot,
 7741            selection.head(),
 7742            false,
 7743            snapshot
 7744                .buffer_snapshot
 7745                .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
 7746            cx,
 7747        ) {
 7748            let wrapped_point = Point::zero();
 7749            self.seek_in_direction(
 7750                &snapshot,
 7751                wrapped_point,
 7752                true,
 7753                snapshot
 7754                    .buffer_snapshot
 7755                    .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
 7756                cx,
 7757            );
 7758        }
 7759    }
 7760
 7761    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 7762        let snapshot = self
 7763            .display_map
 7764            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7765        let selection = self.selections.newest::<Point>(cx);
 7766
 7767        if !self.seek_in_direction(
 7768            &snapshot,
 7769            selection.head(),
 7770            false,
 7771            snapshot
 7772                .buffer_snapshot
 7773                .git_diff_hunks_in_range_rev(0..selection.head().row),
 7774            cx,
 7775        ) {
 7776            let wrapped_point = snapshot.buffer_snapshot.max_point();
 7777            self.seek_in_direction(
 7778                &snapshot,
 7779                wrapped_point,
 7780                true,
 7781                snapshot
 7782                    .buffer_snapshot
 7783                    .git_diff_hunks_in_range_rev(0..wrapped_point.row),
 7784                cx,
 7785            );
 7786        }
 7787    }
 7788
 7789    fn seek_in_direction(
 7790        &mut self,
 7791        snapshot: &DisplaySnapshot,
 7792        initial_point: Point,
 7793        is_wrapped: bool,
 7794        hunks: impl Iterator<Item = DiffHunk<u32>>,
 7795        cx: &mut ViewContext<Editor>,
 7796    ) -> bool {
 7797        let display_point = initial_point.to_display_point(snapshot);
 7798        let mut hunks = hunks
 7799            .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
 7800            .filter(|hunk| {
 7801                if is_wrapped {
 7802                    true
 7803                } else {
 7804                    !hunk.contains_display_row(display_point.row())
 7805                }
 7806            })
 7807            .dedup();
 7808
 7809        if let Some(hunk) = hunks.next() {
 7810            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7811                let row = hunk.start_display_row();
 7812                let point = DisplayPoint::new(row, 0);
 7813                s.select_display_ranges([point..point]);
 7814            });
 7815
 7816            true
 7817        } else {
 7818            false
 7819        }
 7820    }
 7821
 7822    pub fn go_to_definition(
 7823        &mut self,
 7824        _: &GoToDefinition,
 7825        cx: &mut ViewContext<Self>,
 7826    ) -> Task<Result<bool>> {
 7827        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 7828    }
 7829
 7830    pub fn go_to_implementation(
 7831        &mut self,
 7832        _: &GoToImplementation,
 7833        cx: &mut ViewContext<Self>,
 7834    ) -> Task<Result<bool>> {
 7835        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 7836    }
 7837
 7838    pub fn go_to_implementation_split(
 7839        &mut self,
 7840        _: &GoToImplementationSplit,
 7841        cx: &mut ViewContext<Self>,
 7842    ) -> Task<Result<bool>> {
 7843        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 7844    }
 7845
 7846    pub fn go_to_type_definition(
 7847        &mut self,
 7848        _: &GoToTypeDefinition,
 7849        cx: &mut ViewContext<Self>,
 7850    ) -> Task<Result<bool>> {
 7851        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 7852    }
 7853
 7854    pub fn go_to_definition_split(
 7855        &mut self,
 7856        _: &GoToDefinitionSplit,
 7857        cx: &mut ViewContext<Self>,
 7858    ) -> Task<Result<bool>> {
 7859        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 7860    }
 7861
 7862    pub fn go_to_type_definition_split(
 7863        &mut self,
 7864        _: &GoToTypeDefinitionSplit,
 7865        cx: &mut ViewContext<Self>,
 7866    ) -> Task<Result<bool>> {
 7867        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 7868    }
 7869
 7870    fn go_to_definition_of_kind(
 7871        &mut self,
 7872        kind: GotoDefinitionKind,
 7873        split: bool,
 7874        cx: &mut ViewContext<Self>,
 7875    ) -> Task<Result<bool>> {
 7876        let Some(workspace) = self.workspace() else {
 7877            return Task::ready(Ok(false));
 7878        };
 7879        let buffer = self.buffer.read(cx);
 7880        let head = self.selections.newest::<usize>(cx).head();
 7881        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 7882            text_anchor
 7883        } else {
 7884            return Task::ready(Ok(false));
 7885        };
 7886
 7887        let project = workspace.read(cx).project().clone();
 7888        let definitions = project.update(cx, |project, cx| match kind {
 7889            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 7890            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 7891            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 7892        });
 7893
 7894        cx.spawn(|editor, mut cx| async move {
 7895            let definitions = definitions.await?;
 7896            let navigated = editor
 7897                .update(&mut cx, |editor, cx| {
 7898                    editor.navigate_to_hover_links(
 7899                        Some(kind),
 7900                        definitions.into_iter().map(HoverLink::Text).collect(),
 7901                        split,
 7902                        cx,
 7903                    )
 7904                })?
 7905                .await?;
 7906            anyhow::Ok(navigated)
 7907        })
 7908    }
 7909
 7910    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 7911        let position = self.selections.newest_anchor().head();
 7912        let Some((buffer, buffer_position)) =
 7913            self.buffer.read(cx).text_anchor_for_position(position, cx)
 7914        else {
 7915            return;
 7916        };
 7917
 7918        cx.spawn(|editor, mut cx| async move {
 7919            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 7920                editor.update(&mut cx, |_, cx| {
 7921                    cx.open_url(&url);
 7922                })
 7923            } else {
 7924                Ok(())
 7925            }
 7926        })
 7927        .detach();
 7928    }
 7929
 7930    pub(crate) fn navigate_to_hover_links(
 7931        &mut self,
 7932        kind: Option<GotoDefinitionKind>,
 7933        mut definitions: Vec<HoverLink>,
 7934        split: bool,
 7935        cx: &mut ViewContext<Editor>,
 7936    ) -> Task<Result<bool>> {
 7937        // If there is one definition, just open it directly
 7938        if definitions.len() == 1 {
 7939            let definition = definitions.pop().unwrap();
 7940            let target_task = match definition {
 7941                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7942                HoverLink::InlayHint(lsp_location, server_id) => {
 7943                    self.compute_target_location(lsp_location, server_id, cx)
 7944                }
 7945                HoverLink::Url(url) => {
 7946                    cx.open_url(&url);
 7947                    Task::ready(Ok(None))
 7948                }
 7949            };
 7950            cx.spawn(|editor, mut cx| async move {
 7951                let target = target_task.await.context("target resolution task")?;
 7952                if let Some(target) = target {
 7953                    editor.update(&mut cx, |editor, cx| {
 7954                        let Some(workspace) = editor.workspace() else {
 7955                            return false;
 7956                        };
 7957                        let pane = workspace.read(cx).active_pane().clone();
 7958
 7959                        let range = target.range.to_offset(target.buffer.read(cx));
 7960                        let range = editor.range_for_match(&range);
 7961                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 7962                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 7963                                s.select_ranges([range]);
 7964                            });
 7965                        } else {
 7966                            cx.window_context().defer(move |cx| {
 7967                                let target_editor: View<Self> =
 7968                                    workspace.update(cx, |workspace, cx| {
 7969                                        let pane = if split {
 7970                                            workspace.adjacent_pane(cx)
 7971                                        } else {
 7972                                            workspace.active_pane().clone()
 7973                                        };
 7974
 7975                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 7976                                    });
 7977                                target_editor.update(cx, |target_editor, cx| {
 7978                                    // When selecting a definition in a different buffer, disable the nav history
 7979                                    // to avoid creating a history entry at the previous cursor location.
 7980                                    pane.update(cx, |pane, _| pane.disable_history());
 7981                                    target_editor.change_selections(
 7982                                        Some(Autoscroll::focused()),
 7983                                        cx,
 7984                                        |s| {
 7985                                            s.select_ranges([range]);
 7986                                        },
 7987                                    );
 7988                                    pane.update(cx, |pane, _| pane.enable_history());
 7989                                });
 7990                            });
 7991                        }
 7992                        true
 7993                    })
 7994                } else {
 7995                    Ok(false)
 7996                }
 7997            })
 7998        } else if !definitions.is_empty() {
 7999            let replica_id = self.replica_id(cx);
 8000            cx.spawn(|editor, mut cx| async move {
 8001                let (title, location_tasks, workspace) = editor
 8002                    .update(&mut cx, |editor, cx| {
 8003                        let tab_kind = match kind {
 8004                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 8005                            _ => "Definitions",
 8006                        };
 8007                        let title = definitions
 8008                            .iter()
 8009                            .find_map(|definition| match definition {
 8010                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 8011                                    let buffer = origin.buffer.read(cx);
 8012                                    format!(
 8013                                        "{} for {}",
 8014                                        tab_kind,
 8015                                        buffer
 8016                                            .text_for_range(origin.range.clone())
 8017                                            .collect::<String>()
 8018                                    )
 8019                                }),
 8020                                HoverLink::InlayHint(_, _) => None,
 8021                                HoverLink::Url(_) => None,
 8022                            })
 8023                            .unwrap_or(tab_kind.to_string());
 8024                        let location_tasks = definitions
 8025                            .into_iter()
 8026                            .map(|definition| match definition {
 8027                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8028                                HoverLink::InlayHint(lsp_location, server_id) => {
 8029                                    editor.compute_target_location(lsp_location, server_id, cx)
 8030                                }
 8031                                HoverLink::Url(_) => Task::ready(Ok(None)),
 8032                            })
 8033                            .collect::<Vec<_>>();
 8034                        (title, location_tasks, editor.workspace().clone())
 8035                    })
 8036                    .context("location tasks preparation")?;
 8037
 8038                let locations = futures::future::join_all(location_tasks)
 8039                    .await
 8040                    .into_iter()
 8041                    .filter_map(|location| location.transpose())
 8042                    .collect::<Result<_>>()
 8043                    .context("location tasks")?;
 8044
 8045                let Some(workspace) = workspace else {
 8046                    return Ok(false);
 8047                };
 8048                let opened = workspace
 8049                    .update(&mut cx, |workspace, cx| {
 8050                        Self::open_locations_in_multibuffer(
 8051                            workspace, locations, replica_id, title, split, cx,
 8052                        )
 8053                    })
 8054                    .ok();
 8055
 8056                anyhow::Ok(opened.is_some())
 8057            })
 8058        } else {
 8059            Task::ready(Ok(false))
 8060        }
 8061    }
 8062
 8063    fn compute_target_location(
 8064        &self,
 8065        lsp_location: lsp::Location,
 8066        server_id: LanguageServerId,
 8067        cx: &mut ViewContext<Editor>,
 8068    ) -> Task<anyhow::Result<Option<Location>>> {
 8069        let Some(project) = self.project.clone() else {
 8070            return Task::Ready(Some(Ok(None)));
 8071        };
 8072
 8073        cx.spawn(move |editor, mut cx| async move {
 8074            let location_task = editor.update(&mut cx, |editor, cx| {
 8075                project.update(cx, |project, cx| {
 8076                    let language_server_name =
 8077                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 8078                            project
 8079                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 8080                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 8081                        });
 8082                    language_server_name.map(|language_server_name| {
 8083                        project.open_local_buffer_via_lsp(
 8084                            lsp_location.uri.clone(),
 8085                            server_id,
 8086                            language_server_name,
 8087                            cx,
 8088                        )
 8089                    })
 8090                })
 8091            })?;
 8092            let location = match location_task {
 8093                Some(task) => Some({
 8094                    let target_buffer_handle = task.await.context("open local buffer")?;
 8095                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 8096                        let target_start = target_buffer
 8097                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 8098                        let target_end = target_buffer
 8099                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 8100                        target_buffer.anchor_after(target_start)
 8101                            ..target_buffer.anchor_before(target_end)
 8102                    })?;
 8103                    Location {
 8104                        buffer: target_buffer_handle,
 8105                        range,
 8106                    }
 8107                }),
 8108                None => None,
 8109            };
 8110            Ok(location)
 8111        })
 8112    }
 8113
 8114    pub fn find_all_references(
 8115        &mut self,
 8116        _: &FindAllReferences,
 8117        cx: &mut ViewContext<Self>,
 8118    ) -> Option<Task<Result<()>>> {
 8119        let multi_buffer = self.buffer.read(cx);
 8120        let selection = self.selections.newest::<usize>(cx);
 8121        let head = selection.head();
 8122
 8123        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 8124        let head_anchor = multi_buffer_snapshot.anchor_at(
 8125            head,
 8126            if head < selection.tail() {
 8127                Bias::Right
 8128            } else {
 8129                Bias::Left
 8130            },
 8131        );
 8132        match self
 8133            .find_all_references_task_sources
 8134            .binary_search_by(|task_anchor| task_anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 8135        {
 8136            Ok(_) => {
 8137                log::info!(
 8138                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 8139                );
 8140                return None;
 8141            }
 8142            Err(i) => {
 8143                self.find_all_references_task_sources.insert(i, head_anchor);
 8144            }
 8145        }
 8146
 8147        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 8148        let replica_id = self.replica_id(cx);
 8149        let workspace = self.workspace()?;
 8150        let project = workspace.read(cx).project().clone();
 8151        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 8152        let open_task = cx.spawn(|editor, mut cx| async move {
 8153            let mut locations = references.await?;
 8154            let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
 8155            let head_offset = text::ToOffset::to_offset(&head, &snapshot);
 8156
 8157            // LSP may return references that contain the item itself we requested `find_all_references` for (eg. rust-analyzer)
 8158            // So we will remove it from locations
 8159            // If there is only one reference, we will not do this filter cause it may make locations empty
 8160            if locations.len() > 1 {
 8161                cx.update(|cx| {
 8162                    locations.retain(|location| {
 8163                        // fn foo(x : i64) {
 8164                        //         ^
 8165                        //  println!(x);
 8166                        // }
 8167                        // It is ok to find reference when caret being at ^ (the end of the word)
 8168                        // So we turn offset into inclusive to include the end of the word
 8169                        !location
 8170                            .range
 8171                            .to_offset(location.buffer.read(cx))
 8172                            .to_inclusive()
 8173                            .contains(&head_offset)
 8174                    });
 8175                })?;
 8176            }
 8177
 8178            if locations.is_empty() {
 8179                return Ok(());
 8180            }
 8181
 8182            // If there is one reference, just open it directly
 8183            if locations.len() == 1 {
 8184                let target = locations.pop().unwrap();
 8185
 8186                return editor.update(&mut cx, |editor, cx| {
 8187                    let range = target.range.to_offset(target.buffer.read(cx));
 8188                    let range = editor.range_for_match(&range);
 8189
 8190                    if Some(&target.buffer) == editor.buffer().read(cx).as_singleton().as_ref() {
 8191                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8192                            s.select_ranges([range]);
 8193                        });
 8194                    } else {
 8195                        cx.window_context().defer(move |cx| {
 8196                            let target_editor: View<Self> =
 8197                                workspace.update(cx, |workspace, cx| {
 8198                                    workspace.open_project_item(
 8199                                        workspace.active_pane().clone(),
 8200                                        target.buffer.clone(),
 8201                                        cx,
 8202                                    )
 8203                                });
 8204                            target_editor.update(cx, |target_editor, cx| {
 8205                                target_editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8206                                    s.select_ranges([range]);
 8207                                })
 8208                            })
 8209                        })
 8210                    }
 8211                });
 8212            }
 8213
 8214            workspace.update(&mut cx, |workspace, cx| {
 8215                let title = locations
 8216                    .first()
 8217                    .as_ref()
 8218                    .map(|location| {
 8219                        let buffer = location.buffer.read(cx);
 8220                        format!(
 8221                            "References to `{}`",
 8222                            buffer
 8223                                .text_for_range(location.range.clone())
 8224                                .collect::<String>()
 8225                        )
 8226                    })
 8227                    .unwrap();
 8228                Self::open_locations_in_multibuffer(
 8229                    workspace, locations, replica_id, title, false, cx,
 8230                );
 8231            })?;
 8232
 8233            Ok(())
 8234        });
 8235        Some(cx.spawn(|editor, mut cx| async move {
 8236            open_task.await?;
 8237            editor.update(&mut cx, |editor, _| {
 8238                if let Ok(i) =
 8239                    editor
 8240                        .find_all_references_task_sources
 8241                        .binary_search_by(|task_anchor| {
 8242                            task_anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 8243                        })
 8244                {
 8245                    editor.find_all_references_task_sources.remove(i);
 8246                }
 8247            })?;
 8248            anyhow::Ok(())
 8249        }))
 8250    }
 8251
 8252    /// Opens a multibuffer with the given project locations in it
 8253    pub fn open_locations_in_multibuffer(
 8254        workspace: &mut Workspace,
 8255        mut locations: Vec<Location>,
 8256        replica_id: ReplicaId,
 8257        title: String,
 8258        split: bool,
 8259        cx: &mut ViewContext<Workspace>,
 8260    ) {
 8261        // If there are multiple definitions, open them in a multibuffer
 8262        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 8263        let mut locations = locations.into_iter().peekable();
 8264        let mut ranges_to_highlight = Vec::new();
 8265        let capability = workspace.project().read(cx).capability();
 8266
 8267        let excerpt_buffer = cx.new_model(|cx| {
 8268            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 8269            while let Some(location) = locations.next() {
 8270                let buffer = location.buffer.read(cx);
 8271                let mut ranges_for_buffer = Vec::new();
 8272                let range = location.range.to_offset(buffer);
 8273                ranges_for_buffer.push(range.clone());
 8274
 8275                while let Some(next_location) = locations.peek() {
 8276                    if next_location.buffer == location.buffer {
 8277                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 8278                        locations.next();
 8279                    } else {
 8280                        break;
 8281                    }
 8282                }
 8283
 8284                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 8285                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 8286                    location.buffer.clone(),
 8287                    ranges_for_buffer,
 8288                    1,
 8289                    cx,
 8290                ))
 8291            }
 8292
 8293            multibuffer.with_title(title)
 8294        });
 8295
 8296        let editor = cx.new_view(|cx| {
 8297            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
 8298        });
 8299        editor.update(cx, |editor, cx| {
 8300            editor.highlight_background::<Self>(
 8301                ranges_to_highlight,
 8302                |theme| theme.editor_highlighted_line_background,
 8303                cx,
 8304            );
 8305        });
 8306        if split {
 8307            workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
 8308        } else {
 8309            workspace.add_item_to_active_pane(Box::new(editor), cx);
 8310        }
 8311    }
 8312
 8313    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8314        use language::ToOffset as _;
 8315
 8316        let project = self.project.clone()?;
 8317        let selection = self.selections.newest_anchor().clone();
 8318        let (cursor_buffer, cursor_buffer_position) = self
 8319            .buffer
 8320            .read(cx)
 8321            .text_anchor_for_position(selection.head(), cx)?;
 8322        let (tail_buffer, _) = self
 8323            .buffer
 8324            .read(cx)
 8325            .text_anchor_for_position(selection.tail(), cx)?;
 8326        if tail_buffer != cursor_buffer {
 8327            return None;
 8328        }
 8329
 8330        let snapshot = cursor_buffer.read(cx).snapshot();
 8331        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 8332        let prepare_rename = project.update(cx, |project, cx| {
 8333            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 8334        });
 8335        drop(snapshot);
 8336
 8337        Some(cx.spawn(|this, mut cx| async move {
 8338            let rename_range = if let Some(range) = prepare_rename.await? {
 8339                Some(range)
 8340            } else {
 8341                this.update(&mut cx, |this, cx| {
 8342                    let buffer = this.buffer.read(cx).snapshot(cx);
 8343                    let mut buffer_highlights = this
 8344                        .document_highlights_for_position(selection.head(), &buffer)
 8345                        .filter(|highlight| {
 8346                            highlight.start.excerpt_id == selection.head().excerpt_id
 8347                                && highlight.end.excerpt_id == selection.head().excerpt_id
 8348                        });
 8349                    buffer_highlights
 8350                        .next()
 8351                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 8352                })?
 8353            };
 8354            if let Some(rename_range) = rename_range {
 8355                this.update(&mut cx, |this, cx| {
 8356                    let snapshot = cursor_buffer.read(cx).snapshot();
 8357                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 8358                    let cursor_offset_in_rename_range =
 8359                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 8360
 8361                    this.take_rename(false, cx);
 8362                    let buffer = this.buffer.read(cx).read(cx);
 8363                    let cursor_offset = selection.head().to_offset(&buffer);
 8364                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 8365                    let rename_end = rename_start + rename_buffer_range.len();
 8366                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 8367                    let mut old_highlight_id = None;
 8368                    let old_name: Arc<str> = buffer
 8369                        .chunks(rename_start..rename_end, true)
 8370                        .map(|chunk| {
 8371                            if old_highlight_id.is_none() {
 8372                                old_highlight_id = chunk.syntax_highlight_id;
 8373                            }
 8374                            chunk.text
 8375                        })
 8376                        .collect::<String>()
 8377                        .into();
 8378
 8379                    drop(buffer);
 8380
 8381                    // Position the selection in the rename editor so that it matches the current selection.
 8382                    this.show_local_selections = false;
 8383                    let rename_editor = cx.new_view(|cx| {
 8384                        let mut editor = Editor::single_line(cx);
 8385                        editor.buffer.update(cx, |buffer, cx| {
 8386                            buffer.edit([(0..0, old_name.clone())], None, cx)
 8387                        });
 8388                        editor.select_all(&SelectAll, cx);
 8389                        editor
 8390                    });
 8391
 8392                    let ranges = this
 8393                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
 8394                        .into_iter()
 8395                        .flat_map(|(_, ranges)| ranges.into_iter())
 8396                        .chain(
 8397                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
 8398                                .into_iter()
 8399                                .flat_map(|(_, ranges)| ranges.into_iter()),
 8400                        )
 8401                        .collect();
 8402
 8403                    this.highlight_text::<Rename>(
 8404                        ranges,
 8405                        HighlightStyle {
 8406                            fade_out: Some(0.6),
 8407                            ..Default::default()
 8408                        },
 8409                        cx,
 8410                    );
 8411                    let rename_focus_handle = rename_editor.focus_handle(cx);
 8412                    cx.focus(&rename_focus_handle);
 8413                    let block_id = this.insert_blocks(
 8414                        [BlockProperties {
 8415                            style: BlockStyle::Flex,
 8416                            position: range.start,
 8417                            height: 1,
 8418                            render: Arc::new({
 8419                                let rename_editor = rename_editor.clone();
 8420                                move |cx: &mut BlockContext| {
 8421                                    let mut text_style = cx.editor_style.text.clone();
 8422                                    if let Some(highlight_style) = old_highlight_id
 8423                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 8424                                    {
 8425                                        text_style = text_style.highlight(highlight_style);
 8426                                    }
 8427                                    div()
 8428                                        .pl(cx.anchor_x)
 8429                                        .child(EditorElement::new(
 8430                                            &rename_editor,
 8431                                            EditorStyle {
 8432                                                background: cx.theme().system().transparent,
 8433                                                local_player: cx.editor_style.local_player,
 8434                                                text: text_style,
 8435                                                scrollbar_width: cx.editor_style.scrollbar_width,
 8436                                                syntax: cx.editor_style.syntax.clone(),
 8437                                                status: cx.editor_style.status.clone(),
 8438                                                inlay_hints_style: HighlightStyle {
 8439                                                    color: Some(cx.theme().status().hint),
 8440                                                    font_weight: Some(FontWeight::BOLD),
 8441                                                    ..HighlightStyle::default()
 8442                                                },
 8443                                                suggestions_style: HighlightStyle {
 8444                                                    color: Some(cx.theme().status().predictive),
 8445                                                    ..HighlightStyle::default()
 8446                                                },
 8447                                            },
 8448                                        ))
 8449                                        .into_any_element()
 8450                                }
 8451                            }),
 8452                            disposition: BlockDisposition::Below,
 8453                        }],
 8454                        Some(Autoscroll::fit()),
 8455                        cx,
 8456                    )[0];
 8457                    this.pending_rename = Some(RenameState {
 8458                        range,
 8459                        old_name,
 8460                        editor: rename_editor,
 8461                        block_id,
 8462                    });
 8463                })?;
 8464            }
 8465
 8466            Ok(())
 8467        }))
 8468    }
 8469
 8470    pub fn confirm_rename(
 8471        &mut self,
 8472        _: &ConfirmRename,
 8473        cx: &mut ViewContext<Self>,
 8474    ) -> Option<Task<Result<()>>> {
 8475        let rename = self.take_rename(false, cx)?;
 8476        let workspace = self.workspace()?;
 8477        let (start_buffer, start) = self
 8478            .buffer
 8479            .read(cx)
 8480            .text_anchor_for_position(rename.range.start, cx)?;
 8481        let (end_buffer, end) = self
 8482            .buffer
 8483            .read(cx)
 8484            .text_anchor_for_position(rename.range.end, cx)?;
 8485        if start_buffer != end_buffer {
 8486            return None;
 8487        }
 8488
 8489        let buffer = start_buffer;
 8490        let range = start..end;
 8491        let old_name = rename.old_name;
 8492        let new_name = rename.editor.read(cx).text(cx);
 8493
 8494        let rename = workspace
 8495            .read(cx)
 8496            .project()
 8497            .clone()
 8498            .update(cx, |project, cx| {
 8499                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 8500            });
 8501        let workspace = workspace.downgrade();
 8502
 8503        Some(cx.spawn(|editor, mut cx| async move {
 8504            let project_transaction = rename.await?;
 8505            Self::open_project_transaction(
 8506                &editor,
 8507                workspace,
 8508                project_transaction,
 8509                format!("Rename: {}{}", old_name, new_name),
 8510                cx.clone(),
 8511            )
 8512            .await?;
 8513
 8514            editor.update(&mut cx, |editor, cx| {
 8515                editor.refresh_document_highlights(cx);
 8516            })?;
 8517            Ok(())
 8518        }))
 8519    }
 8520
 8521    fn take_rename(
 8522        &mut self,
 8523        moving_cursor: bool,
 8524        cx: &mut ViewContext<Self>,
 8525    ) -> Option<RenameState> {
 8526        let rename = self.pending_rename.take()?;
 8527        if rename.editor.focus_handle(cx).is_focused(cx) {
 8528            cx.focus(&self.focus_handle);
 8529        }
 8530
 8531        self.remove_blocks(
 8532            [rename.block_id].into_iter().collect(),
 8533            Some(Autoscroll::fit()),
 8534            cx,
 8535        );
 8536        self.clear_highlights::<Rename>(cx);
 8537        self.show_local_selections = true;
 8538
 8539        if moving_cursor {
 8540            let rename_editor = rename.editor.read(cx);
 8541            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 8542
 8543            // Update the selection to match the position of the selection inside
 8544            // the rename editor.
 8545            let snapshot = self.buffer.read(cx).read(cx);
 8546            let rename_range = rename.range.to_offset(&snapshot);
 8547            let cursor_in_editor = snapshot
 8548                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 8549                .min(rename_range.end);
 8550            drop(snapshot);
 8551
 8552            self.change_selections(None, cx, |s| {
 8553                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 8554            });
 8555        } else {
 8556            self.refresh_document_highlights(cx);
 8557        }
 8558
 8559        Some(rename)
 8560    }
 8561
 8562    pub fn pending_rename(&self) -> Option<&RenameState> {
 8563        self.pending_rename.as_ref()
 8564    }
 8565
 8566    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8567        let project = match &self.project {
 8568            Some(project) => project.clone(),
 8569            None => return None,
 8570        };
 8571
 8572        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 8573    }
 8574
 8575    fn perform_format(
 8576        &mut self,
 8577        project: Model<Project>,
 8578        trigger: FormatTrigger,
 8579        cx: &mut ViewContext<Self>,
 8580    ) -> Task<Result<()>> {
 8581        let buffer = self.buffer().clone();
 8582        let mut buffers = buffer.read(cx).all_buffers();
 8583        if trigger == FormatTrigger::Save {
 8584            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 8585        }
 8586
 8587        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 8588        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 8589
 8590        cx.spawn(|_, mut cx| async move {
 8591            let transaction = futures::select_biased! {
 8592                () = timeout => {
 8593                    log::warn!("timed out waiting for formatting");
 8594                    None
 8595                }
 8596                transaction = format.log_err().fuse() => transaction,
 8597            };
 8598
 8599            buffer
 8600                .update(&mut cx, |buffer, cx| {
 8601                    if let Some(transaction) = transaction {
 8602                        if !buffer.is_singleton() {
 8603                            buffer.push_transaction(&transaction.0, cx);
 8604                        }
 8605                    }
 8606
 8607                    cx.notify();
 8608                })
 8609                .ok();
 8610
 8611            Ok(())
 8612        })
 8613    }
 8614
 8615    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 8616        if let Some(project) = self.project.clone() {
 8617            self.buffer.update(cx, |multi_buffer, cx| {
 8618                project.update(cx, |project, cx| {
 8619                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 8620                });
 8621            })
 8622        }
 8623    }
 8624
 8625    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 8626        cx.show_character_palette();
 8627    }
 8628
 8629    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 8630        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 8631            let buffer = self.buffer.read(cx).snapshot(cx);
 8632            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 8633            let is_valid = buffer
 8634                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 8635                .any(|entry| {
 8636                    entry.diagnostic.is_primary
 8637                        && !entry.range.is_empty()
 8638                        && entry.range.start == primary_range_start
 8639                        && entry.diagnostic.message == active_diagnostics.primary_message
 8640                });
 8641
 8642            if is_valid != active_diagnostics.is_valid {
 8643                active_diagnostics.is_valid = is_valid;
 8644                let mut new_styles = HashMap::default();
 8645                for (block_id, diagnostic) in &active_diagnostics.blocks {
 8646                    new_styles.insert(
 8647                        *block_id,
 8648                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
 8649                    );
 8650                }
 8651                self.display_map
 8652                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
 8653            }
 8654        }
 8655    }
 8656
 8657    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 8658        self.dismiss_diagnostics(cx);
 8659        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 8660            let buffer = self.buffer.read(cx).snapshot(cx);
 8661
 8662            let mut primary_range = None;
 8663            let mut primary_message = None;
 8664            let mut group_end = Point::zero();
 8665            let diagnostic_group = buffer
 8666                .diagnostic_group::<Point>(group_id)
 8667                .map(|entry| {
 8668                    if entry.range.end > group_end {
 8669                        group_end = entry.range.end;
 8670                    }
 8671                    if entry.diagnostic.is_primary {
 8672                        primary_range = Some(entry.range.clone());
 8673                        primary_message = Some(entry.diagnostic.message.clone());
 8674                    }
 8675                    entry
 8676                })
 8677                .collect::<Vec<_>>();
 8678            let primary_range = primary_range?;
 8679            let primary_message = primary_message?;
 8680            let primary_range =
 8681                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 8682
 8683            let blocks = display_map
 8684                .insert_blocks(
 8685                    diagnostic_group.iter().map(|entry| {
 8686                        let diagnostic = entry.diagnostic.clone();
 8687                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 8688                        BlockProperties {
 8689                            style: BlockStyle::Fixed,
 8690                            position: buffer.anchor_after(entry.range.start),
 8691                            height: message_height,
 8692                            render: diagnostic_block_renderer(diagnostic, true),
 8693                            disposition: BlockDisposition::Below,
 8694                        }
 8695                    }),
 8696                    cx,
 8697                )
 8698                .into_iter()
 8699                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 8700                .collect();
 8701
 8702            Some(ActiveDiagnosticGroup {
 8703                primary_range,
 8704                primary_message,
 8705                blocks,
 8706                is_valid: true,
 8707            })
 8708        });
 8709        self.active_diagnostics.is_some()
 8710    }
 8711
 8712    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 8713        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 8714            self.display_map.update(cx, |display_map, cx| {
 8715                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 8716            });
 8717            cx.notify();
 8718        }
 8719    }
 8720
 8721    pub fn set_selections_from_remote(
 8722        &mut self,
 8723        selections: Vec<Selection<Anchor>>,
 8724        pending_selection: Option<Selection<Anchor>>,
 8725        cx: &mut ViewContext<Self>,
 8726    ) {
 8727        let old_cursor_position = self.selections.newest_anchor().head();
 8728        self.selections.change_with(cx, |s| {
 8729            s.select_anchors(selections);
 8730            if let Some(pending_selection) = pending_selection {
 8731                s.set_pending(pending_selection, SelectMode::Character);
 8732            } else {
 8733                s.clear_pending();
 8734            }
 8735        });
 8736        self.selections_did_change(false, &old_cursor_position, cx);
 8737    }
 8738
 8739    fn push_to_selection_history(&mut self) {
 8740        self.selection_history.push(SelectionHistoryEntry {
 8741            selections: self.selections.disjoint_anchors(),
 8742            select_next_state: self.select_next_state.clone(),
 8743            select_prev_state: self.select_prev_state.clone(),
 8744            add_selections_state: self.add_selections_state.clone(),
 8745        });
 8746    }
 8747
 8748    pub fn transact(
 8749        &mut self,
 8750        cx: &mut ViewContext<Self>,
 8751        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 8752    ) -> Option<TransactionId> {
 8753        self.start_transaction_at(Instant::now(), cx);
 8754        update(self, cx);
 8755        self.end_transaction_at(Instant::now(), cx)
 8756    }
 8757
 8758    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 8759        self.end_selection(cx);
 8760        if let Some(tx_id) = self
 8761            .buffer
 8762            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 8763        {
 8764            self.selection_history
 8765                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 8766            cx.emit(EditorEvent::TransactionBegun {
 8767                transaction_id: tx_id,
 8768            })
 8769        }
 8770    }
 8771
 8772    fn end_transaction_at(
 8773        &mut self,
 8774        now: Instant,
 8775        cx: &mut ViewContext<Self>,
 8776    ) -> Option<TransactionId> {
 8777        if let Some(tx_id) = self
 8778            .buffer
 8779            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 8780        {
 8781            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 8782                *end_selections = Some(self.selections.disjoint_anchors());
 8783            } else {
 8784                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 8785            }
 8786
 8787            cx.emit(EditorEvent::Edited);
 8788            Some(tx_id)
 8789        } else {
 8790            None
 8791        }
 8792    }
 8793
 8794    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 8795        let mut fold_ranges = Vec::new();
 8796
 8797        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8798
 8799        let selections = self.selections.all_adjusted(cx);
 8800        for selection in selections {
 8801            let range = selection.range().sorted();
 8802            let buffer_start_row = range.start.row;
 8803
 8804            for row in (0..=range.end.row).rev() {
 8805                let fold_range = display_map.foldable_range(row);
 8806
 8807                if let Some(fold_range) = fold_range {
 8808                    if fold_range.end.row >= buffer_start_row {
 8809                        fold_ranges.push(fold_range);
 8810                        if row <= range.start.row {
 8811                            break;
 8812                        }
 8813                    }
 8814                }
 8815            }
 8816        }
 8817
 8818        self.fold_ranges(fold_ranges, true, cx);
 8819    }
 8820
 8821    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 8822        let buffer_row = fold_at.buffer_row;
 8823        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8824
 8825        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
 8826            let autoscroll = self
 8827                .selections
 8828                .all::<Point>(cx)
 8829                .iter()
 8830                .any(|selection| fold_range.overlaps(&selection.range()));
 8831
 8832            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
 8833        }
 8834    }
 8835
 8836    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 8837        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8838        let buffer = &display_map.buffer_snapshot;
 8839        let selections = self.selections.all::<Point>(cx);
 8840        let ranges = selections
 8841            .iter()
 8842            .map(|s| {
 8843                let range = s.display_range(&display_map).sorted();
 8844                let mut start = range.start.to_point(&display_map);
 8845                let mut end = range.end.to_point(&display_map);
 8846                start.column = 0;
 8847                end.column = buffer.line_len(end.row);
 8848                start..end
 8849            })
 8850            .collect::<Vec<_>>();
 8851
 8852        self.unfold_ranges(ranges, true, true, cx);
 8853    }
 8854
 8855    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 8856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8857
 8858        let intersection_range = Point::new(unfold_at.buffer_row, 0)
 8859            ..Point::new(
 8860                unfold_at.buffer_row,
 8861                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 8862            );
 8863
 8864        let autoscroll = self
 8865            .selections
 8866            .all::<Point>(cx)
 8867            .iter()
 8868            .any(|selection| selection.range().overlaps(&intersection_range));
 8869
 8870        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 8871    }
 8872
 8873    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 8874        let selections = self.selections.all::<Point>(cx);
 8875        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8876        let line_mode = self.selections.line_mode;
 8877        let ranges = selections.into_iter().map(|s| {
 8878            if line_mode {
 8879                let start = Point::new(s.start.row, 0);
 8880                let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
 8881                start..end
 8882            } else {
 8883                s.start..s.end
 8884            }
 8885        });
 8886        self.fold_ranges(ranges, true, cx);
 8887    }
 8888
 8889    pub fn fold_ranges<T: ToOffset + Clone>(
 8890        &mut self,
 8891        ranges: impl IntoIterator<Item = Range<T>>,
 8892        auto_scroll: bool,
 8893        cx: &mut ViewContext<Self>,
 8894    ) {
 8895        let mut ranges = ranges.into_iter().peekable();
 8896        if ranges.peek().is_some() {
 8897            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 8898
 8899            if auto_scroll {
 8900                self.request_autoscroll(Autoscroll::fit(), cx);
 8901            }
 8902
 8903            cx.notify();
 8904        }
 8905    }
 8906
 8907    pub fn unfold_ranges<T: ToOffset + Clone>(
 8908        &mut self,
 8909        ranges: impl IntoIterator<Item = Range<T>>,
 8910        inclusive: bool,
 8911        auto_scroll: bool,
 8912        cx: &mut ViewContext<Self>,
 8913    ) {
 8914        let mut ranges = ranges.into_iter().peekable();
 8915        if ranges.peek().is_some() {
 8916            self.display_map
 8917                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 8918            if auto_scroll {
 8919                self.request_autoscroll(Autoscroll::fit(), cx);
 8920            }
 8921
 8922            cx.notify();
 8923        }
 8924    }
 8925
 8926    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 8927        if hovered != self.gutter_hovered {
 8928            self.gutter_hovered = hovered;
 8929            cx.notify();
 8930        }
 8931    }
 8932
 8933    pub fn insert_blocks(
 8934        &mut self,
 8935        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 8936        autoscroll: Option<Autoscroll>,
 8937        cx: &mut ViewContext<Self>,
 8938    ) -> Vec<BlockId> {
 8939        let blocks = self
 8940            .display_map
 8941            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 8942        if let Some(autoscroll) = autoscroll {
 8943            self.request_autoscroll(autoscroll, cx);
 8944        }
 8945        blocks
 8946    }
 8947
 8948    pub fn replace_blocks(
 8949        &mut self,
 8950        blocks: HashMap<BlockId, RenderBlock>,
 8951        autoscroll: Option<Autoscroll>,
 8952        cx: &mut ViewContext<Self>,
 8953    ) {
 8954        self.display_map
 8955            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
 8956        if let Some(autoscroll) = autoscroll {
 8957            self.request_autoscroll(autoscroll, cx);
 8958        }
 8959    }
 8960
 8961    pub fn remove_blocks(
 8962        &mut self,
 8963        block_ids: HashSet<BlockId>,
 8964        autoscroll: Option<Autoscroll>,
 8965        cx: &mut ViewContext<Self>,
 8966    ) {
 8967        self.display_map.update(cx, |display_map, cx| {
 8968            display_map.remove_blocks(block_ids, cx)
 8969        });
 8970        if let Some(autoscroll) = autoscroll {
 8971            self.request_autoscroll(autoscroll, cx);
 8972        }
 8973    }
 8974
 8975    pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
 8976        self.display_map
 8977            .update(cx, |map, cx| map.snapshot(cx))
 8978            .longest_row()
 8979    }
 8980
 8981    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 8982        self.display_map
 8983            .update(cx, |map, cx| map.snapshot(cx))
 8984            .max_point()
 8985    }
 8986
 8987    pub fn text(&self, cx: &AppContext) -> String {
 8988        self.buffer.read(cx).read(cx).text()
 8989    }
 8990
 8991    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 8992        let text = self.text(cx);
 8993        let text = text.trim();
 8994
 8995        if text.is_empty() {
 8996            return None;
 8997        }
 8998
 8999        Some(text.to_string())
 9000    }
 9001
 9002    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 9003        self.transact(cx, |this, cx| {
 9004            this.buffer
 9005                .read(cx)
 9006                .as_singleton()
 9007                .expect("you can only call set_text on editors for singleton buffers")
 9008                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 9009        });
 9010    }
 9011
 9012    pub fn display_text(&self, cx: &mut AppContext) -> String {
 9013        self.display_map
 9014            .update(cx, |map, cx| map.snapshot(cx))
 9015            .text()
 9016    }
 9017
 9018    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 9019        let mut wrap_guides = smallvec::smallvec![];
 9020
 9021        if self.show_wrap_guides == Some(false) {
 9022            return wrap_guides;
 9023        }
 9024
 9025        let settings = self.buffer.read(cx).settings_at(0, cx);
 9026        if settings.show_wrap_guides {
 9027            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 9028                wrap_guides.push((soft_wrap as usize, true));
 9029            }
 9030            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 9031        }
 9032
 9033        wrap_guides
 9034    }
 9035
 9036    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 9037        let settings = self.buffer.read(cx).settings_at(0, cx);
 9038        let mode = self
 9039            .soft_wrap_mode_override
 9040            .unwrap_or_else(|| settings.soft_wrap);
 9041        match mode {
 9042            language_settings::SoftWrap::None => SoftWrap::None,
 9043            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 9044            language_settings::SoftWrap::PreferredLineLength => {
 9045                SoftWrap::Column(settings.preferred_line_length)
 9046            }
 9047        }
 9048    }
 9049
 9050    pub fn set_soft_wrap_mode(
 9051        &mut self,
 9052        mode: language_settings::SoftWrap,
 9053        cx: &mut ViewContext<Self>,
 9054    ) {
 9055        self.soft_wrap_mode_override = Some(mode);
 9056        cx.notify();
 9057    }
 9058
 9059    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 9060        let rem_size = cx.rem_size();
 9061        self.display_map.update(cx, |map, cx| {
 9062            map.set_font(
 9063                style.text.font(),
 9064                style.text.font_size.to_pixels(rem_size),
 9065                cx,
 9066            )
 9067        });
 9068        self.style = Some(style);
 9069    }
 9070
 9071    #[cfg(any(test, feature = "test-support"))]
 9072    pub fn style(&self) -> Option<&EditorStyle> {
 9073        self.style.as_ref()
 9074    }
 9075
 9076    // Called by the element. This method is not designed to be called outside of the editor
 9077    // element's layout code because it does not notify when rewrapping is computed synchronously.
 9078    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 9079        self.display_map
 9080            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 9081    }
 9082
 9083    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 9084        if self.soft_wrap_mode_override.is_some() {
 9085            self.soft_wrap_mode_override.take();
 9086        } else {
 9087            let soft_wrap = match self.soft_wrap_mode(cx) {
 9088                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
 9089                SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
 9090            };
 9091            self.soft_wrap_mode_override = Some(soft_wrap);
 9092        }
 9093        cx.notify();
 9094    }
 9095
 9096    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
 9097        let mut editor_settings = EditorSettings::get_global(cx).clone();
 9098        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
 9099        EditorSettings::override_global(editor_settings, cx);
 9100    }
 9101
 9102    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9103        self.show_gutter = show_gutter;
 9104        cx.notify();
 9105    }
 9106
 9107    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 9108        self.show_wrap_guides = Some(show_gutter);
 9109        cx.notify();
 9110    }
 9111
 9112    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 9113        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9114            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9115                cx.reveal_path(&file.abs_path(cx));
 9116            }
 9117        }
 9118    }
 9119
 9120    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 9121        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9122            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9123                if let Some(path) = file.abs_path(cx).to_str() {
 9124                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9125                }
 9126            }
 9127        }
 9128    }
 9129
 9130    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 9131        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 9132            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 9133                if let Some(path) = file.path().to_str() {
 9134                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 9135                }
 9136            }
 9137        }
 9138    }
 9139
 9140    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
 9141        if !self.show_git_blame {
 9142            if let Err(error) = self.show_git_blame_internal(cx) {
 9143                log::error!("failed to toggle on 'git blame': {}", error);
 9144                return;
 9145            }
 9146            self.show_git_blame = true
 9147        } else {
 9148            self.blame_subscription.take();
 9149            self.blame.take();
 9150            self.show_git_blame = false
 9151        }
 9152
 9153        cx.notify();
 9154    }
 9155
 9156    fn show_git_blame_internal(&mut self, cx: &mut ViewContext<Self>) -> Result<()> {
 9157        if let Some(project) = self.project.as_ref() {
 9158            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
 9159                anyhow::bail!("git blame not available in multi buffers")
 9160            };
 9161
 9162            let project = project.clone();
 9163            let blame = cx.new_model(|cx| GitBlame::new(buffer, project, cx));
 9164            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
 9165            self.blame = Some(blame);
 9166        }
 9167
 9168        Ok(())
 9169    }
 9170
 9171    pub fn blame(&self) -> Option<&Model<GitBlame>> {
 9172        self.blame.as_ref()
 9173    }
 9174
 9175    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
 9176        let (path, repo) = maybe!({
 9177            let project_handle = self.project.as_ref()?.clone();
 9178            let project = project_handle.read(cx);
 9179            let buffer = self.buffer().read(cx).as_singleton()?;
 9180            let path = buffer
 9181                .read(cx)
 9182                .file()?
 9183                .as_local()?
 9184                .path()
 9185                .to_str()?
 9186                .to_string();
 9187            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
 9188            Some((path, repo))
 9189        })
 9190        .ok_or_else(|| anyhow!("unable to open git repository"))?;
 9191
 9192        const REMOTE_NAME: &str = "origin";
 9193        let origin_url = repo
 9194            .lock()
 9195            .remote_url(REMOTE_NAME)
 9196            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
 9197        let sha = repo
 9198            .lock()
 9199            .head_sha()
 9200            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
 9201        let selections = self.selections.all::<Point>(cx);
 9202        let selection = selections.iter().peekable().next();
 9203
 9204        build_permalink(BuildPermalinkParams {
 9205            remote_url: &origin_url,
 9206            sha: &sha,
 9207            path: &path,
 9208            selection: selection.map(|selection| {
 9209                let range = selection.range();
 9210                let start = range.start.row;
 9211                let end = range.end.row;
 9212                start..end
 9213            }),
 9214        })
 9215    }
 9216
 9217    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
 9218        let permalink = self.get_permalink_to_line(cx);
 9219
 9220        match permalink {
 9221            Ok(permalink) => {
 9222                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
 9223            }
 9224            Err(err) => {
 9225                let message = format!("Failed to copy permalink: {err}");
 9226
 9227                Err::<(), anyhow::Error>(err).log_err();
 9228
 9229                if let Some(workspace) = self.workspace() {
 9230                    workspace.update(cx, |workspace, cx| {
 9231                        workspace.show_toast(Toast::new(0x156a5f9ee, message), cx)
 9232                    })
 9233                }
 9234            }
 9235        }
 9236    }
 9237
 9238    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
 9239        let permalink = self.get_permalink_to_line(cx);
 9240
 9241        match permalink {
 9242            Ok(permalink) => {
 9243                cx.open_url(permalink.as_ref());
 9244            }
 9245            Err(err) => {
 9246                let message = format!("Failed to open permalink: {err}");
 9247
 9248                Err::<(), anyhow::Error>(err).log_err();
 9249
 9250                if let Some(workspace) = self.workspace() {
 9251                    workspace.update(cx, |workspace, cx| {
 9252                        workspace.show_toast(Toast::new(0x45a8978, message), cx)
 9253                    })
 9254                }
 9255            }
 9256        }
 9257    }
 9258
 9259    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
 9260    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
 9261    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
 9262    pub fn highlight_rows<T: 'static>(
 9263        &mut self,
 9264        rows: Range<Anchor>,
 9265        color: Option<Hsla>,
 9266        cx: &mut ViewContext<Self>,
 9267    ) {
 9268        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 9269        match self.highlighted_rows.entry(TypeId::of::<T>()) {
 9270            hash_map::Entry::Occupied(o) => {
 9271                let row_highlights = o.into_mut();
 9272                let existing_highlight_index =
 9273                    row_highlights.binary_search_by(|(_, highlight_range, _)| {
 9274                        highlight_range
 9275                            .start
 9276                            .cmp(&rows.start, &multi_buffer_snapshot)
 9277                            .then(highlight_range.end.cmp(&rows.end, &multi_buffer_snapshot))
 9278                    });
 9279                match color {
 9280                    Some(color) => {
 9281                        let insert_index = match existing_highlight_index {
 9282                            Ok(i) => i,
 9283                            Err(i) => i,
 9284                        };
 9285                        row_highlights.insert(
 9286                            insert_index,
 9287                            (post_inc(&mut self.highlight_order), rows, color),
 9288                        );
 9289                    }
 9290                    None => {
 9291                        if let Ok(i) = existing_highlight_index {
 9292                            row_highlights.remove(i);
 9293                        }
 9294                    }
 9295                }
 9296            }
 9297            hash_map::Entry::Vacant(v) => {
 9298                if let Some(color) = color {
 9299                    v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
 9300                }
 9301            }
 9302        }
 9303    }
 9304
 9305    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
 9306    pub fn clear_row_highlights<T: 'static>(&mut self) {
 9307        self.highlighted_rows.remove(&TypeId::of::<T>());
 9308    }
 9309
 9310    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
 9311    pub fn highlighted_rows<T: 'static>(
 9312        &self,
 9313    ) -> Option<impl Iterator<Item = (&Range<Anchor>, &Hsla)>> {
 9314        Some(
 9315            self.highlighted_rows
 9316                .get(&TypeId::of::<T>())?
 9317                .iter()
 9318                .map(|(_, range, color)| (range, color)),
 9319        )
 9320    }
 9321
 9322    // Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
 9323    // Rerturns a map of display rows that are highlighted and their corresponding highlight color.
 9324    pub fn highlighted_display_rows(&mut self, cx: &mut WindowContext) -> BTreeMap<u32, Hsla> {
 9325        let snapshot = self.snapshot(cx);
 9326        let mut used_highlight_orders = HashMap::default();
 9327        self.highlighted_rows
 9328            .iter()
 9329            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
 9330            .fold(
 9331                BTreeMap::<u32, Hsla>::new(),
 9332                |mut unique_rows, (highlight_order, anchor_range, hsla)| {
 9333                    let start_row = anchor_range.start.to_display_point(&snapshot).row();
 9334                    let end_row = anchor_range.end.to_display_point(&snapshot).row();
 9335                    for row in start_row..=end_row {
 9336                        let used_index =
 9337                            used_highlight_orders.entry(row).or_insert(*highlight_order);
 9338                        if highlight_order >= used_index {
 9339                            *used_index = *highlight_order;
 9340                            unique_rows.insert(row, *hsla);
 9341                        }
 9342                    }
 9343                    unique_rows
 9344                },
 9345            )
 9346    }
 9347
 9348    pub fn highlight_background<T: 'static>(
 9349        &mut self,
 9350        ranges: Vec<Range<Anchor>>,
 9351        color_fetcher: fn(&ThemeColors) -> Hsla,
 9352        cx: &mut ViewContext<Self>,
 9353    ) {
 9354        let snapshot = self.snapshot(cx);
 9355        // this is to try and catch a panic sooner
 9356        for range in &ranges {
 9357            snapshot
 9358                .buffer_snapshot
 9359                .summary_for_anchor::<usize>(&range.start);
 9360            snapshot
 9361                .buffer_snapshot
 9362                .summary_for_anchor::<usize>(&range.end);
 9363        }
 9364
 9365        self.background_highlights
 9366            .insert(TypeId::of::<T>(), (color_fetcher, ranges));
 9367        cx.notify();
 9368    }
 9369
 9370    pub fn clear_background_highlights<T: 'static>(
 9371        &mut self,
 9372        _cx: &mut ViewContext<Self>,
 9373    ) -> Option<BackgroundHighlight> {
 9374        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
 9375        text_highlights
 9376    }
 9377
 9378    #[cfg(feature = "test-support")]
 9379    pub fn all_text_background_highlights(
 9380        &mut self,
 9381        cx: &mut ViewContext<Self>,
 9382    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9383        let snapshot = self.snapshot(cx);
 9384        let buffer = &snapshot.buffer_snapshot;
 9385        let start = buffer.anchor_before(0);
 9386        let end = buffer.anchor_after(buffer.len());
 9387        let theme = cx.theme().colors();
 9388        self.background_highlights_in_range(start..end, &snapshot, theme)
 9389    }
 9390
 9391    fn document_highlights_for_position<'a>(
 9392        &'a self,
 9393        position: Anchor,
 9394        buffer: &'a MultiBufferSnapshot,
 9395    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
 9396        let read_highlights = self
 9397            .background_highlights
 9398            .get(&TypeId::of::<DocumentHighlightRead>())
 9399            .map(|h| &h.1);
 9400        let write_highlights = self
 9401            .background_highlights
 9402            .get(&TypeId::of::<DocumentHighlightWrite>())
 9403            .map(|h| &h.1);
 9404        let left_position = position.bias_left(buffer);
 9405        let right_position = position.bias_right(buffer);
 9406        read_highlights
 9407            .into_iter()
 9408            .chain(write_highlights)
 9409            .flat_map(move |ranges| {
 9410                let start_ix = match ranges.binary_search_by(|probe| {
 9411                    let cmp = probe.end.cmp(&left_position, buffer);
 9412                    if cmp.is_ge() {
 9413                        Ordering::Greater
 9414                    } else {
 9415                        Ordering::Less
 9416                    }
 9417                }) {
 9418                    Ok(i) | Err(i) => i,
 9419                };
 9420
 9421                ranges[start_ix..]
 9422                    .iter()
 9423                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
 9424            })
 9425    }
 9426
 9427    pub fn has_background_highlights<T: 'static>(&self) -> bool {
 9428        self.background_highlights
 9429            .get(&TypeId::of::<T>())
 9430            .map_or(false, |(_, highlights)| !highlights.is_empty())
 9431    }
 9432
 9433    pub fn background_highlights_in_range(
 9434        &self,
 9435        search_range: Range<Anchor>,
 9436        display_snapshot: &DisplaySnapshot,
 9437        theme: &ThemeColors,
 9438    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9439        let mut results = Vec::new();
 9440        for (color_fetcher, ranges) in self.background_highlights.values() {
 9441            let color = color_fetcher(theme);
 9442            let start_ix = match ranges.binary_search_by(|probe| {
 9443                let cmp = probe
 9444                    .end
 9445                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9446                if cmp.is_gt() {
 9447                    Ordering::Greater
 9448                } else {
 9449                    Ordering::Less
 9450                }
 9451            }) {
 9452                Ok(i) | Err(i) => i,
 9453            };
 9454            for range in &ranges[start_ix..] {
 9455                if range
 9456                    .start
 9457                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9458                    .is_ge()
 9459                {
 9460                    break;
 9461                }
 9462
 9463                let start = range.start.to_display_point(&display_snapshot);
 9464                let end = range.end.to_display_point(&display_snapshot);
 9465                results.push((start..end, color))
 9466            }
 9467        }
 9468        results
 9469    }
 9470
 9471    pub fn background_highlight_row_ranges<T: 'static>(
 9472        &self,
 9473        search_range: Range<Anchor>,
 9474        display_snapshot: &DisplaySnapshot,
 9475        count: usize,
 9476    ) -> Vec<RangeInclusive<DisplayPoint>> {
 9477        let mut results = Vec::new();
 9478        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
 9479            return vec![];
 9480        };
 9481
 9482        let start_ix = match ranges.binary_search_by(|probe| {
 9483            let cmp = probe
 9484                .end
 9485                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9486            if cmp.is_gt() {
 9487                Ordering::Greater
 9488            } else {
 9489                Ordering::Less
 9490            }
 9491        }) {
 9492            Ok(i) | Err(i) => i,
 9493        };
 9494        let mut push_region = |start: Option<Point>, end: Option<Point>| {
 9495            if let (Some(start_display), Some(end_display)) = (start, end) {
 9496                results.push(
 9497                    start_display.to_display_point(display_snapshot)
 9498                        ..=end_display.to_display_point(display_snapshot),
 9499                );
 9500            }
 9501        };
 9502        let mut start_row: Option<Point> = None;
 9503        let mut end_row: Option<Point> = None;
 9504        if ranges.len() > count {
 9505            return Vec::new();
 9506        }
 9507        for range in &ranges[start_ix..] {
 9508            if range
 9509                .start
 9510                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9511                .is_ge()
 9512            {
 9513                break;
 9514            }
 9515            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
 9516            if let Some(current_row) = &end_row {
 9517                if end.row == current_row.row {
 9518                    continue;
 9519                }
 9520            }
 9521            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
 9522            if start_row.is_none() {
 9523                assert_eq!(end_row, None);
 9524                start_row = Some(start);
 9525                end_row = Some(end);
 9526                continue;
 9527            }
 9528            if let Some(current_end) = end_row.as_mut() {
 9529                if start.row > current_end.row + 1 {
 9530                    push_region(start_row, end_row);
 9531                    start_row = Some(start);
 9532                    end_row = Some(end);
 9533                } else {
 9534                    // Merge two hunks.
 9535                    *current_end = end;
 9536                }
 9537            } else {
 9538                unreachable!();
 9539            }
 9540        }
 9541        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
 9542        push_region(start_row, end_row);
 9543        results
 9544    }
 9545
 9546    /// Get the text ranges corresponding to the redaction query
 9547    pub fn redacted_ranges(
 9548        &self,
 9549        search_range: Range<Anchor>,
 9550        display_snapshot: &DisplaySnapshot,
 9551        cx: &WindowContext,
 9552    ) -> Vec<Range<DisplayPoint>> {
 9553        display_snapshot
 9554            .buffer_snapshot
 9555            .redacted_ranges(search_range, |file| {
 9556                if let Some(file) = file {
 9557                    file.is_private()
 9558                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
 9559                } else {
 9560                    false
 9561                }
 9562            })
 9563            .map(|range| {
 9564                range.start.to_display_point(display_snapshot)
 9565                    ..range.end.to_display_point(display_snapshot)
 9566            })
 9567            .collect()
 9568    }
 9569
 9570    pub fn highlight_text<T: 'static>(
 9571        &mut self,
 9572        ranges: Vec<Range<Anchor>>,
 9573        style: HighlightStyle,
 9574        cx: &mut ViewContext<Self>,
 9575    ) {
 9576        self.display_map.update(cx, |map, _| {
 9577            map.highlight_text(TypeId::of::<T>(), ranges, style)
 9578        });
 9579        cx.notify();
 9580    }
 9581
 9582    pub(crate) fn highlight_inlays<T: 'static>(
 9583        &mut self,
 9584        highlights: Vec<InlayHighlight>,
 9585        style: HighlightStyle,
 9586        cx: &mut ViewContext<Self>,
 9587    ) {
 9588        self.display_map.update(cx, |map, _| {
 9589            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
 9590        });
 9591        cx.notify();
 9592    }
 9593
 9594    pub fn text_highlights<'a, T: 'static>(
 9595        &'a self,
 9596        cx: &'a AppContext,
 9597    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
 9598        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
 9599    }
 9600
 9601    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 9602        let cleared = self
 9603            .display_map
 9604            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
 9605        if cleared {
 9606            cx.notify();
 9607        }
 9608    }
 9609
 9610    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
 9611        (self.read_only(cx) || self.blink_manager.read(cx).visible())
 9612            && self.focus_handle.is_focused(cx)
 9613    }
 9614
 9615    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
 9616        cx.notify();
 9617    }
 9618
 9619    fn on_buffer_event(
 9620        &mut self,
 9621        multibuffer: Model<MultiBuffer>,
 9622        event: &multi_buffer::Event,
 9623        cx: &mut ViewContext<Self>,
 9624    ) {
 9625        match event {
 9626            multi_buffer::Event::Edited {
 9627                singleton_buffer_edited,
 9628            } => {
 9629                self.refresh_active_diagnostics(cx);
 9630                self.refresh_code_actions(cx);
 9631                if self.has_active_inline_completion(cx) {
 9632                    self.update_visible_inline_completion(cx);
 9633                }
 9634                cx.emit(EditorEvent::BufferEdited);
 9635                cx.emit(SearchEvent::MatchesInvalidated);
 9636
 9637                if *singleton_buffer_edited {
 9638                    if let Some(project) = &self.project {
 9639                        let project = project.read(cx);
 9640                        let languages_affected = multibuffer
 9641                            .read(cx)
 9642                            .all_buffers()
 9643                            .into_iter()
 9644                            .filter_map(|buffer| {
 9645                                let buffer = buffer.read(cx);
 9646                                let language = buffer.language()?;
 9647                                if project.is_local()
 9648                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
 9649                                {
 9650                                    None
 9651                                } else {
 9652                                    Some(language)
 9653                                }
 9654                            })
 9655                            .cloned()
 9656                            .collect::<HashSet<_>>();
 9657                        if !languages_affected.is_empty() {
 9658                            self.refresh_inlay_hints(
 9659                                InlayHintRefreshReason::BufferEdited(languages_affected),
 9660                                cx,
 9661                            );
 9662                        }
 9663                    }
 9664                }
 9665
 9666                let Some(project) = &self.project else {
 9667                    return;
 9668                };
 9669                let telemetry = project.read(cx).client().telemetry().clone();
 9670                telemetry.log_edit_event("editor");
 9671            }
 9672            multi_buffer::Event::ExcerptsAdded {
 9673                buffer,
 9674                predecessor,
 9675                excerpts,
 9676            } => {
 9677                cx.emit(EditorEvent::ExcerptsAdded {
 9678                    buffer: buffer.clone(),
 9679                    predecessor: *predecessor,
 9680                    excerpts: excerpts.clone(),
 9681                });
 9682                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
 9683            }
 9684            multi_buffer::Event::ExcerptsRemoved { ids } => {
 9685                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
 9686                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
 9687            }
 9688            multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
 9689            multi_buffer::Event::LanguageChanged => {
 9690                cx.emit(EditorEvent::Reparsed);
 9691                cx.notify();
 9692            }
 9693            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
 9694            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
 9695            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
 9696                cx.emit(EditorEvent::TitleChanged)
 9697            }
 9698            multi_buffer::Event::DiffBaseChanged => cx.emit(EditorEvent::DiffBaseChanged),
 9699            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
 9700            multi_buffer::Event::DiagnosticsUpdated => {
 9701                self.refresh_active_diagnostics(cx);
 9702            }
 9703            _ => {}
 9704        };
 9705    }
 9706
 9707    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
 9708        cx.notify();
 9709    }
 9710
 9711    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
 9712        self.refresh_inline_completion(true, cx);
 9713        self.refresh_inlay_hints(
 9714            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
 9715                self.selections.newest_anchor().head(),
 9716                &self.buffer.read(cx).snapshot(cx),
 9717                cx,
 9718            )),
 9719            cx,
 9720        );
 9721        let editor_settings = EditorSettings::get_global(cx);
 9722        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
 9723        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
 9724        cx.notify();
 9725    }
 9726
 9727    pub fn set_searchable(&mut self, searchable: bool) {
 9728        self.searchable = searchable;
 9729    }
 9730
 9731    pub fn searchable(&self) -> bool {
 9732        self.searchable
 9733    }
 9734
 9735    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
 9736        self.open_excerpts_common(true, cx)
 9737    }
 9738
 9739    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
 9740        self.open_excerpts_common(false, cx)
 9741    }
 9742
 9743    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
 9744        let buffer = self.buffer.read(cx);
 9745        if buffer.is_singleton() {
 9746            cx.propagate();
 9747            return;
 9748        }
 9749
 9750        let Some(workspace) = self.workspace() else {
 9751            cx.propagate();
 9752            return;
 9753        };
 9754
 9755        let mut new_selections_by_buffer = HashMap::default();
 9756        for selection in self.selections.all::<usize>(cx) {
 9757            for (buffer, mut range, _) in
 9758                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
 9759            {
 9760                if selection.reversed {
 9761                    mem::swap(&mut range.start, &mut range.end);
 9762                }
 9763                new_selections_by_buffer
 9764                    .entry(buffer)
 9765                    .or_insert(Vec::new())
 9766                    .push(range)
 9767            }
 9768        }
 9769
 9770        // We defer the pane interaction because we ourselves are a workspace item
 9771        // and activating a new item causes the pane to call a method on us reentrantly,
 9772        // which panics if we're on the stack.
 9773        cx.window_context().defer(move |cx| {
 9774            workspace.update(cx, |workspace, cx| {
 9775                let pane = if split {
 9776                    workspace.adjacent_pane(cx)
 9777                } else {
 9778                    workspace.active_pane().clone()
 9779                };
 9780
 9781                for (buffer, ranges) in new_selections_by_buffer {
 9782                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
 9783                    editor.update(cx, |editor, cx| {
 9784                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 9785                            s.select_ranges(ranges);
 9786                        });
 9787                    });
 9788                }
 9789            })
 9790        });
 9791    }
 9792
 9793    fn jump(
 9794        &mut self,
 9795        path: ProjectPath,
 9796        position: Point,
 9797        anchor: language::Anchor,
 9798        offset_from_top: u32,
 9799        cx: &mut ViewContext<Self>,
 9800    ) {
 9801        let workspace = self.workspace();
 9802        cx.spawn(|_, mut cx| async move {
 9803            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
 9804            let editor = workspace.update(&mut cx, |workspace, cx| {
 9805                workspace.open_path(path, None, true, cx)
 9806            })?;
 9807            let editor = editor
 9808                .await?
 9809                .downcast::<Editor>()
 9810                .ok_or_else(|| anyhow!("opened item was not an editor"))?
 9811                .downgrade();
 9812            editor.update(&mut cx, |editor, cx| {
 9813                let buffer = editor
 9814                    .buffer()
 9815                    .read(cx)
 9816                    .as_singleton()
 9817                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
 9818                let buffer = buffer.read(cx);
 9819                let cursor = if buffer.can_resolve(&anchor) {
 9820                    language::ToPoint::to_point(&anchor, buffer)
 9821                } else {
 9822                    buffer.clip_point(position, Bias::Left)
 9823                };
 9824
 9825                let nav_history = editor.nav_history.take();
 9826                editor.change_selections(
 9827                    Some(Autoscroll::top_relative(offset_from_top as usize)),
 9828                    cx,
 9829                    |s| {
 9830                        s.select_ranges([cursor..cursor]);
 9831                    },
 9832                );
 9833                editor.nav_history = nav_history;
 9834
 9835                anyhow::Ok(())
 9836            })??;
 9837
 9838            anyhow::Ok(())
 9839        })
 9840        .detach_and_log_err(cx);
 9841    }
 9842
 9843    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
 9844        let snapshot = self.buffer.read(cx).read(cx);
 9845        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
 9846        Some(
 9847            ranges
 9848                .iter()
 9849                .map(move |range| {
 9850                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
 9851                })
 9852                .collect(),
 9853        )
 9854    }
 9855
 9856    fn selection_replacement_ranges(
 9857        &self,
 9858        range: Range<OffsetUtf16>,
 9859        cx: &AppContext,
 9860    ) -> Vec<Range<OffsetUtf16>> {
 9861        let selections = self.selections.all::<OffsetUtf16>(cx);
 9862        let newest_selection = selections
 9863            .iter()
 9864            .max_by_key(|selection| selection.id)
 9865            .unwrap();
 9866        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
 9867        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
 9868        let snapshot = self.buffer.read(cx).read(cx);
 9869        selections
 9870            .into_iter()
 9871            .map(|mut selection| {
 9872                selection.start.0 =
 9873                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
 9874                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
 9875                snapshot.clip_offset_utf16(selection.start, Bias::Left)
 9876                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
 9877            })
 9878            .collect()
 9879    }
 9880
 9881    fn report_editor_event(
 9882        &self,
 9883        operation: &'static str,
 9884        file_extension: Option<String>,
 9885        cx: &AppContext,
 9886    ) {
 9887        if cfg!(any(test, feature = "test-support")) {
 9888            return;
 9889        }
 9890
 9891        let Some(project) = &self.project else { return };
 9892
 9893        // If None, we are in a file without an extension
 9894        let file = self
 9895            .buffer
 9896            .read(cx)
 9897            .as_singleton()
 9898            .and_then(|b| b.read(cx).file());
 9899        let file_extension = file_extension.or(file
 9900            .as_ref()
 9901            .and_then(|file| Path::new(file.file_name(cx)).extension())
 9902            .and_then(|e| e.to_str())
 9903            .map(|a| a.to_string()));
 9904
 9905        let vim_mode = cx
 9906            .global::<SettingsStore>()
 9907            .raw_user_settings()
 9908            .get("vim_mode")
 9909            == Some(&serde_json::Value::Bool(true));
 9910        let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
 9911        let copilot_enabled_for_language = self
 9912            .buffer
 9913            .read(cx)
 9914            .settings_at(0, cx)
 9915            .show_copilot_suggestions;
 9916
 9917        let telemetry = project.read(cx).client().telemetry().clone();
 9918        telemetry.report_editor_event(
 9919            file_extension,
 9920            vim_mode,
 9921            operation,
 9922            copilot_enabled,
 9923            copilot_enabled_for_language,
 9924        )
 9925    }
 9926
 9927    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
 9928    /// with each line being an array of {text, highlight} objects.
 9929    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
 9930        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
 9931            return;
 9932        };
 9933
 9934        #[derive(Serialize)]
 9935        struct Chunk<'a> {
 9936            text: String,
 9937            highlight: Option<&'a str>,
 9938        }
 9939
 9940        let snapshot = buffer.read(cx).snapshot();
 9941        let range = self
 9942            .selected_text_range(cx)
 9943            .and_then(|selected_range| {
 9944                if selected_range.is_empty() {
 9945                    None
 9946                } else {
 9947                    Some(selected_range)
 9948                }
 9949            })
 9950            .unwrap_or_else(|| 0..snapshot.len());
 9951
 9952        let chunks = snapshot.chunks(range, true);
 9953        let mut lines = Vec::new();
 9954        let mut line: VecDeque<Chunk> = VecDeque::new();
 9955
 9956        let Some(style) = self.style.as_ref() else {
 9957            return;
 9958        };
 9959
 9960        for chunk in chunks {
 9961            let highlight = chunk
 9962                .syntax_highlight_id
 9963                .and_then(|id| id.name(&style.syntax));
 9964            let mut chunk_lines = chunk.text.split('\n').peekable();
 9965            while let Some(text) = chunk_lines.next() {
 9966                let mut merged_with_last_token = false;
 9967                if let Some(last_token) = line.back_mut() {
 9968                    if last_token.highlight == highlight {
 9969                        last_token.text.push_str(text);
 9970                        merged_with_last_token = true;
 9971                    }
 9972                }
 9973
 9974                if !merged_with_last_token {
 9975                    line.push_back(Chunk {
 9976                        text: text.into(),
 9977                        highlight,
 9978                    });
 9979                }
 9980
 9981                if chunk_lines.peek().is_some() {
 9982                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
 9983                        line.pop_front();
 9984                    }
 9985                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
 9986                        line.pop_back();
 9987                    }
 9988
 9989                    lines.push(mem::take(&mut line));
 9990                }
 9991            }
 9992        }
 9993
 9994        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
 9995            return;
 9996        };
 9997        cx.write_to_clipboard(ClipboardItem::new(lines));
 9998    }
 9999
10000    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
10001        &self.inlay_hint_cache
10002    }
10003
10004    pub fn replay_insert_event(
10005        &mut self,
10006        text: &str,
10007        relative_utf16_range: Option<Range<isize>>,
10008        cx: &mut ViewContext<Self>,
10009    ) {
10010        if !self.input_enabled {
10011            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10012            return;
10013        }
10014        if let Some(relative_utf16_range) = relative_utf16_range {
10015            let selections = self.selections.all::<OffsetUtf16>(cx);
10016            self.change_selections(None, cx, |s| {
10017                let new_ranges = selections.into_iter().map(|range| {
10018                    let start = OffsetUtf16(
10019                        range
10020                            .head()
10021                            .0
10022                            .saturating_add_signed(relative_utf16_range.start),
10023                    );
10024                    let end = OffsetUtf16(
10025                        range
10026                            .head()
10027                            .0
10028                            .saturating_add_signed(relative_utf16_range.end),
10029                    );
10030                    start..end
10031                });
10032                s.select_ranges(new_ranges);
10033            });
10034        }
10035
10036        self.handle_input(text, cx);
10037    }
10038
10039    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10040        let Some(project) = self.project.as_ref() else {
10041            return false;
10042        };
10043        let project = project.read(cx);
10044
10045        let mut supports = false;
10046        self.buffer().read(cx).for_each_buffer(|buffer| {
10047            if !supports {
10048                supports = project
10049                    .language_servers_for_buffer(buffer.read(cx), cx)
10050                    .any(
10051                        |(_, server)| match server.capabilities().inlay_hint_provider {
10052                            Some(lsp::OneOf::Left(enabled)) => enabled,
10053                            Some(lsp::OneOf::Right(_)) => true,
10054                            None => false,
10055                        },
10056                    )
10057            }
10058        });
10059        supports
10060    }
10061
10062    pub fn focus(&self, cx: &mut WindowContext) {
10063        cx.focus(&self.focus_handle)
10064    }
10065
10066    pub fn is_focused(&self, cx: &WindowContext) -> bool {
10067        self.focus_handle.is_focused(cx)
10068    }
10069
10070    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
10071        cx.emit(EditorEvent::Focused);
10072
10073        if let Some(rename) = self.pending_rename.as_ref() {
10074            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
10075            cx.focus(&rename_editor_focus_handle);
10076        } else {
10077            self.blink_manager.update(cx, BlinkManager::enable);
10078            self.show_cursor_names(cx);
10079            self.buffer.update(cx, |buffer, cx| {
10080                buffer.finalize_last_transaction(cx);
10081                if self.leader_peer_id.is_none() {
10082                    buffer.set_active_selections(
10083                        &self.selections.disjoint_anchors(),
10084                        self.selections.line_mode,
10085                        self.cursor_shape,
10086                        cx,
10087                    );
10088                }
10089            });
10090        }
10091    }
10092
10093    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
10094        self.blink_manager.update(cx, BlinkManager::disable);
10095        self.buffer
10096            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
10097        self.hide_context_menu(cx);
10098        hide_hover(self, cx);
10099        cx.emit(EditorEvent::Blurred);
10100        cx.notify();
10101    }
10102
10103    pub fn register_action<A: Action>(
10104        &mut self,
10105        listener: impl Fn(&A, &mut WindowContext) + 'static,
10106    ) -> &mut Self {
10107        let listener = Arc::new(listener);
10108
10109        self.editor_actions.push(Box::new(move |cx| {
10110            let _view = cx.view().clone();
10111            let cx = cx.window_context();
10112            let listener = listener.clone();
10113            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
10114                let action = action.downcast_ref().unwrap();
10115                if phase == DispatchPhase::Bubble {
10116                    listener(action, cx)
10117                }
10118            })
10119        }));
10120        self
10121    }
10122}
10123
10124pub trait CollaborationHub {
10125    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
10126    fn user_participant_indices<'a>(
10127        &self,
10128        cx: &'a AppContext,
10129    ) -> &'a HashMap<u64, ParticipantIndex>;
10130    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
10131}
10132
10133impl CollaborationHub for Model<Project> {
10134    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
10135        self.read(cx).collaborators()
10136    }
10137
10138    fn user_participant_indices<'a>(
10139        &self,
10140        cx: &'a AppContext,
10141    ) -> &'a HashMap<u64, ParticipantIndex> {
10142        self.read(cx).user_store().read(cx).participant_indices()
10143    }
10144
10145    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
10146        let this = self.read(cx);
10147        let user_ids = this.collaborators().values().map(|c| c.user_id);
10148        this.user_store().read_with(cx, |user_store, cx| {
10149            user_store.participant_names(user_ids, cx)
10150        })
10151    }
10152}
10153
10154pub trait CompletionProvider {
10155    fn completions(
10156        &self,
10157        buffer: &Model<Buffer>,
10158        buffer_position: text::Anchor,
10159        cx: &mut ViewContext<Editor>,
10160    ) -> Task<Result<Vec<Completion>>>;
10161
10162    fn resolve_completions(
10163        &self,
10164        completion_indices: Vec<usize>,
10165        completions: Arc<RwLock<Box<[Completion]>>>,
10166        cx: &mut ViewContext<Editor>,
10167    ) -> Task<Result<bool>>;
10168
10169    fn apply_additional_edits_for_completion(
10170        &self,
10171        buffer: Model<Buffer>,
10172        completion: Completion,
10173        push_to_history: bool,
10174        cx: &mut ViewContext<Editor>,
10175    ) -> Task<Result<Option<language::Transaction>>>;
10176}
10177
10178impl CompletionProvider for Model<Project> {
10179    fn completions(
10180        &self,
10181        buffer: &Model<Buffer>,
10182        buffer_position: text::Anchor,
10183        cx: &mut ViewContext<Editor>,
10184    ) -> Task<Result<Vec<Completion>>> {
10185        self.update(cx, |project, cx| {
10186            project.completions(&buffer, buffer_position, cx)
10187        })
10188    }
10189
10190    fn resolve_completions(
10191        &self,
10192        completion_indices: Vec<usize>,
10193        completions: Arc<RwLock<Box<[Completion]>>>,
10194        cx: &mut ViewContext<Editor>,
10195    ) -> Task<Result<bool>> {
10196        self.update(cx, |project, cx| {
10197            project.resolve_completions(completion_indices, completions, cx)
10198        })
10199    }
10200
10201    fn apply_additional_edits_for_completion(
10202        &self,
10203        buffer: Model<Buffer>,
10204        completion: Completion,
10205        push_to_history: bool,
10206        cx: &mut ViewContext<Editor>,
10207    ) -> Task<Result<Option<language::Transaction>>> {
10208        self.update(cx, |project, cx| {
10209            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
10210        })
10211    }
10212}
10213
10214fn inlay_hint_settings(
10215    location: Anchor,
10216    snapshot: &MultiBufferSnapshot,
10217    cx: &mut ViewContext<'_, Editor>,
10218) -> InlayHintSettings {
10219    let file = snapshot.file_at(location);
10220    let language = snapshot.language_at(location);
10221    let settings = all_language_settings(file, cx);
10222    settings
10223        .language(language.map(|l| l.name()).as_deref())
10224        .inlay_hints
10225}
10226
10227fn consume_contiguous_rows(
10228    contiguous_row_selections: &mut Vec<Selection<Point>>,
10229    selection: &Selection<Point>,
10230    display_map: &DisplaySnapshot,
10231    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
10232) -> (u32, u32) {
10233    contiguous_row_selections.push(selection.clone());
10234    let start_row = selection.start.row;
10235    let mut end_row = ending_row(selection, display_map);
10236
10237    while let Some(next_selection) = selections.peek() {
10238        if next_selection.start.row <= end_row {
10239            end_row = ending_row(next_selection, display_map);
10240            contiguous_row_selections.push(selections.next().unwrap().clone());
10241        } else {
10242            break;
10243        }
10244    }
10245    (start_row, end_row)
10246}
10247
10248fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
10249    if next_selection.end.column > 0 || next_selection.is_empty() {
10250        display_map.next_line_boundary(next_selection.end).0.row + 1
10251    } else {
10252        next_selection.end.row
10253    }
10254}
10255
10256impl EditorSnapshot {
10257    pub fn remote_selections_in_range<'a>(
10258        &'a self,
10259        range: &'a Range<Anchor>,
10260        collaboration_hub: &dyn CollaborationHub,
10261        cx: &'a AppContext,
10262    ) -> impl 'a + Iterator<Item = RemoteSelection> {
10263        let participant_names = collaboration_hub.user_names(cx);
10264        let participant_indices = collaboration_hub.user_participant_indices(cx);
10265        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
10266        let collaborators_by_replica_id = collaborators_by_peer_id
10267            .iter()
10268            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
10269            .collect::<HashMap<_, _>>();
10270        self.buffer_snapshot
10271            .remote_selections_in_range(range)
10272            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10273                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10274                let participant_index = participant_indices.get(&collaborator.user_id).copied();
10275                let user_name = participant_names.get(&collaborator.user_id).cloned();
10276                Some(RemoteSelection {
10277                    replica_id,
10278                    selection,
10279                    cursor_shape,
10280                    line_mode,
10281                    participant_index,
10282                    peer_id: collaborator.peer_id,
10283                    user_name,
10284                })
10285            })
10286    }
10287
10288    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10289        self.display_snapshot.buffer_snapshot.language_at(position)
10290    }
10291
10292    pub fn is_focused(&self) -> bool {
10293        self.is_focused
10294    }
10295
10296    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10297        self.placeholder_text.as_ref()
10298    }
10299
10300    pub fn scroll_position(&self) -> gpui::Point<f32> {
10301        self.scroll_anchor.scroll_position(&self.display_snapshot)
10302    }
10303
10304    pub fn gutter_dimensions(
10305        &self,
10306        font_id: FontId,
10307        font_size: Pixels,
10308        em_width: Pixels,
10309        max_line_number_width: Pixels,
10310        cx: &AppContext,
10311    ) -> GutterDimensions {
10312        if !self.show_gutter {
10313            return GutterDimensions::default();
10314        }
10315        let descent = cx.text_system().descent(font_id, font_size);
10316
10317        let show_git_gutter = matches!(
10318            ProjectSettings::get_global(cx).git.git_gutter,
10319            Some(GitGutterSetting::TrackedFiles)
10320        );
10321        let gutter_settings = EditorSettings::get_global(cx).gutter;
10322
10323        let line_gutter_width = if gutter_settings.line_numbers {
10324            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10325            let min_width_for_number_on_gutter = em_width * 4.0;
10326            max_line_number_width.max(min_width_for_number_on_gutter)
10327        } else {
10328            0.0.into()
10329        };
10330
10331        let git_blame_entries_width = self
10332            .show_git_blame
10333            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
10334
10335        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
10336        left_padding += if gutter_settings.code_actions {
10337            em_width * 3.0
10338        } else if show_git_gutter && gutter_settings.line_numbers {
10339            em_width * 2.0
10340        } else if show_git_gutter || gutter_settings.line_numbers {
10341            em_width
10342        } else {
10343            px(0.)
10344        };
10345
10346        let right_padding = if gutter_settings.folds && gutter_settings.line_numbers {
10347            em_width * 4.0
10348        } else if gutter_settings.folds {
10349            em_width * 3.0
10350        } else if gutter_settings.line_numbers {
10351            em_width
10352        } else {
10353            px(0.)
10354        };
10355
10356        GutterDimensions {
10357            left_padding,
10358            right_padding,
10359            width: line_gutter_width + left_padding + right_padding,
10360            margin: -descent,
10361            git_blame_entries_width,
10362        }
10363    }
10364}
10365
10366impl Deref for EditorSnapshot {
10367    type Target = DisplaySnapshot;
10368
10369    fn deref(&self) -> &Self::Target {
10370        &self.display_snapshot
10371    }
10372}
10373
10374#[derive(Clone, Debug, PartialEq, Eq)]
10375pub enum EditorEvent {
10376    InputIgnored {
10377        text: Arc<str>,
10378    },
10379    InputHandled {
10380        utf16_range_to_replace: Option<Range<isize>>,
10381        text: Arc<str>,
10382    },
10383    ExcerptsAdded {
10384        buffer: Model<Buffer>,
10385        predecessor: ExcerptId,
10386        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
10387    },
10388    ExcerptsRemoved {
10389        ids: Vec<ExcerptId>,
10390    },
10391    BufferEdited,
10392    Edited,
10393    Reparsed,
10394    Focused,
10395    Blurred,
10396    DirtyChanged,
10397    Saved,
10398    TitleChanged,
10399    DiffBaseChanged,
10400    SelectionsChanged {
10401        local: bool,
10402    },
10403    ScrollPositionChanged {
10404        local: bool,
10405        autoscroll: bool,
10406    },
10407    Closed,
10408    TransactionUndone {
10409        transaction_id: clock::Lamport,
10410    },
10411    TransactionBegun {
10412        transaction_id: clock::Lamport,
10413    },
10414}
10415
10416impl EventEmitter<EditorEvent> for Editor {}
10417
10418impl FocusableView for Editor {
10419    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
10420        self.focus_handle.clone()
10421    }
10422}
10423
10424impl Render for Editor {
10425    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
10426        let settings = ThemeSettings::get_global(cx);
10427        let text_style = match self.mode {
10428            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
10429                color: cx.theme().colors().editor_foreground,
10430                font_family: settings.ui_font.family.clone(),
10431                font_features: settings.ui_font.features,
10432                font_size: rems(0.875).into(),
10433                font_weight: FontWeight::NORMAL,
10434                font_style: FontStyle::Normal,
10435                line_height: relative(settings.buffer_line_height.value()),
10436                background_color: None,
10437                underline: None,
10438                strikethrough: None,
10439                white_space: WhiteSpace::Normal,
10440            },
10441
10442            EditorMode::Full => TextStyle {
10443                color: cx.theme().colors().editor_foreground,
10444                font_family: settings.buffer_font.family.clone(),
10445                font_features: settings.buffer_font.features,
10446                font_size: settings.buffer_font_size(cx).into(),
10447                font_weight: FontWeight::NORMAL,
10448                font_style: FontStyle::Normal,
10449                line_height: relative(settings.buffer_line_height.value()),
10450                background_color: None,
10451                underline: None,
10452                strikethrough: None,
10453                white_space: WhiteSpace::Normal,
10454            },
10455        };
10456
10457        let background = match self.mode {
10458            EditorMode::SingleLine => cx.theme().system().transparent,
10459            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
10460            EditorMode::Full => cx.theme().colors().editor_background,
10461        };
10462
10463        EditorElement::new(
10464            cx.view(),
10465            EditorStyle {
10466                background,
10467                local_player: cx.theme().players().local(),
10468                text: text_style,
10469                scrollbar_width: px(12.),
10470                syntax: cx.theme().syntax().clone(),
10471                status: cx.theme().status().clone(),
10472                inlay_hints_style: HighlightStyle {
10473                    color: Some(cx.theme().status().hint),
10474                    ..HighlightStyle::default()
10475                },
10476                suggestions_style: HighlightStyle {
10477                    color: Some(cx.theme().status().predictive),
10478                    ..HighlightStyle::default()
10479                },
10480            },
10481        )
10482    }
10483}
10484
10485impl ViewInputHandler for Editor {
10486    fn text_for_range(
10487        &mut self,
10488        range_utf16: Range<usize>,
10489        cx: &mut ViewContext<Self>,
10490    ) -> Option<String> {
10491        Some(
10492            self.buffer
10493                .read(cx)
10494                .read(cx)
10495                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
10496                .collect(),
10497        )
10498    }
10499
10500    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10501        // Prevent the IME menu from appearing when holding down an alphabetic key
10502        // while input is disabled.
10503        if !self.input_enabled {
10504            return None;
10505        }
10506
10507        let range = self.selections.newest::<OffsetUtf16>(cx).range();
10508        Some(range.start.0..range.end.0)
10509    }
10510
10511    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10512        let snapshot = self.buffer.read(cx).read(cx);
10513        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
10514        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
10515    }
10516
10517    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
10518        self.clear_highlights::<InputComposition>(cx);
10519        self.ime_transaction.take();
10520    }
10521
10522    fn replace_text_in_range(
10523        &mut self,
10524        range_utf16: Option<Range<usize>>,
10525        text: &str,
10526        cx: &mut ViewContext<Self>,
10527    ) {
10528        if !self.input_enabled {
10529            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10530            return;
10531        }
10532
10533        self.transact(cx, |this, cx| {
10534            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
10535                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10536                Some(this.selection_replacement_ranges(range_utf16, cx))
10537            } else {
10538                this.marked_text_ranges(cx)
10539            };
10540
10541            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
10542                let newest_selection_id = this.selections.newest_anchor().id;
10543                this.selections
10544                    .all::<OffsetUtf16>(cx)
10545                    .iter()
10546                    .zip(ranges_to_replace.iter())
10547                    .find_map(|(selection, range)| {
10548                        if selection.id == newest_selection_id {
10549                            Some(
10550                                (range.start.0 as isize - selection.head().0 as isize)
10551                                    ..(range.end.0 as isize - selection.head().0 as isize),
10552                            )
10553                        } else {
10554                            None
10555                        }
10556                    })
10557            });
10558
10559            cx.emit(EditorEvent::InputHandled {
10560                utf16_range_to_replace: range_to_replace,
10561                text: text.into(),
10562            });
10563
10564            if let Some(new_selected_ranges) = new_selected_ranges {
10565                this.change_selections(None, cx, |selections| {
10566                    selections.select_ranges(new_selected_ranges)
10567                });
10568                this.backspace(&Default::default(), cx);
10569            }
10570
10571            this.handle_input(text, cx);
10572        });
10573
10574        if let Some(transaction) = self.ime_transaction {
10575            self.buffer.update(cx, |buffer, cx| {
10576                buffer.group_until_transaction(transaction, cx);
10577            });
10578        }
10579
10580        self.unmark_text(cx);
10581    }
10582
10583    fn replace_and_mark_text_in_range(
10584        &mut self,
10585        range_utf16: Option<Range<usize>>,
10586        text: &str,
10587        new_selected_range_utf16: Option<Range<usize>>,
10588        cx: &mut ViewContext<Self>,
10589    ) {
10590        if !self.input_enabled {
10591            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10592            return;
10593        }
10594
10595        let transaction = self.transact(cx, |this, cx| {
10596            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
10597                let snapshot = this.buffer.read(cx).read(cx);
10598                if let Some(relative_range_utf16) = range_utf16.as_ref() {
10599                    for marked_range in &mut marked_ranges {
10600                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
10601                        marked_range.start.0 += relative_range_utf16.start;
10602                        marked_range.start =
10603                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
10604                        marked_range.end =
10605                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
10606                    }
10607                }
10608                Some(marked_ranges)
10609            } else if let Some(range_utf16) = range_utf16 {
10610                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10611                Some(this.selection_replacement_ranges(range_utf16, cx))
10612            } else {
10613                None
10614            };
10615
10616            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
10617                let newest_selection_id = this.selections.newest_anchor().id;
10618                this.selections
10619                    .all::<OffsetUtf16>(cx)
10620                    .iter()
10621                    .zip(ranges_to_replace.iter())
10622                    .find_map(|(selection, range)| {
10623                        if selection.id == newest_selection_id {
10624                            Some(
10625                                (range.start.0 as isize - selection.head().0 as isize)
10626                                    ..(range.end.0 as isize - selection.head().0 as isize),
10627                            )
10628                        } else {
10629                            None
10630                        }
10631                    })
10632            });
10633
10634            cx.emit(EditorEvent::InputHandled {
10635                utf16_range_to_replace: range_to_replace,
10636                text: text.into(),
10637            });
10638
10639            if let Some(ranges) = ranges_to_replace {
10640                this.change_selections(None, cx, |s| s.select_ranges(ranges));
10641            }
10642
10643            let marked_ranges = {
10644                let snapshot = this.buffer.read(cx).read(cx);
10645                this.selections
10646                    .disjoint_anchors()
10647                    .iter()
10648                    .map(|selection| {
10649                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
10650                    })
10651                    .collect::<Vec<_>>()
10652            };
10653
10654            if text.is_empty() {
10655                this.unmark_text(cx);
10656            } else {
10657                this.highlight_text::<InputComposition>(
10658                    marked_ranges.clone(),
10659                    HighlightStyle {
10660                        underline: Some(UnderlineStyle {
10661                            thickness: px(1.),
10662                            color: None,
10663                            wavy: false,
10664                        }),
10665                        ..Default::default()
10666                    },
10667                    cx,
10668                );
10669            }
10670
10671            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
10672            let use_autoclose = this.use_autoclose;
10673            this.set_use_autoclose(false);
10674            this.handle_input(text, cx);
10675            this.set_use_autoclose(use_autoclose);
10676
10677            if let Some(new_selected_range) = new_selected_range_utf16 {
10678                let snapshot = this.buffer.read(cx).read(cx);
10679                let new_selected_ranges = marked_ranges
10680                    .into_iter()
10681                    .map(|marked_range| {
10682                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
10683                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
10684                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
10685                        snapshot.clip_offset_utf16(new_start, Bias::Left)
10686                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
10687                    })
10688                    .collect::<Vec<_>>();
10689
10690                drop(snapshot);
10691                this.change_selections(None, cx, |selections| {
10692                    selections.select_ranges(new_selected_ranges)
10693                });
10694            }
10695        });
10696
10697        self.ime_transaction = self.ime_transaction.or(transaction);
10698        if let Some(transaction) = self.ime_transaction {
10699            self.buffer.update(cx, |buffer, cx| {
10700                buffer.group_until_transaction(transaction, cx);
10701            });
10702        }
10703
10704        if self.text_highlights::<InputComposition>(cx).is_none() {
10705            self.ime_transaction.take();
10706        }
10707    }
10708
10709    fn bounds_for_range(
10710        &mut self,
10711        range_utf16: Range<usize>,
10712        element_bounds: gpui::Bounds<Pixels>,
10713        cx: &mut ViewContext<Self>,
10714    ) -> Option<gpui::Bounds<Pixels>> {
10715        let text_layout_details = self.text_layout_details(cx);
10716        let style = &text_layout_details.editor_style;
10717        let font_id = cx.text_system().resolve_font(&style.text.font());
10718        let font_size = style.text.font_size.to_pixels(cx.rem_size());
10719        let line_height = style.text.line_height_in_pixels(cx.rem_size());
10720        let em_width = cx
10721            .text_system()
10722            .typographic_bounds(font_id, font_size, 'm')
10723            .unwrap()
10724            .size
10725            .width;
10726
10727        let snapshot = self.snapshot(cx);
10728        let scroll_position = snapshot.scroll_position();
10729        let scroll_left = scroll_position.x * em_width;
10730
10731        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
10732        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
10733            + self.gutter_width;
10734        let y = line_height * (start.row() as f32 - scroll_position.y);
10735
10736        Some(Bounds {
10737            origin: element_bounds.origin + point(x, y),
10738            size: size(em_width, line_height),
10739        })
10740    }
10741}
10742
10743trait SelectionExt {
10744    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
10745    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
10746    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
10747    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
10748        -> Range<u32>;
10749}
10750
10751impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
10752    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
10753        let start = self.start.to_point(buffer);
10754        let end = self.end.to_point(buffer);
10755        if self.reversed {
10756            end..start
10757        } else {
10758            start..end
10759        }
10760    }
10761
10762    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
10763        let start = self.start.to_offset(buffer);
10764        let end = self.end.to_offset(buffer);
10765        if self.reversed {
10766            end..start
10767        } else {
10768            start..end
10769        }
10770    }
10771
10772    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
10773        let start = self
10774            .start
10775            .to_point(&map.buffer_snapshot)
10776            .to_display_point(map);
10777        let end = self
10778            .end
10779            .to_point(&map.buffer_snapshot)
10780            .to_display_point(map);
10781        if self.reversed {
10782            end..start
10783        } else {
10784            start..end
10785        }
10786    }
10787
10788    fn spanned_rows(
10789        &self,
10790        include_end_if_at_line_start: bool,
10791        map: &DisplaySnapshot,
10792    ) -> Range<u32> {
10793        let start = self.start.to_point(&map.buffer_snapshot);
10794        let mut end = self.end.to_point(&map.buffer_snapshot);
10795        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
10796            end.row -= 1;
10797        }
10798
10799        let buffer_start = map.prev_line_boundary(start).0;
10800        let buffer_end = map.next_line_boundary(end).0;
10801        buffer_start.row..buffer_end.row + 1
10802    }
10803}
10804
10805impl<T: InvalidationRegion> InvalidationStack<T> {
10806    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
10807    where
10808        S: Clone + ToOffset,
10809    {
10810        while let Some(region) = self.last() {
10811            let all_selections_inside_invalidation_ranges =
10812                if selections.len() == region.ranges().len() {
10813                    selections
10814                        .iter()
10815                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
10816                        .all(|(selection, invalidation_range)| {
10817                            let head = selection.head().to_offset(buffer);
10818                            invalidation_range.start <= head && invalidation_range.end >= head
10819                        })
10820                } else {
10821                    false
10822                };
10823
10824            if all_selections_inside_invalidation_ranges {
10825                break;
10826            } else {
10827                self.pop();
10828            }
10829        }
10830    }
10831}
10832
10833impl<T> Default for InvalidationStack<T> {
10834    fn default() -> Self {
10835        Self(Default::default())
10836    }
10837}
10838
10839impl<T> Deref for InvalidationStack<T> {
10840    type Target = Vec<T>;
10841
10842    fn deref(&self) -> &Self::Target {
10843        &self.0
10844    }
10845}
10846
10847impl<T> DerefMut for InvalidationStack<T> {
10848    fn deref_mut(&mut self) -> &mut Self::Target {
10849        &mut self.0
10850    }
10851}
10852
10853impl InvalidationRegion for SnippetState {
10854    fn ranges(&self) -> &[Range<Anchor>] {
10855        &self.ranges[self.active_index]
10856    }
10857}
10858
10859pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
10860    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
10861
10862    Arc::new(move |cx: &mut BlockContext| {
10863        let group_id: SharedString = cx.block_id.to_string().into();
10864
10865        let mut text_style = cx.text_style().clone();
10866        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
10867
10868        let multi_line_diagnostic = diagnostic.message.contains('\n');
10869
10870        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
10871            if multi_line_diagnostic {
10872                v_flex()
10873            } else {
10874                h_flex()
10875            }
10876            .children(diagnostic.is_primary.then(|| {
10877                IconButton::new(("close-block", block_id), IconName::XCircle)
10878                    .icon_color(Color::Muted)
10879                    .size(ButtonSize::Compact)
10880                    .style(ButtonStyle::Transparent)
10881                    .visible_on_hover(group_id.clone())
10882                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
10883                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
10884            }))
10885            .child(
10886                IconButton::new(("copy-block", block_id), IconName::Copy)
10887                    .icon_color(Color::Muted)
10888                    .size(ButtonSize::Compact)
10889                    .style(ButtonStyle::Transparent)
10890                    .visible_on_hover(group_id.clone())
10891                    .on_click({
10892                        let message = diagnostic.message.clone();
10893                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
10894                    })
10895                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
10896            )
10897        };
10898
10899        let icon_size = buttons(&diagnostic, cx.block_id)
10900            .into_any_element()
10901            .measure(AvailableSpace::min_size(), cx);
10902
10903        h_flex()
10904            .id(cx.block_id)
10905            .group(group_id.clone())
10906            .relative()
10907            .size_full()
10908            .pl(cx.gutter_dimensions.width)
10909            .w(cx.max_width + cx.gutter_dimensions.width)
10910            .child(
10911                div()
10912                    .flex()
10913                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
10914                    .flex_shrink(),
10915            )
10916            .child(buttons(&diagnostic, cx.block_id))
10917            .child(div().flex().flex_shrink_0().child(
10918                StyledText::new(text_without_backticks.clone()).with_highlights(
10919                    &text_style,
10920                    code_ranges.iter().map(|range| {
10921                        (
10922                            range.clone(),
10923                            HighlightStyle {
10924                                font_weight: Some(FontWeight::BOLD),
10925                                ..Default::default()
10926                            },
10927                        )
10928                    }),
10929                ),
10930            ))
10931            .into_any_element()
10932    })
10933}
10934
10935pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
10936    let mut text_without_backticks = String::new();
10937    let mut code_ranges = Vec::new();
10938
10939    if let Some(source) = &diagnostic.source {
10940        text_without_backticks.push_str(&source);
10941        code_ranges.push(0..source.len());
10942        text_without_backticks.push_str(": ");
10943    }
10944
10945    let mut prev_offset = 0;
10946    let mut in_code_block = false;
10947    for (ix, _) in diagnostic
10948        .message
10949        .match_indices('`')
10950        .chain([(diagnostic.message.len(), "")])
10951    {
10952        let prev_len = text_without_backticks.len();
10953        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
10954        prev_offset = ix + 1;
10955        if in_code_block {
10956            code_ranges.push(prev_len..text_without_backticks.len());
10957            in_code_block = false;
10958        } else {
10959            in_code_block = true;
10960        }
10961    }
10962
10963    (text_without_backticks.into(), code_ranges)
10964}
10965
10966fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
10967    match (severity, valid) {
10968        (DiagnosticSeverity::ERROR, true) => colors.error,
10969        (DiagnosticSeverity::ERROR, false) => colors.error,
10970        (DiagnosticSeverity::WARNING, true) => colors.warning,
10971        (DiagnosticSeverity::WARNING, false) => colors.warning,
10972        (DiagnosticSeverity::INFORMATION, true) => colors.info,
10973        (DiagnosticSeverity::INFORMATION, false) => colors.info,
10974        (DiagnosticSeverity::HINT, true) => colors.info,
10975        (DiagnosticSeverity::HINT, false) => colors.info,
10976        _ => colors.ignored,
10977    }
10978}
10979
10980pub fn styled_runs_for_code_label<'a>(
10981    label: &'a CodeLabel,
10982    syntax_theme: &'a theme::SyntaxTheme,
10983) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
10984    let fade_out = HighlightStyle {
10985        fade_out: Some(0.35),
10986        ..Default::default()
10987    };
10988
10989    let mut prev_end = label.filter_range.end;
10990    label
10991        .runs
10992        .iter()
10993        .enumerate()
10994        .flat_map(move |(ix, (range, highlight_id))| {
10995            let style = if let Some(style) = highlight_id.style(syntax_theme) {
10996                style
10997            } else {
10998                return Default::default();
10999            };
11000            let mut muted_style = style;
11001            muted_style.highlight(fade_out);
11002
11003            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
11004            if range.start >= label.filter_range.end {
11005                if range.start > prev_end {
11006                    runs.push((prev_end..range.start, fade_out));
11007                }
11008                runs.push((range.clone(), muted_style));
11009            } else if range.end <= label.filter_range.end {
11010                runs.push((range.clone(), style));
11011            } else {
11012                runs.push((range.start..label.filter_range.end, style));
11013                runs.push((label.filter_range.end..range.end, muted_style));
11014            }
11015            prev_end = cmp::max(prev_end, range.end);
11016
11017            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
11018                runs.push((prev_end..label.text.len(), fade_out));
11019            }
11020
11021            runs
11022        })
11023}
11024
11025pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
11026    let mut prev_index = 0;
11027    let mut prev_codepoint: Option<char> = None;
11028    text.char_indices()
11029        .chain([(text.len(), '\0')])
11030        .filter_map(move |(index, codepoint)| {
11031            let prev_codepoint = prev_codepoint.replace(codepoint)?;
11032            let is_boundary = index == text.len()
11033                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
11034                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
11035            if is_boundary {
11036                let chunk = &text[prev_index..index];
11037                prev_index = index;
11038                Some(chunk)
11039            } else {
11040                None
11041            }
11042        })
11043}
11044
11045trait RangeToAnchorExt {
11046    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
11047}
11048
11049impl<T: ToOffset> RangeToAnchorExt for Range<T> {
11050    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
11051        snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
11052    }
11053}