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