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