editor.rs

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