editor.rs

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