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 behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::Restore;
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
   89    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketPair, Buffer, Capability,
  105    CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, DiskState, EditPredictionsMode,
  106    EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
  107    Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use std::iter::Peekable;
  117use task::{ResolvedTask, TaskTemplate, TaskVariables};
  118
  119use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  120pub use lsp::CompletionContext;
  121use lsp::{
  122    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  123    LanguageServerId, LanguageServerName,
  124};
  125
  126use language::BufferSnapshot;
  127use movement::TextLayoutDetails;
  128pub use multi_buffer::{
  129    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  130    ToOffset, ToPoint,
  131};
  132use multi_buffer::{
  133    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  134    ToOffsetUtf16,
  135};
  136use project::{
  137    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  138    project_settings::{GitGutterSetting, ProjectSettings},
  139    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  140    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  141};
  142use rand::prelude::*;
  143use rpc::{proto::*, ErrorExt};
  144use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  145use selections_collection::{
  146    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  147};
  148use serde::{Deserialize, Serialize};
  149use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  150use smallvec::SmallVec;
  151use snippet::Snippet;
  152use std::{
  153    any::TypeId,
  154    borrow::Cow,
  155    cell::RefCell,
  156    cmp::{self, Ordering, Reverse},
  157    mem,
  158    num::NonZeroU32,
  159    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  160    path::{Path, PathBuf},
  161    rc::Rc,
  162    sync::Arc,
  163    time::{Duration, Instant},
  164};
  165pub use sum_tree::Bias;
  166use sum_tree::TreeMap;
  167use text::{BufferId, OffsetUtf16, Rope};
  168use theme::{
  169    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  170    ThemeColors, ThemeSettings,
  171};
  172use ui::{
  173    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  174    Tooltip,
  175};
  176use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  177use workspace::{
  178    item::{ItemHandle, PreviewTabsSettings},
  179    ItemId, RestoreOnStartupBehavior,
  180};
  181use workspace::{
  182    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  183    WorkspaceSettings,
  184};
  185use workspace::{
  186    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  187};
  188use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  189
  190use crate::hover_links::{find_url, find_url_from_range};
  191use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  192
  193pub const FILE_HEADER_HEIGHT: u32 = 2;
  194pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  195pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  196pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  197const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  198const MAX_LINE_LEN: usize = 1024;
  199const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  200const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  201pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  202#[doc(hidden)]
  203pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  204
  205pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  206pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  207
  208pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  209pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  210
  211const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  212    alt: true,
  213    shift: true,
  214    control: false,
  215    platform: false,
  216    function: false,
  217};
  218
  219#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  220pub enum InlayId {
  221    InlineCompletion(usize),
  222    Hint(usize),
  223}
  224
  225impl InlayId {
  226    fn id(&self) -> usize {
  227        match self {
  228            Self::InlineCompletion(id) => *id,
  229            Self::Hint(id) => *id,
  230        }
  231    }
  232}
  233
  234enum DocumentHighlightRead {}
  235enum DocumentHighlightWrite {}
  236enum InputComposition {}
  237enum SelectedTextHighlight {}
  238
  239#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  240pub enum Navigated {
  241    Yes,
  242    No,
  243}
  244
  245impl Navigated {
  246    pub fn from_bool(yes: bool) -> Navigated {
  247        if yes {
  248            Navigated::Yes
  249        } else {
  250            Navigated::No
  251        }
  252    }
  253}
  254
  255pub fn init_settings(cx: &mut App) {
  256    EditorSettings::register(cx);
  257}
  258
  259pub fn init(cx: &mut App) {
  260    init_settings(cx);
  261
  262    workspace::register_project_item::<Editor>(cx);
  263    workspace::FollowableViewRegistry::register::<Editor>(cx);
  264    workspace::register_serializable_item::<Editor>(cx);
  265
  266    cx.observe_new(
  267        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  268            workspace.register_action(Editor::new_file);
  269            workspace.register_action(Editor::new_file_vertical);
  270            workspace.register_action(Editor::new_file_horizontal);
  271            workspace.register_action(Editor::cancel_language_server_work);
  272        },
  273    )
  274    .detach();
  275
  276    cx.on_action(move |_: &workspace::NewFile, cx| {
  277        let app_state = workspace::AppState::global(cx);
  278        if let Some(app_state) = app_state.upgrade() {
  279            workspace::open_new(
  280                Default::default(),
  281                app_state,
  282                cx,
  283                |workspace, window, cx| {
  284                    Editor::new_file(workspace, &Default::default(), window, cx)
  285                },
  286            )
  287            .detach();
  288        }
  289    });
  290    cx.on_action(move |_: &workspace::NewWindow, cx| {
  291        let app_state = workspace::AppState::global(cx);
  292        if let Some(app_state) = app_state.upgrade() {
  293            workspace::open_new(
  294                Default::default(),
  295                app_state,
  296                cx,
  297                |workspace, window, cx| {
  298                    cx.activate(true);
  299                    Editor::new_file(workspace, &Default::default(), window, cx)
  300                },
  301            )
  302            .detach();
  303        }
  304    });
  305}
  306
  307pub struct SearchWithinRange;
  308
  309trait InvalidationRegion {
  310    fn ranges(&self) -> &[Range<Anchor>];
  311}
  312
  313#[derive(Clone, Debug, PartialEq)]
  314pub enum SelectPhase {
  315    Begin {
  316        position: DisplayPoint,
  317        add: bool,
  318        click_count: usize,
  319    },
  320    BeginColumnar {
  321        position: DisplayPoint,
  322        reset: bool,
  323        goal_column: u32,
  324    },
  325    Extend {
  326        position: DisplayPoint,
  327        click_count: usize,
  328    },
  329    Update {
  330        position: DisplayPoint,
  331        goal_column: u32,
  332        scroll_delta: gpui::Point<f32>,
  333    },
  334    End,
  335}
  336
  337#[derive(Clone, Debug)]
  338pub enum SelectMode {
  339    Character,
  340    Word(Range<Anchor>),
  341    Line(Range<Anchor>),
  342    All,
  343}
  344
  345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  346pub enum EditorMode {
  347    SingleLine { auto_width: bool },
  348    AutoHeight { max_lines: usize },
  349    Full,
  350}
  351
  352#[derive(Copy, Clone, Debug)]
  353pub enum SoftWrap {
  354    /// Prefer not to wrap at all.
  355    ///
  356    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  357    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  358    GitDiff,
  359    /// Prefer a single line generally, unless an overly long line is encountered.
  360    None,
  361    /// Soft wrap lines that exceed the editor width.
  362    EditorWidth,
  363    /// Soft wrap lines at the preferred line length.
  364    Column(u32),
  365    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  366    Bounded(u32),
  367}
  368
  369#[derive(Clone)]
  370pub struct EditorStyle {
  371    pub background: Hsla,
  372    pub local_player: PlayerColor,
  373    pub text: TextStyle,
  374    pub scrollbar_width: Pixels,
  375    pub syntax: Arc<SyntaxTheme>,
  376    pub status: StatusColors,
  377    pub inlay_hints_style: HighlightStyle,
  378    pub inline_completion_styles: InlineCompletionStyles,
  379    pub unnecessary_code_fade: f32,
  380}
  381
  382impl Default for EditorStyle {
  383    fn default() -> Self {
  384        Self {
  385            background: Hsla::default(),
  386            local_player: PlayerColor::default(),
  387            text: TextStyle::default(),
  388            scrollbar_width: Pixels::default(),
  389            syntax: Default::default(),
  390            // HACK: Status colors don't have a real default.
  391            // We should look into removing the status colors from the editor
  392            // style and retrieve them directly from the theme.
  393            status: StatusColors::dark(),
  394            inlay_hints_style: HighlightStyle::default(),
  395            inline_completion_styles: InlineCompletionStyles {
  396                insertion: HighlightStyle::default(),
  397                whitespace: HighlightStyle::default(),
  398            },
  399            unnecessary_code_fade: Default::default(),
  400        }
  401    }
  402}
  403
  404pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  405    let show_background = language_settings::language_settings(None, None, cx)
  406        .inlay_hints
  407        .show_background;
  408
  409    HighlightStyle {
  410        color: Some(cx.theme().status().hint),
  411        background_color: show_background.then(|| cx.theme().status().hint_background),
  412        ..HighlightStyle::default()
  413    }
  414}
  415
  416pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  417    InlineCompletionStyles {
  418        insertion: HighlightStyle {
  419            color: Some(cx.theme().status().predictive),
  420            ..HighlightStyle::default()
  421        },
  422        whitespace: HighlightStyle {
  423            background_color: Some(cx.theme().status().created_background),
  424            ..HighlightStyle::default()
  425        },
  426    }
  427}
  428
  429type CompletionId = usize;
  430
  431pub(crate) enum EditDisplayMode {
  432    TabAccept,
  433    DiffPopover,
  434    Inline,
  435}
  436
  437enum InlineCompletion {
  438    Edit {
  439        edits: Vec<(Range<Anchor>, String)>,
  440        edit_preview: Option<EditPreview>,
  441        display_mode: EditDisplayMode,
  442        snapshot: BufferSnapshot,
  443    },
  444    Move {
  445        target: Anchor,
  446        snapshot: BufferSnapshot,
  447    },
  448}
  449
  450struct InlineCompletionState {
  451    inlay_ids: Vec<InlayId>,
  452    completion: InlineCompletion,
  453    completion_id: Option<SharedString>,
  454    invalidation_range: Range<Anchor>,
  455}
  456
  457enum EditPredictionSettings {
  458    Disabled,
  459    Enabled {
  460        show_in_menu: bool,
  461        preview_requires_modifier: bool,
  462    },
  463}
  464
  465enum InlineCompletionHighlight {}
  466
  467pub enum MenuInlineCompletionsPolicy {
  468    Never,
  469    ByProvider,
  470}
  471
  472pub enum EditPredictionPreview {
  473    /// Modifier is not pressed
  474    Inactive,
  475    /// Modifier pressed
  476    Active {
  477        previous_scroll_position: Option<ScrollAnchor>,
  478    },
  479}
  480
  481#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  482struct EditorActionId(usize);
  483
  484impl EditorActionId {
  485    pub fn post_inc(&mut self) -> Self {
  486        let answer = self.0;
  487
  488        *self = Self(answer + 1);
  489
  490        Self(answer)
  491    }
  492}
  493
  494// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  495// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  496
  497type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  498type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  499
  500#[derive(Default)]
  501struct ScrollbarMarkerState {
  502    scrollbar_size: Size<Pixels>,
  503    dirty: bool,
  504    markers: Arc<[PaintQuad]>,
  505    pending_refresh: Option<Task<Result<()>>>,
  506}
  507
  508impl ScrollbarMarkerState {
  509    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  510        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  511    }
  512}
  513
  514#[derive(Clone, Debug)]
  515struct RunnableTasks {
  516    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  517    offset: MultiBufferOffset,
  518    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  519    column: u32,
  520    // Values of all named captures, including those starting with '_'
  521    extra_variables: HashMap<String, String>,
  522    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  523    context_range: Range<BufferOffset>,
  524}
  525
  526impl RunnableTasks {
  527    fn resolve<'a>(
  528        &'a self,
  529        cx: &'a task::TaskContext,
  530    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  531        self.templates.iter().filter_map(|(kind, template)| {
  532            template
  533                .resolve_task(&kind.to_id_base(), cx)
  534                .map(|task| (kind.clone(), task))
  535        })
  536    }
  537}
  538
  539#[derive(Clone)]
  540struct ResolvedTasks {
  541    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  542    position: Anchor,
  543}
  544#[derive(Copy, Clone, Debug)]
  545struct MultiBufferOffset(usize);
  546#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  547struct BufferOffset(usize);
  548
  549// Addons allow storing per-editor state in other crates (e.g. Vim)
  550pub trait Addon: 'static {
  551    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  552
  553    fn render_buffer_header_controls(
  554        &self,
  555        _: &ExcerptInfo,
  556        _: &Window,
  557        _: &App,
  558    ) -> Option<AnyElement> {
  559        None
  560    }
  561
  562    fn to_any(&self) -> &dyn std::any::Any;
  563}
  564
  565#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  566pub enum IsVimMode {
  567    Yes,
  568    No,
  569}
  570
  571/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  572///
  573/// See the [module level documentation](self) for more information.
  574pub struct Editor {
  575    focus_handle: FocusHandle,
  576    last_focused_descendant: Option<WeakFocusHandle>,
  577    /// The text buffer being edited
  578    buffer: Entity<MultiBuffer>,
  579    /// Map of how text in the buffer should be displayed.
  580    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  581    pub display_map: Entity<DisplayMap>,
  582    pub selections: SelectionsCollection,
  583    pub scroll_manager: ScrollManager,
  584    /// When inline assist editors are linked, they all render cursors because
  585    /// typing enters text into each of them, even the ones that aren't focused.
  586    pub(crate) show_cursor_when_unfocused: bool,
  587    columnar_selection_tail: Option<Anchor>,
  588    add_selections_state: Option<AddSelectionsState>,
  589    select_next_state: Option<SelectNextState>,
  590    select_prev_state: Option<SelectNextState>,
  591    selection_history: SelectionHistory,
  592    autoclose_regions: Vec<AutocloseRegion>,
  593    snippet_stack: InvalidationStack<SnippetState>,
  594    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  595    ime_transaction: Option<TransactionId>,
  596    active_diagnostics: Option<ActiveDiagnosticGroup>,
  597    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  598
  599    // TODO: make this a access method
  600    pub project: Option<Entity<Project>>,
  601    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  602    completion_provider: Option<Box<dyn CompletionProvider>>,
  603    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  604    blink_manager: Entity<BlinkManager>,
  605    show_cursor_names: bool,
  606    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  607    pub show_local_selections: bool,
  608    mode: EditorMode,
  609    show_breadcrumbs: bool,
  610    show_gutter: bool,
  611    show_scrollbars: bool,
  612    show_line_numbers: Option<bool>,
  613    use_relative_line_numbers: Option<bool>,
  614    show_git_diff_gutter: Option<bool>,
  615    show_code_actions: Option<bool>,
  616    show_runnables: Option<bool>,
  617    show_wrap_guides: Option<bool>,
  618    show_indent_guides: Option<bool>,
  619    placeholder_text: Option<Arc<str>>,
  620    highlight_order: usize,
  621    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  622    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  623    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  624    scrollbar_marker_state: ScrollbarMarkerState,
  625    active_indent_guides_state: ActiveIndentGuidesState,
  626    nav_history: Option<ItemNavHistory>,
  627    context_menu: RefCell<Option<CodeContextMenu>>,
  628    mouse_context_menu: Option<MouseContextMenu>,
  629    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  630    signature_help_state: SignatureHelpState,
  631    auto_signature_help: Option<bool>,
  632    find_all_references_task_sources: Vec<Anchor>,
  633    next_completion_id: CompletionId,
  634    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  635    code_actions_task: Option<Task<Result<()>>>,
  636    selection_highlight_task: Option<Task<()>>,
  637    document_highlights_task: Option<Task<()>>,
  638    linked_editing_range_task: Option<Task<Option<()>>>,
  639    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  640    pending_rename: Option<RenameState>,
  641    searchable: bool,
  642    cursor_shape: CursorShape,
  643    current_line_highlight: Option<CurrentLineHighlight>,
  644    collapse_matches: bool,
  645    autoindent_mode: Option<AutoindentMode>,
  646    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  647    input_enabled: bool,
  648    use_modal_editing: bool,
  649    read_only: bool,
  650    leader_peer_id: Option<PeerId>,
  651    remote_id: Option<ViewId>,
  652    hover_state: HoverState,
  653    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  654    gutter_hovered: bool,
  655    hovered_link_state: Option<HoveredLinkState>,
  656    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  657    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  658    active_inline_completion: Option<InlineCompletionState>,
  659    /// Used to prevent flickering as the user types while the menu is open
  660    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  661    edit_prediction_settings: EditPredictionSettings,
  662    inline_completions_hidden_for_vim_mode: bool,
  663    show_inline_completions_override: Option<bool>,
  664    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  665    edit_prediction_preview: EditPredictionPreview,
  666    edit_prediction_cursor_on_leading_whitespace: bool,
  667    edit_prediction_requires_modifier_in_leading_space: bool,
  668    inlay_hint_cache: InlayHintCache,
  669    next_inlay_id: usize,
  670    _subscriptions: Vec<Subscription>,
  671    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  672    gutter_dimensions: GutterDimensions,
  673    style: Option<EditorStyle>,
  674    text_style_refinement: Option<TextStyleRefinement>,
  675    next_editor_action_id: EditorActionId,
  676    editor_actions:
  677        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  678    use_autoclose: bool,
  679    use_auto_surround: bool,
  680    auto_replace_emoji_shortcode: bool,
  681    show_git_blame_gutter: bool,
  682    show_git_blame_inline: bool,
  683    show_git_blame_inline_delay_task: Option<Task<()>>,
  684    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  685    distinguish_unstaged_diff_hunks: bool,
  686    git_blame_inline_enabled: bool,
  687    serialize_dirty_buffers: bool,
  688    show_selection_menu: Option<bool>,
  689    blame: Option<Entity<GitBlame>>,
  690    blame_subscription: Option<Subscription>,
  691    custom_context_menu: Option<
  692        Box<
  693            dyn 'static
  694                + Fn(
  695                    &mut Self,
  696                    DisplayPoint,
  697                    &mut Window,
  698                    &mut Context<Self>,
  699                ) -> Option<Entity<ui::ContextMenu>>,
  700        >,
  701    >,
  702    last_bounds: Option<Bounds<Pixels>>,
  703    last_position_map: Option<Rc<PositionMap>>,
  704    expect_bounds_change: Option<Bounds<Pixels>>,
  705    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  706    tasks_update_task: Option<Task<()>>,
  707    in_project_search: bool,
  708    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  709    breadcrumb_header: Option<String>,
  710    focused_block: Option<FocusedBlock>,
  711    next_scroll_position: NextScrollCursorCenterTopBottom,
  712    addons: HashMap<TypeId, Box<dyn Addon>>,
  713    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  714    load_diff_task: Option<Shared<Task<()>>>,
  715    selection_mark_mode: bool,
  716    toggle_fold_multiple_buffers: Task<()>,
  717    _scroll_cursor_center_top_bottom_task: Task<()>,
  718    serialize_selections: Task<()>,
  719}
  720
  721#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  722enum NextScrollCursorCenterTopBottom {
  723    #[default]
  724    Center,
  725    Top,
  726    Bottom,
  727}
  728
  729impl NextScrollCursorCenterTopBottom {
  730    fn next(&self) -> Self {
  731        match self {
  732            Self::Center => Self::Top,
  733            Self::Top => Self::Bottom,
  734            Self::Bottom => Self::Center,
  735        }
  736    }
  737}
  738
  739#[derive(Clone)]
  740pub struct EditorSnapshot {
  741    pub mode: EditorMode,
  742    show_gutter: bool,
  743    show_line_numbers: Option<bool>,
  744    show_git_diff_gutter: Option<bool>,
  745    show_code_actions: Option<bool>,
  746    show_runnables: Option<bool>,
  747    git_blame_gutter_max_author_length: Option<usize>,
  748    pub display_snapshot: DisplaySnapshot,
  749    pub placeholder_text: Option<Arc<str>>,
  750    is_focused: bool,
  751    scroll_anchor: ScrollAnchor,
  752    ongoing_scroll: OngoingScroll,
  753    current_line_highlight: CurrentLineHighlight,
  754    gutter_hovered: bool,
  755}
  756
  757const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  758
  759#[derive(Default, Debug, Clone, Copy)]
  760pub struct GutterDimensions {
  761    pub left_padding: Pixels,
  762    pub right_padding: Pixels,
  763    pub width: Pixels,
  764    pub margin: Pixels,
  765    pub git_blame_entries_width: Option<Pixels>,
  766}
  767
  768impl GutterDimensions {
  769    /// The full width of the space taken up by the gutter.
  770    pub fn full_width(&self) -> Pixels {
  771        self.margin + self.width
  772    }
  773
  774    /// The width of the space reserved for the fold indicators,
  775    /// use alongside 'justify_end' and `gutter_width` to
  776    /// right align content with the line numbers
  777    pub fn fold_area_width(&self) -> Pixels {
  778        self.margin + self.right_padding
  779    }
  780}
  781
  782#[derive(Debug)]
  783pub struct RemoteSelection {
  784    pub replica_id: ReplicaId,
  785    pub selection: Selection<Anchor>,
  786    pub cursor_shape: CursorShape,
  787    pub peer_id: PeerId,
  788    pub line_mode: bool,
  789    pub participant_index: Option<ParticipantIndex>,
  790    pub user_name: Option<SharedString>,
  791}
  792
  793#[derive(Clone, Debug)]
  794struct SelectionHistoryEntry {
  795    selections: Arc<[Selection<Anchor>]>,
  796    select_next_state: Option<SelectNextState>,
  797    select_prev_state: Option<SelectNextState>,
  798    add_selections_state: Option<AddSelectionsState>,
  799}
  800
  801enum SelectionHistoryMode {
  802    Normal,
  803    Undoing,
  804    Redoing,
  805}
  806
  807#[derive(Clone, PartialEq, Eq, Hash)]
  808struct HoveredCursor {
  809    replica_id: u16,
  810    selection_id: usize,
  811}
  812
  813impl Default for SelectionHistoryMode {
  814    fn default() -> Self {
  815        Self::Normal
  816    }
  817}
  818
  819#[derive(Default)]
  820struct SelectionHistory {
  821    #[allow(clippy::type_complexity)]
  822    selections_by_transaction:
  823        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  824    mode: SelectionHistoryMode,
  825    undo_stack: VecDeque<SelectionHistoryEntry>,
  826    redo_stack: VecDeque<SelectionHistoryEntry>,
  827}
  828
  829impl SelectionHistory {
  830    fn insert_transaction(
  831        &mut self,
  832        transaction_id: TransactionId,
  833        selections: Arc<[Selection<Anchor>]>,
  834    ) {
  835        self.selections_by_transaction
  836            .insert(transaction_id, (selections, None));
  837    }
  838
  839    #[allow(clippy::type_complexity)]
  840    fn transaction(
  841        &self,
  842        transaction_id: TransactionId,
  843    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  844        self.selections_by_transaction.get(&transaction_id)
  845    }
  846
  847    #[allow(clippy::type_complexity)]
  848    fn transaction_mut(
  849        &mut self,
  850        transaction_id: TransactionId,
  851    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  852        self.selections_by_transaction.get_mut(&transaction_id)
  853    }
  854
  855    fn push(&mut self, entry: SelectionHistoryEntry) {
  856        if !entry.selections.is_empty() {
  857            match self.mode {
  858                SelectionHistoryMode::Normal => {
  859                    self.push_undo(entry);
  860                    self.redo_stack.clear();
  861                }
  862                SelectionHistoryMode::Undoing => self.push_redo(entry),
  863                SelectionHistoryMode::Redoing => self.push_undo(entry),
  864            }
  865        }
  866    }
  867
  868    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  869        if self
  870            .undo_stack
  871            .back()
  872            .map_or(true, |e| e.selections != entry.selections)
  873        {
  874            self.undo_stack.push_back(entry);
  875            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  876                self.undo_stack.pop_front();
  877            }
  878        }
  879    }
  880
  881    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  882        if self
  883            .redo_stack
  884            .back()
  885            .map_or(true, |e| e.selections != entry.selections)
  886        {
  887            self.redo_stack.push_back(entry);
  888            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  889                self.redo_stack.pop_front();
  890            }
  891        }
  892    }
  893}
  894
  895struct RowHighlight {
  896    index: usize,
  897    range: Range<Anchor>,
  898    color: Hsla,
  899    should_autoscroll: bool,
  900}
  901
  902#[derive(Clone, Debug)]
  903struct AddSelectionsState {
  904    above: bool,
  905    stack: Vec<usize>,
  906}
  907
  908#[derive(Clone)]
  909struct SelectNextState {
  910    query: AhoCorasick,
  911    wordwise: bool,
  912    done: bool,
  913}
  914
  915impl std::fmt::Debug for SelectNextState {
  916    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  917        f.debug_struct(std::any::type_name::<Self>())
  918            .field("wordwise", &self.wordwise)
  919            .field("done", &self.done)
  920            .finish()
  921    }
  922}
  923
  924#[derive(Debug)]
  925struct AutocloseRegion {
  926    selection_id: usize,
  927    range: Range<Anchor>,
  928    pair: BracketPair,
  929}
  930
  931#[derive(Debug)]
  932struct SnippetState {
  933    ranges: Vec<Vec<Range<Anchor>>>,
  934    active_index: usize,
  935    choices: Vec<Option<Vec<String>>>,
  936}
  937
  938#[doc(hidden)]
  939pub struct RenameState {
  940    pub range: Range<Anchor>,
  941    pub old_name: Arc<str>,
  942    pub editor: Entity<Editor>,
  943    block_id: CustomBlockId,
  944}
  945
  946struct InvalidationStack<T>(Vec<T>);
  947
  948struct RegisteredInlineCompletionProvider {
  949    provider: Arc<dyn InlineCompletionProviderHandle>,
  950    _subscription: Subscription,
  951}
  952
  953#[derive(Debug)]
  954struct ActiveDiagnosticGroup {
  955    primary_range: Range<Anchor>,
  956    primary_message: String,
  957    group_id: usize,
  958    blocks: HashMap<CustomBlockId, Diagnostic>,
  959    is_valid: bool,
  960}
  961
  962#[derive(Serialize, Deserialize, Clone, Debug)]
  963pub struct ClipboardSelection {
  964    pub len: usize,
  965    pub is_entire_line: bool,
  966    pub first_line_indent: u32,
  967}
  968
  969#[derive(Debug)]
  970pub(crate) struct NavigationData {
  971    cursor_anchor: Anchor,
  972    cursor_position: Point,
  973    scroll_anchor: ScrollAnchor,
  974    scroll_top_row: u32,
  975}
  976
  977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  978pub enum GotoDefinitionKind {
  979    Symbol,
  980    Declaration,
  981    Type,
  982    Implementation,
  983}
  984
  985#[derive(Debug, Clone)]
  986enum InlayHintRefreshReason {
  987    Toggle(bool),
  988    SettingsChange(InlayHintSettings),
  989    NewLinesShown,
  990    BufferEdited(HashSet<Arc<Language>>),
  991    RefreshRequested,
  992    ExcerptsRemoved(Vec<ExcerptId>),
  993}
  994
  995impl InlayHintRefreshReason {
  996    fn description(&self) -> &'static str {
  997        match self {
  998            Self::Toggle(_) => "toggle",
  999            Self::SettingsChange(_) => "settings change",
 1000            Self::NewLinesShown => "new lines shown",
 1001            Self::BufferEdited(_) => "buffer edited",
 1002            Self::RefreshRequested => "refresh requested",
 1003            Self::ExcerptsRemoved(_) => "excerpts removed",
 1004        }
 1005    }
 1006}
 1007
 1008pub enum FormatTarget {
 1009    Buffers,
 1010    Ranges(Vec<Range<MultiBufferPoint>>),
 1011}
 1012
 1013pub(crate) struct FocusedBlock {
 1014    id: BlockId,
 1015    focus_handle: WeakFocusHandle,
 1016}
 1017
 1018#[derive(Clone)]
 1019enum JumpData {
 1020    MultiBufferRow {
 1021        row: MultiBufferRow,
 1022        line_offset_from_top: u32,
 1023    },
 1024    MultiBufferPoint {
 1025        excerpt_id: ExcerptId,
 1026        position: Point,
 1027        anchor: text::Anchor,
 1028        line_offset_from_top: u32,
 1029    },
 1030}
 1031
 1032pub enum MultibufferSelectionMode {
 1033    First,
 1034    All,
 1035}
 1036
 1037impl Editor {
 1038    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1039        let buffer = cx.new(|cx| Buffer::local("", cx));
 1040        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1041        Self::new(
 1042            EditorMode::SingleLine { auto_width: false },
 1043            buffer,
 1044            None,
 1045            false,
 1046            window,
 1047            cx,
 1048        )
 1049    }
 1050
 1051    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1052        let buffer = cx.new(|cx| Buffer::local("", cx));
 1053        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1054        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1055    }
 1056
 1057    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1058        let buffer = cx.new(|cx| Buffer::local("", cx));
 1059        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1060        Self::new(
 1061            EditorMode::SingleLine { auto_width: true },
 1062            buffer,
 1063            None,
 1064            false,
 1065            window,
 1066            cx,
 1067        )
 1068    }
 1069
 1070    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1071        let buffer = cx.new(|cx| Buffer::local("", cx));
 1072        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1073        Self::new(
 1074            EditorMode::AutoHeight { max_lines },
 1075            buffer,
 1076            None,
 1077            false,
 1078            window,
 1079            cx,
 1080        )
 1081    }
 1082
 1083    pub fn for_buffer(
 1084        buffer: Entity<Buffer>,
 1085        project: Option<Entity<Project>>,
 1086        window: &mut Window,
 1087        cx: &mut Context<Self>,
 1088    ) -> Self {
 1089        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1090        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1091    }
 1092
 1093    pub fn for_multibuffer(
 1094        buffer: Entity<MultiBuffer>,
 1095        project: Option<Entity<Project>>,
 1096        show_excerpt_controls: bool,
 1097        window: &mut Window,
 1098        cx: &mut Context<Self>,
 1099    ) -> Self {
 1100        Self::new(
 1101            EditorMode::Full,
 1102            buffer,
 1103            project,
 1104            show_excerpt_controls,
 1105            window,
 1106            cx,
 1107        )
 1108    }
 1109
 1110    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1111        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1112        let mut clone = Self::new(
 1113            self.mode,
 1114            self.buffer.clone(),
 1115            self.project.clone(),
 1116            show_excerpt_controls,
 1117            window,
 1118            cx,
 1119        );
 1120        self.display_map.update(cx, |display_map, cx| {
 1121            let snapshot = display_map.snapshot(cx);
 1122            clone.display_map.update(cx, |display_map, cx| {
 1123                display_map.set_state(&snapshot, cx);
 1124            });
 1125        });
 1126        clone.selections.clone_state(&self.selections);
 1127        clone.scroll_manager.clone_state(&self.scroll_manager);
 1128        clone.searchable = self.searchable;
 1129        clone
 1130    }
 1131
 1132    pub fn new(
 1133        mode: EditorMode,
 1134        buffer: Entity<MultiBuffer>,
 1135        project: Option<Entity<Project>>,
 1136        show_excerpt_controls: bool,
 1137        window: &mut Window,
 1138        cx: &mut Context<Self>,
 1139    ) -> Self {
 1140        let style = window.text_style();
 1141        let font_size = style.font_size.to_pixels(window.rem_size());
 1142        let editor = cx.entity().downgrade();
 1143        let fold_placeholder = FoldPlaceholder {
 1144            constrain_width: true,
 1145            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1146                let editor = editor.clone();
 1147                div()
 1148                    .id(fold_id)
 1149                    .bg(cx.theme().colors().ghost_element_background)
 1150                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1151                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1152                    .rounded_sm()
 1153                    .size_full()
 1154                    .cursor_pointer()
 1155                    .child("")
 1156                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1157                    .on_click(move |_, _window, cx| {
 1158                        editor
 1159                            .update(cx, |editor, cx| {
 1160                                editor.unfold_ranges(
 1161                                    &[fold_range.start..fold_range.end],
 1162                                    true,
 1163                                    false,
 1164                                    cx,
 1165                                );
 1166                                cx.stop_propagation();
 1167                            })
 1168                            .ok();
 1169                    })
 1170                    .into_any()
 1171            }),
 1172            merge_adjacent: true,
 1173            ..Default::default()
 1174        };
 1175        let display_map = cx.new(|cx| {
 1176            DisplayMap::new(
 1177                buffer.clone(),
 1178                style.font(),
 1179                font_size,
 1180                None,
 1181                show_excerpt_controls,
 1182                FILE_HEADER_HEIGHT,
 1183                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1184                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1185                fold_placeholder,
 1186                cx,
 1187            )
 1188        });
 1189
 1190        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1191
 1192        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1193
 1194        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1195            .then(|| language_settings::SoftWrap::None);
 1196
 1197        let mut project_subscriptions = Vec::new();
 1198        if mode == EditorMode::Full {
 1199            if let Some(project) = project.as_ref() {
 1200                if buffer.read(cx).is_singleton() {
 1201                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1202                        cx.emit(EditorEvent::TitleChanged);
 1203                    }));
 1204                }
 1205                project_subscriptions.push(cx.subscribe_in(
 1206                    project,
 1207                    window,
 1208                    |editor, _, event, window, cx| {
 1209                        if let project::Event::RefreshInlayHints = event {
 1210                            editor
 1211                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1212                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1213                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1214                                let focus_handle = editor.focus_handle(cx);
 1215                                if focus_handle.is_focused(window) {
 1216                                    let snapshot = buffer.read(cx).snapshot();
 1217                                    for (range, snippet) in snippet_edits {
 1218                                        let editor_range =
 1219                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1220                                        editor
 1221                                            .insert_snippet(
 1222                                                &[editor_range],
 1223                                                snippet.clone(),
 1224                                                window,
 1225                                                cx,
 1226                                            )
 1227                                            .ok();
 1228                                    }
 1229                                }
 1230                            }
 1231                        }
 1232                    },
 1233                ));
 1234                if let Some(task_inventory) = project
 1235                    .read(cx)
 1236                    .task_store()
 1237                    .read(cx)
 1238                    .task_inventory()
 1239                    .cloned()
 1240                {
 1241                    project_subscriptions.push(cx.observe_in(
 1242                        &task_inventory,
 1243                        window,
 1244                        |editor, _, window, cx| {
 1245                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1246                        },
 1247                    ));
 1248                }
 1249            }
 1250        }
 1251
 1252        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1253
 1254        let inlay_hint_settings =
 1255            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1256        let focus_handle = cx.focus_handle();
 1257        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1258            .detach();
 1259        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1260            .detach();
 1261        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1262            .detach();
 1263        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1264            .detach();
 1265
 1266        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1267            Some(false)
 1268        } else {
 1269            None
 1270        };
 1271
 1272        let mut code_action_providers = Vec::new();
 1273        let mut load_uncommitted_diff = None;
 1274        if let Some(project) = project.clone() {
 1275            load_uncommitted_diff = Some(
 1276                get_uncommitted_diff_for_buffer(
 1277                    &project,
 1278                    buffer.read(cx).all_buffers(),
 1279                    buffer.clone(),
 1280                    cx,
 1281                )
 1282                .shared(),
 1283            );
 1284            code_action_providers.push(Rc::new(project) as Rc<_>);
 1285        }
 1286
 1287        let mut this = Self {
 1288            focus_handle,
 1289            show_cursor_when_unfocused: false,
 1290            last_focused_descendant: None,
 1291            buffer: buffer.clone(),
 1292            display_map: display_map.clone(),
 1293            selections,
 1294            scroll_manager: ScrollManager::new(cx),
 1295            columnar_selection_tail: None,
 1296            add_selections_state: None,
 1297            select_next_state: None,
 1298            select_prev_state: None,
 1299            selection_history: Default::default(),
 1300            autoclose_regions: Default::default(),
 1301            snippet_stack: Default::default(),
 1302            select_larger_syntax_node_stack: Vec::new(),
 1303            ime_transaction: Default::default(),
 1304            active_diagnostics: None,
 1305            soft_wrap_mode_override,
 1306            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1307            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1308            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1309            project,
 1310            blink_manager: blink_manager.clone(),
 1311            show_local_selections: true,
 1312            show_scrollbars: true,
 1313            mode,
 1314            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1315            show_gutter: mode == EditorMode::Full,
 1316            show_line_numbers: None,
 1317            use_relative_line_numbers: None,
 1318            show_git_diff_gutter: None,
 1319            show_code_actions: None,
 1320            show_runnables: None,
 1321            show_wrap_guides: None,
 1322            show_indent_guides,
 1323            placeholder_text: None,
 1324            highlight_order: 0,
 1325            highlighted_rows: HashMap::default(),
 1326            background_highlights: Default::default(),
 1327            gutter_highlights: TreeMap::default(),
 1328            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1329            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1330            nav_history: None,
 1331            context_menu: RefCell::new(None),
 1332            mouse_context_menu: None,
 1333            completion_tasks: Default::default(),
 1334            signature_help_state: SignatureHelpState::default(),
 1335            auto_signature_help: None,
 1336            find_all_references_task_sources: Vec::new(),
 1337            next_completion_id: 0,
 1338            next_inlay_id: 0,
 1339            code_action_providers,
 1340            available_code_actions: Default::default(),
 1341            code_actions_task: Default::default(),
 1342            selection_highlight_task: Default::default(),
 1343            document_highlights_task: Default::default(),
 1344            linked_editing_range_task: Default::default(),
 1345            pending_rename: Default::default(),
 1346            searchable: true,
 1347            cursor_shape: EditorSettings::get_global(cx)
 1348                .cursor_shape
 1349                .unwrap_or_default(),
 1350            current_line_highlight: None,
 1351            autoindent_mode: Some(AutoindentMode::EachLine),
 1352            collapse_matches: false,
 1353            workspace: None,
 1354            input_enabled: true,
 1355            use_modal_editing: mode == EditorMode::Full,
 1356            read_only: false,
 1357            use_autoclose: true,
 1358            use_auto_surround: true,
 1359            auto_replace_emoji_shortcode: false,
 1360            leader_peer_id: None,
 1361            remote_id: None,
 1362            hover_state: Default::default(),
 1363            pending_mouse_down: None,
 1364            hovered_link_state: Default::default(),
 1365            edit_prediction_provider: None,
 1366            active_inline_completion: None,
 1367            stale_inline_completion_in_menu: None,
 1368            edit_prediction_preview: EditPredictionPreview::Inactive,
 1369            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1370
 1371            gutter_hovered: false,
 1372            pixel_position_of_newest_cursor: None,
 1373            last_bounds: None,
 1374            last_position_map: None,
 1375            expect_bounds_change: None,
 1376            gutter_dimensions: GutterDimensions::default(),
 1377            style: None,
 1378            show_cursor_names: false,
 1379            hovered_cursors: Default::default(),
 1380            next_editor_action_id: EditorActionId::default(),
 1381            editor_actions: Rc::default(),
 1382            inline_completions_hidden_for_vim_mode: false,
 1383            show_inline_completions_override: None,
 1384            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1385            edit_prediction_settings: EditPredictionSettings::Disabled,
 1386            edit_prediction_cursor_on_leading_whitespace: false,
 1387            edit_prediction_requires_modifier_in_leading_space: true,
 1388            custom_context_menu: None,
 1389            show_git_blame_gutter: false,
 1390            show_git_blame_inline: false,
 1391            distinguish_unstaged_diff_hunks: false,
 1392            show_selection_menu: None,
 1393            show_git_blame_inline_delay_task: None,
 1394            git_blame_inline_tooltip: None,
 1395            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1396            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1397                .session
 1398                .restore_unsaved_buffers,
 1399            blame: None,
 1400            blame_subscription: None,
 1401            tasks: Default::default(),
 1402            _subscriptions: vec![
 1403                cx.observe(&buffer, Self::on_buffer_changed),
 1404                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1405                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1406                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1407                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1408                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1409                cx.observe_window_activation(window, |editor, window, cx| {
 1410                    let active = window.is_window_active();
 1411                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1412                        if active {
 1413                            blink_manager.enable(cx);
 1414                        } else {
 1415                            blink_manager.disable(cx);
 1416                        }
 1417                    });
 1418                }),
 1419            ],
 1420            tasks_update_task: None,
 1421            linked_edit_ranges: Default::default(),
 1422            in_project_search: false,
 1423            previous_search_ranges: None,
 1424            breadcrumb_header: None,
 1425            focused_block: None,
 1426            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1427            addons: HashMap::default(),
 1428            registered_buffers: HashMap::default(),
 1429            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1430            selection_mark_mode: false,
 1431            toggle_fold_multiple_buffers: Task::ready(()),
 1432            serialize_selections: Task::ready(()),
 1433            text_style_refinement: None,
 1434            load_diff_task: load_uncommitted_diff,
 1435        };
 1436        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1437        this._subscriptions.extend(project_subscriptions);
 1438
 1439        this.end_selection(window, cx);
 1440        this.scroll_manager.show_scrollbar(window, cx);
 1441
 1442        if mode == EditorMode::Full {
 1443            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1444            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1445
 1446            if this.git_blame_inline_enabled {
 1447                this.git_blame_inline_enabled = true;
 1448                this.start_git_blame_inline(false, window, cx);
 1449            }
 1450
 1451            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1452                if let Some(project) = this.project.as_ref() {
 1453                    let handle = project.update(cx, |project, cx| {
 1454                        project.register_buffer_with_language_servers(&buffer, cx)
 1455                    });
 1456                    this.registered_buffers
 1457                        .insert(buffer.read(cx).remote_id(), handle);
 1458                }
 1459            }
 1460        }
 1461
 1462        this.report_editor_event("Editor Opened", None, cx);
 1463        this
 1464    }
 1465
 1466    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1467        self.mouse_context_menu
 1468            .as_ref()
 1469            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1470    }
 1471
 1472    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1473        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1474    }
 1475
 1476    fn key_context_internal(
 1477        &self,
 1478        has_active_edit_prediction: bool,
 1479        window: &Window,
 1480        cx: &App,
 1481    ) -> KeyContext {
 1482        let mut key_context = KeyContext::new_with_defaults();
 1483        key_context.add("Editor");
 1484        let mode = match self.mode {
 1485            EditorMode::SingleLine { .. } => "single_line",
 1486            EditorMode::AutoHeight { .. } => "auto_height",
 1487            EditorMode::Full => "full",
 1488        };
 1489
 1490        if EditorSettings::jupyter_enabled(cx) {
 1491            key_context.add("jupyter");
 1492        }
 1493
 1494        key_context.set("mode", mode);
 1495        if self.pending_rename.is_some() {
 1496            key_context.add("renaming");
 1497        }
 1498
 1499        match self.context_menu.borrow().as_ref() {
 1500            Some(CodeContextMenu::Completions(_)) => {
 1501                key_context.add("menu");
 1502                key_context.add("showing_completions");
 1503            }
 1504            Some(CodeContextMenu::CodeActions(_)) => {
 1505                key_context.add("menu");
 1506                key_context.add("showing_code_actions")
 1507            }
 1508            None => {}
 1509        }
 1510
 1511        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1512        if !self.focus_handle(cx).contains_focused(window, cx)
 1513            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1514        {
 1515            for addon in self.addons.values() {
 1516                addon.extend_key_context(&mut key_context, cx)
 1517            }
 1518        }
 1519
 1520        if let Some(extension) = self
 1521            .buffer
 1522            .read(cx)
 1523            .as_singleton()
 1524            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1525        {
 1526            key_context.set("extension", extension.to_string());
 1527        }
 1528
 1529        if has_active_edit_prediction {
 1530            if self.edit_prediction_in_conflict() {
 1531                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1532            } else {
 1533                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1534                key_context.add("copilot_suggestion");
 1535            }
 1536        }
 1537
 1538        if self.selection_mark_mode {
 1539            key_context.add("selection_mode");
 1540        }
 1541
 1542        key_context
 1543    }
 1544
 1545    pub fn edit_prediction_in_conflict(&self) -> bool {
 1546        if !self.show_edit_predictions_in_menu() {
 1547            return false;
 1548        }
 1549
 1550        let showing_completions = self
 1551            .context_menu
 1552            .borrow()
 1553            .as_ref()
 1554            .map_or(false, |context| {
 1555                matches!(context, CodeContextMenu::Completions(_))
 1556            });
 1557
 1558        showing_completions
 1559            || self.edit_prediction_requires_modifier()
 1560            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1561            // bindings to insert tab characters.
 1562            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1563    }
 1564
 1565    pub fn accept_edit_prediction_keybind(
 1566        &self,
 1567        window: &Window,
 1568        cx: &App,
 1569    ) -> AcceptEditPredictionBinding {
 1570        let key_context = self.key_context_internal(true, window, cx);
 1571        let in_conflict = self.edit_prediction_in_conflict();
 1572
 1573        AcceptEditPredictionBinding(
 1574            window
 1575                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1576                .into_iter()
 1577                .filter(|binding| {
 1578                    !in_conflict
 1579                        || binding
 1580                            .keystrokes()
 1581                            .first()
 1582                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1583                })
 1584                .rev()
 1585                .min_by_key(|binding| {
 1586                    binding
 1587                        .keystrokes()
 1588                        .first()
 1589                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1590                }),
 1591        )
 1592    }
 1593
 1594    pub fn new_file(
 1595        workspace: &mut Workspace,
 1596        _: &workspace::NewFile,
 1597        window: &mut Window,
 1598        cx: &mut Context<Workspace>,
 1599    ) {
 1600        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1601            "Failed to create buffer",
 1602            window,
 1603            cx,
 1604            |e, _, _| match e.error_code() {
 1605                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1606                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1607                e.error_tag("required").unwrap_or("the latest version")
 1608            )),
 1609                _ => None,
 1610            },
 1611        );
 1612    }
 1613
 1614    pub fn new_in_workspace(
 1615        workspace: &mut Workspace,
 1616        window: &mut Window,
 1617        cx: &mut Context<Workspace>,
 1618    ) -> Task<Result<Entity<Editor>>> {
 1619        let project = workspace.project().clone();
 1620        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1621
 1622        cx.spawn_in(window, |workspace, mut cx| async move {
 1623            let buffer = create.await?;
 1624            workspace.update_in(&mut cx, |workspace, window, cx| {
 1625                let editor =
 1626                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1627                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1628                editor
 1629            })
 1630        })
 1631    }
 1632
 1633    fn new_file_vertical(
 1634        workspace: &mut Workspace,
 1635        _: &workspace::NewFileSplitVertical,
 1636        window: &mut Window,
 1637        cx: &mut Context<Workspace>,
 1638    ) {
 1639        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1640    }
 1641
 1642    fn new_file_horizontal(
 1643        workspace: &mut Workspace,
 1644        _: &workspace::NewFileSplitHorizontal,
 1645        window: &mut Window,
 1646        cx: &mut Context<Workspace>,
 1647    ) {
 1648        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1649    }
 1650
 1651    fn new_file_in_direction(
 1652        workspace: &mut Workspace,
 1653        direction: SplitDirection,
 1654        window: &mut Window,
 1655        cx: &mut Context<Workspace>,
 1656    ) {
 1657        let project = workspace.project().clone();
 1658        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1659
 1660        cx.spawn_in(window, |workspace, mut cx| async move {
 1661            let buffer = create.await?;
 1662            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1663                workspace.split_item(
 1664                    direction,
 1665                    Box::new(
 1666                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1667                    ),
 1668                    window,
 1669                    cx,
 1670                )
 1671            })?;
 1672            anyhow::Ok(())
 1673        })
 1674        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1675            match e.error_code() {
 1676                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1677                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1678                e.error_tag("required").unwrap_or("the latest version")
 1679            )),
 1680                _ => None,
 1681            }
 1682        });
 1683    }
 1684
 1685    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1686        self.leader_peer_id
 1687    }
 1688
 1689    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1690        &self.buffer
 1691    }
 1692
 1693    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1694        self.workspace.as_ref()?.0.upgrade()
 1695    }
 1696
 1697    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1698        self.buffer().read(cx).title(cx)
 1699    }
 1700
 1701    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1702        let git_blame_gutter_max_author_length = self
 1703            .render_git_blame_gutter(cx)
 1704            .then(|| {
 1705                if let Some(blame) = self.blame.as_ref() {
 1706                    let max_author_length =
 1707                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1708                    Some(max_author_length)
 1709                } else {
 1710                    None
 1711                }
 1712            })
 1713            .flatten();
 1714
 1715        EditorSnapshot {
 1716            mode: self.mode,
 1717            show_gutter: self.show_gutter,
 1718            show_line_numbers: self.show_line_numbers,
 1719            show_git_diff_gutter: self.show_git_diff_gutter,
 1720            show_code_actions: self.show_code_actions,
 1721            show_runnables: self.show_runnables,
 1722            git_blame_gutter_max_author_length,
 1723            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1724            scroll_anchor: self.scroll_manager.anchor(),
 1725            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1726            placeholder_text: self.placeholder_text.clone(),
 1727            is_focused: self.focus_handle.is_focused(window),
 1728            current_line_highlight: self
 1729                .current_line_highlight
 1730                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1731            gutter_hovered: self.gutter_hovered,
 1732        }
 1733    }
 1734
 1735    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1736        self.buffer.read(cx).language_at(point, cx)
 1737    }
 1738
 1739    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1740        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1741    }
 1742
 1743    pub fn active_excerpt(
 1744        &self,
 1745        cx: &App,
 1746    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1747        self.buffer
 1748            .read(cx)
 1749            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1750    }
 1751
 1752    pub fn mode(&self) -> EditorMode {
 1753        self.mode
 1754    }
 1755
 1756    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1757        self.collaboration_hub.as_deref()
 1758    }
 1759
 1760    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1761        self.collaboration_hub = Some(hub);
 1762    }
 1763
 1764    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1765        self.in_project_search = in_project_search;
 1766    }
 1767
 1768    pub fn set_custom_context_menu(
 1769        &mut self,
 1770        f: impl 'static
 1771            + Fn(
 1772                &mut Self,
 1773                DisplayPoint,
 1774                &mut Window,
 1775                &mut Context<Self>,
 1776            ) -> Option<Entity<ui::ContextMenu>>,
 1777    ) {
 1778        self.custom_context_menu = Some(Box::new(f))
 1779    }
 1780
 1781    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1782        self.completion_provider = provider;
 1783    }
 1784
 1785    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1786        self.semantics_provider.clone()
 1787    }
 1788
 1789    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1790        self.semantics_provider = provider;
 1791    }
 1792
 1793    pub fn set_edit_prediction_provider<T>(
 1794        &mut self,
 1795        provider: Option<Entity<T>>,
 1796        window: &mut Window,
 1797        cx: &mut Context<Self>,
 1798    ) where
 1799        T: EditPredictionProvider,
 1800    {
 1801        self.edit_prediction_provider =
 1802            provider.map(|provider| RegisteredInlineCompletionProvider {
 1803                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1804                    if this.focus_handle.is_focused(window) {
 1805                        this.update_visible_inline_completion(window, cx);
 1806                    }
 1807                }),
 1808                provider: Arc::new(provider),
 1809            });
 1810        self.refresh_inline_completion(false, false, window, cx);
 1811    }
 1812
 1813    pub fn placeholder_text(&self) -> Option<&str> {
 1814        self.placeholder_text.as_deref()
 1815    }
 1816
 1817    pub fn set_placeholder_text(
 1818        &mut self,
 1819        placeholder_text: impl Into<Arc<str>>,
 1820        cx: &mut Context<Self>,
 1821    ) {
 1822        let placeholder_text = Some(placeholder_text.into());
 1823        if self.placeholder_text != placeholder_text {
 1824            self.placeholder_text = placeholder_text;
 1825            cx.notify();
 1826        }
 1827    }
 1828
 1829    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1830        self.cursor_shape = cursor_shape;
 1831
 1832        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1833        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1834
 1835        cx.notify();
 1836    }
 1837
 1838    pub fn set_current_line_highlight(
 1839        &mut self,
 1840        current_line_highlight: Option<CurrentLineHighlight>,
 1841    ) {
 1842        self.current_line_highlight = current_line_highlight;
 1843    }
 1844
 1845    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1846        self.collapse_matches = collapse_matches;
 1847    }
 1848
 1849    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1850        let buffers = self.buffer.read(cx).all_buffers();
 1851        let Some(project) = self.project.as_ref() else {
 1852            return;
 1853        };
 1854        project.update(cx, |project, cx| {
 1855            for buffer in buffers {
 1856                self.registered_buffers
 1857                    .entry(buffer.read(cx).remote_id())
 1858                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1859            }
 1860        })
 1861    }
 1862
 1863    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1864        if self.collapse_matches {
 1865            return range.start..range.start;
 1866        }
 1867        range.clone()
 1868    }
 1869
 1870    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1871        if self.display_map.read(cx).clip_at_line_ends != clip {
 1872            self.display_map
 1873                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1874        }
 1875    }
 1876
 1877    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1878        self.input_enabled = input_enabled;
 1879    }
 1880
 1881    pub fn set_inline_completions_hidden_for_vim_mode(
 1882        &mut self,
 1883        hidden: bool,
 1884        window: &mut Window,
 1885        cx: &mut Context<Self>,
 1886    ) {
 1887        if hidden != self.inline_completions_hidden_for_vim_mode {
 1888            self.inline_completions_hidden_for_vim_mode = hidden;
 1889            if hidden {
 1890                self.update_visible_inline_completion(window, cx);
 1891            } else {
 1892                self.refresh_inline_completion(true, false, window, cx);
 1893            }
 1894        }
 1895    }
 1896
 1897    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1898        self.menu_inline_completions_policy = value;
 1899    }
 1900
 1901    pub fn set_autoindent(&mut self, autoindent: bool) {
 1902        if autoindent {
 1903            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1904        } else {
 1905            self.autoindent_mode = None;
 1906        }
 1907    }
 1908
 1909    pub fn read_only(&self, cx: &App) -> bool {
 1910        self.read_only || self.buffer.read(cx).read_only()
 1911    }
 1912
 1913    pub fn set_read_only(&mut self, read_only: bool) {
 1914        self.read_only = read_only;
 1915    }
 1916
 1917    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1918        self.use_autoclose = autoclose;
 1919    }
 1920
 1921    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1922        self.use_auto_surround = auto_surround;
 1923    }
 1924
 1925    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1926        self.auto_replace_emoji_shortcode = auto_replace;
 1927    }
 1928
 1929    pub fn toggle_inline_completions(
 1930        &mut self,
 1931        _: &ToggleEditPrediction,
 1932        window: &mut Window,
 1933        cx: &mut Context<Self>,
 1934    ) {
 1935        if self.show_inline_completions_override.is_some() {
 1936            self.set_show_edit_predictions(None, window, cx);
 1937        } else {
 1938            let show_edit_predictions = !self.edit_predictions_enabled();
 1939            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1940        }
 1941    }
 1942
 1943    pub fn set_show_edit_predictions(
 1944        &mut self,
 1945        show_edit_predictions: Option<bool>,
 1946        window: &mut Window,
 1947        cx: &mut Context<Self>,
 1948    ) {
 1949        self.show_inline_completions_override = show_edit_predictions;
 1950        self.refresh_inline_completion(false, true, window, cx);
 1951    }
 1952
 1953    fn inline_completions_disabled_in_scope(
 1954        &self,
 1955        buffer: &Entity<Buffer>,
 1956        buffer_position: language::Anchor,
 1957        cx: &App,
 1958    ) -> bool {
 1959        let snapshot = buffer.read(cx).snapshot();
 1960        let settings = snapshot.settings_at(buffer_position, cx);
 1961
 1962        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1963            return false;
 1964        };
 1965
 1966        scope.override_name().map_or(false, |scope_name| {
 1967            settings
 1968                .edit_predictions_disabled_in
 1969                .iter()
 1970                .any(|s| s == scope_name)
 1971        })
 1972    }
 1973
 1974    pub fn set_use_modal_editing(&mut self, to: bool) {
 1975        self.use_modal_editing = to;
 1976    }
 1977
 1978    pub fn use_modal_editing(&self) -> bool {
 1979        self.use_modal_editing
 1980    }
 1981
 1982    fn selections_did_change(
 1983        &mut self,
 1984        local: bool,
 1985        old_cursor_position: &Anchor,
 1986        show_completions: bool,
 1987        window: &mut Window,
 1988        cx: &mut Context<Self>,
 1989    ) {
 1990        window.invalidate_character_coordinates();
 1991
 1992        // Copy selections to primary selection buffer
 1993        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1994        if local {
 1995            let selections = self.selections.all::<usize>(cx);
 1996            let buffer_handle = self.buffer.read(cx).read(cx);
 1997
 1998            let mut text = String::new();
 1999            for (index, selection) in selections.iter().enumerate() {
 2000                let text_for_selection = buffer_handle
 2001                    .text_for_range(selection.start..selection.end)
 2002                    .collect::<String>();
 2003
 2004                text.push_str(&text_for_selection);
 2005                if index != selections.len() - 1 {
 2006                    text.push('\n');
 2007                }
 2008            }
 2009
 2010            if !text.is_empty() {
 2011                cx.write_to_primary(ClipboardItem::new_string(text));
 2012            }
 2013        }
 2014
 2015        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2016            self.buffer.update(cx, |buffer, cx| {
 2017                buffer.set_active_selections(
 2018                    &self.selections.disjoint_anchors(),
 2019                    self.selections.line_mode,
 2020                    self.cursor_shape,
 2021                    cx,
 2022                )
 2023            });
 2024        }
 2025        let display_map = self
 2026            .display_map
 2027            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2028        let buffer = &display_map.buffer_snapshot;
 2029        self.add_selections_state = None;
 2030        self.select_next_state = None;
 2031        self.select_prev_state = None;
 2032        self.select_larger_syntax_node_stack.clear();
 2033        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2034        self.snippet_stack
 2035            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2036        self.take_rename(false, window, cx);
 2037
 2038        let new_cursor_position = self.selections.newest_anchor().head();
 2039
 2040        self.push_to_nav_history(
 2041            *old_cursor_position,
 2042            Some(new_cursor_position.to_point(buffer)),
 2043            cx,
 2044        );
 2045
 2046        if local {
 2047            let new_cursor_position = self.selections.newest_anchor().head();
 2048            let mut context_menu = self.context_menu.borrow_mut();
 2049            let completion_menu = match context_menu.as_ref() {
 2050                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2051                _ => {
 2052                    *context_menu = None;
 2053                    None
 2054                }
 2055            };
 2056            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2057                if !self.registered_buffers.contains_key(&buffer_id) {
 2058                    if let Some(project) = self.project.as_ref() {
 2059                        project.update(cx, |project, cx| {
 2060                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2061                                return;
 2062                            };
 2063                            self.registered_buffers.insert(
 2064                                buffer_id,
 2065                                project.register_buffer_with_language_servers(&buffer, cx),
 2066                            );
 2067                        })
 2068                    }
 2069                }
 2070            }
 2071
 2072            if let Some(completion_menu) = completion_menu {
 2073                let cursor_position = new_cursor_position.to_offset(buffer);
 2074                let (word_range, kind) =
 2075                    buffer.surrounding_word(completion_menu.initial_position, true);
 2076                if kind == Some(CharKind::Word)
 2077                    && word_range.to_inclusive().contains(&cursor_position)
 2078                {
 2079                    let mut completion_menu = completion_menu.clone();
 2080                    drop(context_menu);
 2081
 2082                    let query = Self::completion_query(buffer, cursor_position);
 2083                    cx.spawn(move |this, mut cx| async move {
 2084                        completion_menu
 2085                            .filter(query.as_deref(), cx.background_executor().clone())
 2086                            .await;
 2087
 2088                        this.update(&mut cx, |this, cx| {
 2089                            let mut context_menu = this.context_menu.borrow_mut();
 2090                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2091                            else {
 2092                                return;
 2093                            };
 2094
 2095                            if menu.id > completion_menu.id {
 2096                                return;
 2097                            }
 2098
 2099                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2100                            drop(context_menu);
 2101                            cx.notify();
 2102                        })
 2103                    })
 2104                    .detach();
 2105
 2106                    if show_completions {
 2107                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2108                    }
 2109                } else {
 2110                    drop(context_menu);
 2111                    self.hide_context_menu(window, cx);
 2112                }
 2113            } else {
 2114                drop(context_menu);
 2115            }
 2116
 2117            hide_hover(self, cx);
 2118
 2119            if old_cursor_position.to_display_point(&display_map).row()
 2120                != new_cursor_position.to_display_point(&display_map).row()
 2121            {
 2122                self.available_code_actions.take();
 2123            }
 2124            self.refresh_code_actions(window, cx);
 2125            self.refresh_document_highlights(cx);
 2126            self.refresh_selected_text_highlights(window, cx);
 2127            refresh_matching_bracket_highlights(self, window, cx);
 2128            self.update_visible_inline_completion(window, cx);
 2129            self.edit_prediction_requires_modifier_in_leading_space = true;
 2130            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2131            if self.git_blame_inline_enabled {
 2132                self.start_inline_blame_timer(window, cx);
 2133            }
 2134        }
 2135
 2136        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2137        cx.emit(EditorEvent::SelectionsChanged { local });
 2138
 2139        let selections = &self.selections.disjoint;
 2140        if selections.len() == 1 {
 2141            cx.emit(SearchEvent::ActiveMatchChanged)
 2142        }
 2143        if local
 2144            && self.is_singleton(cx)
 2145            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2146        {
 2147            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2148                let background_executor = cx.background_executor().clone();
 2149                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2150                let snapshot = self.buffer().read(cx).snapshot(cx);
 2151                let selections = selections.clone();
 2152                self.serialize_selections = cx.background_spawn(async move {
 2153                    background_executor.timer(Duration::from_millis(100)).await;
 2154                    let selections = selections
 2155                        .iter()
 2156                        .map(|selection| {
 2157                            (
 2158                                selection.start.to_offset(&snapshot),
 2159                                selection.end.to_offset(&snapshot),
 2160                            )
 2161                        })
 2162                        .collect();
 2163                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2164                        .await
 2165                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2166                        .log_err();
 2167                });
 2168            }
 2169        }
 2170
 2171        cx.notify();
 2172    }
 2173
 2174    pub fn change_selections<R>(
 2175        &mut self,
 2176        autoscroll: Option<Autoscroll>,
 2177        window: &mut Window,
 2178        cx: &mut Context<Self>,
 2179        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2180    ) -> R {
 2181        self.change_selections_inner(autoscroll, true, window, cx, change)
 2182    }
 2183
 2184    fn change_selections_inner<R>(
 2185        &mut self,
 2186        autoscroll: Option<Autoscroll>,
 2187        request_completions: bool,
 2188        window: &mut Window,
 2189        cx: &mut Context<Self>,
 2190        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2191    ) -> R {
 2192        let old_cursor_position = self.selections.newest_anchor().head();
 2193        self.push_to_selection_history();
 2194
 2195        let (changed, result) = self.selections.change_with(cx, change);
 2196
 2197        if changed {
 2198            if let Some(autoscroll) = autoscroll {
 2199                self.request_autoscroll(autoscroll, cx);
 2200            }
 2201            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2202
 2203            if self.should_open_signature_help_automatically(
 2204                &old_cursor_position,
 2205                self.signature_help_state.backspace_pressed(),
 2206                cx,
 2207            ) {
 2208                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2209            }
 2210            self.signature_help_state.set_backspace_pressed(false);
 2211        }
 2212
 2213        result
 2214    }
 2215
 2216    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2217    where
 2218        I: IntoIterator<Item = (Range<S>, T)>,
 2219        S: ToOffset,
 2220        T: Into<Arc<str>>,
 2221    {
 2222        if self.read_only(cx) {
 2223            return;
 2224        }
 2225
 2226        self.buffer
 2227            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2228    }
 2229
 2230    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2231    where
 2232        I: IntoIterator<Item = (Range<S>, T)>,
 2233        S: ToOffset,
 2234        T: Into<Arc<str>>,
 2235    {
 2236        if self.read_only(cx) {
 2237            return;
 2238        }
 2239
 2240        self.buffer.update(cx, |buffer, cx| {
 2241            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2242        });
 2243    }
 2244
 2245    pub fn edit_with_block_indent<I, S, T>(
 2246        &mut self,
 2247        edits: I,
 2248        original_indent_columns: Vec<u32>,
 2249        cx: &mut Context<Self>,
 2250    ) where
 2251        I: IntoIterator<Item = (Range<S>, T)>,
 2252        S: ToOffset,
 2253        T: Into<Arc<str>>,
 2254    {
 2255        if self.read_only(cx) {
 2256            return;
 2257        }
 2258
 2259        self.buffer.update(cx, |buffer, cx| {
 2260            buffer.edit(
 2261                edits,
 2262                Some(AutoindentMode::Block {
 2263                    original_indent_columns,
 2264                }),
 2265                cx,
 2266            )
 2267        });
 2268    }
 2269
 2270    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2271        self.hide_context_menu(window, cx);
 2272
 2273        match phase {
 2274            SelectPhase::Begin {
 2275                position,
 2276                add,
 2277                click_count,
 2278            } => self.begin_selection(position, add, click_count, window, cx),
 2279            SelectPhase::BeginColumnar {
 2280                position,
 2281                goal_column,
 2282                reset,
 2283            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2284            SelectPhase::Extend {
 2285                position,
 2286                click_count,
 2287            } => self.extend_selection(position, click_count, window, cx),
 2288            SelectPhase::Update {
 2289                position,
 2290                goal_column,
 2291                scroll_delta,
 2292            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2293            SelectPhase::End => self.end_selection(window, cx),
 2294        }
 2295    }
 2296
 2297    fn extend_selection(
 2298        &mut self,
 2299        position: DisplayPoint,
 2300        click_count: usize,
 2301        window: &mut Window,
 2302        cx: &mut Context<Self>,
 2303    ) {
 2304        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2305        let tail = self.selections.newest::<usize>(cx).tail();
 2306        self.begin_selection(position, false, click_count, window, cx);
 2307
 2308        let position = position.to_offset(&display_map, Bias::Left);
 2309        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2310
 2311        let mut pending_selection = self
 2312            .selections
 2313            .pending_anchor()
 2314            .expect("extend_selection not called with pending selection");
 2315        if position >= tail {
 2316            pending_selection.start = tail_anchor;
 2317        } else {
 2318            pending_selection.end = tail_anchor;
 2319            pending_selection.reversed = true;
 2320        }
 2321
 2322        let mut pending_mode = self.selections.pending_mode().unwrap();
 2323        match &mut pending_mode {
 2324            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2325            _ => {}
 2326        }
 2327
 2328        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2329            s.set_pending(pending_selection, pending_mode)
 2330        });
 2331    }
 2332
 2333    fn begin_selection(
 2334        &mut self,
 2335        position: DisplayPoint,
 2336        add: bool,
 2337        click_count: usize,
 2338        window: &mut Window,
 2339        cx: &mut Context<Self>,
 2340    ) {
 2341        if !self.focus_handle.is_focused(window) {
 2342            self.last_focused_descendant = None;
 2343            window.focus(&self.focus_handle);
 2344        }
 2345
 2346        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2347        let buffer = &display_map.buffer_snapshot;
 2348        let newest_selection = self.selections.newest_anchor().clone();
 2349        let position = display_map.clip_point(position, Bias::Left);
 2350
 2351        let start;
 2352        let end;
 2353        let mode;
 2354        let mut auto_scroll;
 2355        match click_count {
 2356            1 => {
 2357                start = buffer.anchor_before(position.to_point(&display_map));
 2358                end = start;
 2359                mode = SelectMode::Character;
 2360                auto_scroll = true;
 2361            }
 2362            2 => {
 2363                let range = movement::surrounding_word(&display_map, position);
 2364                start = buffer.anchor_before(range.start.to_point(&display_map));
 2365                end = buffer.anchor_before(range.end.to_point(&display_map));
 2366                mode = SelectMode::Word(start..end);
 2367                auto_scroll = true;
 2368            }
 2369            3 => {
 2370                let position = display_map
 2371                    .clip_point(position, Bias::Left)
 2372                    .to_point(&display_map);
 2373                let line_start = display_map.prev_line_boundary(position).0;
 2374                let next_line_start = buffer.clip_point(
 2375                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2376                    Bias::Left,
 2377                );
 2378                start = buffer.anchor_before(line_start);
 2379                end = buffer.anchor_before(next_line_start);
 2380                mode = SelectMode::Line(start..end);
 2381                auto_scroll = true;
 2382            }
 2383            _ => {
 2384                start = buffer.anchor_before(0);
 2385                end = buffer.anchor_before(buffer.len());
 2386                mode = SelectMode::All;
 2387                auto_scroll = false;
 2388            }
 2389        }
 2390        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2391
 2392        let point_to_delete: Option<usize> = {
 2393            let selected_points: Vec<Selection<Point>> =
 2394                self.selections.disjoint_in_range(start..end, cx);
 2395
 2396            if !add || click_count > 1 {
 2397                None
 2398            } else if !selected_points.is_empty() {
 2399                Some(selected_points[0].id)
 2400            } else {
 2401                let clicked_point_already_selected =
 2402                    self.selections.disjoint.iter().find(|selection| {
 2403                        selection.start.to_point(buffer) == start.to_point(buffer)
 2404                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2405                    });
 2406
 2407                clicked_point_already_selected.map(|selection| selection.id)
 2408            }
 2409        };
 2410
 2411        let selections_count = self.selections.count();
 2412
 2413        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2414            if let Some(point_to_delete) = point_to_delete {
 2415                s.delete(point_to_delete);
 2416
 2417                if selections_count == 1 {
 2418                    s.set_pending_anchor_range(start..end, mode);
 2419                }
 2420            } else {
 2421                if !add {
 2422                    s.clear_disjoint();
 2423                } else if click_count > 1 {
 2424                    s.delete(newest_selection.id)
 2425                }
 2426
 2427                s.set_pending_anchor_range(start..end, mode);
 2428            }
 2429        });
 2430    }
 2431
 2432    fn begin_columnar_selection(
 2433        &mut self,
 2434        position: DisplayPoint,
 2435        goal_column: u32,
 2436        reset: bool,
 2437        window: &mut Window,
 2438        cx: &mut Context<Self>,
 2439    ) {
 2440        if !self.focus_handle.is_focused(window) {
 2441            self.last_focused_descendant = None;
 2442            window.focus(&self.focus_handle);
 2443        }
 2444
 2445        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2446
 2447        if reset {
 2448            let pointer_position = display_map
 2449                .buffer_snapshot
 2450                .anchor_before(position.to_point(&display_map));
 2451
 2452            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2453                s.clear_disjoint();
 2454                s.set_pending_anchor_range(
 2455                    pointer_position..pointer_position,
 2456                    SelectMode::Character,
 2457                );
 2458            });
 2459        }
 2460
 2461        let tail = self.selections.newest::<Point>(cx).tail();
 2462        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2463
 2464        if !reset {
 2465            self.select_columns(
 2466                tail.to_display_point(&display_map),
 2467                position,
 2468                goal_column,
 2469                &display_map,
 2470                window,
 2471                cx,
 2472            );
 2473        }
 2474    }
 2475
 2476    fn update_selection(
 2477        &mut self,
 2478        position: DisplayPoint,
 2479        goal_column: u32,
 2480        scroll_delta: gpui::Point<f32>,
 2481        window: &mut Window,
 2482        cx: &mut Context<Self>,
 2483    ) {
 2484        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2485
 2486        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2487            let tail = tail.to_display_point(&display_map);
 2488            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2489        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2490            let buffer = self.buffer.read(cx).snapshot(cx);
 2491            let head;
 2492            let tail;
 2493            let mode = self.selections.pending_mode().unwrap();
 2494            match &mode {
 2495                SelectMode::Character => {
 2496                    head = position.to_point(&display_map);
 2497                    tail = pending.tail().to_point(&buffer);
 2498                }
 2499                SelectMode::Word(original_range) => {
 2500                    let original_display_range = original_range.start.to_display_point(&display_map)
 2501                        ..original_range.end.to_display_point(&display_map);
 2502                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2503                        ..original_display_range.end.to_point(&display_map);
 2504                    if movement::is_inside_word(&display_map, position)
 2505                        || original_display_range.contains(&position)
 2506                    {
 2507                        let word_range = movement::surrounding_word(&display_map, position);
 2508                        if word_range.start < original_display_range.start {
 2509                            head = word_range.start.to_point(&display_map);
 2510                        } else {
 2511                            head = word_range.end.to_point(&display_map);
 2512                        }
 2513                    } else {
 2514                        head = position.to_point(&display_map);
 2515                    }
 2516
 2517                    if head <= original_buffer_range.start {
 2518                        tail = original_buffer_range.end;
 2519                    } else {
 2520                        tail = original_buffer_range.start;
 2521                    }
 2522                }
 2523                SelectMode::Line(original_range) => {
 2524                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2525
 2526                    let position = display_map
 2527                        .clip_point(position, Bias::Left)
 2528                        .to_point(&display_map);
 2529                    let line_start = display_map.prev_line_boundary(position).0;
 2530                    let next_line_start = buffer.clip_point(
 2531                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2532                        Bias::Left,
 2533                    );
 2534
 2535                    if line_start < original_range.start {
 2536                        head = line_start
 2537                    } else {
 2538                        head = next_line_start
 2539                    }
 2540
 2541                    if head <= original_range.start {
 2542                        tail = original_range.end;
 2543                    } else {
 2544                        tail = original_range.start;
 2545                    }
 2546                }
 2547                SelectMode::All => {
 2548                    return;
 2549                }
 2550            };
 2551
 2552            if head < tail {
 2553                pending.start = buffer.anchor_before(head);
 2554                pending.end = buffer.anchor_before(tail);
 2555                pending.reversed = true;
 2556            } else {
 2557                pending.start = buffer.anchor_before(tail);
 2558                pending.end = buffer.anchor_before(head);
 2559                pending.reversed = false;
 2560            }
 2561
 2562            self.change_selections(None, window, cx, |s| {
 2563                s.set_pending(pending, mode);
 2564            });
 2565        } else {
 2566            log::error!("update_selection dispatched with no pending selection");
 2567            return;
 2568        }
 2569
 2570        self.apply_scroll_delta(scroll_delta, window, cx);
 2571        cx.notify();
 2572    }
 2573
 2574    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2575        self.columnar_selection_tail.take();
 2576        if self.selections.pending_anchor().is_some() {
 2577            let selections = self.selections.all::<usize>(cx);
 2578            self.change_selections(None, window, cx, |s| {
 2579                s.select(selections);
 2580                s.clear_pending();
 2581            });
 2582        }
 2583    }
 2584
 2585    fn select_columns(
 2586        &mut self,
 2587        tail: DisplayPoint,
 2588        head: DisplayPoint,
 2589        goal_column: u32,
 2590        display_map: &DisplaySnapshot,
 2591        window: &mut Window,
 2592        cx: &mut Context<Self>,
 2593    ) {
 2594        let start_row = cmp::min(tail.row(), head.row());
 2595        let end_row = cmp::max(tail.row(), head.row());
 2596        let start_column = cmp::min(tail.column(), goal_column);
 2597        let end_column = cmp::max(tail.column(), goal_column);
 2598        let reversed = start_column < tail.column();
 2599
 2600        let selection_ranges = (start_row.0..=end_row.0)
 2601            .map(DisplayRow)
 2602            .filter_map(|row| {
 2603                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2604                    let start = display_map
 2605                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2606                        .to_point(display_map);
 2607                    let end = display_map
 2608                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2609                        .to_point(display_map);
 2610                    if reversed {
 2611                        Some(end..start)
 2612                    } else {
 2613                        Some(start..end)
 2614                    }
 2615                } else {
 2616                    None
 2617                }
 2618            })
 2619            .collect::<Vec<_>>();
 2620
 2621        self.change_selections(None, window, cx, |s| {
 2622            s.select_ranges(selection_ranges);
 2623        });
 2624        cx.notify();
 2625    }
 2626
 2627    pub fn has_pending_nonempty_selection(&self) -> bool {
 2628        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2629            Some(Selection { start, end, .. }) => start != end,
 2630            None => false,
 2631        };
 2632
 2633        pending_nonempty_selection
 2634            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2635    }
 2636
 2637    pub fn has_pending_selection(&self) -> bool {
 2638        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2639    }
 2640
 2641    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2642        self.selection_mark_mode = false;
 2643
 2644        if self.clear_expanded_diff_hunks(cx) {
 2645            cx.notify();
 2646            return;
 2647        }
 2648        if self.dismiss_menus_and_popups(true, window, cx) {
 2649            return;
 2650        }
 2651
 2652        if self.mode == EditorMode::Full
 2653            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2654        {
 2655            return;
 2656        }
 2657
 2658        cx.propagate();
 2659    }
 2660
 2661    pub fn dismiss_menus_and_popups(
 2662        &mut self,
 2663        is_user_requested: bool,
 2664        window: &mut Window,
 2665        cx: &mut Context<Self>,
 2666    ) -> bool {
 2667        if self.take_rename(false, window, cx).is_some() {
 2668            return true;
 2669        }
 2670
 2671        if hide_hover(self, cx) {
 2672            return true;
 2673        }
 2674
 2675        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2676            return true;
 2677        }
 2678
 2679        if self.hide_context_menu(window, cx).is_some() {
 2680            return true;
 2681        }
 2682
 2683        if self.mouse_context_menu.take().is_some() {
 2684            return true;
 2685        }
 2686
 2687        if is_user_requested && self.discard_inline_completion(true, cx) {
 2688            return true;
 2689        }
 2690
 2691        if self.snippet_stack.pop().is_some() {
 2692            return true;
 2693        }
 2694
 2695        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2696            self.dismiss_diagnostics(cx);
 2697            return true;
 2698        }
 2699
 2700        false
 2701    }
 2702
 2703    fn linked_editing_ranges_for(
 2704        &self,
 2705        selection: Range<text::Anchor>,
 2706        cx: &App,
 2707    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2708        if self.linked_edit_ranges.is_empty() {
 2709            return None;
 2710        }
 2711        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2712            selection.end.buffer_id.and_then(|end_buffer_id| {
 2713                if selection.start.buffer_id != Some(end_buffer_id) {
 2714                    return None;
 2715                }
 2716                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2717                let snapshot = buffer.read(cx).snapshot();
 2718                self.linked_edit_ranges
 2719                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2720                    .map(|ranges| (ranges, snapshot, buffer))
 2721            })?;
 2722        use text::ToOffset as TO;
 2723        // find offset from the start of current range to current cursor position
 2724        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2725
 2726        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2727        let start_difference = start_offset - start_byte_offset;
 2728        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2729        let end_difference = end_offset - start_byte_offset;
 2730        // Current range has associated linked ranges.
 2731        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2732        for range in linked_ranges.iter() {
 2733            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2734            let end_offset = start_offset + end_difference;
 2735            let start_offset = start_offset + start_difference;
 2736            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2737                continue;
 2738            }
 2739            if self.selections.disjoint_anchor_ranges().any(|s| {
 2740                if s.start.buffer_id != selection.start.buffer_id
 2741                    || s.end.buffer_id != selection.end.buffer_id
 2742                {
 2743                    return false;
 2744                }
 2745                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2746                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2747            }) {
 2748                continue;
 2749            }
 2750            let start = buffer_snapshot.anchor_after(start_offset);
 2751            let end = buffer_snapshot.anchor_after(end_offset);
 2752            linked_edits
 2753                .entry(buffer.clone())
 2754                .or_default()
 2755                .push(start..end);
 2756        }
 2757        Some(linked_edits)
 2758    }
 2759
 2760    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2761        let text: Arc<str> = text.into();
 2762
 2763        if self.read_only(cx) {
 2764            return;
 2765        }
 2766
 2767        let selections = self.selections.all_adjusted(cx);
 2768        let mut bracket_inserted = false;
 2769        let mut edits = Vec::new();
 2770        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2771        let mut new_selections = Vec::with_capacity(selections.len());
 2772        let mut new_autoclose_regions = Vec::new();
 2773        let snapshot = self.buffer.read(cx).read(cx);
 2774
 2775        for (selection, autoclose_region) in
 2776            self.selections_with_autoclose_regions(selections, &snapshot)
 2777        {
 2778            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2779                // Determine if the inserted text matches the opening or closing
 2780                // bracket of any of this language's bracket pairs.
 2781                let mut bracket_pair = None;
 2782                let mut is_bracket_pair_start = false;
 2783                let mut is_bracket_pair_end = false;
 2784                if !text.is_empty() {
 2785                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2786                    //  and they are removing the character that triggered IME popup.
 2787                    for (pair, enabled) in scope.brackets() {
 2788                        if !pair.close && !pair.surround {
 2789                            continue;
 2790                        }
 2791
 2792                        if enabled && pair.start.ends_with(text.as_ref()) {
 2793                            let prefix_len = pair.start.len() - text.len();
 2794                            let preceding_text_matches_prefix = prefix_len == 0
 2795                                || (selection.start.column >= (prefix_len as u32)
 2796                                    && snapshot.contains_str_at(
 2797                                        Point::new(
 2798                                            selection.start.row,
 2799                                            selection.start.column - (prefix_len as u32),
 2800                                        ),
 2801                                        &pair.start[..prefix_len],
 2802                                    ));
 2803                            if preceding_text_matches_prefix {
 2804                                bracket_pair = Some(pair.clone());
 2805                                is_bracket_pair_start = true;
 2806                                break;
 2807                            }
 2808                        }
 2809                        if pair.end.as_str() == text.as_ref() {
 2810                            bracket_pair = Some(pair.clone());
 2811                            is_bracket_pair_end = true;
 2812                            break;
 2813                        }
 2814                    }
 2815                }
 2816
 2817                if let Some(bracket_pair) = bracket_pair {
 2818                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2819                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2820                    let auto_surround =
 2821                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2822                    if selection.is_empty() {
 2823                        if is_bracket_pair_start {
 2824                            // If the inserted text is a suffix of an opening bracket and the
 2825                            // selection is preceded by the rest of the opening bracket, then
 2826                            // insert the closing bracket.
 2827                            let following_text_allows_autoclose = snapshot
 2828                                .chars_at(selection.start)
 2829                                .next()
 2830                                .map_or(true, |c| scope.should_autoclose_before(c));
 2831
 2832                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2833                                && bracket_pair.start.len() == 1
 2834                            {
 2835                                let target = bracket_pair.start.chars().next().unwrap();
 2836                                let current_line_count = snapshot
 2837                                    .reversed_chars_at(selection.start)
 2838                                    .take_while(|&c| c != '\n')
 2839                                    .filter(|&c| c == target)
 2840                                    .count();
 2841                                current_line_count % 2 == 1
 2842                            } else {
 2843                                false
 2844                            };
 2845
 2846                            if autoclose
 2847                                && bracket_pair.close
 2848                                && following_text_allows_autoclose
 2849                                && !is_closing_quote
 2850                            {
 2851                                let anchor = snapshot.anchor_before(selection.end);
 2852                                new_selections.push((selection.map(|_| anchor), text.len()));
 2853                                new_autoclose_regions.push((
 2854                                    anchor,
 2855                                    text.len(),
 2856                                    selection.id,
 2857                                    bracket_pair.clone(),
 2858                                ));
 2859                                edits.push((
 2860                                    selection.range(),
 2861                                    format!("{}{}", text, bracket_pair.end).into(),
 2862                                ));
 2863                                bracket_inserted = true;
 2864                                continue;
 2865                            }
 2866                        }
 2867
 2868                        if let Some(region) = autoclose_region {
 2869                            // If the selection is followed by an auto-inserted closing bracket,
 2870                            // then don't insert that closing bracket again; just move the selection
 2871                            // past the closing bracket.
 2872                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2873                                && text.as_ref() == region.pair.end.as_str();
 2874                            if should_skip {
 2875                                let anchor = snapshot.anchor_after(selection.end);
 2876                                new_selections
 2877                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2878                                continue;
 2879                            }
 2880                        }
 2881
 2882                        let always_treat_brackets_as_autoclosed = snapshot
 2883                            .settings_at(selection.start, cx)
 2884                            .always_treat_brackets_as_autoclosed;
 2885                        if always_treat_brackets_as_autoclosed
 2886                            && is_bracket_pair_end
 2887                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2888                        {
 2889                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2890                            // and the inserted text is a closing bracket and the selection is followed
 2891                            // by the closing bracket then move the selection past the closing bracket.
 2892                            let anchor = snapshot.anchor_after(selection.end);
 2893                            new_selections.push((selection.map(|_| anchor), text.len()));
 2894                            continue;
 2895                        }
 2896                    }
 2897                    // If an opening bracket is 1 character long and is typed while
 2898                    // text is selected, then surround that text with the bracket pair.
 2899                    else if auto_surround
 2900                        && bracket_pair.surround
 2901                        && is_bracket_pair_start
 2902                        && bracket_pair.start.chars().count() == 1
 2903                    {
 2904                        edits.push((selection.start..selection.start, text.clone()));
 2905                        edits.push((
 2906                            selection.end..selection.end,
 2907                            bracket_pair.end.as_str().into(),
 2908                        ));
 2909                        bracket_inserted = true;
 2910                        new_selections.push((
 2911                            Selection {
 2912                                id: selection.id,
 2913                                start: snapshot.anchor_after(selection.start),
 2914                                end: snapshot.anchor_before(selection.end),
 2915                                reversed: selection.reversed,
 2916                                goal: selection.goal,
 2917                            },
 2918                            0,
 2919                        ));
 2920                        continue;
 2921                    }
 2922                }
 2923            }
 2924
 2925            if self.auto_replace_emoji_shortcode
 2926                && selection.is_empty()
 2927                && text.as_ref().ends_with(':')
 2928            {
 2929                if let Some(possible_emoji_short_code) =
 2930                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2931                {
 2932                    if !possible_emoji_short_code.is_empty() {
 2933                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2934                            let emoji_shortcode_start = Point::new(
 2935                                selection.start.row,
 2936                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2937                            );
 2938
 2939                            // Remove shortcode from buffer
 2940                            edits.push((
 2941                                emoji_shortcode_start..selection.start,
 2942                                "".to_string().into(),
 2943                            ));
 2944                            new_selections.push((
 2945                                Selection {
 2946                                    id: selection.id,
 2947                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2948                                    end: snapshot.anchor_before(selection.start),
 2949                                    reversed: selection.reversed,
 2950                                    goal: selection.goal,
 2951                                },
 2952                                0,
 2953                            ));
 2954
 2955                            // Insert emoji
 2956                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2957                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2958                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2959
 2960                            continue;
 2961                        }
 2962                    }
 2963                }
 2964            }
 2965
 2966            // If not handling any auto-close operation, then just replace the selected
 2967            // text with the given input and move the selection to the end of the
 2968            // newly inserted text.
 2969            let anchor = snapshot.anchor_after(selection.end);
 2970            if !self.linked_edit_ranges.is_empty() {
 2971                let start_anchor = snapshot.anchor_before(selection.start);
 2972
 2973                let is_word_char = text.chars().next().map_or(true, |char| {
 2974                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2975                    classifier.is_word(char)
 2976                });
 2977
 2978                if is_word_char {
 2979                    if let Some(ranges) = self
 2980                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2981                    {
 2982                        for (buffer, edits) in ranges {
 2983                            linked_edits
 2984                                .entry(buffer.clone())
 2985                                .or_default()
 2986                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2987                        }
 2988                    }
 2989                }
 2990            }
 2991
 2992            new_selections.push((selection.map(|_| anchor), 0));
 2993            edits.push((selection.start..selection.end, text.clone()));
 2994        }
 2995
 2996        drop(snapshot);
 2997
 2998        self.transact(window, cx, |this, window, cx| {
 2999            this.buffer.update(cx, |buffer, cx| {
 3000                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3001            });
 3002            for (buffer, edits) in linked_edits {
 3003                buffer.update(cx, |buffer, cx| {
 3004                    let snapshot = buffer.snapshot();
 3005                    let edits = edits
 3006                        .into_iter()
 3007                        .map(|(range, text)| {
 3008                            use text::ToPoint as TP;
 3009                            let end_point = TP::to_point(&range.end, &snapshot);
 3010                            let start_point = TP::to_point(&range.start, &snapshot);
 3011                            (start_point..end_point, text)
 3012                        })
 3013                        .sorted_by_key(|(range, _)| range.start)
 3014                        .collect::<Vec<_>>();
 3015                    buffer.edit(edits, None, cx);
 3016                })
 3017            }
 3018            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3019            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3020            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3021            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3022                .zip(new_selection_deltas)
 3023                .map(|(selection, delta)| Selection {
 3024                    id: selection.id,
 3025                    start: selection.start + delta,
 3026                    end: selection.end + delta,
 3027                    reversed: selection.reversed,
 3028                    goal: SelectionGoal::None,
 3029                })
 3030                .collect::<Vec<_>>();
 3031
 3032            let mut i = 0;
 3033            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3034                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3035                let start = map.buffer_snapshot.anchor_before(position);
 3036                let end = map.buffer_snapshot.anchor_after(position);
 3037                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3038                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3039                        Ordering::Less => i += 1,
 3040                        Ordering::Greater => break,
 3041                        Ordering::Equal => {
 3042                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3043                                Ordering::Less => i += 1,
 3044                                Ordering::Equal => break,
 3045                                Ordering::Greater => break,
 3046                            }
 3047                        }
 3048                    }
 3049                }
 3050                this.autoclose_regions.insert(
 3051                    i,
 3052                    AutocloseRegion {
 3053                        selection_id,
 3054                        range: start..end,
 3055                        pair,
 3056                    },
 3057                );
 3058            }
 3059
 3060            let had_active_inline_completion = this.has_active_inline_completion();
 3061            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3062                s.select(new_selections)
 3063            });
 3064
 3065            if !bracket_inserted {
 3066                if let Some(on_type_format_task) =
 3067                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3068                {
 3069                    on_type_format_task.detach_and_log_err(cx);
 3070                }
 3071            }
 3072
 3073            let editor_settings = EditorSettings::get_global(cx);
 3074            if bracket_inserted
 3075                && (editor_settings.auto_signature_help
 3076                    || editor_settings.show_signature_help_after_edits)
 3077            {
 3078                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3079            }
 3080
 3081            let trigger_in_words =
 3082                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3083            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3084            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3085            this.refresh_inline_completion(true, false, window, cx);
 3086        });
 3087    }
 3088
 3089    fn find_possible_emoji_shortcode_at_position(
 3090        snapshot: &MultiBufferSnapshot,
 3091        position: Point,
 3092    ) -> Option<String> {
 3093        let mut chars = Vec::new();
 3094        let mut found_colon = false;
 3095        for char in snapshot.reversed_chars_at(position).take(100) {
 3096            // Found a possible emoji shortcode in the middle of the buffer
 3097            if found_colon {
 3098                if char.is_whitespace() {
 3099                    chars.reverse();
 3100                    return Some(chars.iter().collect());
 3101                }
 3102                // If the previous character is not a whitespace, we are in the middle of a word
 3103                // and we only want to complete the shortcode if the word is made up of other emojis
 3104                let mut containing_word = String::new();
 3105                for ch in snapshot
 3106                    .reversed_chars_at(position)
 3107                    .skip(chars.len() + 1)
 3108                    .take(100)
 3109                {
 3110                    if ch.is_whitespace() {
 3111                        break;
 3112                    }
 3113                    containing_word.push(ch);
 3114                }
 3115                let containing_word = containing_word.chars().rev().collect::<String>();
 3116                if util::word_consists_of_emojis(containing_word.as_str()) {
 3117                    chars.reverse();
 3118                    return Some(chars.iter().collect());
 3119                }
 3120            }
 3121
 3122            if char.is_whitespace() || !char.is_ascii() {
 3123                return None;
 3124            }
 3125            if char == ':' {
 3126                found_colon = true;
 3127            } else {
 3128                chars.push(char);
 3129            }
 3130        }
 3131        // Found a possible emoji shortcode at the beginning of the buffer
 3132        chars.reverse();
 3133        Some(chars.iter().collect())
 3134    }
 3135
 3136    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3137        self.transact(window, cx, |this, window, cx| {
 3138            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3139                let selections = this.selections.all::<usize>(cx);
 3140                let multi_buffer = this.buffer.read(cx);
 3141                let buffer = multi_buffer.snapshot(cx);
 3142                selections
 3143                    .iter()
 3144                    .map(|selection| {
 3145                        let start_point = selection.start.to_point(&buffer);
 3146                        let mut indent =
 3147                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3148                        indent.len = cmp::min(indent.len, start_point.column);
 3149                        let start = selection.start;
 3150                        let end = selection.end;
 3151                        let selection_is_empty = start == end;
 3152                        let language_scope = buffer.language_scope_at(start);
 3153                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3154                            &language_scope
 3155                        {
 3156                            let leading_whitespace_len = buffer
 3157                                .reversed_chars_at(start)
 3158                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3159                                .map(|c| c.len_utf8())
 3160                                .sum::<usize>();
 3161
 3162                            let trailing_whitespace_len = buffer
 3163                                .chars_at(end)
 3164                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3165                                .map(|c| c.len_utf8())
 3166                                .sum::<usize>();
 3167
 3168                            let insert_extra_newline =
 3169                                language.brackets().any(|(pair, enabled)| {
 3170                                    let pair_start = pair.start.trim_end();
 3171                                    let pair_end = pair.end.trim_start();
 3172
 3173                                    enabled
 3174                                        && pair.newline
 3175                                        && buffer.contains_str_at(
 3176                                            end + trailing_whitespace_len,
 3177                                            pair_end,
 3178                                        )
 3179                                        && buffer.contains_str_at(
 3180                                            (start - leading_whitespace_len)
 3181                                                .saturating_sub(pair_start.len()),
 3182                                            pair_start,
 3183                                        )
 3184                                });
 3185
 3186                            // Comment extension on newline is allowed only for cursor selections
 3187                            let comment_delimiter = maybe!({
 3188                                if !selection_is_empty {
 3189                                    return None;
 3190                                }
 3191
 3192                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3193                                    return None;
 3194                                }
 3195
 3196                                let delimiters = language.line_comment_prefixes();
 3197                                let max_len_of_delimiter =
 3198                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3199                                let (snapshot, range) =
 3200                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3201
 3202                                let mut index_of_first_non_whitespace = 0;
 3203                                let comment_candidate = snapshot
 3204                                    .chars_for_range(range)
 3205                                    .skip_while(|c| {
 3206                                        let should_skip = c.is_whitespace();
 3207                                        if should_skip {
 3208                                            index_of_first_non_whitespace += 1;
 3209                                        }
 3210                                        should_skip
 3211                                    })
 3212                                    .take(max_len_of_delimiter)
 3213                                    .collect::<String>();
 3214                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3215                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3216                                })?;
 3217                                let cursor_is_placed_after_comment_marker =
 3218                                    index_of_first_non_whitespace + comment_prefix.len()
 3219                                        <= start_point.column as usize;
 3220                                if cursor_is_placed_after_comment_marker {
 3221                                    Some(comment_prefix.clone())
 3222                                } else {
 3223                                    None
 3224                                }
 3225                            });
 3226                            (comment_delimiter, insert_extra_newline)
 3227                        } else {
 3228                            (None, false)
 3229                        };
 3230
 3231                        let capacity_for_delimiter = comment_delimiter
 3232                            .as_deref()
 3233                            .map(str::len)
 3234                            .unwrap_or_default();
 3235                        let mut new_text =
 3236                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3237                        new_text.push('\n');
 3238                        new_text.extend(indent.chars());
 3239                        if let Some(delimiter) = &comment_delimiter {
 3240                            new_text.push_str(delimiter);
 3241                        }
 3242                        if insert_extra_newline {
 3243                            new_text = new_text.repeat(2);
 3244                        }
 3245
 3246                        let anchor = buffer.anchor_after(end);
 3247                        let new_selection = selection.map(|_| anchor);
 3248                        (
 3249                            (start..end, new_text),
 3250                            (insert_extra_newline, new_selection),
 3251                        )
 3252                    })
 3253                    .unzip()
 3254            };
 3255
 3256            this.edit_with_autoindent(edits, cx);
 3257            let buffer = this.buffer.read(cx).snapshot(cx);
 3258            let new_selections = selection_fixup_info
 3259                .into_iter()
 3260                .map(|(extra_newline_inserted, new_selection)| {
 3261                    let mut cursor = new_selection.end.to_point(&buffer);
 3262                    if extra_newline_inserted {
 3263                        cursor.row -= 1;
 3264                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3265                    }
 3266                    new_selection.map(|_| cursor)
 3267                })
 3268                .collect();
 3269
 3270            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3271                s.select(new_selections)
 3272            });
 3273            this.refresh_inline_completion(true, false, window, cx);
 3274        });
 3275    }
 3276
 3277    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3278        let buffer = self.buffer.read(cx);
 3279        let snapshot = buffer.snapshot(cx);
 3280
 3281        let mut edits = Vec::new();
 3282        let mut rows = Vec::new();
 3283
 3284        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3285            let cursor = selection.head();
 3286            let row = cursor.row;
 3287
 3288            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3289
 3290            let newline = "\n".to_string();
 3291            edits.push((start_of_line..start_of_line, newline));
 3292
 3293            rows.push(row + rows_inserted as u32);
 3294        }
 3295
 3296        self.transact(window, cx, |editor, window, cx| {
 3297            editor.edit(edits, cx);
 3298
 3299            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3300                let mut index = 0;
 3301                s.move_cursors_with(|map, _, _| {
 3302                    let row = rows[index];
 3303                    index += 1;
 3304
 3305                    let point = Point::new(row, 0);
 3306                    let boundary = map.next_line_boundary(point).1;
 3307                    let clipped = map.clip_point(boundary, Bias::Left);
 3308
 3309                    (clipped, SelectionGoal::None)
 3310                });
 3311            });
 3312
 3313            let mut indent_edits = Vec::new();
 3314            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3315            for row in rows {
 3316                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3317                for (row, indent) in indents {
 3318                    if indent.len == 0 {
 3319                        continue;
 3320                    }
 3321
 3322                    let text = match indent.kind {
 3323                        IndentKind::Space => " ".repeat(indent.len as usize),
 3324                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3325                    };
 3326                    let point = Point::new(row.0, 0);
 3327                    indent_edits.push((point..point, text));
 3328                }
 3329            }
 3330            editor.edit(indent_edits, cx);
 3331        });
 3332    }
 3333
 3334    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3335        let buffer = self.buffer.read(cx);
 3336        let snapshot = buffer.snapshot(cx);
 3337
 3338        let mut edits = Vec::new();
 3339        let mut rows = Vec::new();
 3340        let mut rows_inserted = 0;
 3341
 3342        for selection in self.selections.all_adjusted(cx) {
 3343            let cursor = selection.head();
 3344            let row = cursor.row;
 3345
 3346            let point = Point::new(row + 1, 0);
 3347            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3348
 3349            let newline = "\n".to_string();
 3350            edits.push((start_of_line..start_of_line, newline));
 3351
 3352            rows_inserted += 1;
 3353            rows.push(row + rows_inserted);
 3354        }
 3355
 3356        self.transact(window, cx, |editor, window, cx| {
 3357            editor.edit(edits, cx);
 3358
 3359            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3360                let mut index = 0;
 3361                s.move_cursors_with(|map, _, _| {
 3362                    let row = rows[index];
 3363                    index += 1;
 3364
 3365                    let point = Point::new(row, 0);
 3366                    let boundary = map.next_line_boundary(point).1;
 3367                    let clipped = map.clip_point(boundary, Bias::Left);
 3368
 3369                    (clipped, SelectionGoal::None)
 3370                });
 3371            });
 3372
 3373            let mut indent_edits = Vec::new();
 3374            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3375            for row in rows {
 3376                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3377                for (row, indent) in indents {
 3378                    if indent.len == 0 {
 3379                        continue;
 3380                    }
 3381
 3382                    let text = match indent.kind {
 3383                        IndentKind::Space => " ".repeat(indent.len as usize),
 3384                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3385                    };
 3386                    let point = Point::new(row.0, 0);
 3387                    indent_edits.push((point..point, text));
 3388                }
 3389            }
 3390            editor.edit(indent_edits, cx);
 3391        });
 3392    }
 3393
 3394    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3395        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3396            original_indent_columns: Vec::new(),
 3397        });
 3398        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3399    }
 3400
 3401    fn insert_with_autoindent_mode(
 3402        &mut self,
 3403        text: &str,
 3404        autoindent_mode: Option<AutoindentMode>,
 3405        window: &mut Window,
 3406        cx: &mut Context<Self>,
 3407    ) {
 3408        if self.read_only(cx) {
 3409            return;
 3410        }
 3411
 3412        let text: Arc<str> = text.into();
 3413        self.transact(window, cx, |this, window, cx| {
 3414            let old_selections = this.selections.all_adjusted(cx);
 3415            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3416                let anchors = {
 3417                    let snapshot = buffer.read(cx);
 3418                    old_selections
 3419                        .iter()
 3420                        .map(|s| {
 3421                            let anchor = snapshot.anchor_after(s.head());
 3422                            s.map(|_| anchor)
 3423                        })
 3424                        .collect::<Vec<_>>()
 3425                };
 3426                buffer.edit(
 3427                    old_selections
 3428                        .iter()
 3429                        .map(|s| (s.start..s.end, text.clone())),
 3430                    autoindent_mode,
 3431                    cx,
 3432                );
 3433                anchors
 3434            });
 3435
 3436            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3437                s.select_anchors(selection_anchors);
 3438            });
 3439
 3440            cx.notify();
 3441        });
 3442    }
 3443
 3444    fn trigger_completion_on_input(
 3445        &mut self,
 3446        text: &str,
 3447        trigger_in_words: bool,
 3448        window: &mut Window,
 3449        cx: &mut Context<Self>,
 3450    ) {
 3451        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3452            self.show_completions(
 3453                &ShowCompletions {
 3454                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3455                },
 3456                window,
 3457                cx,
 3458            );
 3459        } else {
 3460            self.hide_context_menu(window, cx);
 3461        }
 3462    }
 3463
 3464    fn is_completion_trigger(
 3465        &self,
 3466        text: &str,
 3467        trigger_in_words: bool,
 3468        cx: &mut Context<Self>,
 3469    ) -> bool {
 3470        let position = self.selections.newest_anchor().head();
 3471        let multibuffer = self.buffer.read(cx);
 3472        let Some(buffer) = position
 3473            .buffer_id
 3474            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3475        else {
 3476            return false;
 3477        };
 3478
 3479        if let Some(completion_provider) = &self.completion_provider {
 3480            completion_provider.is_completion_trigger(
 3481                &buffer,
 3482                position.text_anchor,
 3483                text,
 3484                trigger_in_words,
 3485                cx,
 3486            )
 3487        } else {
 3488            false
 3489        }
 3490    }
 3491
 3492    /// If any empty selections is touching the start of its innermost containing autoclose
 3493    /// region, expand it to select the brackets.
 3494    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3495        let selections = self.selections.all::<usize>(cx);
 3496        let buffer = self.buffer.read(cx).read(cx);
 3497        let new_selections = self
 3498            .selections_with_autoclose_regions(selections, &buffer)
 3499            .map(|(mut selection, region)| {
 3500                if !selection.is_empty() {
 3501                    return selection;
 3502                }
 3503
 3504                if let Some(region) = region {
 3505                    let mut range = region.range.to_offset(&buffer);
 3506                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3507                        range.start -= region.pair.start.len();
 3508                        if buffer.contains_str_at(range.start, &region.pair.start)
 3509                            && buffer.contains_str_at(range.end, &region.pair.end)
 3510                        {
 3511                            range.end += region.pair.end.len();
 3512                            selection.start = range.start;
 3513                            selection.end = range.end;
 3514
 3515                            return selection;
 3516                        }
 3517                    }
 3518                }
 3519
 3520                let always_treat_brackets_as_autoclosed = buffer
 3521                    .settings_at(selection.start, cx)
 3522                    .always_treat_brackets_as_autoclosed;
 3523
 3524                if !always_treat_brackets_as_autoclosed {
 3525                    return selection;
 3526                }
 3527
 3528                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3529                    for (pair, enabled) in scope.brackets() {
 3530                        if !enabled || !pair.close {
 3531                            continue;
 3532                        }
 3533
 3534                        if buffer.contains_str_at(selection.start, &pair.end) {
 3535                            let pair_start_len = pair.start.len();
 3536                            if buffer.contains_str_at(
 3537                                selection.start.saturating_sub(pair_start_len),
 3538                                &pair.start,
 3539                            ) {
 3540                                selection.start -= pair_start_len;
 3541                                selection.end += pair.end.len();
 3542
 3543                                return selection;
 3544                            }
 3545                        }
 3546                    }
 3547                }
 3548
 3549                selection
 3550            })
 3551            .collect();
 3552
 3553        drop(buffer);
 3554        self.change_selections(None, window, cx, |selections| {
 3555            selections.select(new_selections)
 3556        });
 3557    }
 3558
 3559    /// Iterate the given selections, and for each one, find the smallest surrounding
 3560    /// autoclose region. This uses the ordering of the selections and the autoclose
 3561    /// regions to avoid repeated comparisons.
 3562    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3563        &'a self,
 3564        selections: impl IntoIterator<Item = Selection<D>>,
 3565        buffer: &'a MultiBufferSnapshot,
 3566    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3567        let mut i = 0;
 3568        let mut regions = self.autoclose_regions.as_slice();
 3569        selections.into_iter().map(move |selection| {
 3570            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3571
 3572            let mut enclosing = None;
 3573            while let Some(pair_state) = regions.get(i) {
 3574                if pair_state.range.end.to_offset(buffer) < range.start {
 3575                    regions = &regions[i + 1..];
 3576                    i = 0;
 3577                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3578                    break;
 3579                } else {
 3580                    if pair_state.selection_id == selection.id {
 3581                        enclosing = Some(pair_state);
 3582                    }
 3583                    i += 1;
 3584                }
 3585            }
 3586
 3587            (selection, enclosing)
 3588        })
 3589    }
 3590
 3591    /// Remove any autoclose regions that no longer contain their selection.
 3592    fn invalidate_autoclose_regions(
 3593        &mut self,
 3594        mut selections: &[Selection<Anchor>],
 3595        buffer: &MultiBufferSnapshot,
 3596    ) {
 3597        self.autoclose_regions.retain(|state| {
 3598            let mut i = 0;
 3599            while let Some(selection) = selections.get(i) {
 3600                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3601                    selections = &selections[1..];
 3602                    continue;
 3603                }
 3604                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3605                    break;
 3606                }
 3607                if selection.id == state.selection_id {
 3608                    return true;
 3609                } else {
 3610                    i += 1;
 3611                }
 3612            }
 3613            false
 3614        });
 3615    }
 3616
 3617    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3618        let offset = position.to_offset(buffer);
 3619        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3620        if offset > word_range.start && kind == Some(CharKind::Word) {
 3621            Some(
 3622                buffer
 3623                    .text_for_range(word_range.start..offset)
 3624                    .collect::<String>(),
 3625            )
 3626        } else {
 3627            None
 3628        }
 3629    }
 3630
 3631    pub fn toggle_inlay_hints(
 3632        &mut self,
 3633        _: &ToggleInlayHints,
 3634        _: &mut Window,
 3635        cx: &mut Context<Self>,
 3636    ) {
 3637        self.refresh_inlay_hints(
 3638            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3639            cx,
 3640        );
 3641    }
 3642
 3643    pub fn inlay_hints_enabled(&self) -> bool {
 3644        self.inlay_hint_cache.enabled
 3645    }
 3646
 3647    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3648        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3649            return;
 3650        }
 3651
 3652        let reason_description = reason.description();
 3653        let ignore_debounce = matches!(
 3654            reason,
 3655            InlayHintRefreshReason::SettingsChange(_)
 3656                | InlayHintRefreshReason::Toggle(_)
 3657                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3658        );
 3659        let (invalidate_cache, required_languages) = match reason {
 3660            InlayHintRefreshReason::Toggle(enabled) => {
 3661                self.inlay_hint_cache.enabled = enabled;
 3662                if enabled {
 3663                    (InvalidationStrategy::RefreshRequested, None)
 3664                } else {
 3665                    self.inlay_hint_cache.clear();
 3666                    self.splice_inlays(
 3667                        &self
 3668                            .visible_inlay_hints(cx)
 3669                            .iter()
 3670                            .map(|inlay| inlay.id)
 3671                            .collect::<Vec<InlayId>>(),
 3672                        Vec::new(),
 3673                        cx,
 3674                    );
 3675                    return;
 3676                }
 3677            }
 3678            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3679                match self.inlay_hint_cache.update_settings(
 3680                    &self.buffer,
 3681                    new_settings,
 3682                    self.visible_inlay_hints(cx),
 3683                    cx,
 3684                ) {
 3685                    ControlFlow::Break(Some(InlaySplice {
 3686                        to_remove,
 3687                        to_insert,
 3688                    })) => {
 3689                        self.splice_inlays(&to_remove, to_insert, cx);
 3690                        return;
 3691                    }
 3692                    ControlFlow::Break(None) => return,
 3693                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3694                }
 3695            }
 3696            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3697                if let Some(InlaySplice {
 3698                    to_remove,
 3699                    to_insert,
 3700                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3701                {
 3702                    self.splice_inlays(&to_remove, to_insert, cx);
 3703                }
 3704                return;
 3705            }
 3706            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3707            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3708                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3709            }
 3710            InlayHintRefreshReason::RefreshRequested => {
 3711                (InvalidationStrategy::RefreshRequested, None)
 3712            }
 3713        };
 3714
 3715        if let Some(InlaySplice {
 3716            to_remove,
 3717            to_insert,
 3718        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3719            reason_description,
 3720            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3721            invalidate_cache,
 3722            ignore_debounce,
 3723            cx,
 3724        ) {
 3725            self.splice_inlays(&to_remove, to_insert, cx);
 3726        }
 3727    }
 3728
 3729    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3730        self.display_map
 3731            .read(cx)
 3732            .current_inlays()
 3733            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3734            .cloned()
 3735            .collect()
 3736    }
 3737
 3738    pub fn excerpts_for_inlay_hints_query(
 3739        &self,
 3740        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3741        cx: &mut Context<Editor>,
 3742    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3743        let Some(project) = self.project.as_ref() else {
 3744            return HashMap::default();
 3745        };
 3746        let project = project.read(cx);
 3747        let multi_buffer = self.buffer().read(cx);
 3748        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3749        let multi_buffer_visible_start = self
 3750            .scroll_manager
 3751            .anchor()
 3752            .anchor
 3753            .to_point(&multi_buffer_snapshot);
 3754        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3755            multi_buffer_visible_start
 3756                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3757            Bias::Left,
 3758        );
 3759        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3760        multi_buffer_snapshot
 3761            .range_to_buffer_ranges(multi_buffer_visible_range)
 3762            .into_iter()
 3763            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3764            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3765                let buffer_file = project::File::from_dyn(buffer.file())?;
 3766                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3767                let worktree_entry = buffer_worktree
 3768                    .read(cx)
 3769                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3770                if worktree_entry.is_ignored {
 3771                    return None;
 3772                }
 3773
 3774                let language = buffer.language()?;
 3775                if let Some(restrict_to_languages) = restrict_to_languages {
 3776                    if !restrict_to_languages.contains(language) {
 3777                        return None;
 3778                    }
 3779                }
 3780                Some((
 3781                    excerpt_id,
 3782                    (
 3783                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3784                        buffer.version().clone(),
 3785                        excerpt_visible_range,
 3786                    ),
 3787                ))
 3788            })
 3789            .collect()
 3790    }
 3791
 3792    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3793        TextLayoutDetails {
 3794            text_system: window.text_system().clone(),
 3795            editor_style: self.style.clone().unwrap(),
 3796            rem_size: window.rem_size(),
 3797            scroll_anchor: self.scroll_manager.anchor(),
 3798            visible_rows: self.visible_line_count(),
 3799            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3800        }
 3801    }
 3802
 3803    pub fn splice_inlays(
 3804        &self,
 3805        to_remove: &[InlayId],
 3806        to_insert: Vec<Inlay>,
 3807        cx: &mut Context<Self>,
 3808    ) {
 3809        self.display_map.update(cx, |display_map, cx| {
 3810            display_map.splice_inlays(to_remove, to_insert, cx)
 3811        });
 3812        cx.notify();
 3813    }
 3814
 3815    fn trigger_on_type_formatting(
 3816        &self,
 3817        input: String,
 3818        window: &mut Window,
 3819        cx: &mut Context<Self>,
 3820    ) -> Option<Task<Result<()>>> {
 3821        if input.len() != 1 {
 3822            return None;
 3823        }
 3824
 3825        let project = self.project.as_ref()?;
 3826        let position = self.selections.newest_anchor().head();
 3827        let (buffer, buffer_position) = self
 3828            .buffer
 3829            .read(cx)
 3830            .text_anchor_for_position(position, cx)?;
 3831
 3832        let settings = language_settings::language_settings(
 3833            buffer
 3834                .read(cx)
 3835                .language_at(buffer_position)
 3836                .map(|l| l.name()),
 3837            buffer.read(cx).file(),
 3838            cx,
 3839        );
 3840        if !settings.use_on_type_format {
 3841            return None;
 3842        }
 3843
 3844        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3845        // hence we do LSP request & edit on host side only — add formats to host's history.
 3846        let push_to_lsp_host_history = true;
 3847        // If this is not the host, append its history with new edits.
 3848        let push_to_client_history = project.read(cx).is_via_collab();
 3849
 3850        let on_type_formatting = project.update(cx, |project, cx| {
 3851            project.on_type_format(
 3852                buffer.clone(),
 3853                buffer_position,
 3854                input,
 3855                push_to_lsp_host_history,
 3856                cx,
 3857            )
 3858        });
 3859        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3860            if let Some(transaction) = on_type_formatting.await? {
 3861                if push_to_client_history {
 3862                    buffer
 3863                        .update(&mut cx, |buffer, _| {
 3864                            buffer.push_transaction(transaction, Instant::now());
 3865                        })
 3866                        .ok();
 3867                }
 3868                editor.update(&mut cx, |editor, cx| {
 3869                    editor.refresh_document_highlights(cx);
 3870                })?;
 3871            }
 3872            Ok(())
 3873        }))
 3874    }
 3875
 3876    pub fn show_completions(
 3877        &mut self,
 3878        options: &ShowCompletions,
 3879        window: &mut Window,
 3880        cx: &mut Context<Self>,
 3881    ) {
 3882        if self.pending_rename.is_some() {
 3883            return;
 3884        }
 3885
 3886        let Some(provider) = self.completion_provider.as_ref() else {
 3887            return;
 3888        };
 3889
 3890        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3891            return;
 3892        }
 3893
 3894        let position = self.selections.newest_anchor().head();
 3895        if position.diff_base_anchor.is_some() {
 3896            return;
 3897        }
 3898        let (buffer, buffer_position) =
 3899            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3900                output
 3901            } else {
 3902                return;
 3903            };
 3904        let show_completion_documentation = buffer
 3905            .read(cx)
 3906            .snapshot()
 3907            .settings_at(buffer_position, cx)
 3908            .show_completion_documentation;
 3909
 3910        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3911
 3912        let trigger_kind = match &options.trigger {
 3913            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3914                CompletionTriggerKind::TRIGGER_CHARACTER
 3915            }
 3916            _ => CompletionTriggerKind::INVOKED,
 3917        };
 3918        let completion_context = CompletionContext {
 3919            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3920                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3921                    Some(String::from(trigger))
 3922                } else {
 3923                    None
 3924                }
 3925            }),
 3926            trigger_kind,
 3927        };
 3928        let completions =
 3929            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3930        let sort_completions = provider.sort_completions();
 3931
 3932        let id = post_inc(&mut self.next_completion_id);
 3933        let task = cx.spawn_in(window, |editor, mut cx| {
 3934            async move {
 3935                editor.update(&mut cx, |this, _| {
 3936                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3937                })?;
 3938                let completions = completions.await.log_err();
 3939                let menu = if let Some(completions) = completions {
 3940                    let mut menu = CompletionsMenu::new(
 3941                        id,
 3942                        sort_completions,
 3943                        show_completion_documentation,
 3944                        position,
 3945                        buffer.clone(),
 3946                        completions.into(),
 3947                    );
 3948
 3949                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3950                        .await;
 3951
 3952                    menu.visible().then_some(menu)
 3953                } else {
 3954                    None
 3955                };
 3956
 3957                editor.update_in(&mut cx, |editor, window, cx| {
 3958                    match editor.context_menu.borrow().as_ref() {
 3959                        None => {}
 3960                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3961                            if prev_menu.id > id {
 3962                                return;
 3963                            }
 3964                        }
 3965                        _ => return,
 3966                    }
 3967
 3968                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3969                        let mut menu = menu.unwrap();
 3970                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3971
 3972                        *editor.context_menu.borrow_mut() =
 3973                            Some(CodeContextMenu::Completions(menu));
 3974
 3975                        if editor.show_edit_predictions_in_menu() {
 3976                            editor.update_visible_inline_completion(window, cx);
 3977                        } else {
 3978                            editor.discard_inline_completion(false, cx);
 3979                        }
 3980
 3981                        cx.notify();
 3982                    } else if editor.completion_tasks.len() <= 1 {
 3983                        // If there are no more completion tasks and the last menu was
 3984                        // empty, we should hide it.
 3985                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3986                        // If it was already hidden and we don't show inline
 3987                        // completions in the menu, we should also show the
 3988                        // inline-completion when available.
 3989                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3990                            editor.update_visible_inline_completion(window, cx);
 3991                        }
 3992                    }
 3993                })?;
 3994
 3995                Ok::<_, anyhow::Error>(())
 3996            }
 3997            .log_err()
 3998        });
 3999
 4000        self.completion_tasks.push((id, task));
 4001    }
 4002
 4003    pub fn confirm_completion(
 4004        &mut self,
 4005        action: &ConfirmCompletion,
 4006        window: &mut Window,
 4007        cx: &mut Context<Self>,
 4008    ) -> Option<Task<Result<()>>> {
 4009        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4010    }
 4011
 4012    pub fn compose_completion(
 4013        &mut self,
 4014        action: &ComposeCompletion,
 4015        window: &mut Window,
 4016        cx: &mut Context<Self>,
 4017    ) -> Option<Task<Result<()>>> {
 4018        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4019    }
 4020
 4021    fn do_completion(
 4022        &mut self,
 4023        item_ix: Option<usize>,
 4024        intent: CompletionIntent,
 4025        window: &mut Window,
 4026        cx: &mut Context<Editor>,
 4027    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4028        use language::ToOffset as _;
 4029
 4030        let completions_menu =
 4031            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4032                menu
 4033            } else {
 4034                return None;
 4035            };
 4036
 4037        let entries = completions_menu.entries.borrow();
 4038        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4039        if self.show_edit_predictions_in_menu() {
 4040            self.discard_inline_completion(true, cx);
 4041        }
 4042        let candidate_id = mat.candidate_id;
 4043        drop(entries);
 4044
 4045        let buffer_handle = completions_menu.buffer;
 4046        let completion = completions_menu
 4047            .completions
 4048            .borrow()
 4049            .get(candidate_id)?
 4050            .clone();
 4051        cx.stop_propagation();
 4052
 4053        let snippet;
 4054        let text;
 4055
 4056        if completion.is_snippet() {
 4057            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4058            text = snippet.as_ref().unwrap().text.clone();
 4059        } else {
 4060            snippet = None;
 4061            text = completion.new_text.clone();
 4062        };
 4063        let selections = self.selections.all::<usize>(cx);
 4064        let buffer = buffer_handle.read(cx);
 4065        let old_range = completion.old_range.to_offset(buffer);
 4066        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4067
 4068        let newest_selection = self.selections.newest_anchor();
 4069        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4070            return None;
 4071        }
 4072
 4073        let lookbehind = newest_selection
 4074            .start
 4075            .text_anchor
 4076            .to_offset(buffer)
 4077            .saturating_sub(old_range.start);
 4078        let lookahead = old_range
 4079            .end
 4080            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4081        let mut common_prefix_len = old_text
 4082            .bytes()
 4083            .zip(text.bytes())
 4084            .take_while(|(a, b)| a == b)
 4085            .count();
 4086
 4087        let snapshot = self.buffer.read(cx).snapshot(cx);
 4088        let mut range_to_replace: Option<Range<isize>> = None;
 4089        let mut ranges = Vec::new();
 4090        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4091        for selection in &selections {
 4092            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4093                let start = selection.start.saturating_sub(lookbehind);
 4094                let end = selection.end + lookahead;
 4095                if selection.id == newest_selection.id {
 4096                    range_to_replace = Some(
 4097                        ((start + common_prefix_len) as isize - selection.start as isize)
 4098                            ..(end as isize - selection.start as isize),
 4099                    );
 4100                }
 4101                ranges.push(start + common_prefix_len..end);
 4102            } else {
 4103                common_prefix_len = 0;
 4104                ranges.clear();
 4105                ranges.extend(selections.iter().map(|s| {
 4106                    if s.id == newest_selection.id {
 4107                        range_to_replace = Some(
 4108                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4109                                - selection.start as isize
 4110                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4111                                    - selection.start as isize,
 4112                        );
 4113                        old_range.clone()
 4114                    } else {
 4115                        s.start..s.end
 4116                    }
 4117                }));
 4118                break;
 4119            }
 4120            if !self.linked_edit_ranges.is_empty() {
 4121                let start_anchor = snapshot.anchor_before(selection.head());
 4122                let end_anchor = snapshot.anchor_after(selection.tail());
 4123                if let Some(ranges) = self
 4124                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4125                {
 4126                    for (buffer, edits) in ranges {
 4127                        linked_edits.entry(buffer.clone()).or_default().extend(
 4128                            edits
 4129                                .into_iter()
 4130                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4131                        );
 4132                    }
 4133                }
 4134            }
 4135        }
 4136        let text = &text[common_prefix_len..];
 4137
 4138        cx.emit(EditorEvent::InputHandled {
 4139            utf16_range_to_replace: range_to_replace,
 4140            text: text.into(),
 4141        });
 4142
 4143        self.transact(window, cx, |this, window, cx| {
 4144            if let Some(mut snippet) = snippet {
 4145                snippet.text = text.to_string();
 4146                for tabstop in snippet
 4147                    .tabstops
 4148                    .iter_mut()
 4149                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4150                {
 4151                    tabstop.start -= common_prefix_len as isize;
 4152                    tabstop.end -= common_prefix_len as isize;
 4153                }
 4154
 4155                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4156            } else {
 4157                this.buffer.update(cx, |buffer, cx| {
 4158                    buffer.edit(
 4159                        ranges.iter().map(|range| (range.clone(), text)),
 4160                        this.autoindent_mode.clone(),
 4161                        cx,
 4162                    );
 4163                });
 4164            }
 4165            for (buffer, edits) in linked_edits {
 4166                buffer.update(cx, |buffer, cx| {
 4167                    let snapshot = buffer.snapshot();
 4168                    let edits = edits
 4169                        .into_iter()
 4170                        .map(|(range, text)| {
 4171                            use text::ToPoint as TP;
 4172                            let end_point = TP::to_point(&range.end, &snapshot);
 4173                            let start_point = TP::to_point(&range.start, &snapshot);
 4174                            (start_point..end_point, text)
 4175                        })
 4176                        .sorted_by_key(|(range, _)| range.start)
 4177                        .collect::<Vec<_>>();
 4178                    buffer.edit(edits, None, cx);
 4179                })
 4180            }
 4181
 4182            this.refresh_inline_completion(true, false, window, cx);
 4183        });
 4184
 4185        let show_new_completions_on_confirm = completion
 4186            .confirm
 4187            .as_ref()
 4188            .map_or(false, |confirm| confirm(intent, window, cx));
 4189        if show_new_completions_on_confirm {
 4190            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4191        }
 4192
 4193        let provider = self.completion_provider.as_ref()?;
 4194        drop(completion);
 4195        let apply_edits = provider.apply_additional_edits_for_completion(
 4196            buffer_handle,
 4197            completions_menu.completions.clone(),
 4198            candidate_id,
 4199            true,
 4200            cx,
 4201        );
 4202
 4203        let editor_settings = EditorSettings::get_global(cx);
 4204        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4205            // After the code completion is finished, users often want to know what signatures are needed.
 4206            // so we should automatically call signature_help
 4207            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4208        }
 4209
 4210        Some(cx.foreground_executor().spawn(async move {
 4211            apply_edits.await?;
 4212            Ok(())
 4213        }))
 4214    }
 4215
 4216    pub fn toggle_code_actions(
 4217        &mut self,
 4218        action: &ToggleCodeActions,
 4219        window: &mut Window,
 4220        cx: &mut Context<Self>,
 4221    ) {
 4222        let mut context_menu = self.context_menu.borrow_mut();
 4223        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4224            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4225                // Toggle if we're selecting the same one
 4226                *context_menu = None;
 4227                cx.notify();
 4228                return;
 4229            } else {
 4230                // Otherwise, clear it and start a new one
 4231                *context_menu = None;
 4232                cx.notify();
 4233            }
 4234        }
 4235        drop(context_menu);
 4236        let snapshot = self.snapshot(window, cx);
 4237        let deployed_from_indicator = action.deployed_from_indicator;
 4238        let mut task = self.code_actions_task.take();
 4239        let action = action.clone();
 4240        cx.spawn_in(window, |editor, mut cx| async move {
 4241            while let Some(prev_task) = task {
 4242                prev_task.await.log_err();
 4243                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4244            }
 4245
 4246            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4247                if editor.focus_handle.is_focused(window) {
 4248                    let multibuffer_point = action
 4249                        .deployed_from_indicator
 4250                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4251                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4252                    let (buffer, buffer_row) = snapshot
 4253                        .buffer_snapshot
 4254                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4255                        .and_then(|(buffer_snapshot, range)| {
 4256                            editor
 4257                                .buffer
 4258                                .read(cx)
 4259                                .buffer(buffer_snapshot.remote_id())
 4260                                .map(|buffer| (buffer, range.start.row))
 4261                        })?;
 4262                    let (_, code_actions) = editor
 4263                        .available_code_actions
 4264                        .clone()
 4265                        .and_then(|(location, code_actions)| {
 4266                            let snapshot = location.buffer.read(cx).snapshot();
 4267                            let point_range = location.range.to_point(&snapshot);
 4268                            let point_range = point_range.start.row..=point_range.end.row;
 4269                            if point_range.contains(&buffer_row) {
 4270                                Some((location, code_actions))
 4271                            } else {
 4272                                None
 4273                            }
 4274                        })
 4275                        .unzip();
 4276                    let buffer_id = buffer.read(cx).remote_id();
 4277                    let tasks = editor
 4278                        .tasks
 4279                        .get(&(buffer_id, buffer_row))
 4280                        .map(|t| Arc::new(t.to_owned()));
 4281                    if tasks.is_none() && code_actions.is_none() {
 4282                        return None;
 4283                    }
 4284
 4285                    editor.completion_tasks.clear();
 4286                    editor.discard_inline_completion(false, cx);
 4287                    let task_context =
 4288                        tasks
 4289                            .as_ref()
 4290                            .zip(editor.project.clone())
 4291                            .map(|(tasks, project)| {
 4292                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4293                            });
 4294
 4295                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4296                        let task_context = match task_context {
 4297                            Some(task_context) => task_context.await,
 4298                            None => None,
 4299                        };
 4300                        let resolved_tasks =
 4301                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4302                                Rc::new(ResolvedTasks {
 4303                                    templates: tasks.resolve(&task_context).collect(),
 4304                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4305                                        multibuffer_point.row,
 4306                                        tasks.column,
 4307                                    )),
 4308                                })
 4309                            });
 4310                        let spawn_straight_away = resolved_tasks
 4311                            .as_ref()
 4312                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4313                            && code_actions
 4314                                .as_ref()
 4315                                .map_or(true, |actions| actions.is_empty());
 4316                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4317                            *editor.context_menu.borrow_mut() =
 4318                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4319                                    buffer,
 4320                                    actions: CodeActionContents {
 4321                                        tasks: resolved_tasks,
 4322                                        actions: code_actions,
 4323                                    },
 4324                                    selected_item: Default::default(),
 4325                                    scroll_handle: UniformListScrollHandle::default(),
 4326                                    deployed_from_indicator,
 4327                                }));
 4328                            if spawn_straight_away {
 4329                                if let Some(task) = editor.confirm_code_action(
 4330                                    &ConfirmCodeAction { item_ix: Some(0) },
 4331                                    window,
 4332                                    cx,
 4333                                ) {
 4334                                    cx.notify();
 4335                                    return task;
 4336                                }
 4337                            }
 4338                            cx.notify();
 4339                            Task::ready(Ok(()))
 4340                        }) {
 4341                            task.await
 4342                        } else {
 4343                            Ok(())
 4344                        }
 4345                    }))
 4346                } else {
 4347                    Some(Task::ready(Ok(())))
 4348                }
 4349            })?;
 4350            if let Some(task) = spawned_test_task {
 4351                task.await?;
 4352            }
 4353
 4354            Ok::<_, anyhow::Error>(())
 4355        })
 4356        .detach_and_log_err(cx);
 4357    }
 4358
 4359    pub fn confirm_code_action(
 4360        &mut self,
 4361        action: &ConfirmCodeAction,
 4362        window: &mut Window,
 4363        cx: &mut Context<Self>,
 4364    ) -> Option<Task<Result<()>>> {
 4365        let actions_menu =
 4366            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4367                menu
 4368            } else {
 4369                return None;
 4370            };
 4371        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4372        let action = actions_menu.actions.get(action_ix)?;
 4373        let title = action.label();
 4374        let buffer = actions_menu.buffer;
 4375        let workspace = self.workspace()?;
 4376
 4377        match action {
 4378            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4379                workspace.update(cx, |workspace, cx| {
 4380                    workspace::tasks::schedule_resolved_task(
 4381                        workspace,
 4382                        task_source_kind,
 4383                        resolved_task,
 4384                        false,
 4385                        cx,
 4386                    );
 4387
 4388                    Some(Task::ready(Ok(())))
 4389                })
 4390            }
 4391            CodeActionsItem::CodeAction {
 4392                excerpt_id,
 4393                action,
 4394                provider,
 4395            } => {
 4396                let apply_code_action =
 4397                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4398                let workspace = workspace.downgrade();
 4399                Some(cx.spawn_in(window, |editor, cx| async move {
 4400                    let project_transaction = apply_code_action.await?;
 4401                    Self::open_project_transaction(
 4402                        &editor,
 4403                        workspace,
 4404                        project_transaction,
 4405                        title,
 4406                        cx,
 4407                    )
 4408                    .await
 4409                }))
 4410            }
 4411        }
 4412    }
 4413
 4414    pub async fn open_project_transaction(
 4415        this: &WeakEntity<Editor>,
 4416        workspace: WeakEntity<Workspace>,
 4417        transaction: ProjectTransaction,
 4418        title: String,
 4419        mut cx: AsyncWindowContext,
 4420    ) -> Result<()> {
 4421        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4422        cx.update(|_, cx| {
 4423            entries.sort_unstable_by_key(|(buffer, _)| {
 4424                buffer.read(cx).file().map(|f| f.path().clone())
 4425            });
 4426        })?;
 4427
 4428        // If the project transaction's edits are all contained within this editor, then
 4429        // avoid opening a new editor to display them.
 4430
 4431        if let Some((buffer, transaction)) = entries.first() {
 4432            if entries.len() == 1 {
 4433                let excerpt = this.update(&mut cx, |editor, cx| {
 4434                    editor
 4435                        .buffer()
 4436                        .read(cx)
 4437                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4438                })?;
 4439                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4440                    if excerpted_buffer == *buffer {
 4441                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4442                            let excerpt_range = excerpt_range.to_offset(buffer);
 4443                            buffer
 4444                                .edited_ranges_for_transaction::<usize>(transaction)
 4445                                .all(|range| {
 4446                                    excerpt_range.start <= range.start
 4447                                        && excerpt_range.end >= range.end
 4448                                })
 4449                        })?;
 4450
 4451                        if all_edits_within_excerpt {
 4452                            return Ok(());
 4453                        }
 4454                    }
 4455                }
 4456            }
 4457        } else {
 4458            return Ok(());
 4459        }
 4460
 4461        let mut ranges_to_highlight = Vec::new();
 4462        let excerpt_buffer = cx.new(|cx| {
 4463            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4464            for (buffer_handle, transaction) in &entries {
 4465                let buffer = buffer_handle.read(cx);
 4466                ranges_to_highlight.extend(
 4467                    multibuffer.push_excerpts_with_context_lines(
 4468                        buffer_handle.clone(),
 4469                        buffer
 4470                            .edited_ranges_for_transaction::<usize>(transaction)
 4471                            .collect(),
 4472                        DEFAULT_MULTIBUFFER_CONTEXT,
 4473                        cx,
 4474                    ),
 4475                );
 4476            }
 4477            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4478            multibuffer
 4479        })?;
 4480
 4481        workspace.update_in(&mut cx, |workspace, window, cx| {
 4482            let project = workspace.project().clone();
 4483            let editor = cx
 4484                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4485            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4486            editor.update(cx, |editor, cx| {
 4487                editor.highlight_background::<Self>(
 4488                    &ranges_to_highlight,
 4489                    |theme| theme.editor_highlighted_line_background,
 4490                    cx,
 4491                );
 4492            });
 4493        })?;
 4494
 4495        Ok(())
 4496    }
 4497
 4498    pub fn clear_code_action_providers(&mut self) {
 4499        self.code_action_providers.clear();
 4500        self.available_code_actions.take();
 4501    }
 4502
 4503    pub fn add_code_action_provider(
 4504        &mut self,
 4505        provider: Rc<dyn CodeActionProvider>,
 4506        window: &mut Window,
 4507        cx: &mut Context<Self>,
 4508    ) {
 4509        if self
 4510            .code_action_providers
 4511            .iter()
 4512            .any(|existing_provider| existing_provider.id() == provider.id())
 4513        {
 4514            return;
 4515        }
 4516
 4517        self.code_action_providers.push(provider);
 4518        self.refresh_code_actions(window, cx);
 4519    }
 4520
 4521    pub fn remove_code_action_provider(
 4522        &mut self,
 4523        id: Arc<str>,
 4524        window: &mut Window,
 4525        cx: &mut Context<Self>,
 4526    ) {
 4527        self.code_action_providers
 4528            .retain(|provider| provider.id() != id);
 4529        self.refresh_code_actions(window, cx);
 4530    }
 4531
 4532    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4533        let buffer = self.buffer.read(cx);
 4534        let newest_selection = self.selections.newest_anchor().clone();
 4535        if newest_selection.head().diff_base_anchor.is_some() {
 4536            return None;
 4537        }
 4538        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4539        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4540        if start_buffer != end_buffer {
 4541            return None;
 4542        }
 4543
 4544        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4545            cx.background_executor()
 4546                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4547                .await;
 4548
 4549            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4550                let providers = this.code_action_providers.clone();
 4551                let tasks = this
 4552                    .code_action_providers
 4553                    .iter()
 4554                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4555                    .collect::<Vec<_>>();
 4556                (providers, tasks)
 4557            })?;
 4558
 4559            let mut actions = Vec::new();
 4560            for (provider, provider_actions) in
 4561                providers.into_iter().zip(future::join_all(tasks).await)
 4562            {
 4563                if let Some(provider_actions) = provider_actions.log_err() {
 4564                    actions.extend(provider_actions.into_iter().map(|action| {
 4565                        AvailableCodeAction {
 4566                            excerpt_id: newest_selection.start.excerpt_id,
 4567                            action,
 4568                            provider: provider.clone(),
 4569                        }
 4570                    }));
 4571                }
 4572            }
 4573
 4574            this.update(&mut cx, |this, cx| {
 4575                this.available_code_actions = if actions.is_empty() {
 4576                    None
 4577                } else {
 4578                    Some((
 4579                        Location {
 4580                            buffer: start_buffer,
 4581                            range: start..end,
 4582                        },
 4583                        actions.into(),
 4584                    ))
 4585                };
 4586                cx.notify();
 4587            })
 4588        }));
 4589        None
 4590    }
 4591
 4592    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4593        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4594            self.show_git_blame_inline = false;
 4595
 4596            self.show_git_blame_inline_delay_task =
 4597                Some(cx.spawn_in(window, |this, mut cx| async move {
 4598                    cx.background_executor().timer(delay).await;
 4599
 4600                    this.update(&mut cx, |this, cx| {
 4601                        this.show_git_blame_inline = true;
 4602                        cx.notify();
 4603                    })
 4604                    .log_err();
 4605                }));
 4606        }
 4607    }
 4608
 4609    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4610        if self.pending_rename.is_some() {
 4611            return None;
 4612        }
 4613
 4614        let provider = self.semantics_provider.clone()?;
 4615        let buffer = self.buffer.read(cx);
 4616        let newest_selection = self.selections.newest_anchor().clone();
 4617        let cursor_position = newest_selection.head();
 4618        let (cursor_buffer, cursor_buffer_position) =
 4619            buffer.text_anchor_for_position(cursor_position, cx)?;
 4620        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4621        if cursor_buffer != tail_buffer {
 4622            return None;
 4623        }
 4624        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4625        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4626            cx.background_executor()
 4627                .timer(Duration::from_millis(debounce))
 4628                .await;
 4629
 4630            let highlights = if let Some(highlights) = cx
 4631                .update(|cx| {
 4632                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4633                })
 4634                .ok()
 4635                .flatten()
 4636            {
 4637                highlights.await.log_err()
 4638            } else {
 4639                None
 4640            };
 4641
 4642            if let Some(highlights) = highlights {
 4643                this.update(&mut cx, |this, cx| {
 4644                    if this.pending_rename.is_some() {
 4645                        return;
 4646                    }
 4647
 4648                    let buffer_id = cursor_position.buffer_id;
 4649                    let buffer = this.buffer.read(cx);
 4650                    if !buffer
 4651                        .text_anchor_for_position(cursor_position, cx)
 4652                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4653                    {
 4654                        return;
 4655                    }
 4656
 4657                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4658                    let mut write_ranges = Vec::new();
 4659                    let mut read_ranges = Vec::new();
 4660                    for highlight in highlights {
 4661                        for (excerpt_id, excerpt_range) in
 4662                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4663                        {
 4664                            let start = highlight
 4665                                .range
 4666                                .start
 4667                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4668                            let end = highlight
 4669                                .range
 4670                                .end
 4671                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4672                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4673                                continue;
 4674                            }
 4675
 4676                            let range = Anchor {
 4677                                buffer_id,
 4678                                excerpt_id,
 4679                                text_anchor: start,
 4680                                diff_base_anchor: None,
 4681                            }..Anchor {
 4682                                buffer_id,
 4683                                excerpt_id,
 4684                                text_anchor: end,
 4685                                diff_base_anchor: None,
 4686                            };
 4687                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4688                                write_ranges.push(range);
 4689                            } else {
 4690                                read_ranges.push(range);
 4691                            }
 4692                        }
 4693                    }
 4694
 4695                    this.highlight_background::<DocumentHighlightRead>(
 4696                        &read_ranges,
 4697                        |theme| theme.editor_document_highlight_read_background,
 4698                        cx,
 4699                    );
 4700                    this.highlight_background::<DocumentHighlightWrite>(
 4701                        &write_ranges,
 4702                        |theme| theme.editor_document_highlight_write_background,
 4703                        cx,
 4704                    );
 4705                    cx.notify();
 4706                })
 4707                .log_err();
 4708            }
 4709        }));
 4710        None
 4711    }
 4712
 4713    pub fn refresh_selected_text_highlights(
 4714        &mut self,
 4715        window: &mut Window,
 4716        cx: &mut Context<Editor>,
 4717    ) {
 4718        self.selection_highlight_task.take();
 4719        if !EditorSettings::get_global(cx).selection_highlight {
 4720            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4721            return;
 4722        }
 4723        if self.selections.count() != 1 || self.selections.line_mode {
 4724            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4725            return;
 4726        }
 4727        let selection = self.selections.newest::<Point>(cx);
 4728        if selection.is_empty() || selection.start.row != selection.end.row {
 4729            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4730            return;
 4731        }
 4732        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4733        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4734            cx.background_executor()
 4735                .timer(Duration::from_millis(debounce))
 4736                .await;
 4737            let Some(Some(matches_task)) = editor
 4738                .update_in(&mut cx, |editor, _, cx| {
 4739                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4740                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4741                        return None;
 4742                    }
 4743                    let selection = editor.selections.newest::<Point>(cx);
 4744                    if selection.is_empty() || selection.start.row != selection.end.row {
 4745                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4746                        return None;
 4747                    }
 4748                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4749                    Some(cx.background_spawn(async move {
 4750                        let mut ranges = Vec::new();
 4751                        let query = buffer.text_for_range(selection.range()).collect::<String>();
 4752                        let selection_anchors = selection.range().to_anchors(&buffer);
 4753                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4754                            for (search_buffer, search_range, excerpt_id) in
 4755                                buffer.range_to_buffer_ranges(range)
 4756                            {
 4757                                ranges.extend(
 4758                                    project::search::SearchQuery::text(
 4759                                        query.clone(),
 4760                                        false,
 4761                                        false,
 4762                                        false,
 4763                                        Default::default(),
 4764                                        Default::default(),
 4765                                        None,
 4766                                    )
 4767                                    .unwrap()
 4768                                    .search(search_buffer, Some(search_range.clone()))
 4769                                    .await
 4770                                    .into_iter()
 4771                                    .filter_map(
 4772                                        |match_range| {
 4773                                            let start = search_buffer.anchor_after(
 4774                                                search_range.start + match_range.start,
 4775                                            );
 4776                                            let end = search_buffer.anchor_before(
 4777                                                search_range.start + match_range.end,
 4778                                            );
 4779                                            let range = Anchor::range_in_buffer(
 4780                                                excerpt_id,
 4781                                                search_buffer.remote_id(),
 4782                                                start..end,
 4783                                            );
 4784                                            (range != selection_anchors).then_some(range)
 4785                                        },
 4786                                    ),
 4787                                );
 4788                            }
 4789                        }
 4790                        ranges
 4791                    }))
 4792                })
 4793                .log_err()
 4794            else {
 4795                return;
 4796            };
 4797            let matches = matches_task.await;
 4798            editor
 4799                .update_in(&mut cx, |editor, _, cx| {
 4800                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4801                    if !matches.is_empty() {
 4802                        editor.highlight_background::<SelectedTextHighlight>(
 4803                            &matches,
 4804                            |theme| theme.editor_document_highlight_bracket_background,
 4805                            cx,
 4806                        )
 4807                    }
 4808                })
 4809                .log_err();
 4810        }));
 4811    }
 4812
 4813    pub fn refresh_inline_completion(
 4814        &mut self,
 4815        debounce: bool,
 4816        user_requested: bool,
 4817        window: &mut Window,
 4818        cx: &mut Context<Self>,
 4819    ) -> Option<()> {
 4820        let provider = self.edit_prediction_provider()?;
 4821        let cursor = self.selections.newest_anchor().head();
 4822        let (buffer, cursor_buffer_position) =
 4823            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4824
 4825        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4826            self.discard_inline_completion(false, cx);
 4827            return None;
 4828        }
 4829
 4830        if !user_requested
 4831            && (!self.should_show_edit_predictions()
 4832                || !self.is_focused(window)
 4833                || buffer.read(cx).is_empty())
 4834        {
 4835            self.discard_inline_completion(false, cx);
 4836            return None;
 4837        }
 4838
 4839        self.update_visible_inline_completion(window, cx);
 4840        provider.refresh(
 4841            self.project.clone(),
 4842            buffer,
 4843            cursor_buffer_position,
 4844            debounce,
 4845            cx,
 4846        );
 4847        Some(())
 4848    }
 4849
 4850    fn show_edit_predictions_in_menu(&self) -> bool {
 4851        match self.edit_prediction_settings {
 4852            EditPredictionSettings::Disabled => false,
 4853            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4854        }
 4855    }
 4856
 4857    pub fn edit_predictions_enabled(&self) -> bool {
 4858        match self.edit_prediction_settings {
 4859            EditPredictionSettings::Disabled => false,
 4860            EditPredictionSettings::Enabled { .. } => true,
 4861        }
 4862    }
 4863
 4864    fn edit_prediction_requires_modifier(&self) -> bool {
 4865        match self.edit_prediction_settings {
 4866            EditPredictionSettings::Disabled => false,
 4867            EditPredictionSettings::Enabled {
 4868                preview_requires_modifier,
 4869                ..
 4870            } => preview_requires_modifier,
 4871        }
 4872    }
 4873
 4874    fn edit_prediction_settings_at_position(
 4875        &self,
 4876        buffer: &Entity<Buffer>,
 4877        buffer_position: language::Anchor,
 4878        cx: &App,
 4879    ) -> EditPredictionSettings {
 4880        if self.mode != EditorMode::Full
 4881            || !self.show_inline_completions_override.unwrap_or(true)
 4882            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4883        {
 4884            return EditPredictionSettings::Disabled;
 4885        }
 4886
 4887        let buffer = buffer.read(cx);
 4888
 4889        let file = buffer.file();
 4890
 4891        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4892            return EditPredictionSettings::Disabled;
 4893        };
 4894
 4895        let by_provider = matches!(
 4896            self.menu_inline_completions_policy,
 4897            MenuInlineCompletionsPolicy::ByProvider
 4898        );
 4899
 4900        let show_in_menu = by_provider
 4901            && self
 4902                .edit_prediction_provider
 4903                .as_ref()
 4904                .map_or(false, |provider| {
 4905                    provider.provider.show_completions_in_menu()
 4906                });
 4907
 4908        let preview_requires_modifier =
 4909            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4910
 4911        EditPredictionSettings::Enabled {
 4912            show_in_menu,
 4913            preview_requires_modifier,
 4914        }
 4915    }
 4916
 4917    fn should_show_edit_predictions(&self) -> bool {
 4918        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4919    }
 4920
 4921    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4922        matches!(
 4923            self.edit_prediction_preview,
 4924            EditPredictionPreview::Active { .. }
 4925        )
 4926    }
 4927
 4928    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4929        let cursor = self.selections.newest_anchor().head();
 4930        if let Some((buffer, cursor_position)) =
 4931            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4932        {
 4933            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4934        } else {
 4935            false
 4936        }
 4937    }
 4938
 4939    fn inline_completions_enabled_in_buffer(
 4940        &self,
 4941        buffer: &Entity<Buffer>,
 4942        buffer_position: language::Anchor,
 4943        cx: &App,
 4944    ) -> bool {
 4945        maybe!({
 4946            let provider = self.edit_prediction_provider()?;
 4947            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4948                return Some(false);
 4949            }
 4950            let buffer = buffer.read(cx);
 4951            let Some(file) = buffer.file() else {
 4952                return Some(true);
 4953            };
 4954            let settings = all_language_settings(Some(file), cx);
 4955            Some(settings.inline_completions_enabled_for_path(file.path()))
 4956        })
 4957        .unwrap_or(false)
 4958    }
 4959
 4960    fn cycle_inline_completion(
 4961        &mut self,
 4962        direction: Direction,
 4963        window: &mut Window,
 4964        cx: &mut Context<Self>,
 4965    ) -> Option<()> {
 4966        let provider = self.edit_prediction_provider()?;
 4967        let cursor = self.selections.newest_anchor().head();
 4968        let (buffer, cursor_buffer_position) =
 4969            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4970        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4971            return None;
 4972        }
 4973
 4974        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4975        self.update_visible_inline_completion(window, cx);
 4976
 4977        Some(())
 4978    }
 4979
 4980    pub fn show_inline_completion(
 4981        &mut self,
 4982        _: &ShowEditPrediction,
 4983        window: &mut Window,
 4984        cx: &mut Context<Self>,
 4985    ) {
 4986        if !self.has_active_inline_completion() {
 4987            self.refresh_inline_completion(false, true, window, cx);
 4988            return;
 4989        }
 4990
 4991        self.update_visible_inline_completion(window, cx);
 4992    }
 4993
 4994    pub fn display_cursor_names(
 4995        &mut self,
 4996        _: &DisplayCursorNames,
 4997        window: &mut Window,
 4998        cx: &mut Context<Self>,
 4999    ) {
 5000        self.show_cursor_names(window, cx);
 5001    }
 5002
 5003    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5004        self.show_cursor_names = true;
 5005        cx.notify();
 5006        cx.spawn_in(window, |this, mut cx| async move {
 5007            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5008            this.update(&mut cx, |this, cx| {
 5009                this.show_cursor_names = false;
 5010                cx.notify()
 5011            })
 5012            .ok()
 5013        })
 5014        .detach();
 5015    }
 5016
 5017    pub fn next_edit_prediction(
 5018        &mut self,
 5019        _: &NextEditPrediction,
 5020        window: &mut Window,
 5021        cx: &mut Context<Self>,
 5022    ) {
 5023        if self.has_active_inline_completion() {
 5024            self.cycle_inline_completion(Direction::Next, window, cx);
 5025        } else {
 5026            let is_copilot_disabled = self
 5027                .refresh_inline_completion(false, true, window, cx)
 5028                .is_none();
 5029            if is_copilot_disabled {
 5030                cx.propagate();
 5031            }
 5032        }
 5033    }
 5034
 5035    pub fn previous_edit_prediction(
 5036        &mut self,
 5037        _: &PreviousEditPrediction,
 5038        window: &mut Window,
 5039        cx: &mut Context<Self>,
 5040    ) {
 5041        if self.has_active_inline_completion() {
 5042            self.cycle_inline_completion(Direction::Prev, window, cx);
 5043        } else {
 5044            let is_copilot_disabled = self
 5045                .refresh_inline_completion(false, true, window, cx)
 5046                .is_none();
 5047            if is_copilot_disabled {
 5048                cx.propagate();
 5049            }
 5050        }
 5051    }
 5052
 5053    pub fn accept_edit_prediction(
 5054        &mut self,
 5055        _: &AcceptEditPrediction,
 5056        window: &mut Window,
 5057        cx: &mut Context<Self>,
 5058    ) {
 5059        if self.show_edit_predictions_in_menu() {
 5060            self.hide_context_menu(window, cx);
 5061        }
 5062
 5063        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5064            return;
 5065        };
 5066
 5067        self.report_inline_completion_event(
 5068            active_inline_completion.completion_id.clone(),
 5069            true,
 5070            cx,
 5071        );
 5072
 5073        match &active_inline_completion.completion {
 5074            InlineCompletion::Move { target, .. } => {
 5075                let target = *target;
 5076
 5077                if let Some(position_map) = &self.last_position_map {
 5078                    if position_map
 5079                        .visible_row_range
 5080                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5081                        || !self.edit_prediction_requires_modifier()
 5082                    {
 5083                        self.unfold_ranges(&[target..target], true, false, cx);
 5084                        // Note that this is also done in vim's handler of the Tab action.
 5085                        self.change_selections(
 5086                            Some(Autoscroll::newest()),
 5087                            window,
 5088                            cx,
 5089                            |selections| {
 5090                                selections.select_anchor_ranges([target..target]);
 5091                            },
 5092                        );
 5093                        self.clear_row_highlights::<EditPredictionPreview>();
 5094
 5095                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5096                            previous_scroll_position: None,
 5097                        };
 5098                    } else {
 5099                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5100                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5101                        };
 5102                        self.highlight_rows::<EditPredictionPreview>(
 5103                            target..target,
 5104                            cx.theme().colors().editor_highlighted_line_background,
 5105                            true,
 5106                            cx,
 5107                        );
 5108                        self.request_autoscroll(Autoscroll::fit(), cx);
 5109                    }
 5110                }
 5111            }
 5112            InlineCompletion::Edit { edits, .. } => {
 5113                if let Some(provider) = self.edit_prediction_provider() {
 5114                    provider.accept(cx);
 5115                }
 5116
 5117                let snapshot = self.buffer.read(cx).snapshot(cx);
 5118                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5119
 5120                self.buffer.update(cx, |buffer, cx| {
 5121                    buffer.edit(edits.iter().cloned(), None, cx)
 5122                });
 5123
 5124                self.change_selections(None, window, cx, |s| {
 5125                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5126                });
 5127
 5128                self.update_visible_inline_completion(window, cx);
 5129                if self.active_inline_completion.is_none() {
 5130                    self.refresh_inline_completion(true, true, window, cx);
 5131                }
 5132
 5133                cx.notify();
 5134            }
 5135        }
 5136
 5137        self.edit_prediction_requires_modifier_in_leading_space = false;
 5138    }
 5139
 5140    pub fn accept_partial_inline_completion(
 5141        &mut self,
 5142        _: &AcceptPartialEditPrediction,
 5143        window: &mut Window,
 5144        cx: &mut Context<Self>,
 5145    ) {
 5146        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5147            return;
 5148        };
 5149        if self.selections.count() != 1 {
 5150            return;
 5151        }
 5152
 5153        self.report_inline_completion_event(
 5154            active_inline_completion.completion_id.clone(),
 5155            true,
 5156            cx,
 5157        );
 5158
 5159        match &active_inline_completion.completion {
 5160            InlineCompletion::Move { target, .. } => {
 5161                let target = *target;
 5162                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5163                    selections.select_anchor_ranges([target..target]);
 5164                });
 5165            }
 5166            InlineCompletion::Edit { edits, .. } => {
 5167                // Find an insertion that starts at the cursor position.
 5168                let snapshot = self.buffer.read(cx).snapshot(cx);
 5169                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5170                let insertion = edits.iter().find_map(|(range, text)| {
 5171                    let range = range.to_offset(&snapshot);
 5172                    if range.is_empty() && range.start == cursor_offset {
 5173                        Some(text)
 5174                    } else {
 5175                        None
 5176                    }
 5177                });
 5178
 5179                if let Some(text) = insertion {
 5180                    let mut partial_completion = text
 5181                        .chars()
 5182                        .by_ref()
 5183                        .take_while(|c| c.is_alphabetic())
 5184                        .collect::<String>();
 5185                    if partial_completion.is_empty() {
 5186                        partial_completion = text
 5187                            .chars()
 5188                            .by_ref()
 5189                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5190                            .collect::<String>();
 5191                    }
 5192
 5193                    cx.emit(EditorEvent::InputHandled {
 5194                        utf16_range_to_replace: None,
 5195                        text: partial_completion.clone().into(),
 5196                    });
 5197
 5198                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5199
 5200                    self.refresh_inline_completion(true, true, window, cx);
 5201                    cx.notify();
 5202                } else {
 5203                    self.accept_edit_prediction(&Default::default(), window, cx);
 5204                }
 5205            }
 5206        }
 5207    }
 5208
 5209    fn discard_inline_completion(
 5210        &mut self,
 5211        should_report_inline_completion_event: bool,
 5212        cx: &mut Context<Self>,
 5213    ) -> bool {
 5214        if should_report_inline_completion_event {
 5215            let completion_id = self
 5216                .active_inline_completion
 5217                .as_ref()
 5218                .and_then(|active_completion| active_completion.completion_id.clone());
 5219
 5220            self.report_inline_completion_event(completion_id, false, cx);
 5221        }
 5222
 5223        if let Some(provider) = self.edit_prediction_provider() {
 5224            provider.discard(cx);
 5225        }
 5226
 5227        self.take_active_inline_completion(cx)
 5228    }
 5229
 5230    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5231        let Some(provider) = self.edit_prediction_provider() else {
 5232            return;
 5233        };
 5234
 5235        let Some((_, buffer, _)) = self
 5236            .buffer
 5237            .read(cx)
 5238            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5239        else {
 5240            return;
 5241        };
 5242
 5243        let extension = buffer
 5244            .read(cx)
 5245            .file()
 5246            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5247
 5248        let event_type = match accepted {
 5249            true => "Edit Prediction Accepted",
 5250            false => "Edit Prediction Discarded",
 5251        };
 5252        telemetry::event!(
 5253            event_type,
 5254            provider = provider.name(),
 5255            prediction_id = id,
 5256            suggestion_accepted = accepted,
 5257            file_extension = extension,
 5258        );
 5259    }
 5260
 5261    pub fn has_active_inline_completion(&self) -> bool {
 5262        self.active_inline_completion.is_some()
 5263    }
 5264
 5265    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5266        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5267            return false;
 5268        };
 5269
 5270        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5271        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5272        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5273        true
 5274    }
 5275
 5276    /// Returns true when we're displaying the edit prediction popover below the cursor
 5277    /// like we are not previewing and the LSP autocomplete menu is visible
 5278    /// or we are in `when_holding_modifier` mode.
 5279    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5280        if self.edit_prediction_preview_is_active()
 5281            || !self.show_edit_predictions_in_menu()
 5282            || !self.edit_predictions_enabled()
 5283        {
 5284            return false;
 5285        }
 5286
 5287        if self.has_visible_completions_menu() {
 5288            return true;
 5289        }
 5290
 5291        has_completion && self.edit_prediction_requires_modifier()
 5292    }
 5293
 5294    fn handle_modifiers_changed(
 5295        &mut self,
 5296        modifiers: Modifiers,
 5297        position_map: &PositionMap,
 5298        window: &mut Window,
 5299        cx: &mut Context<Self>,
 5300    ) {
 5301        if self.show_edit_predictions_in_menu() {
 5302            self.update_edit_prediction_preview(&modifiers, window, cx);
 5303        }
 5304
 5305        self.update_selection_mode(&modifiers, position_map, window, cx);
 5306
 5307        let mouse_position = window.mouse_position();
 5308        if !position_map.text_hitbox.is_hovered(window) {
 5309            return;
 5310        }
 5311
 5312        self.update_hovered_link(
 5313            position_map.point_for_position(mouse_position),
 5314            &position_map.snapshot,
 5315            modifiers,
 5316            window,
 5317            cx,
 5318        )
 5319    }
 5320
 5321    fn update_selection_mode(
 5322        &mut self,
 5323        modifiers: &Modifiers,
 5324        position_map: &PositionMap,
 5325        window: &mut Window,
 5326        cx: &mut Context<Self>,
 5327    ) {
 5328        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5329            return;
 5330        }
 5331
 5332        let mouse_position = window.mouse_position();
 5333        let point_for_position = position_map.point_for_position(mouse_position);
 5334        let position = point_for_position.previous_valid;
 5335
 5336        self.select(
 5337            SelectPhase::BeginColumnar {
 5338                position,
 5339                reset: false,
 5340                goal_column: point_for_position.exact_unclipped.column(),
 5341            },
 5342            window,
 5343            cx,
 5344        );
 5345    }
 5346
 5347    fn update_edit_prediction_preview(
 5348        &mut self,
 5349        modifiers: &Modifiers,
 5350        window: &mut Window,
 5351        cx: &mut Context<Self>,
 5352    ) {
 5353        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5354        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5355            return;
 5356        };
 5357
 5358        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5359            if matches!(
 5360                self.edit_prediction_preview,
 5361                EditPredictionPreview::Inactive
 5362            ) {
 5363                self.edit_prediction_preview = EditPredictionPreview::Active {
 5364                    previous_scroll_position: None,
 5365                };
 5366
 5367                self.update_visible_inline_completion(window, cx);
 5368                cx.notify();
 5369            }
 5370        } else if let EditPredictionPreview::Active {
 5371            previous_scroll_position,
 5372        } = self.edit_prediction_preview
 5373        {
 5374            if let (Some(previous_scroll_position), Some(position_map)) =
 5375                (previous_scroll_position, self.last_position_map.as_ref())
 5376            {
 5377                self.set_scroll_position(
 5378                    previous_scroll_position
 5379                        .scroll_position(&position_map.snapshot.display_snapshot),
 5380                    window,
 5381                    cx,
 5382                );
 5383            }
 5384
 5385            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5386            self.clear_row_highlights::<EditPredictionPreview>();
 5387            self.update_visible_inline_completion(window, cx);
 5388            cx.notify();
 5389        }
 5390    }
 5391
 5392    fn update_visible_inline_completion(
 5393        &mut self,
 5394        _window: &mut Window,
 5395        cx: &mut Context<Self>,
 5396    ) -> Option<()> {
 5397        let selection = self.selections.newest_anchor();
 5398        let cursor = selection.head();
 5399        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5400        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5401        let excerpt_id = cursor.excerpt_id;
 5402
 5403        let show_in_menu = self.show_edit_predictions_in_menu();
 5404        let completions_menu_has_precedence = !show_in_menu
 5405            && (self.context_menu.borrow().is_some()
 5406                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5407
 5408        if completions_menu_has_precedence
 5409            || !offset_selection.is_empty()
 5410            || self
 5411                .active_inline_completion
 5412                .as_ref()
 5413                .map_or(false, |completion| {
 5414                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5415                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5416                    !invalidation_range.contains(&offset_selection.head())
 5417                })
 5418        {
 5419            self.discard_inline_completion(false, cx);
 5420            return None;
 5421        }
 5422
 5423        self.take_active_inline_completion(cx);
 5424        let Some(provider) = self.edit_prediction_provider() else {
 5425            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5426            return None;
 5427        };
 5428
 5429        let (buffer, cursor_buffer_position) =
 5430            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5431
 5432        self.edit_prediction_settings =
 5433            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5434
 5435        self.edit_prediction_cursor_on_leading_whitespace =
 5436            multibuffer.is_line_whitespace_upto(cursor);
 5437
 5438        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5439        let edits = inline_completion
 5440            .edits
 5441            .into_iter()
 5442            .flat_map(|(range, new_text)| {
 5443                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5444                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5445                Some((start..end, new_text))
 5446            })
 5447            .collect::<Vec<_>>();
 5448        if edits.is_empty() {
 5449            return None;
 5450        }
 5451
 5452        let first_edit_start = edits.first().unwrap().0.start;
 5453        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5454        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5455
 5456        let last_edit_end = edits.last().unwrap().0.end;
 5457        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5458        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5459
 5460        let cursor_row = cursor.to_point(&multibuffer).row;
 5461
 5462        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5463
 5464        let mut inlay_ids = Vec::new();
 5465        let invalidation_row_range;
 5466        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5467            Some(cursor_row..edit_end_row)
 5468        } else if cursor_row > edit_end_row {
 5469            Some(edit_start_row..cursor_row)
 5470        } else {
 5471            None
 5472        };
 5473        let is_move =
 5474            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5475        let completion = if is_move {
 5476            invalidation_row_range =
 5477                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5478            let target = first_edit_start;
 5479            InlineCompletion::Move { target, snapshot }
 5480        } else {
 5481            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5482                && !self.inline_completions_hidden_for_vim_mode;
 5483
 5484            if show_completions_in_buffer {
 5485                if edits
 5486                    .iter()
 5487                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5488                {
 5489                    let mut inlays = Vec::new();
 5490                    for (range, new_text) in &edits {
 5491                        let inlay = Inlay::inline_completion(
 5492                            post_inc(&mut self.next_inlay_id),
 5493                            range.start,
 5494                            new_text.as_str(),
 5495                        );
 5496                        inlay_ids.push(inlay.id);
 5497                        inlays.push(inlay);
 5498                    }
 5499
 5500                    self.splice_inlays(&[], inlays, cx);
 5501                } else {
 5502                    let background_color = cx.theme().status().deleted_background;
 5503                    self.highlight_text::<InlineCompletionHighlight>(
 5504                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5505                        HighlightStyle {
 5506                            background_color: Some(background_color),
 5507                            ..Default::default()
 5508                        },
 5509                        cx,
 5510                    );
 5511                }
 5512            }
 5513
 5514            invalidation_row_range = edit_start_row..edit_end_row;
 5515
 5516            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5517                if provider.show_tab_accept_marker() {
 5518                    EditDisplayMode::TabAccept
 5519                } else {
 5520                    EditDisplayMode::Inline
 5521                }
 5522            } else {
 5523                EditDisplayMode::DiffPopover
 5524            };
 5525
 5526            InlineCompletion::Edit {
 5527                edits,
 5528                edit_preview: inline_completion.edit_preview,
 5529                display_mode,
 5530                snapshot,
 5531            }
 5532        };
 5533
 5534        let invalidation_range = multibuffer
 5535            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5536            ..multibuffer.anchor_after(Point::new(
 5537                invalidation_row_range.end,
 5538                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5539            ));
 5540
 5541        self.stale_inline_completion_in_menu = None;
 5542        self.active_inline_completion = Some(InlineCompletionState {
 5543            inlay_ids,
 5544            completion,
 5545            completion_id: inline_completion.id,
 5546            invalidation_range,
 5547        });
 5548
 5549        cx.notify();
 5550
 5551        Some(())
 5552    }
 5553
 5554    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5555        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5556    }
 5557
 5558    fn render_code_actions_indicator(
 5559        &self,
 5560        _style: &EditorStyle,
 5561        row: DisplayRow,
 5562        is_active: bool,
 5563        cx: &mut Context<Self>,
 5564    ) -> Option<IconButton> {
 5565        if self.available_code_actions.is_some() {
 5566            Some(
 5567                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5568                    .shape(ui::IconButtonShape::Square)
 5569                    .icon_size(IconSize::XSmall)
 5570                    .icon_color(Color::Muted)
 5571                    .toggle_state(is_active)
 5572                    .tooltip({
 5573                        let focus_handle = self.focus_handle.clone();
 5574                        move |window, cx| {
 5575                            Tooltip::for_action_in(
 5576                                "Toggle Code Actions",
 5577                                &ToggleCodeActions {
 5578                                    deployed_from_indicator: None,
 5579                                },
 5580                                &focus_handle,
 5581                                window,
 5582                                cx,
 5583                            )
 5584                        }
 5585                    })
 5586                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5587                        window.focus(&editor.focus_handle(cx));
 5588                        editor.toggle_code_actions(
 5589                            &ToggleCodeActions {
 5590                                deployed_from_indicator: Some(row),
 5591                            },
 5592                            window,
 5593                            cx,
 5594                        );
 5595                    })),
 5596            )
 5597        } else {
 5598            None
 5599        }
 5600    }
 5601
 5602    fn clear_tasks(&mut self) {
 5603        self.tasks.clear()
 5604    }
 5605
 5606    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5607        if self.tasks.insert(key, value).is_some() {
 5608            // This case should hopefully be rare, but just in case...
 5609            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5610        }
 5611    }
 5612
 5613    fn build_tasks_context(
 5614        project: &Entity<Project>,
 5615        buffer: &Entity<Buffer>,
 5616        buffer_row: u32,
 5617        tasks: &Arc<RunnableTasks>,
 5618        cx: &mut Context<Self>,
 5619    ) -> Task<Option<task::TaskContext>> {
 5620        let position = Point::new(buffer_row, tasks.column);
 5621        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5622        let location = Location {
 5623            buffer: buffer.clone(),
 5624            range: range_start..range_start,
 5625        };
 5626        // Fill in the environmental variables from the tree-sitter captures
 5627        let mut captured_task_variables = TaskVariables::default();
 5628        for (capture_name, value) in tasks.extra_variables.clone() {
 5629            captured_task_variables.insert(
 5630                task::VariableName::Custom(capture_name.into()),
 5631                value.clone(),
 5632            );
 5633        }
 5634        project.update(cx, |project, cx| {
 5635            project.task_store().update(cx, |task_store, cx| {
 5636                task_store.task_context_for_location(captured_task_variables, location, cx)
 5637            })
 5638        })
 5639    }
 5640
 5641    pub fn spawn_nearest_task(
 5642        &mut self,
 5643        action: &SpawnNearestTask,
 5644        window: &mut Window,
 5645        cx: &mut Context<Self>,
 5646    ) {
 5647        let Some((workspace, _)) = self.workspace.clone() else {
 5648            return;
 5649        };
 5650        let Some(project) = self.project.clone() else {
 5651            return;
 5652        };
 5653
 5654        // Try to find a closest, enclosing node using tree-sitter that has a
 5655        // task
 5656        let Some((buffer, buffer_row, tasks)) = self
 5657            .find_enclosing_node_task(cx)
 5658            // Or find the task that's closest in row-distance.
 5659            .or_else(|| self.find_closest_task(cx))
 5660        else {
 5661            return;
 5662        };
 5663
 5664        let reveal_strategy = action.reveal;
 5665        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5666        cx.spawn_in(window, |_, mut cx| async move {
 5667            let context = task_context.await?;
 5668            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5669
 5670            let resolved = resolved_task.resolved.as_mut()?;
 5671            resolved.reveal = reveal_strategy;
 5672
 5673            workspace
 5674                .update(&mut cx, |workspace, cx| {
 5675                    workspace::tasks::schedule_resolved_task(
 5676                        workspace,
 5677                        task_source_kind,
 5678                        resolved_task,
 5679                        false,
 5680                        cx,
 5681                    );
 5682                })
 5683                .ok()
 5684        })
 5685        .detach();
 5686    }
 5687
 5688    fn find_closest_task(
 5689        &mut self,
 5690        cx: &mut Context<Self>,
 5691    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5692        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5693
 5694        let ((buffer_id, row), tasks) = self
 5695            .tasks
 5696            .iter()
 5697            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5698
 5699        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5700        let tasks = Arc::new(tasks.to_owned());
 5701        Some((buffer, *row, tasks))
 5702    }
 5703
 5704    fn find_enclosing_node_task(
 5705        &mut self,
 5706        cx: &mut Context<Self>,
 5707    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5708        let snapshot = self.buffer.read(cx).snapshot(cx);
 5709        let offset = self.selections.newest::<usize>(cx).head();
 5710        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5711        let buffer_id = excerpt.buffer().remote_id();
 5712
 5713        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5714        let mut cursor = layer.node().walk();
 5715
 5716        while cursor.goto_first_child_for_byte(offset).is_some() {
 5717            if cursor.node().end_byte() == offset {
 5718                cursor.goto_next_sibling();
 5719            }
 5720        }
 5721
 5722        // Ascend to the smallest ancestor that contains the range and has a task.
 5723        loop {
 5724            let node = cursor.node();
 5725            let node_range = node.byte_range();
 5726            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5727
 5728            // Check if this node contains our offset
 5729            if node_range.start <= offset && node_range.end >= offset {
 5730                // If it contains offset, check for task
 5731                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5732                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5733                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5734                }
 5735            }
 5736
 5737            if !cursor.goto_parent() {
 5738                break;
 5739            }
 5740        }
 5741        None
 5742    }
 5743
 5744    fn render_run_indicator(
 5745        &self,
 5746        _style: &EditorStyle,
 5747        is_active: bool,
 5748        row: DisplayRow,
 5749        cx: &mut Context<Self>,
 5750    ) -> IconButton {
 5751        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5752            .shape(ui::IconButtonShape::Square)
 5753            .icon_size(IconSize::XSmall)
 5754            .icon_color(Color::Muted)
 5755            .toggle_state(is_active)
 5756            .on_click(cx.listener(move |editor, _e, window, cx| {
 5757                window.focus(&editor.focus_handle(cx));
 5758                editor.toggle_code_actions(
 5759                    &ToggleCodeActions {
 5760                        deployed_from_indicator: Some(row),
 5761                    },
 5762                    window,
 5763                    cx,
 5764                );
 5765            }))
 5766    }
 5767
 5768    pub fn context_menu_visible(&self) -> bool {
 5769        !self.edit_prediction_preview_is_active()
 5770            && self
 5771                .context_menu
 5772                .borrow()
 5773                .as_ref()
 5774                .map_or(false, |menu| menu.visible())
 5775    }
 5776
 5777    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5778        self.context_menu
 5779            .borrow()
 5780            .as_ref()
 5781            .map(|menu| menu.origin())
 5782    }
 5783
 5784    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5785        px(30.)
 5786    }
 5787
 5788    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5789        if self.read_only(cx) {
 5790            cx.theme().players().read_only()
 5791        } else {
 5792            self.style.as_ref().unwrap().local_player
 5793        }
 5794    }
 5795
 5796    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5797        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5798        let accept_keystroke = accept_binding.keystroke()?;
 5799
 5800        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5801
 5802        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5803            Color::Accent
 5804        } else {
 5805            Color::Muted
 5806        };
 5807
 5808        h_flex()
 5809            .px_0p5()
 5810            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5811            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5812            .text_size(TextSize::XSmall.rems(cx))
 5813            .child(h_flex().children(ui::render_modifiers(
 5814                &accept_keystroke.modifiers,
 5815                PlatformStyle::platform(),
 5816                Some(modifiers_color),
 5817                Some(IconSize::XSmall.rems().into()),
 5818                true,
 5819            )))
 5820            .when(is_platform_style_mac, |parent| {
 5821                parent.child(accept_keystroke.key.clone())
 5822            })
 5823            .when(!is_platform_style_mac, |parent| {
 5824                parent.child(
 5825                    Key::new(
 5826                        util::capitalize(&accept_keystroke.key),
 5827                        Some(Color::Default),
 5828                    )
 5829                    .size(Some(IconSize::XSmall.rems().into())),
 5830                )
 5831            })
 5832            .into()
 5833    }
 5834
 5835    fn render_edit_prediction_line_popover(
 5836        &self,
 5837        label: impl Into<SharedString>,
 5838        icon: Option<IconName>,
 5839        window: &mut Window,
 5840        cx: &App,
 5841    ) -> Option<Div> {
 5842        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5843
 5844        let result = h_flex()
 5845            .py_0p5()
 5846            .pl_1()
 5847            .pr(padding_right)
 5848            .gap_1()
 5849            .rounded(px(6.))
 5850            .border_1()
 5851            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5852            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 5853            .shadow_sm()
 5854            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5855            .child(Label::new(label).size(LabelSize::Small))
 5856            .when_some(icon, |element, icon| {
 5857                element.child(
 5858                    div()
 5859                        .mt(px(1.5))
 5860                        .child(Icon::new(icon).size(IconSize::Small)),
 5861                )
 5862            });
 5863
 5864        Some(result)
 5865    }
 5866
 5867    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5868        let accent_color = cx.theme().colors().text_accent;
 5869        let editor_bg_color = cx.theme().colors().editor_background;
 5870        editor_bg_color.blend(accent_color.opacity(0.1))
 5871    }
 5872
 5873    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 5874        let accent_color = cx.theme().colors().text_accent;
 5875        let editor_bg_color = cx.theme().colors().editor_background;
 5876        editor_bg_color.blend(accent_color.opacity(0.6))
 5877    }
 5878
 5879    #[allow(clippy::too_many_arguments)]
 5880    fn render_edit_prediction_cursor_popover(
 5881        &self,
 5882        min_width: Pixels,
 5883        max_width: Pixels,
 5884        cursor_point: Point,
 5885        style: &EditorStyle,
 5886        accept_keystroke: Option<&gpui::Keystroke>,
 5887        _window: &Window,
 5888        cx: &mut Context<Editor>,
 5889    ) -> Option<AnyElement> {
 5890        let provider = self.edit_prediction_provider.as_ref()?;
 5891
 5892        if provider.provider.needs_terms_acceptance(cx) {
 5893            return Some(
 5894                h_flex()
 5895                    .min_w(min_width)
 5896                    .flex_1()
 5897                    .px_2()
 5898                    .py_1()
 5899                    .gap_3()
 5900                    .elevation_2(cx)
 5901                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5902                    .id("accept-terms")
 5903                    .cursor_pointer()
 5904                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5905                    .on_click(cx.listener(|this, _event, window, cx| {
 5906                        cx.stop_propagation();
 5907                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5908                        window.dispatch_action(
 5909                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5910                            cx,
 5911                        );
 5912                    }))
 5913                    .child(
 5914                        h_flex()
 5915                            .flex_1()
 5916                            .gap_2()
 5917                            .child(Icon::new(IconName::ZedPredict))
 5918                            .child(Label::new("Accept Terms of Service"))
 5919                            .child(div().w_full())
 5920                            .child(
 5921                                Icon::new(IconName::ArrowUpRight)
 5922                                    .color(Color::Muted)
 5923                                    .size(IconSize::Small),
 5924                            )
 5925                            .into_any_element(),
 5926                    )
 5927                    .into_any(),
 5928            );
 5929        }
 5930
 5931        let is_refreshing = provider.provider.is_refreshing(cx);
 5932
 5933        fn pending_completion_container() -> Div {
 5934            h_flex()
 5935                .h_full()
 5936                .flex_1()
 5937                .gap_2()
 5938                .child(Icon::new(IconName::ZedPredict))
 5939        }
 5940
 5941        let completion = match &self.active_inline_completion {
 5942            Some(completion) => match &completion.completion {
 5943                InlineCompletion::Move {
 5944                    target, snapshot, ..
 5945                } if !self.has_visible_completions_menu() => {
 5946                    use text::ToPoint as _;
 5947
 5948                    return Some(
 5949                        h_flex()
 5950                            .px_2()
 5951                            .py_1()
 5952                            .gap_2()
 5953                            .elevation_2(cx)
 5954                            .border_color(cx.theme().colors().border)
 5955                            .rounded(px(6.))
 5956                            .rounded_tl(px(0.))
 5957                            .child(
 5958                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5959                                    Icon::new(IconName::ZedPredictDown)
 5960                                } else {
 5961                                    Icon::new(IconName::ZedPredictUp)
 5962                                },
 5963                            )
 5964                            .child(Label::new("Hold").size(LabelSize::Small))
 5965                            .child(h_flex().children(ui::render_modifiers(
 5966                                &accept_keystroke?.modifiers,
 5967                                PlatformStyle::platform(),
 5968                                Some(Color::Default),
 5969                                Some(IconSize::Small.rems().into()),
 5970                                false,
 5971                            )))
 5972                            .into_any(),
 5973                    );
 5974                }
 5975                _ => self.render_edit_prediction_cursor_popover_preview(
 5976                    completion,
 5977                    cursor_point,
 5978                    style,
 5979                    cx,
 5980                )?,
 5981            },
 5982
 5983            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5984                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5985                    stale_completion,
 5986                    cursor_point,
 5987                    style,
 5988                    cx,
 5989                )?,
 5990
 5991                None => {
 5992                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5993                }
 5994            },
 5995
 5996            None => pending_completion_container().child(Label::new("No Prediction")),
 5997        };
 5998
 5999        let completion = if is_refreshing {
 6000            completion
 6001                .with_animation(
 6002                    "loading-completion",
 6003                    Animation::new(Duration::from_secs(2))
 6004                        .repeat()
 6005                        .with_easing(pulsating_between(0.4, 0.8)),
 6006                    |label, delta| label.opacity(delta),
 6007                )
 6008                .into_any_element()
 6009        } else {
 6010            completion.into_any_element()
 6011        };
 6012
 6013        let has_completion = self.active_inline_completion.is_some();
 6014
 6015        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6016        Some(
 6017            h_flex()
 6018                .min_w(min_width)
 6019                .max_w(max_width)
 6020                .flex_1()
 6021                .elevation_2(cx)
 6022                .border_color(cx.theme().colors().border)
 6023                .child(
 6024                    div()
 6025                        .flex_1()
 6026                        .py_1()
 6027                        .px_2()
 6028                        .overflow_hidden()
 6029                        .child(completion),
 6030                )
 6031                .when_some(accept_keystroke, |el, accept_keystroke| {
 6032                    if !accept_keystroke.modifiers.modified() {
 6033                        return el;
 6034                    }
 6035
 6036                    el.child(
 6037                        h_flex()
 6038                            .h_full()
 6039                            .border_l_1()
 6040                            .rounded_r_lg()
 6041                            .border_color(cx.theme().colors().border)
 6042                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6043                            .gap_1()
 6044                            .py_1()
 6045                            .px_2()
 6046                            .child(
 6047                                h_flex()
 6048                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6049                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6050                                    .child(h_flex().children(ui::render_modifiers(
 6051                                        &accept_keystroke.modifiers,
 6052                                        PlatformStyle::platform(),
 6053                                        Some(if !has_completion {
 6054                                            Color::Muted
 6055                                        } else {
 6056                                            Color::Default
 6057                                        }),
 6058                                        None,
 6059                                        false,
 6060                                    ))),
 6061                            )
 6062                            .child(Label::new("Preview").into_any_element())
 6063                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6064                    )
 6065                })
 6066                .into_any(),
 6067        )
 6068    }
 6069
 6070    fn render_edit_prediction_cursor_popover_preview(
 6071        &self,
 6072        completion: &InlineCompletionState,
 6073        cursor_point: Point,
 6074        style: &EditorStyle,
 6075        cx: &mut Context<Editor>,
 6076    ) -> Option<Div> {
 6077        use text::ToPoint as _;
 6078
 6079        fn render_relative_row_jump(
 6080            prefix: impl Into<String>,
 6081            current_row: u32,
 6082            target_row: u32,
 6083        ) -> Div {
 6084            let (row_diff, arrow) = if target_row < current_row {
 6085                (current_row - target_row, IconName::ArrowUp)
 6086            } else {
 6087                (target_row - current_row, IconName::ArrowDown)
 6088            };
 6089
 6090            h_flex()
 6091                .child(
 6092                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6093                        .color(Color::Muted)
 6094                        .size(LabelSize::Small),
 6095                )
 6096                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6097        }
 6098
 6099        match &completion.completion {
 6100            InlineCompletion::Move {
 6101                target, snapshot, ..
 6102            } => Some(
 6103                h_flex()
 6104                    .px_2()
 6105                    .gap_2()
 6106                    .flex_1()
 6107                    .child(
 6108                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6109                            Icon::new(IconName::ZedPredictDown)
 6110                        } else {
 6111                            Icon::new(IconName::ZedPredictUp)
 6112                        },
 6113                    )
 6114                    .child(Label::new("Jump to Edit")),
 6115            ),
 6116
 6117            InlineCompletion::Edit {
 6118                edits,
 6119                edit_preview,
 6120                snapshot,
 6121                display_mode: _,
 6122            } => {
 6123                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6124
 6125                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6126                    &snapshot,
 6127                    &edits,
 6128                    edit_preview.as_ref()?,
 6129                    true,
 6130                    cx,
 6131                )
 6132                .first_line_preview();
 6133
 6134                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6135                    .with_highlights(&style.text, highlighted_edits.highlights);
 6136
 6137                let preview = h_flex()
 6138                    .gap_1()
 6139                    .min_w_16()
 6140                    .child(styled_text)
 6141                    .when(has_more_lines, |parent| parent.child(""));
 6142
 6143                let left = if first_edit_row != cursor_point.row {
 6144                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6145                        .into_any_element()
 6146                } else {
 6147                    Icon::new(IconName::ZedPredict).into_any_element()
 6148                };
 6149
 6150                Some(
 6151                    h_flex()
 6152                        .h_full()
 6153                        .flex_1()
 6154                        .gap_2()
 6155                        .pr_1()
 6156                        .overflow_x_hidden()
 6157                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6158                        .child(left)
 6159                        .child(preview),
 6160                )
 6161            }
 6162        }
 6163    }
 6164
 6165    fn render_context_menu(
 6166        &self,
 6167        style: &EditorStyle,
 6168        max_height_in_lines: u32,
 6169        y_flipped: bool,
 6170        window: &mut Window,
 6171        cx: &mut Context<Editor>,
 6172    ) -> Option<AnyElement> {
 6173        let menu = self.context_menu.borrow();
 6174        let menu = menu.as_ref()?;
 6175        if !menu.visible() {
 6176            return None;
 6177        };
 6178        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6179    }
 6180
 6181    fn render_context_menu_aside(
 6182        &mut self,
 6183        max_size: Size<Pixels>,
 6184        window: &mut Window,
 6185        cx: &mut Context<Editor>,
 6186    ) -> Option<AnyElement> {
 6187        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6188            if menu.visible() {
 6189                menu.render_aside(self, max_size, window, cx)
 6190            } else {
 6191                None
 6192            }
 6193        })
 6194    }
 6195
 6196    fn hide_context_menu(
 6197        &mut self,
 6198        window: &mut Window,
 6199        cx: &mut Context<Self>,
 6200    ) -> Option<CodeContextMenu> {
 6201        cx.notify();
 6202        self.completion_tasks.clear();
 6203        let context_menu = self.context_menu.borrow_mut().take();
 6204        self.stale_inline_completion_in_menu.take();
 6205        self.update_visible_inline_completion(window, cx);
 6206        context_menu
 6207    }
 6208
 6209    fn show_snippet_choices(
 6210        &mut self,
 6211        choices: &Vec<String>,
 6212        selection: Range<Anchor>,
 6213        cx: &mut Context<Self>,
 6214    ) {
 6215        if selection.start.buffer_id.is_none() {
 6216            return;
 6217        }
 6218        let buffer_id = selection.start.buffer_id.unwrap();
 6219        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6220        let id = post_inc(&mut self.next_completion_id);
 6221
 6222        if let Some(buffer) = buffer {
 6223            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6224                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6225            ));
 6226        }
 6227    }
 6228
 6229    pub fn insert_snippet(
 6230        &mut self,
 6231        insertion_ranges: &[Range<usize>],
 6232        snippet: Snippet,
 6233        window: &mut Window,
 6234        cx: &mut Context<Self>,
 6235    ) -> Result<()> {
 6236        struct Tabstop<T> {
 6237            is_end_tabstop: bool,
 6238            ranges: Vec<Range<T>>,
 6239            choices: Option<Vec<String>>,
 6240        }
 6241
 6242        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6243            let snippet_text: Arc<str> = snippet.text.clone().into();
 6244            buffer.edit(
 6245                insertion_ranges
 6246                    .iter()
 6247                    .cloned()
 6248                    .map(|range| (range, snippet_text.clone())),
 6249                Some(AutoindentMode::EachLine),
 6250                cx,
 6251            );
 6252
 6253            let snapshot = &*buffer.read(cx);
 6254            let snippet = &snippet;
 6255            snippet
 6256                .tabstops
 6257                .iter()
 6258                .map(|tabstop| {
 6259                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6260                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6261                    });
 6262                    let mut tabstop_ranges = tabstop
 6263                        .ranges
 6264                        .iter()
 6265                        .flat_map(|tabstop_range| {
 6266                            let mut delta = 0_isize;
 6267                            insertion_ranges.iter().map(move |insertion_range| {
 6268                                let insertion_start = insertion_range.start as isize + delta;
 6269                                delta +=
 6270                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6271
 6272                                let start = ((insertion_start + tabstop_range.start) as usize)
 6273                                    .min(snapshot.len());
 6274                                let end = ((insertion_start + tabstop_range.end) as usize)
 6275                                    .min(snapshot.len());
 6276                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6277                            })
 6278                        })
 6279                        .collect::<Vec<_>>();
 6280                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6281
 6282                    Tabstop {
 6283                        is_end_tabstop,
 6284                        ranges: tabstop_ranges,
 6285                        choices: tabstop.choices.clone(),
 6286                    }
 6287                })
 6288                .collect::<Vec<_>>()
 6289        });
 6290        if let Some(tabstop) = tabstops.first() {
 6291            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6292                s.select_ranges(tabstop.ranges.iter().cloned());
 6293            });
 6294
 6295            if let Some(choices) = &tabstop.choices {
 6296                if let Some(selection) = tabstop.ranges.first() {
 6297                    self.show_snippet_choices(choices, selection.clone(), cx)
 6298                }
 6299            }
 6300
 6301            // If we're already at the last tabstop and it's at the end of the snippet,
 6302            // we're done, we don't need to keep the state around.
 6303            if !tabstop.is_end_tabstop {
 6304                let choices = tabstops
 6305                    .iter()
 6306                    .map(|tabstop| tabstop.choices.clone())
 6307                    .collect();
 6308
 6309                let ranges = tabstops
 6310                    .into_iter()
 6311                    .map(|tabstop| tabstop.ranges)
 6312                    .collect::<Vec<_>>();
 6313
 6314                self.snippet_stack.push(SnippetState {
 6315                    active_index: 0,
 6316                    ranges,
 6317                    choices,
 6318                });
 6319            }
 6320
 6321            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6322            if self.autoclose_regions.is_empty() {
 6323                let snapshot = self.buffer.read(cx).snapshot(cx);
 6324                for selection in &mut self.selections.all::<Point>(cx) {
 6325                    let selection_head = selection.head();
 6326                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6327                        continue;
 6328                    };
 6329
 6330                    let mut bracket_pair = None;
 6331                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6332                    let prev_chars = snapshot
 6333                        .reversed_chars_at(selection_head)
 6334                        .collect::<String>();
 6335                    for (pair, enabled) in scope.brackets() {
 6336                        if enabled
 6337                            && pair.close
 6338                            && prev_chars.starts_with(pair.start.as_str())
 6339                            && next_chars.starts_with(pair.end.as_str())
 6340                        {
 6341                            bracket_pair = Some(pair.clone());
 6342                            break;
 6343                        }
 6344                    }
 6345                    if let Some(pair) = bracket_pair {
 6346                        let start = snapshot.anchor_after(selection_head);
 6347                        let end = snapshot.anchor_after(selection_head);
 6348                        self.autoclose_regions.push(AutocloseRegion {
 6349                            selection_id: selection.id,
 6350                            range: start..end,
 6351                            pair,
 6352                        });
 6353                    }
 6354                }
 6355            }
 6356        }
 6357        Ok(())
 6358    }
 6359
 6360    pub fn move_to_next_snippet_tabstop(
 6361        &mut self,
 6362        window: &mut Window,
 6363        cx: &mut Context<Self>,
 6364    ) -> bool {
 6365        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6366    }
 6367
 6368    pub fn move_to_prev_snippet_tabstop(
 6369        &mut self,
 6370        window: &mut Window,
 6371        cx: &mut Context<Self>,
 6372    ) -> bool {
 6373        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6374    }
 6375
 6376    pub fn move_to_snippet_tabstop(
 6377        &mut self,
 6378        bias: Bias,
 6379        window: &mut Window,
 6380        cx: &mut Context<Self>,
 6381    ) -> bool {
 6382        if let Some(mut snippet) = self.snippet_stack.pop() {
 6383            match bias {
 6384                Bias::Left => {
 6385                    if snippet.active_index > 0 {
 6386                        snippet.active_index -= 1;
 6387                    } else {
 6388                        self.snippet_stack.push(snippet);
 6389                        return false;
 6390                    }
 6391                }
 6392                Bias::Right => {
 6393                    if snippet.active_index + 1 < snippet.ranges.len() {
 6394                        snippet.active_index += 1;
 6395                    } else {
 6396                        self.snippet_stack.push(snippet);
 6397                        return false;
 6398                    }
 6399                }
 6400            }
 6401            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6402                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6403                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6404                });
 6405
 6406                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6407                    if let Some(selection) = current_ranges.first() {
 6408                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6409                    }
 6410                }
 6411
 6412                // If snippet state is not at the last tabstop, push it back on the stack
 6413                if snippet.active_index + 1 < snippet.ranges.len() {
 6414                    self.snippet_stack.push(snippet);
 6415                }
 6416                return true;
 6417            }
 6418        }
 6419
 6420        false
 6421    }
 6422
 6423    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6424        self.transact(window, cx, |this, window, cx| {
 6425            this.select_all(&SelectAll, window, cx);
 6426            this.insert("", window, cx);
 6427        });
 6428    }
 6429
 6430    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6431        self.transact(window, cx, |this, window, cx| {
 6432            this.select_autoclose_pair(window, cx);
 6433            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6434            if !this.linked_edit_ranges.is_empty() {
 6435                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6436                let snapshot = this.buffer.read(cx).snapshot(cx);
 6437
 6438                for selection in selections.iter() {
 6439                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6440                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6441                    if selection_start.buffer_id != selection_end.buffer_id {
 6442                        continue;
 6443                    }
 6444                    if let Some(ranges) =
 6445                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6446                    {
 6447                        for (buffer, entries) in ranges {
 6448                            linked_ranges.entry(buffer).or_default().extend(entries);
 6449                        }
 6450                    }
 6451                }
 6452            }
 6453
 6454            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6455            if !this.selections.line_mode {
 6456                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6457                for selection in &mut selections {
 6458                    if selection.is_empty() {
 6459                        let old_head = selection.head();
 6460                        let mut new_head =
 6461                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6462                                .to_point(&display_map);
 6463                        if let Some((buffer, line_buffer_range)) = display_map
 6464                            .buffer_snapshot
 6465                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6466                        {
 6467                            let indent_size =
 6468                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6469                            let indent_len = match indent_size.kind {
 6470                                IndentKind::Space => {
 6471                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6472                                }
 6473                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6474                            };
 6475                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6476                                let indent_len = indent_len.get();
 6477                                new_head = cmp::min(
 6478                                    new_head,
 6479                                    MultiBufferPoint::new(
 6480                                        old_head.row,
 6481                                        ((old_head.column - 1) / indent_len) * indent_len,
 6482                                    ),
 6483                                );
 6484                            }
 6485                        }
 6486
 6487                        selection.set_head(new_head, SelectionGoal::None);
 6488                    }
 6489                }
 6490            }
 6491
 6492            this.signature_help_state.set_backspace_pressed(true);
 6493            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6494                s.select(selections)
 6495            });
 6496            this.insert("", window, cx);
 6497            let empty_str: Arc<str> = Arc::from("");
 6498            for (buffer, edits) in linked_ranges {
 6499                let snapshot = buffer.read(cx).snapshot();
 6500                use text::ToPoint as TP;
 6501
 6502                let edits = edits
 6503                    .into_iter()
 6504                    .map(|range| {
 6505                        let end_point = TP::to_point(&range.end, &snapshot);
 6506                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6507
 6508                        if end_point == start_point {
 6509                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6510                                .saturating_sub(1);
 6511                            start_point =
 6512                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6513                        };
 6514
 6515                        (start_point..end_point, empty_str.clone())
 6516                    })
 6517                    .sorted_by_key(|(range, _)| range.start)
 6518                    .collect::<Vec<_>>();
 6519                buffer.update(cx, |this, cx| {
 6520                    this.edit(edits, None, cx);
 6521                })
 6522            }
 6523            this.refresh_inline_completion(true, false, window, cx);
 6524            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6525        });
 6526    }
 6527
 6528    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6529        self.transact(window, cx, |this, window, cx| {
 6530            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6531                let line_mode = s.line_mode;
 6532                s.move_with(|map, selection| {
 6533                    if selection.is_empty() && !line_mode {
 6534                        let cursor = movement::right(map, selection.head());
 6535                        selection.end = cursor;
 6536                        selection.reversed = true;
 6537                        selection.goal = SelectionGoal::None;
 6538                    }
 6539                })
 6540            });
 6541            this.insert("", window, cx);
 6542            this.refresh_inline_completion(true, false, window, cx);
 6543        });
 6544    }
 6545
 6546    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6547        if self.move_to_prev_snippet_tabstop(window, cx) {
 6548            return;
 6549        }
 6550
 6551        self.outdent(&Outdent, window, cx);
 6552    }
 6553
 6554    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6555        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6556            return;
 6557        }
 6558
 6559        let mut selections = self.selections.all_adjusted(cx);
 6560        let buffer = self.buffer.read(cx);
 6561        let snapshot = buffer.snapshot(cx);
 6562        let rows_iter = selections.iter().map(|s| s.head().row);
 6563        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6564
 6565        let mut edits = Vec::new();
 6566        let mut prev_edited_row = 0;
 6567        let mut row_delta = 0;
 6568        for selection in &mut selections {
 6569            if selection.start.row != prev_edited_row {
 6570                row_delta = 0;
 6571            }
 6572            prev_edited_row = selection.end.row;
 6573
 6574            // If the selection is non-empty, then increase the indentation of the selected lines.
 6575            if !selection.is_empty() {
 6576                row_delta =
 6577                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6578                continue;
 6579            }
 6580
 6581            // If the selection is empty and the cursor is in the leading whitespace before the
 6582            // suggested indentation, then auto-indent the line.
 6583            let cursor = selection.head();
 6584            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6585            if let Some(suggested_indent) =
 6586                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6587            {
 6588                if cursor.column < suggested_indent.len
 6589                    && cursor.column <= current_indent.len
 6590                    && current_indent.len <= suggested_indent.len
 6591                {
 6592                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6593                    selection.end = selection.start;
 6594                    if row_delta == 0 {
 6595                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6596                            cursor.row,
 6597                            current_indent,
 6598                            suggested_indent,
 6599                        ));
 6600                        row_delta = suggested_indent.len - current_indent.len;
 6601                    }
 6602                    continue;
 6603                }
 6604            }
 6605
 6606            // Otherwise, insert a hard or soft tab.
 6607            let settings = buffer.settings_at(cursor, cx);
 6608            let tab_size = if settings.hard_tabs {
 6609                IndentSize::tab()
 6610            } else {
 6611                let tab_size = settings.tab_size.get();
 6612                let char_column = snapshot
 6613                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6614                    .flat_map(str::chars)
 6615                    .count()
 6616                    + row_delta as usize;
 6617                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6618                IndentSize::spaces(chars_to_next_tab_stop)
 6619            };
 6620            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6621            selection.end = selection.start;
 6622            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6623            row_delta += tab_size.len;
 6624        }
 6625
 6626        self.transact(window, cx, |this, window, cx| {
 6627            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6628            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6629                s.select(selections)
 6630            });
 6631            this.refresh_inline_completion(true, false, window, cx);
 6632        });
 6633    }
 6634
 6635    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6636        if self.read_only(cx) {
 6637            return;
 6638        }
 6639        let mut selections = self.selections.all::<Point>(cx);
 6640        let mut prev_edited_row = 0;
 6641        let mut row_delta = 0;
 6642        let mut edits = Vec::new();
 6643        let buffer = self.buffer.read(cx);
 6644        let snapshot = buffer.snapshot(cx);
 6645        for selection in &mut selections {
 6646            if selection.start.row != prev_edited_row {
 6647                row_delta = 0;
 6648            }
 6649            prev_edited_row = selection.end.row;
 6650
 6651            row_delta =
 6652                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6653        }
 6654
 6655        self.transact(window, cx, |this, window, cx| {
 6656            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6657            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6658                s.select(selections)
 6659            });
 6660        });
 6661    }
 6662
 6663    fn indent_selection(
 6664        buffer: &MultiBuffer,
 6665        snapshot: &MultiBufferSnapshot,
 6666        selection: &mut Selection<Point>,
 6667        edits: &mut Vec<(Range<Point>, String)>,
 6668        delta_for_start_row: u32,
 6669        cx: &App,
 6670    ) -> u32 {
 6671        let settings = buffer.settings_at(selection.start, cx);
 6672        let tab_size = settings.tab_size.get();
 6673        let indent_kind = if settings.hard_tabs {
 6674            IndentKind::Tab
 6675        } else {
 6676            IndentKind::Space
 6677        };
 6678        let mut start_row = selection.start.row;
 6679        let mut end_row = selection.end.row + 1;
 6680
 6681        // If a selection ends at the beginning of a line, don't indent
 6682        // that last line.
 6683        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6684            end_row -= 1;
 6685        }
 6686
 6687        // Avoid re-indenting a row that has already been indented by a
 6688        // previous selection, but still update this selection's column
 6689        // to reflect that indentation.
 6690        if delta_for_start_row > 0 {
 6691            start_row += 1;
 6692            selection.start.column += delta_for_start_row;
 6693            if selection.end.row == selection.start.row {
 6694                selection.end.column += delta_for_start_row;
 6695            }
 6696        }
 6697
 6698        let mut delta_for_end_row = 0;
 6699        let has_multiple_rows = start_row + 1 != end_row;
 6700        for row in start_row..end_row {
 6701            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6702            let indent_delta = match (current_indent.kind, indent_kind) {
 6703                (IndentKind::Space, IndentKind::Space) => {
 6704                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6705                    IndentSize::spaces(columns_to_next_tab_stop)
 6706                }
 6707                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6708                (_, IndentKind::Tab) => IndentSize::tab(),
 6709            };
 6710
 6711            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6712                0
 6713            } else {
 6714                selection.start.column
 6715            };
 6716            let row_start = Point::new(row, start);
 6717            edits.push((
 6718                row_start..row_start,
 6719                indent_delta.chars().collect::<String>(),
 6720            ));
 6721
 6722            // Update this selection's endpoints to reflect the indentation.
 6723            if row == selection.start.row {
 6724                selection.start.column += indent_delta.len;
 6725            }
 6726            if row == selection.end.row {
 6727                selection.end.column += indent_delta.len;
 6728                delta_for_end_row = indent_delta.len;
 6729            }
 6730        }
 6731
 6732        if selection.start.row == selection.end.row {
 6733            delta_for_start_row + delta_for_end_row
 6734        } else {
 6735            delta_for_end_row
 6736        }
 6737    }
 6738
 6739    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6740        if self.read_only(cx) {
 6741            return;
 6742        }
 6743        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6744        let selections = self.selections.all::<Point>(cx);
 6745        let mut deletion_ranges = Vec::new();
 6746        let mut last_outdent = None;
 6747        {
 6748            let buffer = self.buffer.read(cx);
 6749            let snapshot = buffer.snapshot(cx);
 6750            for selection in &selections {
 6751                let settings = buffer.settings_at(selection.start, cx);
 6752                let tab_size = settings.tab_size.get();
 6753                let mut rows = selection.spanned_rows(false, &display_map);
 6754
 6755                // Avoid re-outdenting a row that has already been outdented by a
 6756                // previous selection.
 6757                if let Some(last_row) = last_outdent {
 6758                    if last_row == rows.start {
 6759                        rows.start = rows.start.next_row();
 6760                    }
 6761                }
 6762                let has_multiple_rows = rows.len() > 1;
 6763                for row in rows.iter_rows() {
 6764                    let indent_size = snapshot.indent_size_for_line(row);
 6765                    if indent_size.len > 0 {
 6766                        let deletion_len = match indent_size.kind {
 6767                            IndentKind::Space => {
 6768                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6769                                if columns_to_prev_tab_stop == 0 {
 6770                                    tab_size
 6771                                } else {
 6772                                    columns_to_prev_tab_stop
 6773                                }
 6774                            }
 6775                            IndentKind::Tab => 1,
 6776                        };
 6777                        let start = if has_multiple_rows
 6778                            || deletion_len > selection.start.column
 6779                            || indent_size.len < selection.start.column
 6780                        {
 6781                            0
 6782                        } else {
 6783                            selection.start.column - deletion_len
 6784                        };
 6785                        deletion_ranges.push(
 6786                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6787                        );
 6788                        last_outdent = Some(row);
 6789                    }
 6790                }
 6791            }
 6792        }
 6793
 6794        self.transact(window, cx, |this, window, cx| {
 6795            this.buffer.update(cx, |buffer, cx| {
 6796                let empty_str: Arc<str> = Arc::default();
 6797                buffer.edit(
 6798                    deletion_ranges
 6799                        .into_iter()
 6800                        .map(|range| (range, empty_str.clone())),
 6801                    None,
 6802                    cx,
 6803                );
 6804            });
 6805            let selections = this.selections.all::<usize>(cx);
 6806            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6807                s.select(selections)
 6808            });
 6809        });
 6810    }
 6811
 6812    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6813        if self.read_only(cx) {
 6814            return;
 6815        }
 6816        let selections = self
 6817            .selections
 6818            .all::<usize>(cx)
 6819            .into_iter()
 6820            .map(|s| s.range());
 6821
 6822        self.transact(window, cx, |this, window, cx| {
 6823            this.buffer.update(cx, |buffer, cx| {
 6824                buffer.autoindent_ranges(selections, cx);
 6825            });
 6826            let selections = this.selections.all::<usize>(cx);
 6827            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6828                s.select(selections)
 6829            });
 6830        });
 6831    }
 6832
 6833    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6834        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6835        let selections = self.selections.all::<Point>(cx);
 6836
 6837        let mut new_cursors = Vec::new();
 6838        let mut edit_ranges = Vec::new();
 6839        let mut selections = selections.iter().peekable();
 6840        while let Some(selection) = selections.next() {
 6841            let mut rows = selection.spanned_rows(false, &display_map);
 6842            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6843
 6844            // Accumulate contiguous regions of rows that we want to delete.
 6845            while let Some(next_selection) = selections.peek() {
 6846                let next_rows = next_selection.spanned_rows(false, &display_map);
 6847                if next_rows.start <= rows.end {
 6848                    rows.end = next_rows.end;
 6849                    selections.next().unwrap();
 6850                } else {
 6851                    break;
 6852                }
 6853            }
 6854
 6855            let buffer = &display_map.buffer_snapshot;
 6856            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6857            let edit_end;
 6858            let cursor_buffer_row;
 6859            if buffer.max_point().row >= rows.end.0 {
 6860                // If there's a line after the range, delete the \n from the end of the row range
 6861                // and position the cursor on the next line.
 6862                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6863                cursor_buffer_row = rows.end;
 6864            } else {
 6865                // If there isn't a line after the range, delete the \n from the line before the
 6866                // start of the row range and position the cursor there.
 6867                edit_start = edit_start.saturating_sub(1);
 6868                edit_end = buffer.len();
 6869                cursor_buffer_row = rows.start.previous_row();
 6870            }
 6871
 6872            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6873            *cursor.column_mut() =
 6874                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6875
 6876            new_cursors.push((
 6877                selection.id,
 6878                buffer.anchor_after(cursor.to_point(&display_map)),
 6879            ));
 6880            edit_ranges.push(edit_start..edit_end);
 6881        }
 6882
 6883        self.transact(window, cx, |this, window, cx| {
 6884            let buffer = this.buffer.update(cx, |buffer, cx| {
 6885                let empty_str: Arc<str> = Arc::default();
 6886                buffer.edit(
 6887                    edit_ranges
 6888                        .into_iter()
 6889                        .map(|range| (range, empty_str.clone())),
 6890                    None,
 6891                    cx,
 6892                );
 6893                buffer.snapshot(cx)
 6894            });
 6895            let new_selections = new_cursors
 6896                .into_iter()
 6897                .map(|(id, cursor)| {
 6898                    let cursor = cursor.to_point(&buffer);
 6899                    Selection {
 6900                        id,
 6901                        start: cursor,
 6902                        end: cursor,
 6903                        reversed: false,
 6904                        goal: SelectionGoal::None,
 6905                    }
 6906                })
 6907                .collect();
 6908
 6909            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6910                s.select(new_selections);
 6911            });
 6912        });
 6913    }
 6914
 6915    pub fn join_lines_impl(
 6916        &mut self,
 6917        insert_whitespace: bool,
 6918        window: &mut Window,
 6919        cx: &mut Context<Self>,
 6920    ) {
 6921        if self.read_only(cx) {
 6922            return;
 6923        }
 6924        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6925        for selection in self.selections.all::<Point>(cx) {
 6926            let start = MultiBufferRow(selection.start.row);
 6927            // Treat single line selections as if they include the next line. Otherwise this action
 6928            // would do nothing for single line selections individual cursors.
 6929            let end = if selection.start.row == selection.end.row {
 6930                MultiBufferRow(selection.start.row + 1)
 6931            } else {
 6932                MultiBufferRow(selection.end.row)
 6933            };
 6934
 6935            if let Some(last_row_range) = row_ranges.last_mut() {
 6936                if start <= last_row_range.end {
 6937                    last_row_range.end = end;
 6938                    continue;
 6939                }
 6940            }
 6941            row_ranges.push(start..end);
 6942        }
 6943
 6944        let snapshot = self.buffer.read(cx).snapshot(cx);
 6945        let mut cursor_positions = Vec::new();
 6946        for row_range in &row_ranges {
 6947            let anchor = snapshot.anchor_before(Point::new(
 6948                row_range.end.previous_row().0,
 6949                snapshot.line_len(row_range.end.previous_row()),
 6950            ));
 6951            cursor_positions.push(anchor..anchor);
 6952        }
 6953
 6954        self.transact(window, cx, |this, window, cx| {
 6955            for row_range in row_ranges.into_iter().rev() {
 6956                for row in row_range.iter_rows().rev() {
 6957                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6958                    let next_line_row = row.next_row();
 6959                    let indent = snapshot.indent_size_for_line(next_line_row);
 6960                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6961
 6962                    let replace =
 6963                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6964                            " "
 6965                        } else {
 6966                            ""
 6967                        };
 6968
 6969                    this.buffer.update(cx, |buffer, cx| {
 6970                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6971                    });
 6972                }
 6973            }
 6974
 6975            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6976                s.select_anchor_ranges(cursor_positions)
 6977            });
 6978        });
 6979    }
 6980
 6981    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6982        self.join_lines_impl(true, window, cx);
 6983    }
 6984
 6985    pub fn sort_lines_case_sensitive(
 6986        &mut self,
 6987        _: &SortLinesCaseSensitive,
 6988        window: &mut Window,
 6989        cx: &mut Context<Self>,
 6990    ) {
 6991        self.manipulate_lines(window, cx, |lines| lines.sort())
 6992    }
 6993
 6994    pub fn sort_lines_case_insensitive(
 6995        &mut self,
 6996        _: &SortLinesCaseInsensitive,
 6997        window: &mut Window,
 6998        cx: &mut Context<Self>,
 6999    ) {
 7000        self.manipulate_lines(window, cx, |lines| {
 7001            lines.sort_by_key(|line| line.to_lowercase())
 7002        })
 7003    }
 7004
 7005    pub fn unique_lines_case_insensitive(
 7006        &mut self,
 7007        _: &UniqueLinesCaseInsensitive,
 7008        window: &mut Window,
 7009        cx: &mut Context<Self>,
 7010    ) {
 7011        self.manipulate_lines(window, cx, |lines| {
 7012            let mut seen = HashSet::default();
 7013            lines.retain(|line| seen.insert(line.to_lowercase()));
 7014        })
 7015    }
 7016
 7017    pub fn unique_lines_case_sensitive(
 7018        &mut self,
 7019        _: &UniqueLinesCaseSensitive,
 7020        window: &mut Window,
 7021        cx: &mut Context<Self>,
 7022    ) {
 7023        self.manipulate_lines(window, cx, |lines| {
 7024            let mut seen = HashSet::default();
 7025            lines.retain(|line| seen.insert(*line));
 7026        })
 7027    }
 7028
 7029    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7030        let Some(project) = self.project.clone() else {
 7031            return;
 7032        };
 7033        self.reload(project, window, cx)
 7034            .detach_and_notify_err(window, cx);
 7035    }
 7036
 7037    pub fn restore_file(
 7038        &mut self,
 7039        _: &::git::RestoreFile,
 7040        window: &mut Window,
 7041        cx: &mut Context<Self>,
 7042    ) {
 7043        let mut buffer_ids = HashSet::default();
 7044        let snapshot = self.buffer().read(cx).snapshot(cx);
 7045        for selection in self.selections.all::<usize>(cx) {
 7046            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7047        }
 7048
 7049        let buffer = self.buffer().read(cx);
 7050        let ranges = buffer_ids
 7051            .into_iter()
 7052            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7053            .collect::<Vec<_>>();
 7054
 7055        self.restore_hunks_in_ranges(ranges, window, cx);
 7056    }
 7057
 7058    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7059        let selections = self
 7060            .selections
 7061            .all(cx)
 7062            .into_iter()
 7063            .map(|s| s.range())
 7064            .collect();
 7065        self.restore_hunks_in_ranges(selections, window, cx);
 7066    }
 7067
 7068    fn restore_hunks_in_ranges(
 7069        &mut self,
 7070        ranges: Vec<Range<Point>>,
 7071        window: &mut Window,
 7072        cx: &mut Context<Editor>,
 7073    ) {
 7074        let mut revert_changes = HashMap::default();
 7075        let snapshot = self.buffer.read(cx).snapshot(cx);
 7076        let Some(project) = &self.project else {
 7077            return;
 7078        };
 7079
 7080        let chunk_by = self
 7081            .snapshot(window, cx)
 7082            .hunks_for_ranges(ranges.into_iter())
 7083            .into_iter()
 7084            .chunk_by(|hunk| hunk.buffer_id);
 7085        for (buffer_id, hunks) in &chunk_by {
 7086            let hunks = hunks.collect::<Vec<_>>();
 7087            for hunk in &hunks {
 7088                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7089            }
 7090            Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7091        }
 7092        drop(chunk_by);
 7093        if !revert_changes.is_empty() {
 7094            self.transact(window, cx, |editor, window, cx| {
 7095                editor.revert(revert_changes, window, cx);
 7096            });
 7097        }
 7098    }
 7099
 7100    pub fn open_active_item_in_terminal(
 7101        &mut self,
 7102        _: &OpenInTerminal,
 7103        window: &mut Window,
 7104        cx: &mut Context<Self>,
 7105    ) {
 7106        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7107            let project_path = buffer.read(cx).project_path(cx)?;
 7108            let project = self.project.as_ref()?.read(cx);
 7109            let entry = project.entry_for_path(&project_path, cx)?;
 7110            let parent = match &entry.canonical_path {
 7111                Some(canonical_path) => canonical_path.to_path_buf(),
 7112                None => project.absolute_path(&project_path, cx)?,
 7113            }
 7114            .parent()?
 7115            .to_path_buf();
 7116            Some(parent)
 7117        }) {
 7118            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7119        }
 7120    }
 7121
 7122    pub fn prepare_restore_change(
 7123        &self,
 7124        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7125        hunk: &MultiBufferDiffHunk,
 7126        cx: &mut App,
 7127    ) -> Option<()> {
 7128        let buffer = self.buffer.read(cx);
 7129        let diff = buffer.diff_for(hunk.buffer_id)?;
 7130        let buffer = buffer.buffer(hunk.buffer_id)?;
 7131        let buffer = buffer.read(cx);
 7132        let original_text = diff
 7133            .read(cx)
 7134            .base_text()
 7135            .as_ref()?
 7136            .as_rope()
 7137            .slice(hunk.diff_base_byte_range.clone());
 7138        let buffer_snapshot = buffer.snapshot();
 7139        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7140        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7141            probe
 7142                .0
 7143                .start
 7144                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7145                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7146        }) {
 7147            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7148            Some(())
 7149        } else {
 7150            None
 7151        }
 7152    }
 7153
 7154    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7155        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7156    }
 7157
 7158    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7159        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7160    }
 7161
 7162    fn manipulate_lines<Fn>(
 7163        &mut self,
 7164        window: &mut Window,
 7165        cx: &mut Context<Self>,
 7166        mut callback: Fn,
 7167    ) where
 7168        Fn: FnMut(&mut Vec<&str>),
 7169    {
 7170        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7171        let buffer = self.buffer.read(cx).snapshot(cx);
 7172
 7173        let mut edits = Vec::new();
 7174
 7175        let selections = self.selections.all::<Point>(cx);
 7176        let mut selections = selections.iter().peekable();
 7177        let mut contiguous_row_selections = Vec::new();
 7178        let mut new_selections = Vec::new();
 7179        let mut added_lines = 0;
 7180        let mut removed_lines = 0;
 7181
 7182        while let Some(selection) = selections.next() {
 7183            let (start_row, end_row) = consume_contiguous_rows(
 7184                &mut contiguous_row_selections,
 7185                selection,
 7186                &display_map,
 7187                &mut selections,
 7188            );
 7189
 7190            let start_point = Point::new(start_row.0, 0);
 7191            let end_point = Point::new(
 7192                end_row.previous_row().0,
 7193                buffer.line_len(end_row.previous_row()),
 7194            );
 7195            let text = buffer
 7196                .text_for_range(start_point..end_point)
 7197                .collect::<String>();
 7198
 7199            let mut lines = text.split('\n').collect_vec();
 7200
 7201            let lines_before = lines.len();
 7202            callback(&mut lines);
 7203            let lines_after = lines.len();
 7204
 7205            edits.push((start_point..end_point, lines.join("\n")));
 7206
 7207            // Selections must change based on added and removed line count
 7208            let start_row =
 7209                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7210            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7211            new_selections.push(Selection {
 7212                id: selection.id,
 7213                start: start_row,
 7214                end: end_row,
 7215                goal: SelectionGoal::None,
 7216                reversed: selection.reversed,
 7217            });
 7218
 7219            if lines_after > lines_before {
 7220                added_lines += lines_after - lines_before;
 7221            } else if lines_before > lines_after {
 7222                removed_lines += lines_before - lines_after;
 7223            }
 7224        }
 7225
 7226        self.transact(window, cx, |this, window, cx| {
 7227            let buffer = this.buffer.update(cx, |buffer, cx| {
 7228                buffer.edit(edits, None, cx);
 7229                buffer.snapshot(cx)
 7230            });
 7231
 7232            // Recalculate offsets on newly edited buffer
 7233            let new_selections = new_selections
 7234                .iter()
 7235                .map(|s| {
 7236                    let start_point = Point::new(s.start.0, 0);
 7237                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7238                    Selection {
 7239                        id: s.id,
 7240                        start: buffer.point_to_offset(start_point),
 7241                        end: buffer.point_to_offset(end_point),
 7242                        goal: s.goal,
 7243                        reversed: s.reversed,
 7244                    }
 7245                })
 7246                .collect();
 7247
 7248            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7249                s.select(new_selections);
 7250            });
 7251
 7252            this.request_autoscroll(Autoscroll::fit(), cx);
 7253        });
 7254    }
 7255
 7256    pub fn convert_to_upper_case(
 7257        &mut self,
 7258        _: &ConvertToUpperCase,
 7259        window: &mut Window,
 7260        cx: &mut Context<Self>,
 7261    ) {
 7262        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7263    }
 7264
 7265    pub fn convert_to_lower_case(
 7266        &mut self,
 7267        _: &ConvertToLowerCase,
 7268        window: &mut Window,
 7269        cx: &mut Context<Self>,
 7270    ) {
 7271        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7272    }
 7273
 7274    pub fn convert_to_title_case(
 7275        &mut self,
 7276        _: &ConvertToTitleCase,
 7277        window: &mut Window,
 7278        cx: &mut Context<Self>,
 7279    ) {
 7280        self.manipulate_text(window, cx, |text| {
 7281            text.split('\n')
 7282                .map(|line| line.to_case(Case::Title))
 7283                .join("\n")
 7284        })
 7285    }
 7286
 7287    pub fn convert_to_snake_case(
 7288        &mut self,
 7289        _: &ConvertToSnakeCase,
 7290        window: &mut Window,
 7291        cx: &mut Context<Self>,
 7292    ) {
 7293        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7294    }
 7295
 7296    pub fn convert_to_kebab_case(
 7297        &mut self,
 7298        _: &ConvertToKebabCase,
 7299        window: &mut Window,
 7300        cx: &mut Context<Self>,
 7301    ) {
 7302        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7303    }
 7304
 7305    pub fn convert_to_upper_camel_case(
 7306        &mut self,
 7307        _: &ConvertToUpperCamelCase,
 7308        window: &mut Window,
 7309        cx: &mut Context<Self>,
 7310    ) {
 7311        self.manipulate_text(window, cx, |text| {
 7312            text.split('\n')
 7313                .map(|line| line.to_case(Case::UpperCamel))
 7314                .join("\n")
 7315        })
 7316    }
 7317
 7318    pub fn convert_to_lower_camel_case(
 7319        &mut self,
 7320        _: &ConvertToLowerCamelCase,
 7321        window: &mut Window,
 7322        cx: &mut Context<Self>,
 7323    ) {
 7324        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7325    }
 7326
 7327    pub fn convert_to_opposite_case(
 7328        &mut self,
 7329        _: &ConvertToOppositeCase,
 7330        window: &mut Window,
 7331        cx: &mut Context<Self>,
 7332    ) {
 7333        self.manipulate_text(window, cx, |text| {
 7334            text.chars()
 7335                .fold(String::with_capacity(text.len()), |mut t, c| {
 7336                    if c.is_uppercase() {
 7337                        t.extend(c.to_lowercase());
 7338                    } else {
 7339                        t.extend(c.to_uppercase());
 7340                    }
 7341                    t
 7342                })
 7343        })
 7344    }
 7345
 7346    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7347    where
 7348        Fn: FnMut(&str) -> String,
 7349    {
 7350        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7351        let buffer = self.buffer.read(cx).snapshot(cx);
 7352
 7353        let mut new_selections = Vec::new();
 7354        let mut edits = Vec::new();
 7355        let mut selection_adjustment = 0i32;
 7356
 7357        for selection in self.selections.all::<usize>(cx) {
 7358            let selection_is_empty = selection.is_empty();
 7359
 7360            let (start, end) = if selection_is_empty {
 7361                let word_range = movement::surrounding_word(
 7362                    &display_map,
 7363                    selection.start.to_display_point(&display_map),
 7364                );
 7365                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7366                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7367                (start, end)
 7368            } else {
 7369                (selection.start, selection.end)
 7370            };
 7371
 7372            let text = buffer.text_for_range(start..end).collect::<String>();
 7373            let old_length = text.len() as i32;
 7374            let text = callback(&text);
 7375
 7376            new_selections.push(Selection {
 7377                start: (start as i32 - selection_adjustment) as usize,
 7378                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7379                goal: SelectionGoal::None,
 7380                ..selection
 7381            });
 7382
 7383            selection_adjustment += old_length - text.len() as i32;
 7384
 7385            edits.push((start..end, text));
 7386        }
 7387
 7388        self.transact(window, cx, |this, window, cx| {
 7389            this.buffer.update(cx, |buffer, cx| {
 7390                buffer.edit(edits, None, cx);
 7391            });
 7392
 7393            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7394                s.select(new_selections);
 7395            });
 7396
 7397            this.request_autoscroll(Autoscroll::fit(), cx);
 7398        });
 7399    }
 7400
 7401    pub fn duplicate(
 7402        &mut self,
 7403        upwards: bool,
 7404        whole_lines: bool,
 7405        window: &mut Window,
 7406        cx: &mut Context<Self>,
 7407    ) {
 7408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7409        let buffer = &display_map.buffer_snapshot;
 7410        let selections = self.selections.all::<Point>(cx);
 7411
 7412        let mut edits = Vec::new();
 7413        let mut selections_iter = selections.iter().peekable();
 7414        while let Some(selection) = selections_iter.next() {
 7415            let mut rows = selection.spanned_rows(false, &display_map);
 7416            // duplicate line-wise
 7417            if whole_lines || selection.start == selection.end {
 7418                // Avoid duplicating the same lines twice.
 7419                while let Some(next_selection) = selections_iter.peek() {
 7420                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7421                    if next_rows.start < rows.end {
 7422                        rows.end = next_rows.end;
 7423                        selections_iter.next().unwrap();
 7424                    } else {
 7425                        break;
 7426                    }
 7427                }
 7428
 7429                // Copy the text from the selected row region and splice it either at the start
 7430                // or end of the region.
 7431                let start = Point::new(rows.start.0, 0);
 7432                let end = Point::new(
 7433                    rows.end.previous_row().0,
 7434                    buffer.line_len(rows.end.previous_row()),
 7435                );
 7436                let text = buffer
 7437                    .text_for_range(start..end)
 7438                    .chain(Some("\n"))
 7439                    .collect::<String>();
 7440                let insert_location = if upwards {
 7441                    Point::new(rows.end.0, 0)
 7442                } else {
 7443                    start
 7444                };
 7445                edits.push((insert_location..insert_location, text));
 7446            } else {
 7447                // duplicate character-wise
 7448                let start = selection.start;
 7449                let end = selection.end;
 7450                let text = buffer.text_for_range(start..end).collect::<String>();
 7451                edits.push((selection.end..selection.end, text));
 7452            }
 7453        }
 7454
 7455        self.transact(window, cx, |this, _, cx| {
 7456            this.buffer.update(cx, |buffer, cx| {
 7457                buffer.edit(edits, None, cx);
 7458            });
 7459
 7460            this.request_autoscroll(Autoscroll::fit(), cx);
 7461        });
 7462    }
 7463
 7464    pub fn duplicate_line_up(
 7465        &mut self,
 7466        _: &DuplicateLineUp,
 7467        window: &mut Window,
 7468        cx: &mut Context<Self>,
 7469    ) {
 7470        self.duplicate(true, true, window, cx);
 7471    }
 7472
 7473    pub fn duplicate_line_down(
 7474        &mut self,
 7475        _: &DuplicateLineDown,
 7476        window: &mut Window,
 7477        cx: &mut Context<Self>,
 7478    ) {
 7479        self.duplicate(false, true, window, cx);
 7480    }
 7481
 7482    pub fn duplicate_selection(
 7483        &mut self,
 7484        _: &DuplicateSelection,
 7485        window: &mut Window,
 7486        cx: &mut Context<Self>,
 7487    ) {
 7488        self.duplicate(false, false, window, cx);
 7489    }
 7490
 7491    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7492        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7493        let buffer = self.buffer.read(cx).snapshot(cx);
 7494
 7495        let mut edits = Vec::new();
 7496        let mut unfold_ranges = Vec::new();
 7497        let mut refold_creases = Vec::new();
 7498
 7499        let selections = self.selections.all::<Point>(cx);
 7500        let mut selections = selections.iter().peekable();
 7501        let mut contiguous_row_selections = Vec::new();
 7502        let mut new_selections = Vec::new();
 7503
 7504        while let Some(selection) = selections.next() {
 7505            // Find all the selections that span a contiguous row range
 7506            let (start_row, end_row) = consume_contiguous_rows(
 7507                &mut contiguous_row_selections,
 7508                selection,
 7509                &display_map,
 7510                &mut selections,
 7511            );
 7512
 7513            // Move the text spanned by the row range to be before the line preceding the row range
 7514            if start_row.0 > 0 {
 7515                let range_to_move = Point::new(
 7516                    start_row.previous_row().0,
 7517                    buffer.line_len(start_row.previous_row()),
 7518                )
 7519                    ..Point::new(
 7520                        end_row.previous_row().0,
 7521                        buffer.line_len(end_row.previous_row()),
 7522                    );
 7523                let insertion_point = display_map
 7524                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7525                    .0;
 7526
 7527                // Don't move lines across excerpts
 7528                if buffer
 7529                    .excerpt_containing(insertion_point..range_to_move.end)
 7530                    .is_some()
 7531                {
 7532                    let text = buffer
 7533                        .text_for_range(range_to_move.clone())
 7534                        .flat_map(|s| s.chars())
 7535                        .skip(1)
 7536                        .chain(['\n'])
 7537                        .collect::<String>();
 7538
 7539                    edits.push((
 7540                        buffer.anchor_after(range_to_move.start)
 7541                            ..buffer.anchor_before(range_to_move.end),
 7542                        String::new(),
 7543                    ));
 7544                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7545                    edits.push((insertion_anchor..insertion_anchor, text));
 7546
 7547                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7548
 7549                    // Move selections up
 7550                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7551                        |mut selection| {
 7552                            selection.start.row -= row_delta;
 7553                            selection.end.row -= row_delta;
 7554                            selection
 7555                        },
 7556                    ));
 7557
 7558                    // Move folds up
 7559                    unfold_ranges.push(range_to_move.clone());
 7560                    for fold in display_map.folds_in_range(
 7561                        buffer.anchor_before(range_to_move.start)
 7562                            ..buffer.anchor_after(range_to_move.end),
 7563                    ) {
 7564                        let mut start = fold.range.start.to_point(&buffer);
 7565                        let mut end = fold.range.end.to_point(&buffer);
 7566                        start.row -= row_delta;
 7567                        end.row -= row_delta;
 7568                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7569                    }
 7570                }
 7571            }
 7572
 7573            // If we didn't move line(s), preserve the existing selections
 7574            new_selections.append(&mut contiguous_row_selections);
 7575        }
 7576
 7577        self.transact(window, cx, |this, window, cx| {
 7578            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7579            this.buffer.update(cx, |buffer, cx| {
 7580                for (range, text) in edits {
 7581                    buffer.edit([(range, text)], None, cx);
 7582                }
 7583            });
 7584            this.fold_creases(refold_creases, true, window, cx);
 7585            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7586                s.select(new_selections);
 7587            })
 7588        });
 7589    }
 7590
 7591    pub fn move_line_down(
 7592        &mut self,
 7593        _: &MoveLineDown,
 7594        window: &mut Window,
 7595        cx: &mut Context<Self>,
 7596    ) {
 7597        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7598        let buffer = self.buffer.read(cx).snapshot(cx);
 7599
 7600        let mut edits = Vec::new();
 7601        let mut unfold_ranges = Vec::new();
 7602        let mut refold_creases = Vec::new();
 7603
 7604        let selections = self.selections.all::<Point>(cx);
 7605        let mut selections = selections.iter().peekable();
 7606        let mut contiguous_row_selections = Vec::new();
 7607        let mut new_selections = Vec::new();
 7608
 7609        while let Some(selection) = selections.next() {
 7610            // Find all the selections that span a contiguous row range
 7611            let (start_row, end_row) = consume_contiguous_rows(
 7612                &mut contiguous_row_selections,
 7613                selection,
 7614                &display_map,
 7615                &mut selections,
 7616            );
 7617
 7618            // Move the text spanned by the row range to be after the last line of the row range
 7619            if end_row.0 <= buffer.max_point().row {
 7620                let range_to_move =
 7621                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7622                let insertion_point = display_map
 7623                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7624                    .0;
 7625
 7626                // Don't move lines across excerpt boundaries
 7627                if buffer
 7628                    .excerpt_containing(range_to_move.start..insertion_point)
 7629                    .is_some()
 7630                {
 7631                    let mut text = String::from("\n");
 7632                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7633                    text.pop(); // Drop trailing newline
 7634                    edits.push((
 7635                        buffer.anchor_after(range_to_move.start)
 7636                            ..buffer.anchor_before(range_to_move.end),
 7637                        String::new(),
 7638                    ));
 7639                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7640                    edits.push((insertion_anchor..insertion_anchor, text));
 7641
 7642                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7643
 7644                    // Move selections down
 7645                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7646                        |mut selection| {
 7647                            selection.start.row += row_delta;
 7648                            selection.end.row += row_delta;
 7649                            selection
 7650                        },
 7651                    ));
 7652
 7653                    // Move folds down
 7654                    unfold_ranges.push(range_to_move.clone());
 7655                    for fold in display_map.folds_in_range(
 7656                        buffer.anchor_before(range_to_move.start)
 7657                            ..buffer.anchor_after(range_to_move.end),
 7658                    ) {
 7659                        let mut start = fold.range.start.to_point(&buffer);
 7660                        let mut end = fold.range.end.to_point(&buffer);
 7661                        start.row += row_delta;
 7662                        end.row += row_delta;
 7663                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7664                    }
 7665                }
 7666            }
 7667
 7668            // If we didn't move line(s), preserve the existing selections
 7669            new_selections.append(&mut contiguous_row_selections);
 7670        }
 7671
 7672        self.transact(window, cx, |this, window, cx| {
 7673            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7674            this.buffer.update(cx, |buffer, cx| {
 7675                for (range, text) in edits {
 7676                    buffer.edit([(range, text)], None, cx);
 7677                }
 7678            });
 7679            this.fold_creases(refold_creases, true, window, cx);
 7680            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7681                s.select(new_selections)
 7682            });
 7683        });
 7684    }
 7685
 7686    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7687        let text_layout_details = &self.text_layout_details(window);
 7688        self.transact(window, cx, |this, window, cx| {
 7689            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7690                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7691                let line_mode = s.line_mode;
 7692                s.move_with(|display_map, selection| {
 7693                    if !selection.is_empty() || line_mode {
 7694                        return;
 7695                    }
 7696
 7697                    let mut head = selection.head();
 7698                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7699                    if head.column() == display_map.line_len(head.row()) {
 7700                        transpose_offset = display_map
 7701                            .buffer_snapshot
 7702                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7703                    }
 7704
 7705                    if transpose_offset == 0 {
 7706                        return;
 7707                    }
 7708
 7709                    *head.column_mut() += 1;
 7710                    head = display_map.clip_point(head, Bias::Right);
 7711                    let goal = SelectionGoal::HorizontalPosition(
 7712                        display_map
 7713                            .x_for_display_point(head, text_layout_details)
 7714                            .into(),
 7715                    );
 7716                    selection.collapse_to(head, goal);
 7717
 7718                    let transpose_start = display_map
 7719                        .buffer_snapshot
 7720                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7721                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7722                        let transpose_end = display_map
 7723                            .buffer_snapshot
 7724                            .clip_offset(transpose_offset + 1, Bias::Right);
 7725                        if let Some(ch) =
 7726                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7727                        {
 7728                            edits.push((transpose_start..transpose_offset, String::new()));
 7729                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7730                        }
 7731                    }
 7732                });
 7733                edits
 7734            });
 7735            this.buffer
 7736                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7737            let selections = this.selections.all::<usize>(cx);
 7738            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7739                s.select(selections);
 7740            });
 7741        });
 7742    }
 7743
 7744    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7745        self.rewrap_impl(IsVimMode::No, cx)
 7746    }
 7747
 7748    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7749        let buffer = self.buffer.read(cx).snapshot(cx);
 7750        let selections = self.selections.all::<Point>(cx);
 7751        let mut selections = selections.iter().peekable();
 7752
 7753        let mut edits = Vec::new();
 7754        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7755
 7756        while let Some(selection) = selections.next() {
 7757            let mut start_row = selection.start.row;
 7758            let mut end_row = selection.end.row;
 7759
 7760            // Skip selections that overlap with a range that has already been rewrapped.
 7761            let selection_range = start_row..end_row;
 7762            if rewrapped_row_ranges
 7763                .iter()
 7764                .any(|range| range.overlaps(&selection_range))
 7765            {
 7766                continue;
 7767            }
 7768
 7769            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7770
 7771            // Since not all lines in the selection may be at the same indent
 7772            // level, choose the indent size that is the most common between all
 7773            // of the lines.
 7774            //
 7775            // If there is a tie, we use the deepest indent.
 7776            let (indent_size, indent_end) = {
 7777                let mut indent_size_occurrences = HashMap::default();
 7778                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7779
 7780                for row in start_row..=end_row {
 7781                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7782                    rows_by_indent_size.entry(indent).or_default().push(row);
 7783                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7784                }
 7785
 7786                let indent_size = indent_size_occurrences
 7787                    .into_iter()
 7788                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7789                    .map(|(indent, _)| indent)
 7790                    .unwrap_or_default();
 7791                let row = rows_by_indent_size[&indent_size][0];
 7792                let indent_end = Point::new(row, indent_size.len);
 7793
 7794                (indent_size, indent_end)
 7795            };
 7796
 7797            let mut line_prefix = indent_size.chars().collect::<String>();
 7798
 7799            let mut inside_comment = false;
 7800            if let Some(comment_prefix) =
 7801                buffer
 7802                    .language_scope_at(selection.head())
 7803                    .and_then(|language| {
 7804                        language
 7805                            .line_comment_prefixes()
 7806                            .iter()
 7807                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7808                            .cloned()
 7809                    })
 7810            {
 7811                line_prefix.push_str(&comment_prefix);
 7812                inside_comment = true;
 7813            }
 7814
 7815            let language_settings = buffer.settings_at(selection.head(), cx);
 7816            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 7817                RewrapBehavior::InComments => inside_comment,
 7818                RewrapBehavior::InSelections => !selection.is_empty(),
 7819                RewrapBehavior::Anywhere => true,
 7820            };
 7821
 7822            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 7823            if !should_rewrap {
 7824                continue;
 7825            }
 7826
 7827            if selection.is_empty() {
 7828                'expand_upwards: while start_row > 0 {
 7829                    let prev_row = start_row - 1;
 7830                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7831                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7832                    {
 7833                        start_row = prev_row;
 7834                    } else {
 7835                        break 'expand_upwards;
 7836                    }
 7837                }
 7838
 7839                'expand_downwards: while end_row < buffer.max_point().row {
 7840                    let next_row = end_row + 1;
 7841                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7842                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7843                    {
 7844                        end_row = next_row;
 7845                    } else {
 7846                        break 'expand_downwards;
 7847                    }
 7848                }
 7849            }
 7850
 7851            let start = Point::new(start_row, 0);
 7852            let start_offset = start.to_offset(&buffer);
 7853            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7854            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7855            let Some(lines_without_prefixes) = selection_text
 7856                .lines()
 7857                .map(|line| {
 7858                    line.strip_prefix(&line_prefix)
 7859                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7860                        .ok_or_else(|| {
 7861                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7862                        })
 7863                })
 7864                .collect::<Result<Vec<_>, _>>()
 7865                .log_err()
 7866            else {
 7867                continue;
 7868            };
 7869
 7870            let wrap_column = buffer
 7871                .settings_at(Point::new(start_row, 0), cx)
 7872                .preferred_line_length as usize;
 7873            let wrapped_text = wrap_with_prefix(
 7874                line_prefix,
 7875                lines_without_prefixes.join(" "),
 7876                wrap_column,
 7877                tab_size,
 7878            );
 7879
 7880            // TODO: should always use char-based diff while still supporting cursor behavior that
 7881            // matches vim.
 7882            let mut diff_options = DiffOptions::default();
 7883            if is_vim_mode == IsVimMode::Yes {
 7884                diff_options.max_word_diff_len = 0;
 7885                diff_options.max_word_diff_line_count = 0;
 7886            } else {
 7887                diff_options.max_word_diff_len = usize::MAX;
 7888                diff_options.max_word_diff_line_count = usize::MAX;
 7889            }
 7890
 7891            for (old_range, new_text) in
 7892                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 7893            {
 7894                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 7895                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 7896                edits.push((edit_start..edit_end, new_text));
 7897            }
 7898
 7899            rewrapped_row_ranges.push(start_row..=end_row);
 7900        }
 7901
 7902        self.buffer
 7903            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7904    }
 7905
 7906    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7907        let mut text = String::new();
 7908        let buffer = self.buffer.read(cx).snapshot(cx);
 7909        let mut selections = self.selections.all::<Point>(cx);
 7910        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7911        {
 7912            let max_point = buffer.max_point();
 7913            let mut is_first = true;
 7914            for selection in &mut selections {
 7915                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7916                if is_entire_line {
 7917                    selection.start = Point::new(selection.start.row, 0);
 7918                    if !selection.is_empty() && selection.end.column == 0 {
 7919                        selection.end = cmp::min(max_point, selection.end);
 7920                    } else {
 7921                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7922                    }
 7923                    selection.goal = SelectionGoal::None;
 7924                }
 7925                if is_first {
 7926                    is_first = false;
 7927                } else {
 7928                    text += "\n";
 7929                }
 7930                let mut len = 0;
 7931                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7932                    text.push_str(chunk);
 7933                    len += chunk.len();
 7934                }
 7935                clipboard_selections.push(ClipboardSelection {
 7936                    len,
 7937                    is_entire_line,
 7938                    first_line_indent: buffer
 7939                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7940                        .len,
 7941                });
 7942            }
 7943        }
 7944
 7945        self.transact(window, cx, |this, window, cx| {
 7946            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7947                s.select(selections);
 7948            });
 7949            this.insert("", window, cx);
 7950        });
 7951        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7952    }
 7953
 7954    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7955        let item = self.cut_common(window, cx);
 7956        cx.write_to_clipboard(item);
 7957    }
 7958
 7959    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7960        self.change_selections(None, window, cx, |s| {
 7961            s.move_with(|snapshot, sel| {
 7962                if sel.is_empty() {
 7963                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7964                }
 7965            });
 7966        });
 7967        let item = self.cut_common(window, cx);
 7968        cx.set_global(KillRing(item))
 7969    }
 7970
 7971    pub fn kill_ring_yank(
 7972        &mut self,
 7973        _: &KillRingYank,
 7974        window: &mut Window,
 7975        cx: &mut Context<Self>,
 7976    ) {
 7977        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7978            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7979                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7980            } else {
 7981                return;
 7982            }
 7983        } else {
 7984            return;
 7985        };
 7986        self.do_paste(&text, metadata, false, window, cx);
 7987    }
 7988
 7989    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7990        let selections = self.selections.all::<Point>(cx);
 7991        let buffer = self.buffer.read(cx).read(cx);
 7992        let mut text = String::new();
 7993
 7994        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7995        {
 7996            let max_point = buffer.max_point();
 7997            let mut is_first = true;
 7998            for selection in selections.iter() {
 7999                let mut start = selection.start;
 8000                let mut end = selection.end;
 8001                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8002                if is_entire_line {
 8003                    start = Point::new(start.row, 0);
 8004                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8005                }
 8006                if is_first {
 8007                    is_first = false;
 8008                } else {
 8009                    text += "\n";
 8010                }
 8011                let mut len = 0;
 8012                for chunk in buffer.text_for_range(start..end) {
 8013                    text.push_str(chunk);
 8014                    len += chunk.len();
 8015                }
 8016                clipboard_selections.push(ClipboardSelection {
 8017                    len,
 8018                    is_entire_line,
 8019                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8020                });
 8021            }
 8022        }
 8023
 8024        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8025            text,
 8026            clipboard_selections,
 8027        ));
 8028    }
 8029
 8030    pub fn do_paste(
 8031        &mut self,
 8032        text: &String,
 8033        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8034        handle_entire_lines: bool,
 8035        window: &mut Window,
 8036        cx: &mut Context<Self>,
 8037    ) {
 8038        if self.read_only(cx) {
 8039            return;
 8040        }
 8041
 8042        let clipboard_text = Cow::Borrowed(text);
 8043
 8044        self.transact(window, cx, |this, window, cx| {
 8045            if let Some(mut clipboard_selections) = clipboard_selections {
 8046                let old_selections = this.selections.all::<usize>(cx);
 8047                let all_selections_were_entire_line =
 8048                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8049                let first_selection_indent_column =
 8050                    clipboard_selections.first().map(|s| s.first_line_indent);
 8051                if clipboard_selections.len() != old_selections.len() {
 8052                    clipboard_selections.drain(..);
 8053                }
 8054                let cursor_offset = this.selections.last::<usize>(cx).head();
 8055                let mut auto_indent_on_paste = true;
 8056
 8057                this.buffer.update(cx, |buffer, cx| {
 8058                    let snapshot = buffer.read(cx);
 8059                    auto_indent_on_paste =
 8060                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8061
 8062                    let mut start_offset = 0;
 8063                    let mut edits = Vec::new();
 8064                    let mut original_indent_columns = Vec::new();
 8065                    for (ix, selection) in old_selections.iter().enumerate() {
 8066                        let to_insert;
 8067                        let entire_line;
 8068                        let original_indent_column;
 8069                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8070                            let end_offset = start_offset + clipboard_selection.len;
 8071                            to_insert = &clipboard_text[start_offset..end_offset];
 8072                            entire_line = clipboard_selection.is_entire_line;
 8073                            start_offset = end_offset + 1;
 8074                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8075                        } else {
 8076                            to_insert = clipboard_text.as_str();
 8077                            entire_line = all_selections_were_entire_line;
 8078                            original_indent_column = first_selection_indent_column
 8079                        }
 8080
 8081                        // If the corresponding selection was empty when this slice of the
 8082                        // clipboard text was written, then the entire line containing the
 8083                        // selection was copied. If this selection is also currently empty,
 8084                        // then paste the line before the current line of the buffer.
 8085                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8086                            let column = selection.start.to_point(&snapshot).column as usize;
 8087                            let line_start = selection.start - column;
 8088                            line_start..line_start
 8089                        } else {
 8090                            selection.range()
 8091                        };
 8092
 8093                        edits.push((range, to_insert));
 8094                        original_indent_columns.extend(original_indent_column);
 8095                    }
 8096                    drop(snapshot);
 8097
 8098                    buffer.edit(
 8099                        edits,
 8100                        if auto_indent_on_paste {
 8101                            Some(AutoindentMode::Block {
 8102                                original_indent_columns,
 8103                            })
 8104                        } else {
 8105                            None
 8106                        },
 8107                        cx,
 8108                    );
 8109                });
 8110
 8111                let selections = this.selections.all::<usize>(cx);
 8112                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8113                    s.select(selections)
 8114                });
 8115            } else {
 8116                this.insert(&clipboard_text, window, cx);
 8117            }
 8118        });
 8119    }
 8120
 8121    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8122        if let Some(item) = cx.read_from_clipboard() {
 8123            let entries = item.entries();
 8124
 8125            match entries.first() {
 8126                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8127                // of all the pasted entries.
 8128                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8129                    .do_paste(
 8130                        clipboard_string.text(),
 8131                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8132                        true,
 8133                        window,
 8134                        cx,
 8135                    ),
 8136                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8137            }
 8138        }
 8139    }
 8140
 8141    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8142        if self.read_only(cx) {
 8143            return;
 8144        }
 8145
 8146        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8147            if let Some((selections, _)) =
 8148                self.selection_history.transaction(transaction_id).cloned()
 8149            {
 8150                self.change_selections(None, window, cx, |s| {
 8151                    s.select_anchors(selections.to_vec());
 8152                });
 8153            }
 8154            self.request_autoscroll(Autoscroll::fit(), cx);
 8155            self.unmark_text(window, cx);
 8156            self.refresh_inline_completion(true, false, window, cx);
 8157            cx.emit(EditorEvent::Edited { transaction_id });
 8158            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8159        }
 8160    }
 8161
 8162    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8163        if self.read_only(cx) {
 8164            return;
 8165        }
 8166
 8167        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8168            if let Some((_, Some(selections))) =
 8169                self.selection_history.transaction(transaction_id).cloned()
 8170            {
 8171                self.change_selections(None, window, cx, |s| {
 8172                    s.select_anchors(selections.to_vec());
 8173                });
 8174            }
 8175            self.request_autoscroll(Autoscroll::fit(), cx);
 8176            self.unmark_text(window, cx);
 8177            self.refresh_inline_completion(true, false, window, cx);
 8178            cx.emit(EditorEvent::Edited { transaction_id });
 8179        }
 8180    }
 8181
 8182    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8183        self.buffer
 8184            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8185    }
 8186
 8187    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8188        self.buffer
 8189            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8190    }
 8191
 8192    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8193        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8194            let line_mode = s.line_mode;
 8195            s.move_with(|map, selection| {
 8196                let cursor = if selection.is_empty() && !line_mode {
 8197                    movement::left(map, selection.start)
 8198                } else {
 8199                    selection.start
 8200                };
 8201                selection.collapse_to(cursor, SelectionGoal::None);
 8202            });
 8203        })
 8204    }
 8205
 8206    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8207        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8208            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8209        })
 8210    }
 8211
 8212    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8213        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8214            let line_mode = s.line_mode;
 8215            s.move_with(|map, selection| {
 8216                let cursor = if selection.is_empty() && !line_mode {
 8217                    movement::right(map, selection.end)
 8218                } else {
 8219                    selection.end
 8220                };
 8221                selection.collapse_to(cursor, SelectionGoal::None)
 8222            });
 8223        })
 8224    }
 8225
 8226    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8227        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8228            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8229        })
 8230    }
 8231
 8232    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8233        if self.take_rename(true, window, cx).is_some() {
 8234            return;
 8235        }
 8236
 8237        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8238            cx.propagate();
 8239            return;
 8240        }
 8241
 8242        let text_layout_details = &self.text_layout_details(window);
 8243        let selection_count = self.selections.count();
 8244        let first_selection = self.selections.first_anchor();
 8245
 8246        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8247            let line_mode = s.line_mode;
 8248            s.move_with(|map, selection| {
 8249                if !selection.is_empty() && !line_mode {
 8250                    selection.goal = SelectionGoal::None;
 8251                }
 8252                let (cursor, goal) = movement::up(
 8253                    map,
 8254                    selection.start,
 8255                    selection.goal,
 8256                    false,
 8257                    text_layout_details,
 8258                );
 8259                selection.collapse_to(cursor, goal);
 8260            });
 8261        });
 8262
 8263        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8264        {
 8265            cx.propagate();
 8266        }
 8267    }
 8268
 8269    pub fn move_up_by_lines(
 8270        &mut self,
 8271        action: &MoveUpByLines,
 8272        window: &mut Window,
 8273        cx: &mut Context<Self>,
 8274    ) {
 8275        if self.take_rename(true, window, cx).is_some() {
 8276            return;
 8277        }
 8278
 8279        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8280            cx.propagate();
 8281            return;
 8282        }
 8283
 8284        let text_layout_details = &self.text_layout_details(window);
 8285
 8286        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8287            let line_mode = s.line_mode;
 8288            s.move_with(|map, selection| {
 8289                if !selection.is_empty() && !line_mode {
 8290                    selection.goal = SelectionGoal::None;
 8291                }
 8292                let (cursor, goal) = movement::up_by_rows(
 8293                    map,
 8294                    selection.start,
 8295                    action.lines,
 8296                    selection.goal,
 8297                    false,
 8298                    text_layout_details,
 8299                );
 8300                selection.collapse_to(cursor, goal);
 8301            });
 8302        })
 8303    }
 8304
 8305    pub fn move_down_by_lines(
 8306        &mut self,
 8307        action: &MoveDownByLines,
 8308        window: &mut Window,
 8309        cx: &mut Context<Self>,
 8310    ) {
 8311        if self.take_rename(true, window, cx).is_some() {
 8312            return;
 8313        }
 8314
 8315        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8316            cx.propagate();
 8317            return;
 8318        }
 8319
 8320        let text_layout_details = &self.text_layout_details(window);
 8321
 8322        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8323            let line_mode = s.line_mode;
 8324            s.move_with(|map, selection| {
 8325                if !selection.is_empty() && !line_mode {
 8326                    selection.goal = SelectionGoal::None;
 8327                }
 8328                let (cursor, goal) = movement::down_by_rows(
 8329                    map,
 8330                    selection.start,
 8331                    action.lines,
 8332                    selection.goal,
 8333                    false,
 8334                    text_layout_details,
 8335                );
 8336                selection.collapse_to(cursor, goal);
 8337            });
 8338        })
 8339    }
 8340
 8341    pub fn select_down_by_lines(
 8342        &mut self,
 8343        action: &SelectDownByLines,
 8344        window: &mut Window,
 8345        cx: &mut Context<Self>,
 8346    ) {
 8347        let text_layout_details = &self.text_layout_details(window);
 8348        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8349            s.move_heads_with(|map, head, goal| {
 8350                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8351            })
 8352        })
 8353    }
 8354
 8355    pub fn select_up_by_lines(
 8356        &mut self,
 8357        action: &SelectUpByLines,
 8358        window: &mut Window,
 8359        cx: &mut Context<Self>,
 8360    ) {
 8361        let text_layout_details = &self.text_layout_details(window);
 8362        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8363            s.move_heads_with(|map, head, goal| {
 8364                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8365            })
 8366        })
 8367    }
 8368
 8369    pub fn select_page_up(
 8370        &mut self,
 8371        _: &SelectPageUp,
 8372        window: &mut Window,
 8373        cx: &mut Context<Self>,
 8374    ) {
 8375        let Some(row_count) = self.visible_row_count() else {
 8376            return;
 8377        };
 8378
 8379        let text_layout_details = &self.text_layout_details(window);
 8380
 8381        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8382            s.move_heads_with(|map, head, goal| {
 8383                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8384            })
 8385        })
 8386    }
 8387
 8388    pub fn move_page_up(
 8389        &mut self,
 8390        action: &MovePageUp,
 8391        window: &mut Window,
 8392        cx: &mut Context<Self>,
 8393    ) {
 8394        if self.take_rename(true, window, cx).is_some() {
 8395            return;
 8396        }
 8397
 8398        if self
 8399            .context_menu
 8400            .borrow_mut()
 8401            .as_mut()
 8402            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8403            .unwrap_or(false)
 8404        {
 8405            return;
 8406        }
 8407
 8408        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8409            cx.propagate();
 8410            return;
 8411        }
 8412
 8413        let Some(row_count) = self.visible_row_count() else {
 8414            return;
 8415        };
 8416
 8417        let autoscroll = if action.center_cursor {
 8418            Autoscroll::center()
 8419        } else {
 8420            Autoscroll::fit()
 8421        };
 8422
 8423        let text_layout_details = &self.text_layout_details(window);
 8424
 8425        self.change_selections(Some(autoscroll), window, cx, |s| {
 8426            let line_mode = s.line_mode;
 8427            s.move_with(|map, selection| {
 8428                if !selection.is_empty() && !line_mode {
 8429                    selection.goal = SelectionGoal::None;
 8430                }
 8431                let (cursor, goal) = movement::up_by_rows(
 8432                    map,
 8433                    selection.end,
 8434                    row_count,
 8435                    selection.goal,
 8436                    false,
 8437                    text_layout_details,
 8438                );
 8439                selection.collapse_to(cursor, goal);
 8440            });
 8441        });
 8442    }
 8443
 8444    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8445        let text_layout_details = &self.text_layout_details(window);
 8446        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8447            s.move_heads_with(|map, head, goal| {
 8448                movement::up(map, head, goal, false, text_layout_details)
 8449            })
 8450        })
 8451    }
 8452
 8453    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8454        self.take_rename(true, window, cx);
 8455
 8456        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8457            cx.propagate();
 8458            return;
 8459        }
 8460
 8461        let text_layout_details = &self.text_layout_details(window);
 8462        let selection_count = self.selections.count();
 8463        let first_selection = self.selections.first_anchor();
 8464
 8465        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8466            let line_mode = s.line_mode;
 8467            s.move_with(|map, selection| {
 8468                if !selection.is_empty() && !line_mode {
 8469                    selection.goal = SelectionGoal::None;
 8470                }
 8471                let (cursor, goal) = movement::down(
 8472                    map,
 8473                    selection.end,
 8474                    selection.goal,
 8475                    false,
 8476                    text_layout_details,
 8477                );
 8478                selection.collapse_to(cursor, goal);
 8479            });
 8480        });
 8481
 8482        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8483        {
 8484            cx.propagate();
 8485        }
 8486    }
 8487
 8488    pub fn select_page_down(
 8489        &mut self,
 8490        _: &SelectPageDown,
 8491        window: &mut Window,
 8492        cx: &mut Context<Self>,
 8493    ) {
 8494        let Some(row_count) = self.visible_row_count() else {
 8495            return;
 8496        };
 8497
 8498        let text_layout_details = &self.text_layout_details(window);
 8499
 8500        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8501            s.move_heads_with(|map, head, goal| {
 8502                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8503            })
 8504        })
 8505    }
 8506
 8507    pub fn move_page_down(
 8508        &mut self,
 8509        action: &MovePageDown,
 8510        window: &mut Window,
 8511        cx: &mut Context<Self>,
 8512    ) {
 8513        if self.take_rename(true, window, cx).is_some() {
 8514            return;
 8515        }
 8516
 8517        if self
 8518            .context_menu
 8519            .borrow_mut()
 8520            .as_mut()
 8521            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8522            .unwrap_or(false)
 8523        {
 8524            return;
 8525        }
 8526
 8527        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8528            cx.propagate();
 8529            return;
 8530        }
 8531
 8532        let Some(row_count) = self.visible_row_count() else {
 8533            return;
 8534        };
 8535
 8536        let autoscroll = if action.center_cursor {
 8537            Autoscroll::center()
 8538        } else {
 8539            Autoscroll::fit()
 8540        };
 8541
 8542        let text_layout_details = &self.text_layout_details(window);
 8543        self.change_selections(Some(autoscroll), window, cx, |s| {
 8544            let line_mode = s.line_mode;
 8545            s.move_with(|map, selection| {
 8546                if !selection.is_empty() && !line_mode {
 8547                    selection.goal = SelectionGoal::None;
 8548                }
 8549                let (cursor, goal) = movement::down_by_rows(
 8550                    map,
 8551                    selection.end,
 8552                    row_count,
 8553                    selection.goal,
 8554                    false,
 8555                    text_layout_details,
 8556                );
 8557                selection.collapse_to(cursor, goal);
 8558            });
 8559        });
 8560    }
 8561
 8562    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8563        let text_layout_details = &self.text_layout_details(window);
 8564        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8565            s.move_heads_with(|map, head, goal| {
 8566                movement::down(map, head, goal, false, text_layout_details)
 8567            })
 8568        });
 8569    }
 8570
 8571    pub fn context_menu_first(
 8572        &mut self,
 8573        _: &ContextMenuFirst,
 8574        _window: &mut Window,
 8575        cx: &mut Context<Self>,
 8576    ) {
 8577        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8578            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8579        }
 8580    }
 8581
 8582    pub fn context_menu_prev(
 8583        &mut self,
 8584        _: &ContextMenuPrev,
 8585        _window: &mut Window,
 8586        cx: &mut Context<Self>,
 8587    ) {
 8588        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8589            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8590        }
 8591    }
 8592
 8593    pub fn context_menu_next(
 8594        &mut self,
 8595        _: &ContextMenuNext,
 8596        _window: &mut Window,
 8597        cx: &mut Context<Self>,
 8598    ) {
 8599        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8600            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8601        }
 8602    }
 8603
 8604    pub fn context_menu_last(
 8605        &mut self,
 8606        _: &ContextMenuLast,
 8607        _window: &mut Window,
 8608        cx: &mut Context<Self>,
 8609    ) {
 8610        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8611            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8612        }
 8613    }
 8614
 8615    pub fn move_to_previous_word_start(
 8616        &mut self,
 8617        _: &MoveToPreviousWordStart,
 8618        window: &mut Window,
 8619        cx: &mut Context<Self>,
 8620    ) {
 8621        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8622            s.move_cursors_with(|map, head, _| {
 8623                (
 8624                    movement::previous_word_start(map, head),
 8625                    SelectionGoal::None,
 8626                )
 8627            });
 8628        })
 8629    }
 8630
 8631    pub fn move_to_previous_subword_start(
 8632        &mut self,
 8633        _: &MoveToPreviousSubwordStart,
 8634        window: &mut Window,
 8635        cx: &mut Context<Self>,
 8636    ) {
 8637        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8638            s.move_cursors_with(|map, head, _| {
 8639                (
 8640                    movement::previous_subword_start(map, head),
 8641                    SelectionGoal::None,
 8642                )
 8643            });
 8644        })
 8645    }
 8646
 8647    pub fn select_to_previous_word_start(
 8648        &mut self,
 8649        _: &SelectToPreviousWordStart,
 8650        window: &mut Window,
 8651        cx: &mut Context<Self>,
 8652    ) {
 8653        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8654            s.move_heads_with(|map, head, _| {
 8655                (
 8656                    movement::previous_word_start(map, head),
 8657                    SelectionGoal::None,
 8658                )
 8659            });
 8660        })
 8661    }
 8662
 8663    pub fn select_to_previous_subword_start(
 8664        &mut self,
 8665        _: &SelectToPreviousSubwordStart,
 8666        window: &mut Window,
 8667        cx: &mut Context<Self>,
 8668    ) {
 8669        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8670            s.move_heads_with(|map, head, _| {
 8671                (
 8672                    movement::previous_subword_start(map, head),
 8673                    SelectionGoal::None,
 8674                )
 8675            });
 8676        })
 8677    }
 8678
 8679    pub fn delete_to_previous_word_start(
 8680        &mut self,
 8681        action: &DeleteToPreviousWordStart,
 8682        window: &mut Window,
 8683        cx: &mut Context<Self>,
 8684    ) {
 8685        self.transact(window, cx, |this, window, cx| {
 8686            this.select_autoclose_pair(window, cx);
 8687            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8688                let line_mode = s.line_mode;
 8689                s.move_with(|map, selection| {
 8690                    if selection.is_empty() && !line_mode {
 8691                        let cursor = if action.ignore_newlines {
 8692                            movement::previous_word_start(map, selection.head())
 8693                        } else {
 8694                            movement::previous_word_start_or_newline(map, selection.head())
 8695                        };
 8696                        selection.set_head(cursor, SelectionGoal::None);
 8697                    }
 8698                });
 8699            });
 8700            this.insert("", window, cx);
 8701        });
 8702    }
 8703
 8704    pub fn delete_to_previous_subword_start(
 8705        &mut self,
 8706        _: &DeleteToPreviousSubwordStart,
 8707        window: &mut Window,
 8708        cx: &mut Context<Self>,
 8709    ) {
 8710        self.transact(window, cx, |this, window, cx| {
 8711            this.select_autoclose_pair(window, cx);
 8712            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8713                let line_mode = s.line_mode;
 8714                s.move_with(|map, selection| {
 8715                    if selection.is_empty() && !line_mode {
 8716                        let cursor = movement::previous_subword_start(map, selection.head());
 8717                        selection.set_head(cursor, SelectionGoal::None);
 8718                    }
 8719                });
 8720            });
 8721            this.insert("", window, cx);
 8722        });
 8723    }
 8724
 8725    pub fn move_to_next_word_end(
 8726        &mut self,
 8727        _: &MoveToNextWordEnd,
 8728        window: &mut Window,
 8729        cx: &mut Context<Self>,
 8730    ) {
 8731        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8732            s.move_cursors_with(|map, head, _| {
 8733                (movement::next_word_end(map, head), SelectionGoal::None)
 8734            });
 8735        })
 8736    }
 8737
 8738    pub fn move_to_next_subword_end(
 8739        &mut self,
 8740        _: &MoveToNextSubwordEnd,
 8741        window: &mut Window,
 8742        cx: &mut Context<Self>,
 8743    ) {
 8744        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8745            s.move_cursors_with(|map, head, _| {
 8746                (movement::next_subword_end(map, head), SelectionGoal::None)
 8747            });
 8748        })
 8749    }
 8750
 8751    pub fn select_to_next_word_end(
 8752        &mut self,
 8753        _: &SelectToNextWordEnd,
 8754        window: &mut Window,
 8755        cx: &mut Context<Self>,
 8756    ) {
 8757        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8758            s.move_heads_with(|map, head, _| {
 8759                (movement::next_word_end(map, head), SelectionGoal::None)
 8760            });
 8761        })
 8762    }
 8763
 8764    pub fn select_to_next_subword_end(
 8765        &mut self,
 8766        _: &SelectToNextSubwordEnd,
 8767        window: &mut Window,
 8768        cx: &mut Context<Self>,
 8769    ) {
 8770        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8771            s.move_heads_with(|map, head, _| {
 8772                (movement::next_subword_end(map, head), SelectionGoal::None)
 8773            });
 8774        })
 8775    }
 8776
 8777    pub fn delete_to_next_word_end(
 8778        &mut self,
 8779        action: &DeleteToNextWordEnd,
 8780        window: &mut Window,
 8781        cx: &mut Context<Self>,
 8782    ) {
 8783        self.transact(window, cx, |this, window, cx| {
 8784            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8785                let line_mode = s.line_mode;
 8786                s.move_with(|map, selection| {
 8787                    if selection.is_empty() && !line_mode {
 8788                        let cursor = if action.ignore_newlines {
 8789                            movement::next_word_end(map, selection.head())
 8790                        } else {
 8791                            movement::next_word_end_or_newline(map, selection.head())
 8792                        };
 8793                        selection.set_head(cursor, SelectionGoal::None);
 8794                    }
 8795                });
 8796            });
 8797            this.insert("", window, cx);
 8798        });
 8799    }
 8800
 8801    pub fn delete_to_next_subword_end(
 8802        &mut self,
 8803        _: &DeleteToNextSubwordEnd,
 8804        window: &mut Window,
 8805        cx: &mut Context<Self>,
 8806    ) {
 8807        self.transact(window, cx, |this, window, cx| {
 8808            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8809                s.move_with(|map, selection| {
 8810                    if selection.is_empty() {
 8811                        let cursor = movement::next_subword_end(map, selection.head());
 8812                        selection.set_head(cursor, SelectionGoal::None);
 8813                    }
 8814                });
 8815            });
 8816            this.insert("", window, cx);
 8817        });
 8818    }
 8819
 8820    pub fn move_to_beginning_of_line(
 8821        &mut self,
 8822        action: &MoveToBeginningOfLine,
 8823        window: &mut Window,
 8824        cx: &mut Context<Self>,
 8825    ) {
 8826        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8827            s.move_cursors_with(|map, head, _| {
 8828                (
 8829                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8830                    SelectionGoal::None,
 8831                )
 8832            });
 8833        })
 8834    }
 8835
 8836    pub fn select_to_beginning_of_line(
 8837        &mut self,
 8838        action: &SelectToBeginningOfLine,
 8839        window: &mut Window,
 8840        cx: &mut Context<Self>,
 8841    ) {
 8842        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8843            s.move_heads_with(|map, head, _| {
 8844                (
 8845                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8846                    SelectionGoal::None,
 8847                )
 8848            });
 8849        });
 8850    }
 8851
 8852    pub fn delete_to_beginning_of_line(
 8853        &mut self,
 8854        _: &DeleteToBeginningOfLine,
 8855        window: &mut Window,
 8856        cx: &mut Context<Self>,
 8857    ) {
 8858        self.transact(window, cx, |this, window, cx| {
 8859            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8860                s.move_with(|_, selection| {
 8861                    selection.reversed = true;
 8862                });
 8863            });
 8864
 8865            this.select_to_beginning_of_line(
 8866                &SelectToBeginningOfLine {
 8867                    stop_at_soft_wraps: false,
 8868                },
 8869                window,
 8870                cx,
 8871            );
 8872            this.backspace(&Backspace, window, cx);
 8873        });
 8874    }
 8875
 8876    pub fn move_to_end_of_line(
 8877        &mut self,
 8878        action: &MoveToEndOfLine,
 8879        window: &mut Window,
 8880        cx: &mut Context<Self>,
 8881    ) {
 8882        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8883            s.move_cursors_with(|map, head, _| {
 8884                (
 8885                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8886                    SelectionGoal::None,
 8887                )
 8888            });
 8889        })
 8890    }
 8891
 8892    pub fn select_to_end_of_line(
 8893        &mut self,
 8894        action: &SelectToEndOfLine,
 8895        window: &mut Window,
 8896        cx: &mut Context<Self>,
 8897    ) {
 8898        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8899            s.move_heads_with(|map, head, _| {
 8900                (
 8901                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8902                    SelectionGoal::None,
 8903                )
 8904            });
 8905        })
 8906    }
 8907
 8908    pub fn delete_to_end_of_line(
 8909        &mut self,
 8910        _: &DeleteToEndOfLine,
 8911        window: &mut Window,
 8912        cx: &mut Context<Self>,
 8913    ) {
 8914        self.transact(window, cx, |this, window, cx| {
 8915            this.select_to_end_of_line(
 8916                &SelectToEndOfLine {
 8917                    stop_at_soft_wraps: false,
 8918                },
 8919                window,
 8920                cx,
 8921            );
 8922            this.delete(&Delete, window, cx);
 8923        });
 8924    }
 8925
 8926    pub fn cut_to_end_of_line(
 8927        &mut self,
 8928        _: &CutToEndOfLine,
 8929        window: &mut Window,
 8930        cx: &mut Context<Self>,
 8931    ) {
 8932        self.transact(window, cx, |this, window, cx| {
 8933            this.select_to_end_of_line(
 8934                &SelectToEndOfLine {
 8935                    stop_at_soft_wraps: false,
 8936                },
 8937                window,
 8938                cx,
 8939            );
 8940            this.cut(&Cut, window, cx);
 8941        });
 8942    }
 8943
 8944    pub fn move_to_start_of_paragraph(
 8945        &mut self,
 8946        _: &MoveToStartOfParagraph,
 8947        window: &mut Window,
 8948        cx: &mut Context<Self>,
 8949    ) {
 8950        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8951            cx.propagate();
 8952            return;
 8953        }
 8954
 8955        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8956            s.move_with(|map, selection| {
 8957                selection.collapse_to(
 8958                    movement::start_of_paragraph(map, selection.head(), 1),
 8959                    SelectionGoal::None,
 8960                )
 8961            });
 8962        })
 8963    }
 8964
 8965    pub fn move_to_end_of_paragraph(
 8966        &mut self,
 8967        _: &MoveToEndOfParagraph,
 8968        window: &mut Window,
 8969        cx: &mut Context<Self>,
 8970    ) {
 8971        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8972            cx.propagate();
 8973            return;
 8974        }
 8975
 8976        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8977            s.move_with(|map, selection| {
 8978                selection.collapse_to(
 8979                    movement::end_of_paragraph(map, selection.head(), 1),
 8980                    SelectionGoal::None,
 8981                )
 8982            });
 8983        })
 8984    }
 8985
 8986    pub fn select_to_start_of_paragraph(
 8987        &mut self,
 8988        _: &SelectToStartOfParagraph,
 8989        window: &mut Window,
 8990        cx: &mut Context<Self>,
 8991    ) {
 8992        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8993            cx.propagate();
 8994            return;
 8995        }
 8996
 8997        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8998            s.move_heads_with(|map, head, _| {
 8999                (
 9000                    movement::start_of_paragraph(map, head, 1),
 9001                    SelectionGoal::None,
 9002                )
 9003            });
 9004        })
 9005    }
 9006
 9007    pub fn select_to_end_of_paragraph(
 9008        &mut self,
 9009        _: &SelectToEndOfParagraph,
 9010        window: &mut Window,
 9011        cx: &mut Context<Self>,
 9012    ) {
 9013        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9014            cx.propagate();
 9015            return;
 9016        }
 9017
 9018        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9019            s.move_heads_with(|map, head, _| {
 9020                (
 9021                    movement::end_of_paragraph(map, head, 1),
 9022                    SelectionGoal::None,
 9023                )
 9024            });
 9025        })
 9026    }
 9027
 9028    pub fn move_to_beginning(
 9029        &mut self,
 9030        _: &MoveToBeginning,
 9031        window: &mut Window,
 9032        cx: &mut Context<Self>,
 9033    ) {
 9034        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9035            cx.propagate();
 9036            return;
 9037        }
 9038
 9039        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9040            s.select_ranges(vec![0..0]);
 9041        });
 9042    }
 9043
 9044    pub fn select_to_beginning(
 9045        &mut self,
 9046        _: &SelectToBeginning,
 9047        window: &mut Window,
 9048        cx: &mut Context<Self>,
 9049    ) {
 9050        let mut selection = self.selections.last::<Point>(cx);
 9051        selection.set_head(Point::zero(), SelectionGoal::None);
 9052
 9053        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9054            s.select(vec![selection]);
 9055        });
 9056    }
 9057
 9058    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9059        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9060            cx.propagate();
 9061            return;
 9062        }
 9063
 9064        let cursor = self.buffer.read(cx).read(cx).len();
 9065        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9066            s.select_ranges(vec![cursor..cursor])
 9067        });
 9068    }
 9069
 9070    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9071        self.nav_history = nav_history;
 9072    }
 9073
 9074    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9075        self.nav_history.as_ref()
 9076    }
 9077
 9078    fn push_to_nav_history(
 9079        &mut self,
 9080        cursor_anchor: Anchor,
 9081        new_position: Option<Point>,
 9082        cx: &mut Context<Self>,
 9083    ) {
 9084        if let Some(nav_history) = self.nav_history.as_mut() {
 9085            let buffer = self.buffer.read(cx).read(cx);
 9086            let cursor_position = cursor_anchor.to_point(&buffer);
 9087            let scroll_state = self.scroll_manager.anchor();
 9088            let scroll_top_row = scroll_state.top_row(&buffer);
 9089            drop(buffer);
 9090
 9091            if let Some(new_position) = new_position {
 9092                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9093                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9094                    return;
 9095                }
 9096            }
 9097
 9098            nav_history.push(
 9099                Some(NavigationData {
 9100                    cursor_anchor,
 9101                    cursor_position,
 9102                    scroll_anchor: scroll_state,
 9103                    scroll_top_row,
 9104                }),
 9105                cx,
 9106            );
 9107        }
 9108    }
 9109
 9110    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9111        let buffer = self.buffer.read(cx).snapshot(cx);
 9112        let mut selection = self.selections.first::<usize>(cx);
 9113        selection.set_head(buffer.len(), SelectionGoal::None);
 9114        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9115            s.select(vec![selection]);
 9116        });
 9117    }
 9118
 9119    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9120        let end = self.buffer.read(cx).read(cx).len();
 9121        self.change_selections(None, window, cx, |s| {
 9122            s.select_ranges(vec![0..end]);
 9123        });
 9124    }
 9125
 9126    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9127        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9128        let mut selections = self.selections.all::<Point>(cx);
 9129        let max_point = display_map.buffer_snapshot.max_point();
 9130        for selection in &mut selections {
 9131            let rows = selection.spanned_rows(true, &display_map);
 9132            selection.start = Point::new(rows.start.0, 0);
 9133            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9134            selection.reversed = false;
 9135        }
 9136        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9137            s.select(selections);
 9138        });
 9139    }
 9140
 9141    pub fn split_selection_into_lines(
 9142        &mut self,
 9143        _: &SplitSelectionIntoLines,
 9144        window: &mut Window,
 9145        cx: &mut Context<Self>,
 9146    ) {
 9147        let selections = self
 9148            .selections
 9149            .all::<Point>(cx)
 9150            .into_iter()
 9151            .map(|selection| selection.start..selection.end)
 9152            .collect::<Vec<_>>();
 9153        self.unfold_ranges(&selections, true, true, cx);
 9154
 9155        let mut new_selection_ranges = Vec::new();
 9156        {
 9157            let buffer = self.buffer.read(cx).read(cx);
 9158            for selection in selections {
 9159                for row in selection.start.row..selection.end.row {
 9160                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9161                    new_selection_ranges.push(cursor..cursor);
 9162                }
 9163
 9164                let is_multiline_selection = selection.start.row != selection.end.row;
 9165                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9166                // so this action feels more ergonomic when paired with other selection operations
 9167                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9168                if !should_skip_last {
 9169                    new_selection_ranges.push(selection.end..selection.end);
 9170                }
 9171            }
 9172        }
 9173        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9174            s.select_ranges(new_selection_ranges);
 9175        });
 9176    }
 9177
 9178    pub fn add_selection_above(
 9179        &mut self,
 9180        _: &AddSelectionAbove,
 9181        window: &mut Window,
 9182        cx: &mut Context<Self>,
 9183    ) {
 9184        self.add_selection(true, window, cx);
 9185    }
 9186
 9187    pub fn add_selection_below(
 9188        &mut self,
 9189        _: &AddSelectionBelow,
 9190        window: &mut Window,
 9191        cx: &mut Context<Self>,
 9192    ) {
 9193        self.add_selection(false, window, cx);
 9194    }
 9195
 9196    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9197        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9198        let mut selections = self.selections.all::<Point>(cx);
 9199        let text_layout_details = self.text_layout_details(window);
 9200        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9201            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9202            let range = oldest_selection.display_range(&display_map).sorted();
 9203
 9204            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9205            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9206            let positions = start_x.min(end_x)..start_x.max(end_x);
 9207
 9208            selections.clear();
 9209            let mut stack = Vec::new();
 9210            for row in range.start.row().0..=range.end.row().0 {
 9211                if let Some(selection) = self.selections.build_columnar_selection(
 9212                    &display_map,
 9213                    DisplayRow(row),
 9214                    &positions,
 9215                    oldest_selection.reversed,
 9216                    &text_layout_details,
 9217                ) {
 9218                    stack.push(selection.id);
 9219                    selections.push(selection);
 9220                }
 9221            }
 9222
 9223            if above {
 9224                stack.reverse();
 9225            }
 9226
 9227            AddSelectionsState { above, stack }
 9228        });
 9229
 9230        let last_added_selection = *state.stack.last().unwrap();
 9231        let mut new_selections = Vec::new();
 9232        if above == state.above {
 9233            let end_row = if above {
 9234                DisplayRow(0)
 9235            } else {
 9236                display_map.max_point().row()
 9237            };
 9238
 9239            'outer: for selection in selections {
 9240                if selection.id == last_added_selection {
 9241                    let range = selection.display_range(&display_map).sorted();
 9242                    debug_assert_eq!(range.start.row(), range.end.row());
 9243                    let mut row = range.start.row();
 9244                    let positions =
 9245                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9246                            px(start)..px(end)
 9247                        } else {
 9248                            let start_x =
 9249                                display_map.x_for_display_point(range.start, &text_layout_details);
 9250                            let end_x =
 9251                                display_map.x_for_display_point(range.end, &text_layout_details);
 9252                            start_x.min(end_x)..start_x.max(end_x)
 9253                        };
 9254
 9255                    while row != end_row {
 9256                        if above {
 9257                            row.0 -= 1;
 9258                        } else {
 9259                            row.0 += 1;
 9260                        }
 9261
 9262                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9263                            &display_map,
 9264                            row,
 9265                            &positions,
 9266                            selection.reversed,
 9267                            &text_layout_details,
 9268                        ) {
 9269                            state.stack.push(new_selection.id);
 9270                            if above {
 9271                                new_selections.push(new_selection);
 9272                                new_selections.push(selection);
 9273                            } else {
 9274                                new_selections.push(selection);
 9275                                new_selections.push(new_selection);
 9276                            }
 9277
 9278                            continue 'outer;
 9279                        }
 9280                    }
 9281                }
 9282
 9283                new_selections.push(selection);
 9284            }
 9285        } else {
 9286            new_selections = selections;
 9287            new_selections.retain(|s| s.id != last_added_selection);
 9288            state.stack.pop();
 9289        }
 9290
 9291        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9292            s.select(new_selections);
 9293        });
 9294        if state.stack.len() > 1 {
 9295            self.add_selections_state = Some(state);
 9296        }
 9297    }
 9298
 9299    pub fn select_next_match_internal(
 9300        &mut self,
 9301        display_map: &DisplaySnapshot,
 9302        replace_newest: bool,
 9303        autoscroll: Option<Autoscroll>,
 9304        window: &mut Window,
 9305        cx: &mut Context<Self>,
 9306    ) -> Result<()> {
 9307        fn select_next_match_ranges(
 9308            this: &mut Editor,
 9309            range: Range<usize>,
 9310            replace_newest: bool,
 9311            auto_scroll: Option<Autoscroll>,
 9312            window: &mut Window,
 9313            cx: &mut Context<Editor>,
 9314        ) {
 9315            this.unfold_ranges(&[range.clone()], false, true, cx);
 9316            this.change_selections(auto_scroll, window, cx, |s| {
 9317                if replace_newest {
 9318                    s.delete(s.newest_anchor().id);
 9319                }
 9320                s.insert_range(range.clone());
 9321            });
 9322        }
 9323
 9324        let buffer = &display_map.buffer_snapshot;
 9325        let mut selections = self.selections.all::<usize>(cx);
 9326        if let Some(mut select_next_state) = self.select_next_state.take() {
 9327            let query = &select_next_state.query;
 9328            if !select_next_state.done {
 9329                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9330                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9331                let mut next_selected_range = None;
 9332
 9333                let bytes_after_last_selection =
 9334                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9335                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9336                let query_matches = query
 9337                    .stream_find_iter(bytes_after_last_selection)
 9338                    .map(|result| (last_selection.end, result))
 9339                    .chain(
 9340                        query
 9341                            .stream_find_iter(bytes_before_first_selection)
 9342                            .map(|result| (0, result)),
 9343                    );
 9344
 9345                for (start_offset, query_match) in query_matches {
 9346                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9347                    let offset_range =
 9348                        start_offset + query_match.start()..start_offset + query_match.end();
 9349                    let display_range = offset_range.start.to_display_point(display_map)
 9350                        ..offset_range.end.to_display_point(display_map);
 9351
 9352                    if !select_next_state.wordwise
 9353                        || (!movement::is_inside_word(display_map, display_range.start)
 9354                            && !movement::is_inside_word(display_map, display_range.end))
 9355                    {
 9356                        // TODO: This is n^2, because we might check all the selections
 9357                        if !selections
 9358                            .iter()
 9359                            .any(|selection| selection.range().overlaps(&offset_range))
 9360                        {
 9361                            next_selected_range = Some(offset_range);
 9362                            break;
 9363                        }
 9364                    }
 9365                }
 9366
 9367                if let Some(next_selected_range) = next_selected_range {
 9368                    select_next_match_ranges(
 9369                        self,
 9370                        next_selected_range,
 9371                        replace_newest,
 9372                        autoscroll,
 9373                        window,
 9374                        cx,
 9375                    );
 9376                } else {
 9377                    select_next_state.done = true;
 9378                }
 9379            }
 9380
 9381            self.select_next_state = Some(select_next_state);
 9382        } else {
 9383            let mut only_carets = true;
 9384            let mut same_text_selected = true;
 9385            let mut selected_text = None;
 9386
 9387            let mut selections_iter = selections.iter().peekable();
 9388            while let Some(selection) = selections_iter.next() {
 9389                if selection.start != selection.end {
 9390                    only_carets = false;
 9391                }
 9392
 9393                if same_text_selected {
 9394                    if selected_text.is_none() {
 9395                        selected_text =
 9396                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9397                    }
 9398
 9399                    if let Some(next_selection) = selections_iter.peek() {
 9400                        if next_selection.range().len() == selection.range().len() {
 9401                            let next_selected_text = buffer
 9402                                .text_for_range(next_selection.range())
 9403                                .collect::<String>();
 9404                            if Some(next_selected_text) != selected_text {
 9405                                same_text_selected = false;
 9406                                selected_text = None;
 9407                            }
 9408                        } else {
 9409                            same_text_selected = false;
 9410                            selected_text = None;
 9411                        }
 9412                    }
 9413                }
 9414            }
 9415
 9416            if only_carets {
 9417                for selection in &mut selections {
 9418                    let word_range = movement::surrounding_word(
 9419                        display_map,
 9420                        selection.start.to_display_point(display_map),
 9421                    );
 9422                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9423                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9424                    selection.goal = SelectionGoal::None;
 9425                    selection.reversed = false;
 9426                    select_next_match_ranges(
 9427                        self,
 9428                        selection.start..selection.end,
 9429                        replace_newest,
 9430                        autoscroll,
 9431                        window,
 9432                        cx,
 9433                    );
 9434                }
 9435
 9436                if selections.len() == 1 {
 9437                    let selection = selections
 9438                        .last()
 9439                        .expect("ensured that there's only one selection");
 9440                    let query = buffer
 9441                        .text_for_range(selection.start..selection.end)
 9442                        .collect::<String>();
 9443                    let is_empty = query.is_empty();
 9444                    let select_state = SelectNextState {
 9445                        query: AhoCorasick::new(&[query])?,
 9446                        wordwise: true,
 9447                        done: is_empty,
 9448                    };
 9449                    self.select_next_state = Some(select_state);
 9450                } else {
 9451                    self.select_next_state = None;
 9452                }
 9453            } else if let Some(selected_text) = selected_text {
 9454                self.select_next_state = Some(SelectNextState {
 9455                    query: AhoCorasick::new(&[selected_text])?,
 9456                    wordwise: false,
 9457                    done: false,
 9458                });
 9459                self.select_next_match_internal(
 9460                    display_map,
 9461                    replace_newest,
 9462                    autoscroll,
 9463                    window,
 9464                    cx,
 9465                )?;
 9466            }
 9467        }
 9468        Ok(())
 9469    }
 9470
 9471    pub fn select_all_matches(
 9472        &mut self,
 9473        _action: &SelectAllMatches,
 9474        window: &mut Window,
 9475        cx: &mut Context<Self>,
 9476    ) -> Result<()> {
 9477        self.push_to_selection_history();
 9478        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9479
 9480        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9481        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9482            return Ok(());
 9483        };
 9484        if select_next_state.done {
 9485            return Ok(());
 9486        }
 9487
 9488        let mut new_selections = self.selections.all::<usize>(cx);
 9489
 9490        let buffer = &display_map.buffer_snapshot;
 9491        let query_matches = select_next_state
 9492            .query
 9493            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9494
 9495        for query_match in query_matches {
 9496            let query_match = query_match.unwrap(); // can only fail due to I/O
 9497            let offset_range = query_match.start()..query_match.end();
 9498            let display_range = offset_range.start.to_display_point(&display_map)
 9499                ..offset_range.end.to_display_point(&display_map);
 9500
 9501            if !select_next_state.wordwise
 9502                || (!movement::is_inside_word(&display_map, display_range.start)
 9503                    && !movement::is_inside_word(&display_map, display_range.end))
 9504            {
 9505                self.selections.change_with(cx, |selections| {
 9506                    new_selections.push(Selection {
 9507                        id: selections.new_selection_id(),
 9508                        start: offset_range.start,
 9509                        end: offset_range.end,
 9510                        reversed: false,
 9511                        goal: SelectionGoal::None,
 9512                    });
 9513                });
 9514            }
 9515        }
 9516
 9517        new_selections.sort_by_key(|selection| selection.start);
 9518        let mut ix = 0;
 9519        while ix + 1 < new_selections.len() {
 9520            let current_selection = &new_selections[ix];
 9521            let next_selection = &new_selections[ix + 1];
 9522            if current_selection.range().overlaps(&next_selection.range()) {
 9523                if current_selection.id < next_selection.id {
 9524                    new_selections.remove(ix + 1);
 9525                } else {
 9526                    new_selections.remove(ix);
 9527                }
 9528            } else {
 9529                ix += 1;
 9530            }
 9531        }
 9532
 9533        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9534
 9535        for selection in new_selections.iter_mut() {
 9536            selection.reversed = reversed;
 9537        }
 9538
 9539        select_next_state.done = true;
 9540        self.unfold_ranges(
 9541            &new_selections
 9542                .iter()
 9543                .map(|selection| selection.range())
 9544                .collect::<Vec<_>>(),
 9545            false,
 9546            false,
 9547            cx,
 9548        );
 9549        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9550            selections.select(new_selections)
 9551        });
 9552
 9553        Ok(())
 9554    }
 9555
 9556    pub fn select_next(
 9557        &mut self,
 9558        action: &SelectNext,
 9559        window: &mut Window,
 9560        cx: &mut Context<Self>,
 9561    ) -> Result<()> {
 9562        self.push_to_selection_history();
 9563        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9564        self.select_next_match_internal(
 9565            &display_map,
 9566            action.replace_newest,
 9567            Some(Autoscroll::newest()),
 9568            window,
 9569            cx,
 9570        )?;
 9571        Ok(())
 9572    }
 9573
 9574    pub fn select_previous(
 9575        &mut self,
 9576        action: &SelectPrevious,
 9577        window: &mut Window,
 9578        cx: &mut Context<Self>,
 9579    ) -> Result<()> {
 9580        self.push_to_selection_history();
 9581        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9582        let buffer = &display_map.buffer_snapshot;
 9583        let mut selections = self.selections.all::<usize>(cx);
 9584        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9585            let query = &select_prev_state.query;
 9586            if !select_prev_state.done {
 9587                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9588                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9589                let mut next_selected_range = None;
 9590                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9591                let bytes_before_last_selection =
 9592                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9593                let bytes_after_first_selection =
 9594                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9595                let query_matches = query
 9596                    .stream_find_iter(bytes_before_last_selection)
 9597                    .map(|result| (last_selection.start, result))
 9598                    .chain(
 9599                        query
 9600                            .stream_find_iter(bytes_after_first_selection)
 9601                            .map(|result| (buffer.len(), result)),
 9602                    );
 9603                for (end_offset, query_match) in query_matches {
 9604                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9605                    let offset_range =
 9606                        end_offset - query_match.end()..end_offset - query_match.start();
 9607                    let display_range = offset_range.start.to_display_point(&display_map)
 9608                        ..offset_range.end.to_display_point(&display_map);
 9609
 9610                    if !select_prev_state.wordwise
 9611                        || (!movement::is_inside_word(&display_map, display_range.start)
 9612                            && !movement::is_inside_word(&display_map, display_range.end))
 9613                    {
 9614                        next_selected_range = Some(offset_range);
 9615                        break;
 9616                    }
 9617                }
 9618
 9619                if let Some(next_selected_range) = next_selected_range {
 9620                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9621                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9622                        if action.replace_newest {
 9623                            s.delete(s.newest_anchor().id);
 9624                        }
 9625                        s.insert_range(next_selected_range);
 9626                    });
 9627                } else {
 9628                    select_prev_state.done = true;
 9629                }
 9630            }
 9631
 9632            self.select_prev_state = Some(select_prev_state);
 9633        } else {
 9634            let mut only_carets = true;
 9635            let mut same_text_selected = true;
 9636            let mut selected_text = None;
 9637
 9638            let mut selections_iter = selections.iter().peekable();
 9639            while let Some(selection) = selections_iter.next() {
 9640                if selection.start != selection.end {
 9641                    only_carets = false;
 9642                }
 9643
 9644                if same_text_selected {
 9645                    if selected_text.is_none() {
 9646                        selected_text =
 9647                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9648                    }
 9649
 9650                    if let Some(next_selection) = selections_iter.peek() {
 9651                        if next_selection.range().len() == selection.range().len() {
 9652                            let next_selected_text = buffer
 9653                                .text_for_range(next_selection.range())
 9654                                .collect::<String>();
 9655                            if Some(next_selected_text) != selected_text {
 9656                                same_text_selected = false;
 9657                                selected_text = None;
 9658                            }
 9659                        } else {
 9660                            same_text_selected = false;
 9661                            selected_text = None;
 9662                        }
 9663                    }
 9664                }
 9665            }
 9666
 9667            if only_carets {
 9668                for selection in &mut selections {
 9669                    let word_range = movement::surrounding_word(
 9670                        &display_map,
 9671                        selection.start.to_display_point(&display_map),
 9672                    );
 9673                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9674                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9675                    selection.goal = SelectionGoal::None;
 9676                    selection.reversed = false;
 9677                }
 9678                if selections.len() == 1 {
 9679                    let selection = selections
 9680                        .last()
 9681                        .expect("ensured that there's only one selection");
 9682                    let query = buffer
 9683                        .text_for_range(selection.start..selection.end)
 9684                        .collect::<String>();
 9685                    let is_empty = query.is_empty();
 9686                    let select_state = SelectNextState {
 9687                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9688                        wordwise: true,
 9689                        done: is_empty,
 9690                    };
 9691                    self.select_prev_state = Some(select_state);
 9692                } else {
 9693                    self.select_prev_state = None;
 9694                }
 9695
 9696                self.unfold_ranges(
 9697                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9698                    false,
 9699                    true,
 9700                    cx,
 9701                );
 9702                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9703                    s.select(selections);
 9704                });
 9705            } else if let Some(selected_text) = selected_text {
 9706                self.select_prev_state = Some(SelectNextState {
 9707                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9708                    wordwise: false,
 9709                    done: false,
 9710                });
 9711                self.select_previous(action, window, cx)?;
 9712            }
 9713        }
 9714        Ok(())
 9715    }
 9716
 9717    pub fn toggle_comments(
 9718        &mut self,
 9719        action: &ToggleComments,
 9720        window: &mut Window,
 9721        cx: &mut Context<Self>,
 9722    ) {
 9723        if self.read_only(cx) {
 9724            return;
 9725        }
 9726        let text_layout_details = &self.text_layout_details(window);
 9727        self.transact(window, cx, |this, window, cx| {
 9728            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9729            let mut edits = Vec::new();
 9730            let mut selection_edit_ranges = Vec::new();
 9731            let mut last_toggled_row = None;
 9732            let snapshot = this.buffer.read(cx).read(cx);
 9733            let empty_str: Arc<str> = Arc::default();
 9734            let mut suffixes_inserted = Vec::new();
 9735            let ignore_indent = action.ignore_indent;
 9736
 9737            fn comment_prefix_range(
 9738                snapshot: &MultiBufferSnapshot,
 9739                row: MultiBufferRow,
 9740                comment_prefix: &str,
 9741                comment_prefix_whitespace: &str,
 9742                ignore_indent: bool,
 9743            ) -> Range<Point> {
 9744                let indent_size = if ignore_indent {
 9745                    0
 9746                } else {
 9747                    snapshot.indent_size_for_line(row).len
 9748                };
 9749
 9750                let start = Point::new(row.0, indent_size);
 9751
 9752                let mut line_bytes = snapshot
 9753                    .bytes_in_range(start..snapshot.max_point())
 9754                    .flatten()
 9755                    .copied();
 9756
 9757                // If this line currently begins with the line comment prefix, then record
 9758                // the range containing the prefix.
 9759                if line_bytes
 9760                    .by_ref()
 9761                    .take(comment_prefix.len())
 9762                    .eq(comment_prefix.bytes())
 9763                {
 9764                    // Include any whitespace that matches the comment prefix.
 9765                    let matching_whitespace_len = line_bytes
 9766                        .zip(comment_prefix_whitespace.bytes())
 9767                        .take_while(|(a, b)| a == b)
 9768                        .count() as u32;
 9769                    let end = Point::new(
 9770                        start.row,
 9771                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9772                    );
 9773                    start..end
 9774                } else {
 9775                    start..start
 9776                }
 9777            }
 9778
 9779            fn comment_suffix_range(
 9780                snapshot: &MultiBufferSnapshot,
 9781                row: MultiBufferRow,
 9782                comment_suffix: &str,
 9783                comment_suffix_has_leading_space: bool,
 9784            ) -> Range<Point> {
 9785                let end = Point::new(row.0, snapshot.line_len(row));
 9786                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9787
 9788                let mut line_end_bytes = snapshot
 9789                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9790                    .flatten()
 9791                    .copied();
 9792
 9793                let leading_space_len = if suffix_start_column > 0
 9794                    && line_end_bytes.next() == Some(b' ')
 9795                    && comment_suffix_has_leading_space
 9796                {
 9797                    1
 9798                } else {
 9799                    0
 9800                };
 9801
 9802                // If this line currently begins with the line comment prefix, then record
 9803                // the range containing the prefix.
 9804                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9805                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9806                    start..end
 9807                } else {
 9808                    end..end
 9809                }
 9810            }
 9811
 9812            // TODO: Handle selections that cross excerpts
 9813            for selection in &mut selections {
 9814                let start_column = snapshot
 9815                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9816                    .len;
 9817                let language = if let Some(language) =
 9818                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9819                {
 9820                    language
 9821                } else {
 9822                    continue;
 9823                };
 9824
 9825                selection_edit_ranges.clear();
 9826
 9827                // If multiple selections contain a given row, avoid processing that
 9828                // row more than once.
 9829                let mut start_row = MultiBufferRow(selection.start.row);
 9830                if last_toggled_row == Some(start_row) {
 9831                    start_row = start_row.next_row();
 9832                }
 9833                let end_row =
 9834                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9835                        MultiBufferRow(selection.end.row - 1)
 9836                    } else {
 9837                        MultiBufferRow(selection.end.row)
 9838                    };
 9839                last_toggled_row = Some(end_row);
 9840
 9841                if start_row > end_row {
 9842                    continue;
 9843                }
 9844
 9845                // If the language has line comments, toggle those.
 9846                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9847
 9848                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9849                if ignore_indent {
 9850                    full_comment_prefixes = full_comment_prefixes
 9851                        .into_iter()
 9852                        .map(|s| Arc::from(s.trim_end()))
 9853                        .collect();
 9854                }
 9855
 9856                if !full_comment_prefixes.is_empty() {
 9857                    let first_prefix = full_comment_prefixes
 9858                        .first()
 9859                        .expect("prefixes is non-empty");
 9860                    let prefix_trimmed_lengths = full_comment_prefixes
 9861                        .iter()
 9862                        .map(|p| p.trim_end_matches(' ').len())
 9863                        .collect::<SmallVec<[usize; 4]>>();
 9864
 9865                    let mut all_selection_lines_are_comments = true;
 9866
 9867                    for row in start_row.0..=end_row.0 {
 9868                        let row = MultiBufferRow(row);
 9869                        if start_row < end_row && snapshot.is_line_blank(row) {
 9870                            continue;
 9871                        }
 9872
 9873                        let prefix_range = full_comment_prefixes
 9874                            .iter()
 9875                            .zip(prefix_trimmed_lengths.iter().copied())
 9876                            .map(|(prefix, trimmed_prefix_len)| {
 9877                                comment_prefix_range(
 9878                                    snapshot.deref(),
 9879                                    row,
 9880                                    &prefix[..trimmed_prefix_len],
 9881                                    &prefix[trimmed_prefix_len..],
 9882                                    ignore_indent,
 9883                                )
 9884                            })
 9885                            .max_by_key(|range| range.end.column - range.start.column)
 9886                            .expect("prefixes is non-empty");
 9887
 9888                        if prefix_range.is_empty() {
 9889                            all_selection_lines_are_comments = false;
 9890                        }
 9891
 9892                        selection_edit_ranges.push(prefix_range);
 9893                    }
 9894
 9895                    if all_selection_lines_are_comments {
 9896                        edits.extend(
 9897                            selection_edit_ranges
 9898                                .iter()
 9899                                .cloned()
 9900                                .map(|range| (range, empty_str.clone())),
 9901                        );
 9902                    } else {
 9903                        let min_column = selection_edit_ranges
 9904                            .iter()
 9905                            .map(|range| range.start.column)
 9906                            .min()
 9907                            .unwrap_or(0);
 9908                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9909                            let position = Point::new(range.start.row, min_column);
 9910                            (position..position, first_prefix.clone())
 9911                        }));
 9912                    }
 9913                } else if let Some((full_comment_prefix, comment_suffix)) =
 9914                    language.block_comment_delimiters()
 9915                {
 9916                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9917                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9918                    let prefix_range = comment_prefix_range(
 9919                        snapshot.deref(),
 9920                        start_row,
 9921                        comment_prefix,
 9922                        comment_prefix_whitespace,
 9923                        ignore_indent,
 9924                    );
 9925                    let suffix_range = comment_suffix_range(
 9926                        snapshot.deref(),
 9927                        end_row,
 9928                        comment_suffix.trim_start_matches(' '),
 9929                        comment_suffix.starts_with(' '),
 9930                    );
 9931
 9932                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9933                        edits.push((
 9934                            prefix_range.start..prefix_range.start,
 9935                            full_comment_prefix.clone(),
 9936                        ));
 9937                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9938                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9939                    } else {
 9940                        edits.push((prefix_range, empty_str.clone()));
 9941                        edits.push((suffix_range, empty_str.clone()));
 9942                    }
 9943                } else {
 9944                    continue;
 9945                }
 9946            }
 9947
 9948            drop(snapshot);
 9949            this.buffer.update(cx, |buffer, cx| {
 9950                buffer.edit(edits, None, cx);
 9951            });
 9952
 9953            // Adjust selections so that they end before any comment suffixes that
 9954            // were inserted.
 9955            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9956            let mut selections = this.selections.all::<Point>(cx);
 9957            let snapshot = this.buffer.read(cx).read(cx);
 9958            for selection in &mut selections {
 9959                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9960                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9961                        Ordering::Less => {
 9962                            suffixes_inserted.next();
 9963                            continue;
 9964                        }
 9965                        Ordering::Greater => break,
 9966                        Ordering::Equal => {
 9967                            if selection.end.column == snapshot.line_len(row) {
 9968                                if selection.is_empty() {
 9969                                    selection.start.column -= suffix_len as u32;
 9970                                }
 9971                                selection.end.column -= suffix_len as u32;
 9972                            }
 9973                            break;
 9974                        }
 9975                    }
 9976                }
 9977            }
 9978
 9979            drop(snapshot);
 9980            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9981                s.select(selections)
 9982            });
 9983
 9984            let selections = this.selections.all::<Point>(cx);
 9985            let selections_on_single_row = selections.windows(2).all(|selections| {
 9986                selections[0].start.row == selections[1].start.row
 9987                    && selections[0].end.row == selections[1].end.row
 9988                    && selections[0].start.row == selections[0].end.row
 9989            });
 9990            let selections_selecting = selections
 9991                .iter()
 9992                .any(|selection| selection.start != selection.end);
 9993            let advance_downwards = action.advance_downwards
 9994                && selections_on_single_row
 9995                && !selections_selecting
 9996                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9997
 9998            if advance_downwards {
 9999                let snapshot = this.buffer.read(cx).snapshot(cx);
10000
10001                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10002                    s.move_cursors_with(|display_snapshot, display_point, _| {
10003                        let mut point = display_point.to_point(display_snapshot);
10004                        point.row += 1;
10005                        point = snapshot.clip_point(point, Bias::Left);
10006                        let display_point = point.to_display_point(display_snapshot);
10007                        let goal = SelectionGoal::HorizontalPosition(
10008                            display_snapshot
10009                                .x_for_display_point(display_point, text_layout_details)
10010                                .into(),
10011                        );
10012                        (display_point, goal)
10013                    })
10014                });
10015            }
10016        });
10017    }
10018
10019    pub fn select_enclosing_symbol(
10020        &mut self,
10021        _: &SelectEnclosingSymbol,
10022        window: &mut Window,
10023        cx: &mut Context<Self>,
10024    ) {
10025        let buffer = self.buffer.read(cx).snapshot(cx);
10026        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10027
10028        fn update_selection(
10029            selection: &Selection<usize>,
10030            buffer_snap: &MultiBufferSnapshot,
10031        ) -> Option<Selection<usize>> {
10032            let cursor = selection.head();
10033            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10034            for symbol in symbols.iter().rev() {
10035                let start = symbol.range.start.to_offset(buffer_snap);
10036                let end = symbol.range.end.to_offset(buffer_snap);
10037                let new_range = start..end;
10038                if start < selection.start || end > selection.end {
10039                    return Some(Selection {
10040                        id: selection.id,
10041                        start: new_range.start,
10042                        end: new_range.end,
10043                        goal: SelectionGoal::None,
10044                        reversed: selection.reversed,
10045                    });
10046                }
10047            }
10048            None
10049        }
10050
10051        let mut selected_larger_symbol = false;
10052        let new_selections = old_selections
10053            .iter()
10054            .map(|selection| match update_selection(selection, &buffer) {
10055                Some(new_selection) => {
10056                    if new_selection.range() != selection.range() {
10057                        selected_larger_symbol = true;
10058                    }
10059                    new_selection
10060                }
10061                None => selection.clone(),
10062            })
10063            .collect::<Vec<_>>();
10064
10065        if selected_larger_symbol {
10066            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10067                s.select(new_selections);
10068            });
10069        }
10070    }
10071
10072    pub fn select_larger_syntax_node(
10073        &mut self,
10074        _: &SelectLargerSyntaxNode,
10075        window: &mut Window,
10076        cx: &mut Context<Self>,
10077    ) {
10078        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10079        let buffer = self.buffer.read(cx).snapshot(cx);
10080        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10081
10082        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10083        let mut selected_larger_node = false;
10084        let new_selections = old_selections
10085            .iter()
10086            .map(|selection| {
10087                let old_range = selection.start..selection.end;
10088                let mut new_range = old_range.clone();
10089                let mut new_node = None;
10090                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10091                {
10092                    new_node = Some(node);
10093                    new_range = containing_range;
10094                    if !display_map.intersects_fold(new_range.start)
10095                        && !display_map.intersects_fold(new_range.end)
10096                    {
10097                        break;
10098                    }
10099                }
10100
10101                if let Some(node) = new_node {
10102                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10103                    // nodes. Parent and grandparent are also logged because this operation will not
10104                    // visit nodes that have the same range as their parent.
10105                    log::info!("Node: {node:?}");
10106                    let parent = node.parent();
10107                    log::info!("Parent: {parent:?}");
10108                    let grandparent = parent.and_then(|x| x.parent());
10109                    log::info!("Grandparent: {grandparent:?}");
10110                }
10111
10112                selected_larger_node |= new_range != old_range;
10113                Selection {
10114                    id: selection.id,
10115                    start: new_range.start,
10116                    end: new_range.end,
10117                    goal: SelectionGoal::None,
10118                    reversed: selection.reversed,
10119                }
10120            })
10121            .collect::<Vec<_>>();
10122
10123        if selected_larger_node {
10124            stack.push(old_selections);
10125            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10126                s.select(new_selections);
10127            });
10128        }
10129        self.select_larger_syntax_node_stack = stack;
10130    }
10131
10132    pub fn select_smaller_syntax_node(
10133        &mut self,
10134        _: &SelectSmallerSyntaxNode,
10135        window: &mut Window,
10136        cx: &mut Context<Self>,
10137    ) {
10138        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10139        if let Some(selections) = stack.pop() {
10140            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10141                s.select(selections.to_vec());
10142            });
10143        }
10144        self.select_larger_syntax_node_stack = stack;
10145    }
10146
10147    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10148        if !EditorSettings::get_global(cx).gutter.runnables {
10149            self.clear_tasks();
10150            return Task::ready(());
10151        }
10152        let project = self.project.as_ref().map(Entity::downgrade);
10153        cx.spawn_in(window, |this, mut cx| async move {
10154            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10155            let Some(project) = project.and_then(|p| p.upgrade()) else {
10156                return;
10157            };
10158            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10159                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10160            }) else {
10161                return;
10162            };
10163
10164            let hide_runnables = project
10165                .update(&mut cx, |project, cx| {
10166                    // Do not display any test indicators in non-dev server remote projects.
10167                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10168                })
10169                .unwrap_or(true);
10170            if hide_runnables {
10171                return;
10172            }
10173            let new_rows =
10174                cx.background_spawn({
10175                    let snapshot = display_snapshot.clone();
10176                    async move {
10177                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10178                    }
10179                })
10180                    .await;
10181
10182            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10183            this.update(&mut cx, |this, _| {
10184                this.clear_tasks();
10185                for (key, value) in rows {
10186                    this.insert_tasks(key, value);
10187                }
10188            })
10189            .ok();
10190        })
10191    }
10192    fn fetch_runnable_ranges(
10193        snapshot: &DisplaySnapshot,
10194        range: Range<Anchor>,
10195    ) -> Vec<language::RunnableRange> {
10196        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10197    }
10198
10199    fn runnable_rows(
10200        project: Entity<Project>,
10201        snapshot: DisplaySnapshot,
10202        runnable_ranges: Vec<RunnableRange>,
10203        mut cx: AsyncWindowContext,
10204    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10205        runnable_ranges
10206            .into_iter()
10207            .filter_map(|mut runnable| {
10208                let tasks = cx
10209                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10210                    .ok()?;
10211                if tasks.is_empty() {
10212                    return None;
10213                }
10214
10215                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10216
10217                let row = snapshot
10218                    .buffer_snapshot
10219                    .buffer_line_for_row(MultiBufferRow(point.row))?
10220                    .1
10221                    .start
10222                    .row;
10223
10224                let context_range =
10225                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10226                Some((
10227                    (runnable.buffer_id, row),
10228                    RunnableTasks {
10229                        templates: tasks,
10230                        offset: MultiBufferOffset(runnable.run_range.start),
10231                        context_range,
10232                        column: point.column,
10233                        extra_variables: runnable.extra_captures,
10234                    },
10235                ))
10236            })
10237            .collect()
10238    }
10239
10240    fn templates_with_tags(
10241        project: &Entity<Project>,
10242        runnable: &mut Runnable,
10243        cx: &mut App,
10244    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10245        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10246            let (worktree_id, file) = project
10247                .buffer_for_id(runnable.buffer, cx)
10248                .and_then(|buffer| buffer.read(cx).file())
10249                .map(|file| (file.worktree_id(cx), file.clone()))
10250                .unzip();
10251
10252            (
10253                project.task_store().read(cx).task_inventory().cloned(),
10254                worktree_id,
10255                file,
10256            )
10257        });
10258
10259        let tags = mem::take(&mut runnable.tags);
10260        let mut tags: Vec<_> = tags
10261            .into_iter()
10262            .flat_map(|tag| {
10263                let tag = tag.0.clone();
10264                inventory
10265                    .as_ref()
10266                    .into_iter()
10267                    .flat_map(|inventory| {
10268                        inventory.read(cx).list_tasks(
10269                            file.clone(),
10270                            Some(runnable.language.clone()),
10271                            worktree_id,
10272                            cx,
10273                        )
10274                    })
10275                    .filter(move |(_, template)| {
10276                        template.tags.iter().any(|source_tag| source_tag == &tag)
10277                    })
10278            })
10279            .sorted_by_key(|(kind, _)| kind.to_owned())
10280            .collect();
10281        if let Some((leading_tag_source, _)) = tags.first() {
10282            // Strongest source wins; if we have worktree tag binding, prefer that to
10283            // global and language bindings;
10284            // if we have a global binding, prefer that to language binding.
10285            let first_mismatch = tags
10286                .iter()
10287                .position(|(tag_source, _)| tag_source != leading_tag_source);
10288            if let Some(index) = first_mismatch {
10289                tags.truncate(index);
10290            }
10291        }
10292
10293        tags
10294    }
10295
10296    pub fn move_to_enclosing_bracket(
10297        &mut self,
10298        _: &MoveToEnclosingBracket,
10299        window: &mut Window,
10300        cx: &mut Context<Self>,
10301    ) {
10302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10303            s.move_offsets_with(|snapshot, selection| {
10304                let Some(enclosing_bracket_ranges) =
10305                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10306                else {
10307                    return;
10308                };
10309
10310                let mut best_length = usize::MAX;
10311                let mut best_inside = false;
10312                let mut best_in_bracket_range = false;
10313                let mut best_destination = None;
10314                for (open, close) in enclosing_bracket_ranges {
10315                    let close = close.to_inclusive();
10316                    let length = close.end() - open.start;
10317                    let inside = selection.start >= open.end && selection.end <= *close.start();
10318                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10319                        || close.contains(&selection.head());
10320
10321                    // If best is next to a bracket and current isn't, skip
10322                    if !in_bracket_range && best_in_bracket_range {
10323                        continue;
10324                    }
10325
10326                    // Prefer smaller lengths unless best is inside and current isn't
10327                    if length > best_length && (best_inside || !inside) {
10328                        continue;
10329                    }
10330
10331                    best_length = length;
10332                    best_inside = inside;
10333                    best_in_bracket_range = in_bracket_range;
10334                    best_destination = Some(
10335                        if close.contains(&selection.start) && close.contains(&selection.end) {
10336                            if inside {
10337                                open.end
10338                            } else {
10339                                open.start
10340                            }
10341                        } else if inside {
10342                            *close.start()
10343                        } else {
10344                            *close.end()
10345                        },
10346                    );
10347                }
10348
10349                if let Some(destination) = best_destination {
10350                    selection.collapse_to(destination, SelectionGoal::None);
10351                }
10352            })
10353        });
10354    }
10355
10356    pub fn undo_selection(
10357        &mut self,
10358        _: &UndoSelection,
10359        window: &mut Window,
10360        cx: &mut Context<Self>,
10361    ) {
10362        self.end_selection(window, cx);
10363        self.selection_history.mode = SelectionHistoryMode::Undoing;
10364        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10365            self.change_selections(None, window, cx, |s| {
10366                s.select_anchors(entry.selections.to_vec())
10367            });
10368            self.select_next_state = entry.select_next_state;
10369            self.select_prev_state = entry.select_prev_state;
10370            self.add_selections_state = entry.add_selections_state;
10371            self.request_autoscroll(Autoscroll::newest(), cx);
10372        }
10373        self.selection_history.mode = SelectionHistoryMode::Normal;
10374    }
10375
10376    pub fn redo_selection(
10377        &mut self,
10378        _: &RedoSelection,
10379        window: &mut Window,
10380        cx: &mut Context<Self>,
10381    ) {
10382        self.end_selection(window, cx);
10383        self.selection_history.mode = SelectionHistoryMode::Redoing;
10384        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10385            self.change_selections(None, window, cx, |s| {
10386                s.select_anchors(entry.selections.to_vec())
10387            });
10388            self.select_next_state = entry.select_next_state;
10389            self.select_prev_state = entry.select_prev_state;
10390            self.add_selections_state = entry.add_selections_state;
10391            self.request_autoscroll(Autoscroll::newest(), cx);
10392        }
10393        self.selection_history.mode = SelectionHistoryMode::Normal;
10394    }
10395
10396    pub fn expand_excerpts(
10397        &mut self,
10398        action: &ExpandExcerpts,
10399        _: &mut Window,
10400        cx: &mut Context<Self>,
10401    ) {
10402        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10403    }
10404
10405    pub fn expand_excerpts_down(
10406        &mut self,
10407        action: &ExpandExcerptsDown,
10408        _: &mut Window,
10409        cx: &mut Context<Self>,
10410    ) {
10411        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10412    }
10413
10414    pub fn expand_excerpts_up(
10415        &mut self,
10416        action: &ExpandExcerptsUp,
10417        _: &mut Window,
10418        cx: &mut Context<Self>,
10419    ) {
10420        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10421    }
10422
10423    pub fn expand_excerpts_for_direction(
10424        &mut self,
10425        lines: u32,
10426        direction: ExpandExcerptDirection,
10427
10428        cx: &mut Context<Self>,
10429    ) {
10430        let selections = self.selections.disjoint_anchors();
10431
10432        let lines = if lines == 0 {
10433            EditorSettings::get_global(cx).expand_excerpt_lines
10434        } else {
10435            lines
10436        };
10437
10438        self.buffer.update(cx, |buffer, cx| {
10439            let snapshot = buffer.snapshot(cx);
10440            let mut excerpt_ids = selections
10441                .iter()
10442                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10443                .collect::<Vec<_>>();
10444            excerpt_ids.sort();
10445            excerpt_ids.dedup();
10446            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10447        })
10448    }
10449
10450    pub fn expand_excerpt(
10451        &mut self,
10452        excerpt: ExcerptId,
10453        direction: ExpandExcerptDirection,
10454        cx: &mut Context<Self>,
10455    ) {
10456        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10457        self.buffer.update(cx, |buffer, cx| {
10458            buffer.expand_excerpts([excerpt], lines, direction, cx)
10459        })
10460    }
10461
10462    pub fn go_to_singleton_buffer_point(
10463        &mut self,
10464        point: Point,
10465        window: &mut Window,
10466        cx: &mut Context<Self>,
10467    ) {
10468        self.go_to_singleton_buffer_range(point..point, window, cx);
10469    }
10470
10471    pub fn go_to_singleton_buffer_range(
10472        &mut self,
10473        range: Range<Point>,
10474        window: &mut Window,
10475        cx: &mut Context<Self>,
10476    ) {
10477        let multibuffer = self.buffer().read(cx);
10478        let Some(buffer) = multibuffer.as_singleton() else {
10479            return;
10480        };
10481        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10482            return;
10483        };
10484        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10485            return;
10486        };
10487        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10488            s.select_anchor_ranges([start..end])
10489        });
10490    }
10491
10492    fn go_to_diagnostic(
10493        &mut self,
10494        _: &GoToDiagnostic,
10495        window: &mut Window,
10496        cx: &mut Context<Self>,
10497    ) {
10498        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10499    }
10500
10501    fn go_to_prev_diagnostic(
10502        &mut self,
10503        _: &GoToPrevDiagnostic,
10504        window: &mut Window,
10505        cx: &mut Context<Self>,
10506    ) {
10507        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10508    }
10509
10510    pub fn go_to_diagnostic_impl(
10511        &mut self,
10512        direction: Direction,
10513        window: &mut Window,
10514        cx: &mut Context<Self>,
10515    ) {
10516        let buffer = self.buffer.read(cx).snapshot(cx);
10517        let selection = self.selections.newest::<usize>(cx);
10518
10519        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10520        if direction == Direction::Next {
10521            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10522                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10523                    return;
10524                };
10525                self.activate_diagnostics(
10526                    buffer_id,
10527                    popover.local_diagnostic.diagnostic.group_id,
10528                    window,
10529                    cx,
10530                );
10531                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10532                    let primary_range_start = active_diagnostics.primary_range.start;
10533                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10534                        let mut new_selection = s.newest_anchor().clone();
10535                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10536                        s.select_anchors(vec![new_selection.clone()]);
10537                    });
10538                    self.refresh_inline_completion(false, true, window, cx);
10539                }
10540                return;
10541            }
10542        }
10543
10544        let active_group_id = self
10545            .active_diagnostics
10546            .as_ref()
10547            .map(|active_group| active_group.group_id);
10548        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10549            active_diagnostics
10550                .primary_range
10551                .to_offset(&buffer)
10552                .to_inclusive()
10553        });
10554        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10555            if active_primary_range.contains(&selection.head()) {
10556                *active_primary_range.start()
10557            } else {
10558                selection.head()
10559            }
10560        } else {
10561            selection.head()
10562        };
10563
10564        let snapshot = self.snapshot(window, cx);
10565        let primary_diagnostics_before = buffer
10566            .diagnostics_in_range::<usize>(0..search_start)
10567            .filter(|entry| entry.diagnostic.is_primary)
10568            .filter(|entry| entry.range.start != entry.range.end)
10569            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10570            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10571            .collect::<Vec<_>>();
10572        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10573            primary_diagnostics_before
10574                .iter()
10575                .position(|entry| entry.diagnostic.group_id == active_group_id)
10576        });
10577
10578        let primary_diagnostics_after = buffer
10579            .diagnostics_in_range::<usize>(search_start..buffer.len())
10580            .filter(|entry| entry.diagnostic.is_primary)
10581            .filter(|entry| entry.range.start != entry.range.end)
10582            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10583            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10584            .collect::<Vec<_>>();
10585        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10586            primary_diagnostics_after
10587                .iter()
10588                .enumerate()
10589                .rev()
10590                .find_map(|(i, entry)| {
10591                    if entry.diagnostic.group_id == active_group_id {
10592                        Some(i)
10593                    } else {
10594                        None
10595                    }
10596                })
10597        });
10598
10599        let next_primary_diagnostic = match direction {
10600            Direction::Prev => primary_diagnostics_before
10601                .iter()
10602                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10603                .rev()
10604                .next(),
10605            Direction::Next => primary_diagnostics_after
10606                .iter()
10607                .skip(
10608                    last_same_group_diagnostic_after
10609                        .map(|index| index + 1)
10610                        .unwrap_or(0),
10611                )
10612                .next(),
10613        };
10614
10615        // Cycle around to the start of the buffer, potentially moving back to the start of
10616        // the currently active diagnostic.
10617        let cycle_around = || match direction {
10618            Direction::Prev => primary_diagnostics_after
10619                .iter()
10620                .rev()
10621                .chain(primary_diagnostics_before.iter().rev())
10622                .next(),
10623            Direction::Next => primary_diagnostics_before
10624                .iter()
10625                .chain(primary_diagnostics_after.iter())
10626                .next(),
10627        };
10628
10629        if let Some((primary_range, group_id)) = next_primary_diagnostic
10630            .or_else(cycle_around)
10631            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10632        {
10633            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10634                return;
10635            };
10636            self.activate_diagnostics(buffer_id, group_id, window, cx);
10637            if self.active_diagnostics.is_some() {
10638                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10639                    s.select(vec![Selection {
10640                        id: selection.id,
10641                        start: primary_range.start,
10642                        end: primary_range.start,
10643                        reversed: false,
10644                        goal: SelectionGoal::None,
10645                    }]);
10646                });
10647                self.refresh_inline_completion(false, true, window, cx);
10648            }
10649        }
10650    }
10651
10652    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10653        let snapshot = self.snapshot(window, cx);
10654        let selection = self.selections.newest::<Point>(cx);
10655        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10656    }
10657
10658    fn go_to_hunk_after_position(
10659        &mut self,
10660        snapshot: &EditorSnapshot,
10661        position: Point,
10662        window: &mut Window,
10663        cx: &mut Context<Editor>,
10664    ) -> Option<MultiBufferDiffHunk> {
10665        let mut hunk = snapshot
10666            .buffer_snapshot
10667            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10668            .find(|hunk| hunk.row_range.start.0 > position.row);
10669        if hunk.is_none() {
10670            hunk = snapshot
10671                .buffer_snapshot
10672                .diff_hunks_in_range(Point::zero()..position)
10673                .find(|hunk| hunk.row_range.end.0 < position.row)
10674        }
10675        if let Some(hunk) = &hunk {
10676            let destination = Point::new(hunk.row_range.start.0, 0);
10677            self.unfold_ranges(&[destination..destination], false, false, cx);
10678            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10679                s.select_ranges(vec![destination..destination]);
10680            });
10681        }
10682
10683        hunk
10684    }
10685
10686    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10687        let snapshot = self.snapshot(window, cx);
10688        let selection = self.selections.newest::<Point>(cx);
10689        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10690    }
10691
10692    fn go_to_hunk_before_position(
10693        &mut self,
10694        snapshot: &EditorSnapshot,
10695        position: Point,
10696        window: &mut Window,
10697        cx: &mut Context<Editor>,
10698    ) -> Option<MultiBufferDiffHunk> {
10699        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10700        if hunk.is_none() {
10701            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10702        }
10703        if let Some(hunk) = &hunk {
10704            let destination = Point::new(hunk.row_range.start.0, 0);
10705            self.unfold_ranges(&[destination..destination], false, false, cx);
10706            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10707                s.select_ranges(vec![destination..destination]);
10708            });
10709        }
10710
10711        hunk
10712    }
10713
10714    pub fn go_to_definition(
10715        &mut self,
10716        _: &GoToDefinition,
10717        window: &mut Window,
10718        cx: &mut Context<Self>,
10719    ) -> Task<Result<Navigated>> {
10720        let definition =
10721            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10722        cx.spawn_in(window, |editor, mut cx| async move {
10723            if definition.await? == Navigated::Yes {
10724                return Ok(Navigated::Yes);
10725            }
10726            match editor.update_in(&mut cx, |editor, window, cx| {
10727                editor.find_all_references(&FindAllReferences, window, cx)
10728            })? {
10729                Some(references) => references.await,
10730                None => Ok(Navigated::No),
10731            }
10732        })
10733    }
10734
10735    pub fn go_to_declaration(
10736        &mut self,
10737        _: &GoToDeclaration,
10738        window: &mut Window,
10739        cx: &mut Context<Self>,
10740    ) -> Task<Result<Navigated>> {
10741        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10742    }
10743
10744    pub fn go_to_declaration_split(
10745        &mut self,
10746        _: &GoToDeclaration,
10747        window: &mut Window,
10748        cx: &mut Context<Self>,
10749    ) -> Task<Result<Navigated>> {
10750        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10751    }
10752
10753    pub fn go_to_implementation(
10754        &mut self,
10755        _: &GoToImplementation,
10756        window: &mut Window,
10757        cx: &mut Context<Self>,
10758    ) -> Task<Result<Navigated>> {
10759        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10760    }
10761
10762    pub fn go_to_implementation_split(
10763        &mut self,
10764        _: &GoToImplementationSplit,
10765        window: &mut Window,
10766        cx: &mut Context<Self>,
10767    ) -> Task<Result<Navigated>> {
10768        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10769    }
10770
10771    pub fn go_to_type_definition(
10772        &mut self,
10773        _: &GoToTypeDefinition,
10774        window: &mut Window,
10775        cx: &mut Context<Self>,
10776    ) -> Task<Result<Navigated>> {
10777        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10778    }
10779
10780    pub fn go_to_definition_split(
10781        &mut self,
10782        _: &GoToDefinitionSplit,
10783        window: &mut Window,
10784        cx: &mut Context<Self>,
10785    ) -> Task<Result<Navigated>> {
10786        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10787    }
10788
10789    pub fn go_to_type_definition_split(
10790        &mut self,
10791        _: &GoToTypeDefinitionSplit,
10792        window: &mut Window,
10793        cx: &mut Context<Self>,
10794    ) -> Task<Result<Navigated>> {
10795        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10796    }
10797
10798    fn go_to_definition_of_kind(
10799        &mut self,
10800        kind: GotoDefinitionKind,
10801        split: bool,
10802        window: &mut Window,
10803        cx: &mut Context<Self>,
10804    ) -> Task<Result<Navigated>> {
10805        let Some(provider) = self.semantics_provider.clone() else {
10806            return Task::ready(Ok(Navigated::No));
10807        };
10808        let head = self.selections.newest::<usize>(cx).head();
10809        let buffer = self.buffer.read(cx);
10810        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10811            text_anchor
10812        } else {
10813            return Task::ready(Ok(Navigated::No));
10814        };
10815
10816        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10817            return Task::ready(Ok(Navigated::No));
10818        };
10819
10820        cx.spawn_in(window, |editor, mut cx| async move {
10821            let definitions = definitions.await?;
10822            let navigated = editor
10823                .update_in(&mut cx, |editor, window, cx| {
10824                    editor.navigate_to_hover_links(
10825                        Some(kind),
10826                        definitions
10827                            .into_iter()
10828                            .filter(|location| {
10829                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10830                            })
10831                            .map(HoverLink::Text)
10832                            .collect::<Vec<_>>(),
10833                        split,
10834                        window,
10835                        cx,
10836                    )
10837                })?
10838                .await?;
10839            anyhow::Ok(navigated)
10840        })
10841    }
10842
10843    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10844        let selection = self.selections.newest_anchor();
10845        let head = selection.head();
10846        let tail = selection.tail();
10847
10848        let Some((buffer, start_position)) =
10849            self.buffer.read(cx).text_anchor_for_position(head, cx)
10850        else {
10851            return;
10852        };
10853
10854        let end_position = if head != tail {
10855            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10856                return;
10857            };
10858            Some(pos)
10859        } else {
10860            None
10861        };
10862
10863        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10864            let url = if let Some(end_pos) = end_position {
10865                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10866            } else {
10867                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10868            };
10869
10870            if let Some(url) = url {
10871                editor.update(&mut cx, |_, cx| {
10872                    cx.open_url(&url);
10873                })
10874            } else {
10875                Ok(())
10876            }
10877        });
10878
10879        url_finder.detach();
10880    }
10881
10882    pub fn open_selected_filename(
10883        &mut self,
10884        _: &OpenSelectedFilename,
10885        window: &mut Window,
10886        cx: &mut Context<Self>,
10887    ) {
10888        let Some(workspace) = self.workspace() else {
10889            return;
10890        };
10891
10892        let position = self.selections.newest_anchor().head();
10893
10894        let Some((buffer, buffer_position)) =
10895            self.buffer.read(cx).text_anchor_for_position(position, cx)
10896        else {
10897            return;
10898        };
10899
10900        let project = self.project.clone();
10901
10902        cx.spawn_in(window, |_, mut cx| async move {
10903            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10904
10905            if let Some((_, path)) = result {
10906                workspace
10907                    .update_in(&mut cx, |workspace, window, cx| {
10908                        workspace.open_resolved_path(path, window, cx)
10909                    })?
10910                    .await?;
10911            }
10912            anyhow::Ok(())
10913        })
10914        .detach();
10915    }
10916
10917    pub(crate) fn navigate_to_hover_links(
10918        &mut self,
10919        kind: Option<GotoDefinitionKind>,
10920        mut definitions: Vec<HoverLink>,
10921        split: bool,
10922        window: &mut Window,
10923        cx: &mut Context<Editor>,
10924    ) -> Task<Result<Navigated>> {
10925        // If there is one definition, just open it directly
10926        if definitions.len() == 1 {
10927            let definition = definitions.pop().unwrap();
10928
10929            enum TargetTaskResult {
10930                Location(Option<Location>),
10931                AlreadyNavigated,
10932            }
10933
10934            let target_task = match definition {
10935                HoverLink::Text(link) => {
10936                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10937                }
10938                HoverLink::InlayHint(lsp_location, server_id) => {
10939                    let computation =
10940                        self.compute_target_location(lsp_location, server_id, window, cx);
10941                    cx.background_spawn(async move {
10942                        let location = computation.await?;
10943                        Ok(TargetTaskResult::Location(location))
10944                    })
10945                }
10946                HoverLink::Url(url) => {
10947                    cx.open_url(&url);
10948                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10949                }
10950                HoverLink::File(path) => {
10951                    if let Some(workspace) = self.workspace() {
10952                        cx.spawn_in(window, |_, mut cx| async move {
10953                            workspace
10954                                .update_in(&mut cx, |workspace, window, cx| {
10955                                    workspace.open_resolved_path(path, window, cx)
10956                                })?
10957                                .await
10958                                .map(|_| TargetTaskResult::AlreadyNavigated)
10959                        })
10960                    } else {
10961                        Task::ready(Ok(TargetTaskResult::Location(None)))
10962                    }
10963                }
10964            };
10965            cx.spawn_in(window, |editor, mut cx| async move {
10966                let target = match target_task.await.context("target resolution task")? {
10967                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10968                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10969                    TargetTaskResult::Location(Some(target)) => target,
10970                };
10971
10972                editor.update_in(&mut cx, |editor, window, cx| {
10973                    let Some(workspace) = editor.workspace() else {
10974                        return Navigated::No;
10975                    };
10976                    let pane = workspace.read(cx).active_pane().clone();
10977
10978                    let range = target.range.to_point(target.buffer.read(cx));
10979                    let range = editor.range_for_match(&range);
10980                    let range = collapse_multiline_range(range);
10981
10982                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10983                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10984                    } else {
10985                        window.defer(cx, move |window, cx| {
10986                            let target_editor: Entity<Self> =
10987                                workspace.update(cx, |workspace, cx| {
10988                                    let pane = if split {
10989                                        workspace.adjacent_pane(window, cx)
10990                                    } else {
10991                                        workspace.active_pane().clone()
10992                                    };
10993
10994                                    workspace.open_project_item(
10995                                        pane,
10996                                        target.buffer.clone(),
10997                                        true,
10998                                        true,
10999                                        window,
11000                                        cx,
11001                                    )
11002                                });
11003                            target_editor.update(cx, |target_editor, cx| {
11004                                // When selecting a definition in a different buffer, disable the nav history
11005                                // to avoid creating a history entry at the previous cursor location.
11006                                pane.update(cx, |pane, _| pane.disable_history());
11007                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11008                                pane.update(cx, |pane, _| pane.enable_history());
11009                            });
11010                        });
11011                    }
11012                    Navigated::Yes
11013                })
11014            })
11015        } else if !definitions.is_empty() {
11016            cx.spawn_in(window, |editor, mut cx| async move {
11017                let (title, location_tasks, workspace) = editor
11018                    .update_in(&mut cx, |editor, window, cx| {
11019                        let tab_kind = match kind {
11020                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11021                            _ => "Definitions",
11022                        };
11023                        let title = definitions
11024                            .iter()
11025                            .find_map(|definition| match definition {
11026                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11027                                    let buffer = origin.buffer.read(cx);
11028                                    format!(
11029                                        "{} for {}",
11030                                        tab_kind,
11031                                        buffer
11032                                            .text_for_range(origin.range.clone())
11033                                            .collect::<String>()
11034                                    )
11035                                }),
11036                                HoverLink::InlayHint(_, _) => None,
11037                                HoverLink::Url(_) => None,
11038                                HoverLink::File(_) => None,
11039                            })
11040                            .unwrap_or(tab_kind.to_string());
11041                        let location_tasks = definitions
11042                            .into_iter()
11043                            .map(|definition| match definition {
11044                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11045                                HoverLink::InlayHint(lsp_location, server_id) => editor
11046                                    .compute_target_location(lsp_location, server_id, window, cx),
11047                                HoverLink::Url(_) => Task::ready(Ok(None)),
11048                                HoverLink::File(_) => Task::ready(Ok(None)),
11049                            })
11050                            .collect::<Vec<_>>();
11051                        (title, location_tasks, editor.workspace().clone())
11052                    })
11053                    .context("location tasks preparation")?;
11054
11055                let locations = future::join_all(location_tasks)
11056                    .await
11057                    .into_iter()
11058                    .filter_map(|location| location.transpose())
11059                    .collect::<Result<_>>()
11060                    .context("location tasks")?;
11061
11062                let Some(workspace) = workspace else {
11063                    return Ok(Navigated::No);
11064                };
11065                let opened = workspace
11066                    .update_in(&mut cx, |workspace, window, cx| {
11067                        Self::open_locations_in_multibuffer(
11068                            workspace,
11069                            locations,
11070                            title,
11071                            split,
11072                            MultibufferSelectionMode::First,
11073                            window,
11074                            cx,
11075                        )
11076                    })
11077                    .ok();
11078
11079                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11080            })
11081        } else {
11082            Task::ready(Ok(Navigated::No))
11083        }
11084    }
11085
11086    fn compute_target_location(
11087        &self,
11088        lsp_location: lsp::Location,
11089        server_id: LanguageServerId,
11090        window: &mut Window,
11091        cx: &mut Context<Self>,
11092    ) -> Task<anyhow::Result<Option<Location>>> {
11093        let Some(project) = self.project.clone() else {
11094            return Task::ready(Ok(None));
11095        };
11096
11097        cx.spawn_in(window, move |editor, mut cx| async move {
11098            let location_task = editor.update(&mut cx, |_, cx| {
11099                project.update(cx, |project, cx| {
11100                    let language_server_name = project
11101                        .language_server_statuses(cx)
11102                        .find(|(id, _)| server_id == *id)
11103                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11104                    language_server_name.map(|language_server_name| {
11105                        project.open_local_buffer_via_lsp(
11106                            lsp_location.uri.clone(),
11107                            server_id,
11108                            language_server_name,
11109                            cx,
11110                        )
11111                    })
11112                })
11113            })?;
11114            let location = match location_task {
11115                Some(task) => Some({
11116                    let target_buffer_handle = task.await.context("open local buffer")?;
11117                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11118                        let target_start = target_buffer
11119                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11120                        let target_end = target_buffer
11121                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11122                        target_buffer.anchor_after(target_start)
11123                            ..target_buffer.anchor_before(target_end)
11124                    })?;
11125                    Location {
11126                        buffer: target_buffer_handle,
11127                        range,
11128                    }
11129                }),
11130                None => None,
11131            };
11132            Ok(location)
11133        })
11134    }
11135
11136    pub fn find_all_references(
11137        &mut self,
11138        _: &FindAllReferences,
11139        window: &mut Window,
11140        cx: &mut Context<Self>,
11141    ) -> Option<Task<Result<Navigated>>> {
11142        let selection = self.selections.newest::<usize>(cx);
11143        let multi_buffer = self.buffer.read(cx);
11144        let head = selection.head();
11145
11146        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11147        let head_anchor = multi_buffer_snapshot.anchor_at(
11148            head,
11149            if head < selection.tail() {
11150                Bias::Right
11151            } else {
11152                Bias::Left
11153            },
11154        );
11155
11156        match self
11157            .find_all_references_task_sources
11158            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11159        {
11160            Ok(_) => {
11161                log::info!(
11162                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11163                );
11164                return None;
11165            }
11166            Err(i) => {
11167                self.find_all_references_task_sources.insert(i, head_anchor);
11168            }
11169        }
11170
11171        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11172        let workspace = self.workspace()?;
11173        let project = workspace.read(cx).project().clone();
11174        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11175        Some(cx.spawn_in(window, |editor, mut cx| async move {
11176            let _cleanup = defer({
11177                let mut cx = cx.clone();
11178                move || {
11179                    let _ = editor.update(&mut cx, |editor, _| {
11180                        if let Ok(i) =
11181                            editor
11182                                .find_all_references_task_sources
11183                                .binary_search_by(|anchor| {
11184                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11185                                })
11186                        {
11187                            editor.find_all_references_task_sources.remove(i);
11188                        }
11189                    });
11190                }
11191            });
11192
11193            let locations = references.await?;
11194            if locations.is_empty() {
11195                return anyhow::Ok(Navigated::No);
11196            }
11197
11198            workspace.update_in(&mut cx, |workspace, window, cx| {
11199                let title = locations
11200                    .first()
11201                    .as_ref()
11202                    .map(|location| {
11203                        let buffer = location.buffer.read(cx);
11204                        format!(
11205                            "References to `{}`",
11206                            buffer
11207                                .text_for_range(location.range.clone())
11208                                .collect::<String>()
11209                        )
11210                    })
11211                    .unwrap();
11212                Self::open_locations_in_multibuffer(
11213                    workspace,
11214                    locations,
11215                    title,
11216                    false,
11217                    MultibufferSelectionMode::First,
11218                    window,
11219                    cx,
11220                );
11221                Navigated::Yes
11222            })
11223        }))
11224    }
11225
11226    /// Opens a multibuffer with the given project locations in it
11227    pub fn open_locations_in_multibuffer(
11228        workspace: &mut Workspace,
11229        mut locations: Vec<Location>,
11230        title: String,
11231        split: bool,
11232        multibuffer_selection_mode: MultibufferSelectionMode,
11233        window: &mut Window,
11234        cx: &mut Context<Workspace>,
11235    ) {
11236        // If there are multiple definitions, open them in a multibuffer
11237        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11238        let mut locations = locations.into_iter().peekable();
11239        let mut ranges = Vec::new();
11240        let capability = workspace.project().read(cx).capability();
11241
11242        let excerpt_buffer = cx.new(|cx| {
11243            let mut multibuffer = MultiBuffer::new(capability);
11244            while let Some(location) = locations.next() {
11245                let buffer = location.buffer.read(cx);
11246                let mut ranges_for_buffer = Vec::new();
11247                let range = location.range.to_offset(buffer);
11248                ranges_for_buffer.push(range.clone());
11249
11250                while let Some(next_location) = locations.peek() {
11251                    if next_location.buffer == location.buffer {
11252                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11253                        locations.next();
11254                    } else {
11255                        break;
11256                    }
11257                }
11258
11259                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11260                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11261                    location.buffer.clone(),
11262                    ranges_for_buffer,
11263                    DEFAULT_MULTIBUFFER_CONTEXT,
11264                    cx,
11265                ))
11266            }
11267
11268            multibuffer.with_title(title)
11269        });
11270
11271        let editor = cx.new(|cx| {
11272            Editor::for_multibuffer(
11273                excerpt_buffer,
11274                Some(workspace.project().clone()),
11275                true,
11276                window,
11277                cx,
11278            )
11279        });
11280        editor.update(cx, |editor, cx| {
11281            match multibuffer_selection_mode {
11282                MultibufferSelectionMode::First => {
11283                    if let Some(first_range) = ranges.first() {
11284                        editor.change_selections(None, window, cx, |selections| {
11285                            selections.clear_disjoint();
11286                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11287                        });
11288                    }
11289                    editor.highlight_background::<Self>(
11290                        &ranges,
11291                        |theme| theme.editor_highlighted_line_background,
11292                        cx,
11293                    );
11294                }
11295                MultibufferSelectionMode::All => {
11296                    editor.change_selections(None, window, cx, |selections| {
11297                        selections.clear_disjoint();
11298                        selections.select_anchor_ranges(ranges);
11299                    });
11300                }
11301            }
11302            editor.register_buffers_with_language_servers(cx);
11303        });
11304
11305        let item = Box::new(editor);
11306        let item_id = item.item_id();
11307
11308        if split {
11309            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11310        } else {
11311            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11312                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11313                    pane.close_current_preview_item(window, cx)
11314                } else {
11315                    None
11316                }
11317            });
11318            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11319        }
11320        workspace.active_pane().update(cx, |pane, cx| {
11321            pane.set_preview_item_id(Some(item_id), cx);
11322        });
11323    }
11324
11325    pub fn rename(
11326        &mut self,
11327        _: &Rename,
11328        window: &mut Window,
11329        cx: &mut Context<Self>,
11330    ) -> Option<Task<Result<()>>> {
11331        use language::ToOffset as _;
11332
11333        let provider = self.semantics_provider.clone()?;
11334        let selection = self.selections.newest_anchor().clone();
11335        let (cursor_buffer, cursor_buffer_position) = self
11336            .buffer
11337            .read(cx)
11338            .text_anchor_for_position(selection.head(), cx)?;
11339        let (tail_buffer, cursor_buffer_position_end) = self
11340            .buffer
11341            .read(cx)
11342            .text_anchor_for_position(selection.tail(), cx)?;
11343        if tail_buffer != cursor_buffer {
11344            return None;
11345        }
11346
11347        let snapshot = cursor_buffer.read(cx).snapshot();
11348        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11349        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11350        let prepare_rename = provider
11351            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11352            .unwrap_or_else(|| Task::ready(Ok(None)));
11353        drop(snapshot);
11354
11355        Some(cx.spawn_in(window, |this, mut cx| async move {
11356            let rename_range = if let Some(range) = prepare_rename.await? {
11357                Some(range)
11358            } else {
11359                this.update(&mut cx, |this, cx| {
11360                    let buffer = this.buffer.read(cx).snapshot(cx);
11361                    let mut buffer_highlights = this
11362                        .document_highlights_for_position(selection.head(), &buffer)
11363                        .filter(|highlight| {
11364                            highlight.start.excerpt_id == selection.head().excerpt_id
11365                                && highlight.end.excerpt_id == selection.head().excerpt_id
11366                        });
11367                    buffer_highlights
11368                        .next()
11369                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11370                })?
11371            };
11372            if let Some(rename_range) = rename_range {
11373                this.update_in(&mut cx, |this, window, cx| {
11374                    let snapshot = cursor_buffer.read(cx).snapshot();
11375                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11376                    let cursor_offset_in_rename_range =
11377                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11378                    let cursor_offset_in_rename_range_end =
11379                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11380
11381                    this.take_rename(false, window, cx);
11382                    let buffer = this.buffer.read(cx).read(cx);
11383                    let cursor_offset = selection.head().to_offset(&buffer);
11384                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11385                    let rename_end = rename_start + rename_buffer_range.len();
11386                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11387                    let mut old_highlight_id = None;
11388                    let old_name: Arc<str> = buffer
11389                        .chunks(rename_start..rename_end, true)
11390                        .map(|chunk| {
11391                            if old_highlight_id.is_none() {
11392                                old_highlight_id = chunk.syntax_highlight_id;
11393                            }
11394                            chunk.text
11395                        })
11396                        .collect::<String>()
11397                        .into();
11398
11399                    drop(buffer);
11400
11401                    // Position the selection in the rename editor so that it matches the current selection.
11402                    this.show_local_selections = false;
11403                    let rename_editor = cx.new(|cx| {
11404                        let mut editor = Editor::single_line(window, cx);
11405                        editor.buffer.update(cx, |buffer, cx| {
11406                            buffer.edit([(0..0, old_name.clone())], None, cx)
11407                        });
11408                        let rename_selection_range = match cursor_offset_in_rename_range
11409                            .cmp(&cursor_offset_in_rename_range_end)
11410                        {
11411                            Ordering::Equal => {
11412                                editor.select_all(&SelectAll, window, cx);
11413                                return editor;
11414                            }
11415                            Ordering::Less => {
11416                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11417                            }
11418                            Ordering::Greater => {
11419                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11420                            }
11421                        };
11422                        if rename_selection_range.end > old_name.len() {
11423                            editor.select_all(&SelectAll, window, cx);
11424                        } else {
11425                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11426                                s.select_ranges([rename_selection_range]);
11427                            });
11428                        }
11429                        editor
11430                    });
11431                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11432                        if e == &EditorEvent::Focused {
11433                            cx.emit(EditorEvent::FocusedIn)
11434                        }
11435                    })
11436                    .detach();
11437
11438                    let write_highlights =
11439                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11440                    let read_highlights =
11441                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11442                    let ranges = write_highlights
11443                        .iter()
11444                        .flat_map(|(_, ranges)| ranges.iter())
11445                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11446                        .cloned()
11447                        .collect();
11448
11449                    this.highlight_text::<Rename>(
11450                        ranges,
11451                        HighlightStyle {
11452                            fade_out: Some(0.6),
11453                            ..Default::default()
11454                        },
11455                        cx,
11456                    );
11457                    let rename_focus_handle = rename_editor.focus_handle(cx);
11458                    window.focus(&rename_focus_handle);
11459                    let block_id = this.insert_blocks(
11460                        [BlockProperties {
11461                            style: BlockStyle::Flex,
11462                            placement: BlockPlacement::Below(range.start),
11463                            height: 1,
11464                            render: Arc::new({
11465                                let rename_editor = rename_editor.clone();
11466                                move |cx: &mut BlockContext| {
11467                                    let mut text_style = cx.editor_style.text.clone();
11468                                    if let Some(highlight_style) = old_highlight_id
11469                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11470                                    {
11471                                        text_style = text_style.highlight(highlight_style);
11472                                    }
11473                                    div()
11474                                        .block_mouse_down()
11475                                        .pl(cx.anchor_x)
11476                                        .child(EditorElement::new(
11477                                            &rename_editor,
11478                                            EditorStyle {
11479                                                background: cx.theme().system().transparent,
11480                                                local_player: cx.editor_style.local_player,
11481                                                text: text_style,
11482                                                scrollbar_width: cx.editor_style.scrollbar_width,
11483                                                syntax: cx.editor_style.syntax.clone(),
11484                                                status: cx.editor_style.status.clone(),
11485                                                inlay_hints_style: HighlightStyle {
11486                                                    font_weight: Some(FontWeight::BOLD),
11487                                                    ..make_inlay_hints_style(cx.app)
11488                                                },
11489                                                inline_completion_styles: make_suggestion_styles(
11490                                                    cx.app,
11491                                                ),
11492                                                ..EditorStyle::default()
11493                                            },
11494                                        ))
11495                                        .into_any_element()
11496                                }
11497                            }),
11498                            priority: 0,
11499                        }],
11500                        Some(Autoscroll::fit()),
11501                        cx,
11502                    )[0];
11503                    this.pending_rename = Some(RenameState {
11504                        range,
11505                        old_name,
11506                        editor: rename_editor,
11507                        block_id,
11508                    });
11509                })?;
11510            }
11511
11512            Ok(())
11513        }))
11514    }
11515
11516    pub fn confirm_rename(
11517        &mut self,
11518        _: &ConfirmRename,
11519        window: &mut Window,
11520        cx: &mut Context<Self>,
11521    ) -> Option<Task<Result<()>>> {
11522        let rename = self.take_rename(false, window, cx)?;
11523        let workspace = self.workspace()?.downgrade();
11524        let (buffer, start) = self
11525            .buffer
11526            .read(cx)
11527            .text_anchor_for_position(rename.range.start, cx)?;
11528        let (end_buffer, _) = self
11529            .buffer
11530            .read(cx)
11531            .text_anchor_for_position(rename.range.end, cx)?;
11532        if buffer != end_buffer {
11533            return None;
11534        }
11535
11536        let old_name = rename.old_name;
11537        let new_name = rename.editor.read(cx).text(cx);
11538
11539        let rename = self.semantics_provider.as_ref()?.perform_rename(
11540            &buffer,
11541            start,
11542            new_name.clone(),
11543            cx,
11544        )?;
11545
11546        Some(cx.spawn_in(window, |editor, mut cx| async move {
11547            let project_transaction = rename.await?;
11548            Self::open_project_transaction(
11549                &editor,
11550                workspace,
11551                project_transaction,
11552                format!("Rename: {}{}", old_name, new_name),
11553                cx.clone(),
11554            )
11555            .await?;
11556
11557            editor.update(&mut cx, |editor, cx| {
11558                editor.refresh_document_highlights(cx);
11559            })?;
11560            Ok(())
11561        }))
11562    }
11563
11564    fn take_rename(
11565        &mut self,
11566        moving_cursor: bool,
11567        window: &mut Window,
11568        cx: &mut Context<Self>,
11569    ) -> Option<RenameState> {
11570        let rename = self.pending_rename.take()?;
11571        if rename.editor.focus_handle(cx).is_focused(window) {
11572            window.focus(&self.focus_handle);
11573        }
11574
11575        self.remove_blocks(
11576            [rename.block_id].into_iter().collect(),
11577            Some(Autoscroll::fit()),
11578            cx,
11579        );
11580        self.clear_highlights::<Rename>(cx);
11581        self.show_local_selections = true;
11582
11583        if moving_cursor {
11584            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11585                editor.selections.newest::<usize>(cx).head()
11586            });
11587
11588            // Update the selection to match the position of the selection inside
11589            // the rename editor.
11590            let snapshot = self.buffer.read(cx).read(cx);
11591            let rename_range = rename.range.to_offset(&snapshot);
11592            let cursor_in_editor = snapshot
11593                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11594                .min(rename_range.end);
11595            drop(snapshot);
11596
11597            self.change_selections(None, window, cx, |s| {
11598                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11599            });
11600        } else {
11601            self.refresh_document_highlights(cx);
11602        }
11603
11604        Some(rename)
11605    }
11606
11607    pub fn pending_rename(&self) -> Option<&RenameState> {
11608        self.pending_rename.as_ref()
11609    }
11610
11611    fn format(
11612        &mut self,
11613        _: &Format,
11614        window: &mut Window,
11615        cx: &mut Context<Self>,
11616    ) -> Option<Task<Result<()>>> {
11617        let project = match &self.project {
11618            Some(project) => project.clone(),
11619            None => return None,
11620        };
11621
11622        Some(self.perform_format(
11623            project,
11624            FormatTrigger::Manual,
11625            FormatTarget::Buffers,
11626            window,
11627            cx,
11628        ))
11629    }
11630
11631    fn format_selections(
11632        &mut self,
11633        _: &FormatSelections,
11634        window: &mut Window,
11635        cx: &mut Context<Self>,
11636    ) -> Option<Task<Result<()>>> {
11637        let project = match &self.project {
11638            Some(project) => project.clone(),
11639            None => return None,
11640        };
11641
11642        let ranges = self
11643            .selections
11644            .all_adjusted(cx)
11645            .into_iter()
11646            .map(|selection| selection.range())
11647            .collect_vec();
11648
11649        Some(self.perform_format(
11650            project,
11651            FormatTrigger::Manual,
11652            FormatTarget::Ranges(ranges),
11653            window,
11654            cx,
11655        ))
11656    }
11657
11658    fn perform_format(
11659        &mut self,
11660        project: Entity<Project>,
11661        trigger: FormatTrigger,
11662        target: FormatTarget,
11663        window: &mut Window,
11664        cx: &mut Context<Self>,
11665    ) -> Task<Result<()>> {
11666        let buffer = self.buffer.clone();
11667        let (buffers, target) = match target {
11668            FormatTarget::Buffers => {
11669                let mut buffers = buffer.read(cx).all_buffers();
11670                if trigger == FormatTrigger::Save {
11671                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11672                }
11673                (buffers, LspFormatTarget::Buffers)
11674            }
11675            FormatTarget::Ranges(selection_ranges) => {
11676                let multi_buffer = buffer.read(cx);
11677                let snapshot = multi_buffer.read(cx);
11678                let mut buffers = HashSet::default();
11679                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11680                    BTreeMap::new();
11681                for selection_range in selection_ranges {
11682                    for (buffer, buffer_range, _) in
11683                        snapshot.range_to_buffer_ranges(selection_range)
11684                    {
11685                        let buffer_id = buffer.remote_id();
11686                        let start = buffer.anchor_before(buffer_range.start);
11687                        let end = buffer.anchor_after(buffer_range.end);
11688                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11689                        buffer_id_to_ranges
11690                            .entry(buffer_id)
11691                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11692                            .or_insert_with(|| vec![start..end]);
11693                    }
11694                }
11695                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11696            }
11697        };
11698
11699        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11700        let format = project.update(cx, |project, cx| {
11701            project.format(buffers, target, true, trigger, cx)
11702        });
11703
11704        cx.spawn_in(window, |_, mut cx| async move {
11705            let transaction = futures::select_biased! {
11706                () = timeout => {
11707                    log::warn!("timed out waiting for formatting");
11708                    None
11709                }
11710                transaction = format.log_err().fuse() => transaction,
11711            };
11712
11713            buffer
11714                .update(&mut cx, |buffer, cx| {
11715                    if let Some(transaction) = transaction {
11716                        if !buffer.is_singleton() {
11717                            buffer.push_transaction(&transaction.0, cx);
11718                        }
11719                    }
11720
11721                    cx.notify();
11722                })
11723                .ok();
11724
11725            Ok(())
11726        })
11727    }
11728
11729    fn restart_language_server(
11730        &mut self,
11731        _: &RestartLanguageServer,
11732        _: &mut Window,
11733        cx: &mut Context<Self>,
11734    ) {
11735        if let Some(project) = self.project.clone() {
11736            self.buffer.update(cx, |multi_buffer, cx| {
11737                project.update(cx, |project, cx| {
11738                    project.restart_language_servers_for_buffers(
11739                        multi_buffer.all_buffers().into_iter().collect(),
11740                        cx,
11741                    );
11742                });
11743            })
11744        }
11745    }
11746
11747    fn cancel_language_server_work(
11748        workspace: &mut Workspace,
11749        _: &actions::CancelLanguageServerWork,
11750        _: &mut Window,
11751        cx: &mut Context<Workspace>,
11752    ) {
11753        let project = workspace.project();
11754        let buffers = workspace
11755            .active_item(cx)
11756            .and_then(|item| item.act_as::<Editor>(cx))
11757            .map_or(HashSet::default(), |editor| {
11758                editor.read(cx).buffer.read(cx).all_buffers()
11759            });
11760        project.update(cx, |project, cx| {
11761            project.cancel_language_server_work_for_buffers(buffers, cx);
11762        });
11763    }
11764
11765    fn show_character_palette(
11766        &mut self,
11767        _: &ShowCharacterPalette,
11768        window: &mut Window,
11769        _: &mut Context<Self>,
11770    ) {
11771        window.show_character_palette();
11772    }
11773
11774    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11775        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11776            let buffer = self.buffer.read(cx).snapshot(cx);
11777            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11778            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11779            let is_valid = buffer
11780                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11781                .any(|entry| {
11782                    entry.diagnostic.is_primary
11783                        && !entry.range.is_empty()
11784                        && entry.range.start == primary_range_start
11785                        && entry.diagnostic.message == active_diagnostics.primary_message
11786                });
11787
11788            if is_valid != active_diagnostics.is_valid {
11789                active_diagnostics.is_valid = is_valid;
11790                let mut new_styles = HashMap::default();
11791                for (block_id, diagnostic) in &active_diagnostics.blocks {
11792                    new_styles.insert(
11793                        *block_id,
11794                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11795                    );
11796                }
11797                self.display_map.update(cx, |display_map, _cx| {
11798                    display_map.replace_blocks(new_styles)
11799                });
11800            }
11801        }
11802    }
11803
11804    fn activate_diagnostics(
11805        &mut self,
11806        buffer_id: BufferId,
11807        group_id: usize,
11808        window: &mut Window,
11809        cx: &mut Context<Self>,
11810    ) {
11811        self.dismiss_diagnostics(cx);
11812        let snapshot = self.snapshot(window, cx);
11813        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11814            let buffer = self.buffer.read(cx).snapshot(cx);
11815
11816            let mut primary_range = None;
11817            let mut primary_message = None;
11818            let diagnostic_group = buffer
11819                .diagnostic_group(buffer_id, group_id)
11820                .filter_map(|entry| {
11821                    let start = entry.range.start;
11822                    let end = entry.range.end;
11823                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11824                        && (start.row == end.row
11825                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11826                    {
11827                        return None;
11828                    }
11829                    if entry.diagnostic.is_primary {
11830                        primary_range = Some(entry.range.clone());
11831                        primary_message = Some(entry.diagnostic.message.clone());
11832                    }
11833                    Some(entry)
11834                })
11835                .collect::<Vec<_>>();
11836            let primary_range = primary_range?;
11837            let primary_message = primary_message?;
11838
11839            let blocks = display_map
11840                .insert_blocks(
11841                    diagnostic_group.iter().map(|entry| {
11842                        let diagnostic = entry.diagnostic.clone();
11843                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11844                        BlockProperties {
11845                            style: BlockStyle::Fixed,
11846                            placement: BlockPlacement::Below(
11847                                buffer.anchor_after(entry.range.start),
11848                            ),
11849                            height: message_height,
11850                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11851                            priority: 0,
11852                        }
11853                    }),
11854                    cx,
11855                )
11856                .into_iter()
11857                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11858                .collect();
11859
11860            Some(ActiveDiagnosticGroup {
11861                primary_range: buffer.anchor_before(primary_range.start)
11862                    ..buffer.anchor_after(primary_range.end),
11863                primary_message,
11864                group_id,
11865                blocks,
11866                is_valid: true,
11867            })
11868        });
11869    }
11870
11871    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11872        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11873            self.display_map.update(cx, |display_map, cx| {
11874                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11875            });
11876            cx.notify();
11877        }
11878    }
11879
11880    pub fn set_selections_from_remote(
11881        &mut self,
11882        selections: Vec<Selection<Anchor>>,
11883        pending_selection: Option<Selection<Anchor>>,
11884        window: &mut Window,
11885        cx: &mut Context<Self>,
11886    ) {
11887        let old_cursor_position = self.selections.newest_anchor().head();
11888        self.selections.change_with(cx, |s| {
11889            s.select_anchors(selections);
11890            if let Some(pending_selection) = pending_selection {
11891                s.set_pending(pending_selection, SelectMode::Character);
11892            } else {
11893                s.clear_pending();
11894            }
11895        });
11896        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11897    }
11898
11899    fn push_to_selection_history(&mut self) {
11900        self.selection_history.push(SelectionHistoryEntry {
11901            selections: self.selections.disjoint_anchors(),
11902            select_next_state: self.select_next_state.clone(),
11903            select_prev_state: self.select_prev_state.clone(),
11904            add_selections_state: self.add_selections_state.clone(),
11905        });
11906    }
11907
11908    pub fn transact(
11909        &mut self,
11910        window: &mut Window,
11911        cx: &mut Context<Self>,
11912        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11913    ) -> Option<TransactionId> {
11914        self.start_transaction_at(Instant::now(), window, cx);
11915        update(self, window, cx);
11916        self.end_transaction_at(Instant::now(), cx)
11917    }
11918
11919    pub fn start_transaction_at(
11920        &mut self,
11921        now: Instant,
11922        window: &mut Window,
11923        cx: &mut Context<Self>,
11924    ) {
11925        self.end_selection(window, cx);
11926        if let Some(tx_id) = self
11927            .buffer
11928            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11929        {
11930            self.selection_history
11931                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11932            cx.emit(EditorEvent::TransactionBegun {
11933                transaction_id: tx_id,
11934            })
11935        }
11936    }
11937
11938    pub fn end_transaction_at(
11939        &mut self,
11940        now: Instant,
11941        cx: &mut Context<Self>,
11942    ) -> Option<TransactionId> {
11943        if let Some(transaction_id) = self
11944            .buffer
11945            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11946        {
11947            if let Some((_, end_selections)) =
11948                self.selection_history.transaction_mut(transaction_id)
11949            {
11950                *end_selections = Some(self.selections.disjoint_anchors());
11951            } else {
11952                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11953            }
11954
11955            cx.emit(EditorEvent::Edited { transaction_id });
11956            Some(transaction_id)
11957        } else {
11958            None
11959        }
11960    }
11961
11962    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11963        if self.selection_mark_mode {
11964            self.change_selections(None, window, cx, |s| {
11965                s.move_with(|_, sel| {
11966                    sel.collapse_to(sel.head(), SelectionGoal::None);
11967                });
11968            })
11969        }
11970        self.selection_mark_mode = true;
11971        cx.notify();
11972    }
11973
11974    pub fn swap_selection_ends(
11975        &mut self,
11976        _: &actions::SwapSelectionEnds,
11977        window: &mut Window,
11978        cx: &mut Context<Self>,
11979    ) {
11980        self.change_selections(None, window, cx, |s| {
11981            s.move_with(|_, sel| {
11982                if sel.start != sel.end {
11983                    sel.reversed = !sel.reversed
11984                }
11985            });
11986        });
11987        self.request_autoscroll(Autoscroll::newest(), cx);
11988        cx.notify();
11989    }
11990
11991    pub fn toggle_fold(
11992        &mut self,
11993        _: &actions::ToggleFold,
11994        window: &mut Window,
11995        cx: &mut Context<Self>,
11996    ) {
11997        if self.is_singleton(cx) {
11998            let selection = self.selections.newest::<Point>(cx);
11999
12000            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12001            let range = if selection.is_empty() {
12002                let point = selection.head().to_display_point(&display_map);
12003                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12004                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12005                    .to_point(&display_map);
12006                start..end
12007            } else {
12008                selection.range()
12009            };
12010            if display_map.folds_in_range(range).next().is_some() {
12011                self.unfold_lines(&Default::default(), window, cx)
12012            } else {
12013                self.fold(&Default::default(), window, cx)
12014            }
12015        } else {
12016            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12017            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12018                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12019                .map(|(snapshot, _, _)| snapshot.remote_id())
12020                .collect();
12021
12022            for buffer_id in buffer_ids {
12023                if self.is_buffer_folded(buffer_id, cx) {
12024                    self.unfold_buffer(buffer_id, cx);
12025                } else {
12026                    self.fold_buffer(buffer_id, cx);
12027                }
12028            }
12029        }
12030    }
12031
12032    pub fn toggle_fold_recursive(
12033        &mut self,
12034        _: &actions::ToggleFoldRecursive,
12035        window: &mut Window,
12036        cx: &mut Context<Self>,
12037    ) {
12038        let selection = self.selections.newest::<Point>(cx);
12039
12040        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12041        let range = if selection.is_empty() {
12042            let point = selection.head().to_display_point(&display_map);
12043            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12044            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12045                .to_point(&display_map);
12046            start..end
12047        } else {
12048            selection.range()
12049        };
12050        if display_map.folds_in_range(range).next().is_some() {
12051            self.unfold_recursive(&Default::default(), window, cx)
12052        } else {
12053            self.fold_recursive(&Default::default(), window, cx)
12054        }
12055    }
12056
12057    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12058        if self.is_singleton(cx) {
12059            let mut to_fold = Vec::new();
12060            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12061            let selections = self.selections.all_adjusted(cx);
12062
12063            for selection in selections {
12064                let range = selection.range().sorted();
12065                let buffer_start_row = range.start.row;
12066
12067                if range.start.row != range.end.row {
12068                    let mut found = false;
12069                    let mut row = range.start.row;
12070                    while row <= range.end.row {
12071                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12072                        {
12073                            found = true;
12074                            row = crease.range().end.row + 1;
12075                            to_fold.push(crease);
12076                        } else {
12077                            row += 1
12078                        }
12079                    }
12080                    if found {
12081                        continue;
12082                    }
12083                }
12084
12085                for row in (0..=range.start.row).rev() {
12086                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12087                        if crease.range().end.row >= buffer_start_row {
12088                            to_fold.push(crease);
12089                            if row <= range.start.row {
12090                                break;
12091                            }
12092                        }
12093                    }
12094                }
12095            }
12096
12097            self.fold_creases(to_fold, true, window, cx);
12098        } else {
12099            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12100
12101            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12102                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12103                .map(|(snapshot, _, _)| snapshot.remote_id())
12104                .collect();
12105            for buffer_id in buffer_ids {
12106                self.fold_buffer(buffer_id, cx);
12107            }
12108        }
12109    }
12110
12111    fn fold_at_level(
12112        &mut self,
12113        fold_at: &FoldAtLevel,
12114        window: &mut Window,
12115        cx: &mut Context<Self>,
12116    ) {
12117        if !self.buffer.read(cx).is_singleton() {
12118            return;
12119        }
12120
12121        let fold_at_level = fold_at.0;
12122        let snapshot = self.buffer.read(cx).snapshot(cx);
12123        let mut to_fold = Vec::new();
12124        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12125
12126        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12127            while start_row < end_row {
12128                match self
12129                    .snapshot(window, cx)
12130                    .crease_for_buffer_row(MultiBufferRow(start_row))
12131                {
12132                    Some(crease) => {
12133                        let nested_start_row = crease.range().start.row + 1;
12134                        let nested_end_row = crease.range().end.row;
12135
12136                        if current_level < fold_at_level {
12137                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12138                        } else if current_level == fold_at_level {
12139                            to_fold.push(crease);
12140                        }
12141
12142                        start_row = nested_end_row + 1;
12143                    }
12144                    None => start_row += 1,
12145                }
12146            }
12147        }
12148
12149        self.fold_creases(to_fold, true, window, cx);
12150    }
12151
12152    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12153        if self.buffer.read(cx).is_singleton() {
12154            let mut fold_ranges = Vec::new();
12155            let snapshot = self.buffer.read(cx).snapshot(cx);
12156
12157            for row in 0..snapshot.max_row().0 {
12158                if let Some(foldable_range) = self
12159                    .snapshot(window, cx)
12160                    .crease_for_buffer_row(MultiBufferRow(row))
12161                {
12162                    fold_ranges.push(foldable_range);
12163                }
12164            }
12165
12166            self.fold_creases(fold_ranges, true, window, cx);
12167        } else {
12168            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12169                editor
12170                    .update_in(&mut cx, |editor, _, cx| {
12171                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12172                            editor.fold_buffer(buffer_id, cx);
12173                        }
12174                    })
12175                    .ok();
12176            });
12177        }
12178    }
12179
12180    pub fn fold_function_bodies(
12181        &mut self,
12182        _: &actions::FoldFunctionBodies,
12183        window: &mut Window,
12184        cx: &mut Context<Self>,
12185    ) {
12186        let snapshot = self.buffer.read(cx).snapshot(cx);
12187
12188        let ranges = snapshot
12189            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12190            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12191            .collect::<Vec<_>>();
12192
12193        let creases = ranges
12194            .into_iter()
12195            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12196            .collect();
12197
12198        self.fold_creases(creases, true, window, cx);
12199    }
12200
12201    pub fn fold_recursive(
12202        &mut self,
12203        _: &actions::FoldRecursive,
12204        window: &mut Window,
12205        cx: &mut Context<Self>,
12206    ) {
12207        let mut to_fold = Vec::new();
12208        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12209        let selections = self.selections.all_adjusted(cx);
12210
12211        for selection in selections {
12212            let range = selection.range().sorted();
12213            let buffer_start_row = range.start.row;
12214
12215            if range.start.row != range.end.row {
12216                let mut found = false;
12217                for row in range.start.row..=range.end.row {
12218                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12219                        found = true;
12220                        to_fold.push(crease);
12221                    }
12222                }
12223                if found {
12224                    continue;
12225                }
12226            }
12227
12228            for row in (0..=range.start.row).rev() {
12229                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12230                    if crease.range().end.row >= buffer_start_row {
12231                        to_fold.push(crease);
12232                    } else {
12233                        break;
12234                    }
12235                }
12236            }
12237        }
12238
12239        self.fold_creases(to_fold, true, window, cx);
12240    }
12241
12242    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12243        let buffer_row = fold_at.buffer_row;
12244        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12245
12246        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12247            let autoscroll = self
12248                .selections
12249                .all::<Point>(cx)
12250                .iter()
12251                .any(|selection| crease.range().overlaps(&selection.range()));
12252
12253            self.fold_creases(vec![crease], autoscroll, window, cx);
12254        }
12255    }
12256
12257    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12258        if self.is_singleton(cx) {
12259            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12260            let buffer = &display_map.buffer_snapshot;
12261            let selections = self.selections.all::<Point>(cx);
12262            let ranges = selections
12263                .iter()
12264                .map(|s| {
12265                    let range = s.display_range(&display_map).sorted();
12266                    let mut start = range.start.to_point(&display_map);
12267                    let mut end = range.end.to_point(&display_map);
12268                    start.column = 0;
12269                    end.column = buffer.line_len(MultiBufferRow(end.row));
12270                    start..end
12271                })
12272                .collect::<Vec<_>>();
12273
12274            self.unfold_ranges(&ranges, true, true, cx);
12275        } else {
12276            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12277            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12278                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12279                .map(|(snapshot, _, _)| snapshot.remote_id())
12280                .collect();
12281            for buffer_id in buffer_ids {
12282                self.unfold_buffer(buffer_id, cx);
12283            }
12284        }
12285    }
12286
12287    pub fn unfold_recursive(
12288        &mut self,
12289        _: &UnfoldRecursive,
12290        _window: &mut Window,
12291        cx: &mut Context<Self>,
12292    ) {
12293        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12294        let selections = self.selections.all::<Point>(cx);
12295        let ranges = selections
12296            .iter()
12297            .map(|s| {
12298                let mut range = s.display_range(&display_map).sorted();
12299                *range.start.column_mut() = 0;
12300                *range.end.column_mut() = display_map.line_len(range.end.row());
12301                let start = range.start.to_point(&display_map);
12302                let end = range.end.to_point(&display_map);
12303                start..end
12304            })
12305            .collect::<Vec<_>>();
12306
12307        self.unfold_ranges(&ranges, true, true, cx);
12308    }
12309
12310    pub fn unfold_at(
12311        &mut self,
12312        unfold_at: &UnfoldAt,
12313        _window: &mut Window,
12314        cx: &mut Context<Self>,
12315    ) {
12316        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12317
12318        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12319            ..Point::new(
12320                unfold_at.buffer_row.0,
12321                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12322            );
12323
12324        let autoscroll = self
12325            .selections
12326            .all::<Point>(cx)
12327            .iter()
12328            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12329
12330        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12331    }
12332
12333    pub fn unfold_all(
12334        &mut self,
12335        _: &actions::UnfoldAll,
12336        _window: &mut Window,
12337        cx: &mut Context<Self>,
12338    ) {
12339        if self.buffer.read(cx).is_singleton() {
12340            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12341            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12342        } else {
12343            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12344                editor
12345                    .update(&mut cx, |editor, cx| {
12346                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12347                            editor.unfold_buffer(buffer_id, cx);
12348                        }
12349                    })
12350                    .ok();
12351            });
12352        }
12353    }
12354
12355    pub fn fold_selected_ranges(
12356        &mut self,
12357        _: &FoldSelectedRanges,
12358        window: &mut Window,
12359        cx: &mut Context<Self>,
12360    ) {
12361        let selections = self.selections.all::<Point>(cx);
12362        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12363        let line_mode = self.selections.line_mode;
12364        let ranges = selections
12365            .into_iter()
12366            .map(|s| {
12367                if line_mode {
12368                    let start = Point::new(s.start.row, 0);
12369                    let end = Point::new(
12370                        s.end.row,
12371                        display_map
12372                            .buffer_snapshot
12373                            .line_len(MultiBufferRow(s.end.row)),
12374                    );
12375                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12376                } else {
12377                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12378                }
12379            })
12380            .collect::<Vec<_>>();
12381        self.fold_creases(ranges, true, window, cx);
12382    }
12383
12384    pub fn fold_ranges<T: ToOffset + Clone>(
12385        &mut self,
12386        ranges: Vec<Range<T>>,
12387        auto_scroll: bool,
12388        window: &mut Window,
12389        cx: &mut Context<Self>,
12390    ) {
12391        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12392        let ranges = ranges
12393            .into_iter()
12394            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12395            .collect::<Vec<_>>();
12396        self.fold_creases(ranges, auto_scroll, window, cx);
12397    }
12398
12399    pub fn fold_creases<T: ToOffset + Clone>(
12400        &mut self,
12401        creases: Vec<Crease<T>>,
12402        auto_scroll: bool,
12403        window: &mut Window,
12404        cx: &mut Context<Self>,
12405    ) {
12406        if creases.is_empty() {
12407            return;
12408        }
12409
12410        let mut buffers_affected = HashSet::default();
12411        let multi_buffer = self.buffer().read(cx);
12412        for crease in &creases {
12413            if let Some((_, buffer, _)) =
12414                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12415            {
12416                buffers_affected.insert(buffer.read(cx).remote_id());
12417            };
12418        }
12419
12420        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12421
12422        if auto_scroll {
12423            self.request_autoscroll(Autoscroll::fit(), cx);
12424        }
12425
12426        cx.notify();
12427
12428        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12429            // Clear diagnostics block when folding a range that contains it.
12430            let snapshot = self.snapshot(window, cx);
12431            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12432                drop(snapshot);
12433                self.active_diagnostics = Some(active_diagnostics);
12434                self.dismiss_diagnostics(cx);
12435            } else {
12436                self.active_diagnostics = Some(active_diagnostics);
12437            }
12438        }
12439
12440        self.scrollbar_marker_state.dirty = true;
12441    }
12442
12443    /// Removes any folds whose ranges intersect any of the given ranges.
12444    pub fn unfold_ranges<T: ToOffset + Clone>(
12445        &mut self,
12446        ranges: &[Range<T>],
12447        inclusive: bool,
12448        auto_scroll: bool,
12449        cx: &mut Context<Self>,
12450    ) {
12451        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12452            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12453        });
12454    }
12455
12456    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12457        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12458            return;
12459        }
12460        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12461        self.display_map
12462            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12463        cx.emit(EditorEvent::BufferFoldToggled {
12464            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12465            folded: true,
12466        });
12467        cx.notify();
12468    }
12469
12470    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12471        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12472            return;
12473        }
12474        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12475        self.display_map.update(cx, |display_map, cx| {
12476            display_map.unfold_buffer(buffer_id, cx);
12477        });
12478        cx.emit(EditorEvent::BufferFoldToggled {
12479            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12480            folded: false,
12481        });
12482        cx.notify();
12483    }
12484
12485    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12486        self.display_map.read(cx).is_buffer_folded(buffer)
12487    }
12488
12489    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12490        self.display_map.read(cx).folded_buffers()
12491    }
12492
12493    /// Removes any folds with the given ranges.
12494    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12495        &mut self,
12496        ranges: &[Range<T>],
12497        type_id: TypeId,
12498        auto_scroll: bool,
12499        cx: &mut Context<Self>,
12500    ) {
12501        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12502            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12503        });
12504    }
12505
12506    fn remove_folds_with<T: ToOffset + Clone>(
12507        &mut self,
12508        ranges: &[Range<T>],
12509        auto_scroll: bool,
12510        cx: &mut Context<Self>,
12511        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12512    ) {
12513        if ranges.is_empty() {
12514            return;
12515        }
12516
12517        let mut buffers_affected = HashSet::default();
12518        let multi_buffer = self.buffer().read(cx);
12519        for range in ranges {
12520            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12521                buffers_affected.insert(buffer.read(cx).remote_id());
12522            };
12523        }
12524
12525        self.display_map.update(cx, update);
12526
12527        if auto_scroll {
12528            self.request_autoscroll(Autoscroll::fit(), cx);
12529        }
12530
12531        cx.notify();
12532        self.scrollbar_marker_state.dirty = true;
12533        self.active_indent_guides_state.dirty = true;
12534    }
12535
12536    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12537        self.display_map.read(cx).fold_placeholder.clone()
12538    }
12539
12540    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12541        self.buffer.update(cx, |buffer, cx| {
12542            buffer.set_all_diff_hunks_expanded(cx);
12543        });
12544    }
12545
12546    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12547        self.distinguish_unstaged_diff_hunks = true;
12548    }
12549
12550    pub fn expand_all_diff_hunks(
12551        &mut self,
12552        _: &ExpandAllHunkDiffs,
12553        _window: &mut Window,
12554        cx: &mut Context<Self>,
12555    ) {
12556        self.buffer.update(cx, |buffer, cx| {
12557            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12558        });
12559    }
12560
12561    pub fn toggle_selected_diff_hunks(
12562        &mut self,
12563        _: &ToggleSelectedDiffHunks,
12564        _window: &mut Window,
12565        cx: &mut Context<Self>,
12566    ) {
12567        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12568        self.toggle_diff_hunks_in_ranges(ranges, cx);
12569    }
12570
12571    fn diff_hunks_in_ranges<'a>(
12572        &'a self,
12573        ranges: &'a [Range<Anchor>],
12574        buffer: &'a MultiBufferSnapshot,
12575    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12576        ranges.iter().flat_map(move |range| {
12577            let end_excerpt_id = range.end.excerpt_id;
12578            let range = range.to_point(buffer);
12579            let mut peek_end = range.end;
12580            if range.end.row < buffer.max_row().0 {
12581                peek_end = Point::new(range.end.row + 1, 0);
12582            }
12583            buffer
12584                .diff_hunks_in_range(range.start..peek_end)
12585                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12586        })
12587    }
12588
12589    pub fn has_stageable_diff_hunks_in_ranges(
12590        &self,
12591        ranges: &[Range<Anchor>],
12592        snapshot: &MultiBufferSnapshot,
12593    ) -> bool {
12594        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12595        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12596    }
12597
12598    pub fn toggle_staged_selected_diff_hunks(
12599        &mut self,
12600        _: &::git::ToggleStaged,
12601        _window: &mut Window,
12602        cx: &mut Context<Self>,
12603    ) {
12604        let snapshot = self.buffer.read(cx).snapshot(cx);
12605        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12606        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
12607        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
12608    }
12609
12610    pub fn stage_and_next(
12611        &mut self,
12612        _: &::git::StageAndNext,
12613        window: &mut Window,
12614        cx: &mut Context<Self>,
12615    ) {
12616        let head = self.selections.newest_anchor().head();
12617        self.stage_or_unstage_diff_hunks(true, &[head..head], cx);
12618        self.go_to_next_hunk(&Default::default(), window, cx);
12619    }
12620
12621    pub fn unstage_and_next(
12622        &mut self,
12623        _: &::git::UnstageAndNext,
12624        window: &mut Window,
12625        cx: &mut Context<Self>,
12626    ) {
12627        let head = self.selections.newest_anchor().head();
12628        self.stage_or_unstage_diff_hunks(false, &[head..head], cx);
12629        self.go_to_next_hunk(&Default::default(), window, cx);
12630    }
12631
12632    pub fn stage_or_unstage_diff_hunks(
12633        &mut self,
12634        stage: bool,
12635        ranges: &[Range<Anchor>],
12636        cx: &mut Context<Self>,
12637    ) {
12638        let snapshot = self.buffer.read(cx).snapshot(cx);
12639        let Some(project) = &self.project else {
12640            return;
12641        };
12642
12643        let chunk_by = self
12644            .diff_hunks_in_ranges(&ranges, &snapshot)
12645            .chunk_by(|hunk| hunk.buffer_id);
12646        for (buffer_id, hunks) in &chunk_by {
12647            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
12648        }
12649    }
12650
12651    fn do_stage_or_unstage(
12652        project: &Entity<Project>,
12653        stage: bool,
12654        buffer_id: BufferId,
12655        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
12656        snapshot: &MultiBufferSnapshot,
12657        cx: &mut Context<Self>,
12658    ) {
12659        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12660            log::debug!("no buffer for id");
12661            return;
12662        };
12663        let buffer = buffer.read(cx).snapshot();
12664        let Some((repo, path)) = project
12665            .read(cx)
12666            .repository_and_path_for_buffer_id(buffer_id, cx)
12667        else {
12668            log::debug!("no git repo for buffer id");
12669            return;
12670        };
12671        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12672            log::debug!("no diff for buffer id");
12673            return;
12674        };
12675        let Some(secondary_diff) = diff.secondary_diff() else {
12676            log::debug!("no secondary diff for buffer id");
12677            return;
12678        };
12679
12680        let edits = diff.secondary_edits_for_stage_or_unstage(
12681            stage,
12682            hunks.filter_map(|hunk| {
12683                if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
12684                    return None;
12685                } else if !stage
12686                    && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12687                {
12688                    return None;
12689                }
12690                Some((
12691                    hunk.diff_base_byte_range.clone(),
12692                    hunk.secondary_diff_base_byte_range.clone(),
12693                    hunk.buffer_range.clone(),
12694                ))
12695            }),
12696            &buffer,
12697        );
12698
12699        let Some(index_base) = secondary_diff
12700            .base_text()
12701            .map(|snapshot| snapshot.text.as_rope().clone())
12702        else {
12703            log::debug!("no index base");
12704            return;
12705        };
12706        let index_buffer = cx.new(|cx| {
12707            Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12708        });
12709        let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12710            index_buffer.edit(edits, None, cx);
12711            index_buffer.snapshot().as_rope().to_string()
12712        });
12713        let new_index_text = if new_index_text.is_empty()
12714            && (diff.is_single_insertion
12715                || buffer
12716                    .file()
12717                    .map_or(false, |file| file.disk_state() == DiskState::New))
12718        {
12719            log::debug!("removing from index");
12720            None
12721        } else {
12722            Some(new_index_text)
12723        };
12724
12725        let _ = repo.read(cx).set_index_text(&path, new_index_text);
12726    }
12727
12728    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12729        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12730        self.buffer
12731            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12732    }
12733
12734    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12735        self.buffer.update(cx, |buffer, cx| {
12736            let ranges = vec![Anchor::min()..Anchor::max()];
12737            if !buffer.all_diff_hunks_expanded()
12738                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12739            {
12740                buffer.collapse_diff_hunks(ranges, cx);
12741                true
12742            } else {
12743                false
12744            }
12745        })
12746    }
12747
12748    fn toggle_diff_hunks_in_ranges(
12749        &mut self,
12750        ranges: Vec<Range<Anchor>>,
12751        cx: &mut Context<'_, Editor>,
12752    ) {
12753        self.buffer.update(cx, |buffer, cx| {
12754            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12755            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12756        })
12757    }
12758
12759    fn toggle_diff_hunks_in_ranges_narrow(
12760        &mut self,
12761        ranges: Vec<Range<Anchor>>,
12762        cx: &mut Context<'_, Editor>,
12763    ) {
12764        self.buffer.update(cx, |buffer, cx| {
12765            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12766            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12767        })
12768    }
12769
12770    pub(crate) fn apply_all_diff_hunks(
12771        &mut self,
12772        _: &ApplyAllDiffHunks,
12773        window: &mut Window,
12774        cx: &mut Context<Self>,
12775    ) {
12776        let buffers = self.buffer.read(cx).all_buffers();
12777        for branch_buffer in buffers {
12778            branch_buffer.update(cx, |branch_buffer, cx| {
12779                branch_buffer.merge_into_base(Vec::new(), cx);
12780            });
12781        }
12782
12783        if let Some(project) = self.project.clone() {
12784            self.save(true, project, window, cx).detach_and_log_err(cx);
12785        }
12786    }
12787
12788    pub(crate) fn apply_selected_diff_hunks(
12789        &mut self,
12790        _: &ApplyDiffHunk,
12791        window: &mut Window,
12792        cx: &mut Context<Self>,
12793    ) {
12794        let snapshot = self.snapshot(window, cx);
12795        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12796        let mut ranges_by_buffer = HashMap::default();
12797        self.transact(window, cx, |editor, _window, cx| {
12798            for hunk in hunks {
12799                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12800                    ranges_by_buffer
12801                        .entry(buffer.clone())
12802                        .or_insert_with(Vec::new)
12803                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12804                }
12805            }
12806
12807            for (buffer, ranges) in ranges_by_buffer {
12808                buffer.update(cx, |buffer, cx| {
12809                    buffer.merge_into_base(ranges, cx);
12810                });
12811            }
12812        });
12813
12814        if let Some(project) = self.project.clone() {
12815            self.save(true, project, window, cx).detach_and_log_err(cx);
12816        }
12817    }
12818
12819    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12820        if hovered != self.gutter_hovered {
12821            self.gutter_hovered = hovered;
12822            cx.notify();
12823        }
12824    }
12825
12826    pub fn insert_blocks(
12827        &mut self,
12828        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12829        autoscroll: Option<Autoscroll>,
12830        cx: &mut Context<Self>,
12831    ) -> Vec<CustomBlockId> {
12832        let blocks = self
12833            .display_map
12834            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12835        if let Some(autoscroll) = autoscroll {
12836            self.request_autoscroll(autoscroll, cx);
12837        }
12838        cx.notify();
12839        blocks
12840    }
12841
12842    pub fn resize_blocks(
12843        &mut self,
12844        heights: HashMap<CustomBlockId, u32>,
12845        autoscroll: Option<Autoscroll>,
12846        cx: &mut Context<Self>,
12847    ) {
12848        self.display_map
12849            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12850        if let Some(autoscroll) = autoscroll {
12851            self.request_autoscroll(autoscroll, cx);
12852        }
12853        cx.notify();
12854    }
12855
12856    pub fn replace_blocks(
12857        &mut self,
12858        renderers: HashMap<CustomBlockId, RenderBlock>,
12859        autoscroll: Option<Autoscroll>,
12860        cx: &mut Context<Self>,
12861    ) {
12862        self.display_map
12863            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12864        if let Some(autoscroll) = autoscroll {
12865            self.request_autoscroll(autoscroll, cx);
12866        }
12867        cx.notify();
12868    }
12869
12870    pub fn remove_blocks(
12871        &mut self,
12872        block_ids: HashSet<CustomBlockId>,
12873        autoscroll: Option<Autoscroll>,
12874        cx: &mut Context<Self>,
12875    ) {
12876        self.display_map.update(cx, |display_map, cx| {
12877            display_map.remove_blocks(block_ids, cx)
12878        });
12879        if let Some(autoscroll) = autoscroll {
12880            self.request_autoscroll(autoscroll, cx);
12881        }
12882        cx.notify();
12883    }
12884
12885    pub fn row_for_block(
12886        &self,
12887        block_id: CustomBlockId,
12888        cx: &mut Context<Self>,
12889    ) -> Option<DisplayRow> {
12890        self.display_map
12891            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12892    }
12893
12894    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12895        self.focused_block = Some(focused_block);
12896    }
12897
12898    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12899        self.focused_block.take()
12900    }
12901
12902    pub fn insert_creases(
12903        &mut self,
12904        creases: impl IntoIterator<Item = Crease<Anchor>>,
12905        cx: &mut Context<Self>,
12906    ) -> Vec<CreaseId> {
12907        self.display_map
12908            .update(cx, |map, cx| map.insert_creases(creases, cx))
12909    }
12910
12911    pub fn remove_creases(
12912        &mut self,
12913        ids: impl IntoIterator<Item = CreaseId>,
12914        cx: &mut Context<Self>,
12915    ) {
12916        self.display_map
12917            .update(cx, |map, cx| map.remove_creases(ids, cx));
12918    }
12919
12920    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12921        self.display_map
12922            .update(cx, |map, cx| map.snapshot(cx))
12923            .longest_row()
12924    }
12925
12926    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12927        self.display_map
12928            .update(cx, |map, cx| map.snapshot(cx))
12929            .max_point()
12930    }
12931
12932    pub fn text(&self, cx: &App) -> String {
12933        self.buffer.read(cx).read(cx).text()
12934    }
12935
12936    pub fn is_empty(&self, cx: &App) -> bool {
12937        self.buffer.read(cx).read(cx).is_empty()
12938    }
12939
12940    pub fn text_option(&self, cx: &App) -> Option<String> {
12941        let text = self.text(cx);
12942        let text = text.trim();
12943
12944        if text.is_empty() {
12945            return None;
12946        }
12947
12948        Some(text.to_string())
12949    }
12950
12951    pub fn set_text(
12952        &mut self,
12953        text: impl Into<Arc<str>>,
12954        window: &mut Window,
12955        cx: &mut Context<Self>,
12956    ) {
12957        self.transact(window, cx, |this, _, cx| {
12958            this.buffer
12959                .read(cx)
12960                .as_singleton()
12961                .expect("you can only call set_text on editors for singleton buffers")
12962                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12963        });
12964    }
12965
12966    pub fn display_text(&self, cx: &mut App) -> String {
12967        self.display_map
12968            .update(cx, |map, cx| map.snapshot(cx))
12969            .text()
12970    }
12971
12972    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12973        let mut wrap_guides = smallvec::smallvec![];
12974
12975        if self.show_wrap_guides == Some(false) {
12976            return wrap_guides;
12977        }
12978
12979        let settings = self.buffer.read(cx).settings_at(0, cx);
12980        if settings.show_wrap_guides {
12981            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12982                wrap_guides.push((soft_wrap as usize, true));
12983            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12984                wrap_guides.push((soft_wrap as usize, true));
12985            }
12986            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12987        }
12988
12989        wrap_guides
12990    }
12991
12992    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12993        let settings = self.buffer.read(cx).settings_at(0, cx);
12994        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12995        match mode {
12996            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12997                SoftWrap::None
12998            }
12999            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13000            language_settings::SoftWrap::PreferredLineLength => {
13001                SoftWrap::Column(settings.preferred_line_length)
13002            }
13003            language_settings::SoftWrap::Bounded => {
13004                SoftWrap::Bounded(settings.preferred_line_length)
13005            }
13006        }
13007    }
13008
13009    pub fn set_soft_wrap_mode(
13010        &mut self,
13011        mode: language_settings::SoftWrap,
13012
13013        cx: &mut Context<Self>,
13014    ) {
13015        self.soft_wrap_mode_override = Some(mode);
13016        cx.notify();
13017    }
13018
13019    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13020        self.text_style_refinement = Some(style);
13021    }
13022
13023    /// called by the Element so we know what style we were most recently rendered with.
13024    pub(crate) fn set_style(
13025        &mut self,
13026        style: EditorStyle,
13027        window: &mut Window,
13028        cx: &mut Context<Self>,
13029    ) {
13030        let rem_size = window.rem_size();
13031        self.display_map.update(cx, |map, cx| {
13032            map.set_font(
13033                style.text.font(),
13034                style.text.font_size.to_pixels(rem_size),
13035                cx,
13036            )
13037        });
13038        self.style = Some(style);
13039    }
13040
13041    pub fn style(&self) -> Option<&EditorStyle> {
13042        self.style.as_ref()
13043    }
13044
13045    // Called by the element. This method is not designed to be called outside of the editor
13046    // element's layout code because it does not notify when rewrapping is computed synchronously.
13047    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13048        self.display_map
13049            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13050    }
13051
13052    pub fn set_soft_wrap(&mut self) {
13053        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13054    }
13055
13056    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13057        if self.soft_wrap_mode_override.is_some() {
13058            self.soft_wrap_mode_override.take();
13059        } else {
13060            let soft_wrap = match self.soft_wrap_mode(cx) {
13061                SoftWrap::GitDiff => return,
13062                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13063                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13064                    language_settings::SoftWrap::None
13065                }
13066            };
13067            self.soft_wrap_mode_override = Some(soft_wrap);
13068        }
13069        cx.notify();
13070    }
13071
13072    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13073        let Some(workspace) = self.workspace() else {
13074            return;
13075        };
13076        let fs = workspace.read(cx).app_state().fs.clone();
13077        let current_show = TabBarSettings::get_global(cx).show;
13078        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13079            setting.show = Some(!current_show);
13080        });
13081    }
13082
13083    pub fn toggle_indent_guides(
13084        &mut self,
13085        _: &ToggleIndentGuides,
13086        _: &mut Window,
13087        cx: &mut Context<Self>,
13088    ) {
13089        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13090            self.buffer
13091                .read(cx)
13092                .settings_at(0, cx)
13093                .indent_guides
13094                .enabled
13095        });
13096        self.show_indent_guides = Some(!currently_enabled);
13097        cx.notify();
13098    }
13099
13100    fn should_show_indent_guides(&self) -> Option<bool> {
13101        self.show_indent_guides
13102    }
13103
13104    pub fn toggle_line_numbers(
13105        &mut self,
13106        _: &ToggleLineNumbers,
13107        _: &mut Window,
13108        cx: &mut Context<Self>,
13109    ) {
13110        let mut editor_settings = EditorSettings::get_global(cx).clone();
13111        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13112        EditorSettings::override_global(editor_settings, cx);
13113    }
13114
13115    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13116        self.use_relative_line_numbers
13117            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13118    }
13119
13120    pub fn toggle_relative_line_numbers(
13121        &mut self,
13122        _: &ToggleRelativeLineNumbers,
13123        _: &mut Window,
13124        cx: &mut Context<Self>,
13125    ) {
13126        let is_relative = self.should_use_relative_line_numbers(cx);
13127        self.set_relative_line_number(Some(!is_relative), cx)
13128    }
13129
13130    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13131        self.use_relative_line_numbers = is_relative;
13132        cx.notify();
13133    }
13134
13135    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13136        self.show_gutter = show_gutter;
13137        cx.notify();
13138    }
13139
13140    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13141        self.show_scrollbars = show_scrollbars;
13142        cx.notify();
13143    }
13144
13145    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13146        self.show_line_numbers = Some(show_line_numbers);
13147        cx.notify();
13148    }
13149
13150    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13151        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13152        cx.notify();
13153    }
13154
13155    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13156        self.show_code_actions = Some(show_code_actions);
13157        cx.notify();
13158    }
13159
13160    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13161        self.show_runnables = Some(show_runnables);
13162        cx.notify();
13163    }
13164
13165    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13166        if self.display_map.read(cx).masked != masked {
13167            self.display_map.update(cx, |map, _| map.masked = masked);
13168        }
13169        cx.notify()
13170    }
13171
13172    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13173        self.show_wrap_guides = Some(show_wrap_guides);
13174        cx.notify();
13175    }
13176
13177    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13178        self.show_indent_guides = Some(show_indent_guides);
13179        cx.notify();
13180    }
13181
13182    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13183        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13184            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13185                if let Some(dir) = file.abs_path(cx).parent() {
13186                    return Some(dir.to_owned());
13187                }
13188            }
13189
13190            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13191                return Some(project_path.path.to_path_buf());
13192            }
13193        }
13194
13195        None
13196    }
13197
13198    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13199        self.active_excerpt(cx)?
13200            .1
13201            .read(cx)
13202            .file()
13203            .and_then(|f| f.as_local())
13204    }
13205
13206    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13207        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13208            let buffer = buffer.read(cx);
13209            if let Some(project_path) = buffer.project_path(cx) {
13210                let project = self.project.as_ref()?.read(cx);
13211                project.absolute_path(&project_path, cx)
13212            } else {
13213                buffer
13214                    .file()
13215                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13216            }
13217        })
13218    }
13219
13220    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13221        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13222            let project_path = buffer.read(cx).project_path(cx)?;
13223            let project = self.project.as_ref()?.read(cx);
13224            let entry = project.entry_for_path(&project_path, cx)?;
13225            let path = entry.path.to_path_buf();
13226            Some(path)
13227        })
13228    }
13229
13230    pub fn reveal_in_finder(
13231        &mut self,
13232        _: &RevealInFileManager,
13233        _window: &mut Window,
13234        cx: &mut Context<Self>,
13235    ) {
13236        if let Some(target) = self.target_file(cx) {
13237            cx.reveal_path(&target.abs_path(cx));
13238        }
13239    }
13240
13241    pub fn copy_path(
13242        &mut self,
13243        _: &zed_actions::workspace::CopyPath,
13244        _window: &mut Window,
13245        cx: &mut Context<Self>,
13246    ) {
13247        if let Some(path) = self.target_file_abs_path(cx) {
13248            if let Some(path) = path.to_str() {
13249                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13250            }
13251        }
13252    }
13253
13254    pub fn copy_relative_path(
13255        &mut self,
13256        _: &zed_actions::workspace::CopyRelativePath,
13257        _window: &mut Window,
13258        cx: &mut Context<Self>,
13259    ) {
13260        if let Some(path) = self.target_file_path(cx) {
13261            if let Some(path) = path.to_str() {
13262                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13263            }
13264        }
13265    }
13266
13267    pub fn copy_file_name_without_extension(
13268        &mut self,
13269        _: &CopyFileNameWithoutExtension,
13270        _: &mut Window,
13271        cx: &mut Context<Self>,
13272    ) {
13273        if let Some(file) = self.target_file(cx) {
13274            if let Some(file_stem) = file.path().file_stem() {
13275                if let Some(name) = file_stem.to_str() {
13276                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13277                }
13278            }
13279        }
13280    }
13281
13282    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13283        if let Some(file) = self.target_file(cx) {
13284            if let Some(file_name) = file.path().file_name() {
13285                if let Some(name) = file_name.to_str() {
13286                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13287                }
13288            }
13289        }
13290    }
13291
13292    pub fn toggle_git_blame(
13293        &mut self,
13294        _: &ToggleGitBlame,
13295        window: &mut Window,
13296        cx: &mut Context<Self>,
13297    ) {
13298        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13299
13300        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13301            self.start_git_blame(true, window, cx);
13302        }
13303
13304        cx.notify();
13305    }
13306
13307    pub fn toggle_git_blame_inline(
13308        &mut self,
13309        _: &ToggleGitBlameInline,
13310        window: &mut Window,
13311        cx: &mut Context<Self>,
13312    ) {
13313        self.toggle_git_blame_inline_internal(true, window, cx);
13314        cx.notify();
13315    }
13316
13317    pub fn git_blame_inline_enabled(&self) -> bool {
13318        self.git_blame_inline_enabled
13319    }
13320
13321    pub fn toggle_selection_menu(
13322        &mut self,
13323        _: &ToggleSelectionMenu,
13324        _: &mut Window,
13325        cx: &mut Context<Self>,
13326    ) {
13327        self.show_selection_menu = self
13328            .show_selection_menu
13329            .map(|show_selections_menu| !show_selections_menu)
13330            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13331
13332        cx.notify();
13333    }
13334
13335    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13336        self.show_selection_menu
13337            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13338    }
13339
13340    fn start_git_blame(
13341        &mut self,
13342        user_triggered: bool,
13343        window: &mut Window,
13344        cx: &mut Context<Self>,
13345    ) {
13346        if let Some(project) = self.project.as_ref() {
13347            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13348                return;
13349            };
13350
13351            if buffer.read(cx).file().is_none() {
13352                return;
13353            }
13354
13355            let focused = self.focus_handle(cx).contains_focused(window, cx);
13356
13357            let project = project.clone();
13358            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13359            self.blame_subscription =
13360                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13361            self.blame = Some(blame);
13362        }
13363    }
13364
13365    fn toggle_git_blame_inline_internal(
13366        &mut self,
13367        user_triggered: bool,
13368        window: &mut Window,
13369        cx: &mut Context<Self>,
13370    ) {
13371        if self.git_blame_inline_enabled {
13372            self.git_blame_inline_enabled = false;
13373            self.show_git_blame_inline = false;
13374            self.show_git_blame_inline_delay_task.take();
13375        } else {
13376            self.git_blame_inline_enabled = true;
13377            self.start_git_blame_inline(user_triggered, window, cx);
13378        }
13379
13380        cx.notify();
13381    }
13382
13383    fn start_git_blame_inline(
13384        &mut self,
13385        user_triggered: bool,
13386        window: &mut Window,
13387        cx: &mut Context<Self>,
13388    ) {
13389        self.start_git_blame(user_triggered, window, cx);
13390
13391        if ProjectSettings::get_global(cx)
13392            .git
13393            .inline_blame_delay()
13394            .is_some()
13395        {
13396            self.start_inline_blame_timer(window, cx);
13397        } else {
13398            self.show_git_blame_inline = true
13399        }
13400    }
13401
13402    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13403        self.blame.as_ref()
13404    }
13405
13406    pub fn show_git_blame_gutter(&self) -> bool {
13407        self.show_git_blame_gutter
13408    }
13409
13410    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13411        self.show_git_blame_gutter && self.has_blame_entries(cx)
13412    }
13413
13414    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13415        self.show_git_blame_inline
13416            && (self.focus_handle.is_focused(window)
13417                || self
13418                    .git_blame_inline_tooltip
13419                    .as_ref()
13420                    .and_then(|t| t.upgrade())
13421                    .is_some())
13422            && !self.newest_selection_head_on_empty_line(cx)
13423            && self.has_blame_entries(cx)
13424    }
13425
13426    fn has_blame_entries(&self, cx: &App) -> bool {
13427        self.blame()
13428            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13429    }
13430
13431    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13432        let cursor_anchor = self.selections.newest_anchor().head();
13433
13434        let snapshot = self.buffer.read(cx).snapshot(cx);
13435        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13436
13437        snapshot.line_len(buffer_row) == 0
13438    }
13439
13440    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13441        let buffer_and_selection = maybe!({
13442            let selection = self.selections.newest::<Point>(cx);
13443            let selection_range = selection.range();
13444
13445            let multi_buffer = self.buffer().read(cx);
13446            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13447            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13448
13449            let (buffer, range, _) = if selection.reversed {
13450                buffer_ranges.first()
13451            } else {
13452                buffer_ranges.last()
13453            }?;
13454
13455            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13456                ..text::ToPoint::to_point(&range.end, &buffer).row;
13457            Some((
13458                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13459                selection,
13460            ))
13461        });
13462
13463        let Some((buffer, selection)) = buffer_and_selection else {
13464            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13465        };
13466
13467        let Some(project) = self.project.as_ref() else {
13468            return Task::ready(Err(anyhow!("editor does not have project")));
13469        };
13470
13471        project.update(cx, |project, cx| {
13472            project.get_permalink_to_line(&buffer, selection, cx)
13473        })
13474    }
13475
13476    pub fn copy_permalink_to_line(
13477        &mut self,
13478        _: &CopyPermalinkToLine,
13479        window: &mut Window,
13480        cx: &mut Context<Self>,
13481    ) {
13482        let permalink_task = self.get_permalink_to_line(cx);
13483        let workspace = self.workspace();
13484
13485        cx.spawn_in(window, |_, mut cx| async move {
13486            match permalink_task.await {
13487                Ok(permalink) => {
13488                    cx.update(|_, cx| {
13489                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13490                    })
13491                    .ok();
13492                }
13493                Err(err) => {
13494                    let message = format!("Failed to copy permalink: {err}");
13495
13496                    Err::<(), anyhow::Error>(err).log_err();
13497
13498                    if let Some(workspace) = workspace {
13499                        workspace
13500                            .update_in(&mut cx, |workspace, _, cx| {
13501                                struct CopyPermalinkToLine;
13502
13503                                workspace.show_toast(
13504                                    Toast::new(
13505                                        NotificationId::unique::<CopyPermalinkToLine>(),
13506                                        message,
13507                                    ),
13508                                    cx,
13509                                )
13510                            })
13511                            .ok();
13512                    }
13513                }
13514            }
13515        })
13516        .detach();
13517    }
13518
13519    pub fn copy_file_location(
13520        &mut self,
13521        _: &CopyFileLocation,
13522        _: &mut Window,
13523        cx: &mut Context<Self>,
13524    ) {
13525        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13526        if let Some(file) = self.target_file(cx) {
13527            if let Some(path) = file.path().to_str() {
13528                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13529            }
13530        }
13531    }
13532
13533    pub fn open_permalink_to_line(
13534        &mut self,
13535        _: &OpenPermalinkToLine,
13536        window: &mut Window,
13537        cx: &mut Context<Self>,
13538    ) {
13539        let permalink_task = self.get_permalink_to_line(cx);
13540        let workspace = self.workspace();
13541
13542        cx.spawn_in(window, |_, mut cx| async move {
13543            match permalink_task.await {
13544                Ok(permalink) => {
13545                    cx.update(|_, cx| {
13546                        cx.open_url(permalink.as_ref());
13547                    })
13548                    .ok();
13549                }
13550                Err(err) => {
13551                    let message = format!("Failed to open permalink: {err}");
13552
13553                    Err::<(), anyhow::Error>(err).log_err();
13554
13555                    if let Some(workspace) = workspace {
13556                        workspace
13557                            .update(&mut cx, |workspace, cx| {
13558                                struct OpenPermalinkToLine;
13559
13560                                workspace.show_toast(
13561                                    Toast::new(
13562                                        NotificationId::unique::<OpenPermalinkToLine>(),
13563                                        message,
13564                                    ),
13565                                    cx,
13566                                )
13567                            })
13568                            .ok();
13569                    }
13570                }
13571            }
13572        })
13573        .detach();
13574    }
13575
13576    pub fn insert_uuid_v4(
13577        &mut self,
13578        _: &InsertUuidV4,
13579        window: &mut Window,
13580        cx: &mut Context<Self>,
13581    ) {
13582        self.insert_uuid(UuidVersion::V4, window, cx);
13583    }
13584
13585    pub fn insert_uuid_v7(
13586        &mut self,
13587        _: &InsertUuidV7,
13588        window: &mut Window,
13589        cx: &mut Context<Self>,
13590    ) {
13591        self.insert_uuid(UuidVersion::V7, window, cx);
13592    }
13593
13594    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13595        self.transact(window, cx, |this, window, cx| {
13596            let edits = this
13597                .selections
13598                .all::<Point>(cx)
13599                .into_iter()
13600                .map(|selection| {
13601                    let uuid = match version {
13602                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13603                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13604                    };
13605
13606                    (selection.range(), uuid.to_string())
13607                });
13608            this.edit(edits, cx);
13609            this.refresh_inline_completion(true, false, window, cx);
13610        });
13611    }
13612
13613    pub fn open_selections_in_multibuffer(
13614        &mut self,
13615        _: &OpenSelectionsInMultibuffer,
13616        window: &mut Window,
13617        cx: &mut Context<Self>,
13618    ) {
13619        let multibuffer = self.buffer.read(cx);
13620
13621        let Some(buffer) = multibuffer.as_singleton() else {
13622            return;
13623        };
13624
13625        let Some(workspace) = self.workspace() else {
13626            return;
13627        };
13628
13629        let locations = self
13630            .selections
13631            .disjoint_anchors()
13632            .iter()
13633            .map(|range| Location {
13634                buffer: buffer.clone(),
13635                range: range.start.text_anchor..range.end.text_anchor,
13636            })
13637            .collect::<Vec<_>>();
13638
13639        let title = multibuffer.title(cx).to_string();
13640
13641        cx.spawn_in(window, |_, mut cx| async move {
13642            workspace.update_in(&mut cx, |workspace, window, cx| {
13643                Self::open_locations_in_multibuffer(
13644                    workspace,
13645                    locations,
13646                    format!("Selections for '{title}'"),
13647                    false,
13648                    MultibufferSelectionMode::All,
13649                    window,
13650                    cx,
13651                );
13652            })
13653        })
13654        .detach();
13655    }
13656
13657    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13658    /// last highlight added will be used.
13659    ///
13660    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13661    pub fn highlight_rows<T: 'static>(
13662        &mut self,
13663        range: Range<Anchor>,
13664        color: Hsla,
13665        should_autoscroll: bool,
13666        cx: &mut Context<Self>,
13667    ) {
13668        let snapshot = self.buffer().read(cx).snapshot(cx);
13669        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13670        let ix = row_highlights.binary_search_by(|highlight| {
13671            Ordering::Equal
13672                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13673                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13674        });
13675
13676        if let Err(mut ix) = ix {
13677            let index = post_inc(&mut self.highlight_order);
13678
13679            // If this range intersects with the preceding highlight, then merge it with
13680            // the preceding highlight. Otherwise insert a new highlight.
13681            let mut merged = false;
13682            if ix > 0 {
13683                let prev_highlight = &mut row_highlights[ix - 1];
13684                if prev_highlight
13685                    .range
13686                    .end
13687                    .cmp(&range.start, &snapshot)
13688                    .is_ge()
13689                {
13690                    ix -= 1;
13691                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13692                        prev_highlight.range.end = range.end;
13693                    }
13694                    merged = true;
13695                    prev_highlight.index = index;
13696                    prev_highlight.color = color;
13697                    prev_highlight.should_autoscroll = should_autoscroll;
13698                }
13699            }
13700
13701            if !merged {
13702                row_highlights.insert(
13703                    ix,
13704                    RowHighlight {
13705                        range: range.clone(),
13706                        index,
13707                        color,
13708                        should_autoscroll,
13709                    },
13710                );
13711            }
13712
13713            // If any of the following highlights intersect with this one, merge them.
13714            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13715                let highlight = &row_highlights[ix];
13716                if next_highlight
13717                    .range
13718                    .start
13719                    .cmp(&highlight.range.end, &snapshot)
13720                    .is_le()
13721                {
13722                    if next_highlight
13723                        .range
13724                        .end
13725                        .cmp(&highlight.range.end, &snapshot)
13726                        .is_gt()
13727                    {
13728                        row_highlights[ix].range.end = next_highlight.range.end;
13729                    }
13730                    row_highlights.remove(ix + 1);
13731                } else {
13732                    break;
13733                }
13734            }
13735        }
13736    }
13737
13738    /// Remove any highlighted row ranges of the given type that intersect the
13739    /// given ranges.
13740    pub fn remove_highlighted_rows<T: 'static>(
13741        &mut self,
13742        ranges_to_remove: Vec<Range<Anchor>>,
13743        cx: &mut Context<Self>,
13744    ) {
13745        let snapshot = self.buffer().read(cx).snapshot(cx);
13746        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13747        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13748        row_highlights.retain(|highlight| {
13749            while let Some(range_to_remove) = ranges_to_remove.peek() {
13750                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13751                    Ordering::Less | Ordering::Equal => {
13752                        ranges_to_remove.next();
13753                    }
13754                    Ordering::Greater => {
13755                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13756                            Ordering::Less | Ordering::Equal => {
13757                                return false;
13758                            }
13759                            Ordering::Greater => break,
13760                        }
13761                    }
13762                }
13763            }
13764
13765            true
13766        })
13767    }
13768
13769    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13770    pub fn clear_row_highlights<T: 'static>(&mut self) {
13771        self.highlighted_rows.remove(&TypeId::of::<T>());
13772    }
13773
13774    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13775    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13776        self.highlighted_rows
13777            .get(&TypeId::of::<T>())
13778            .map_or(&[] as &[_], |vec| vec.as_slice())
13779            .iter()
13780            .map(|highlight| (highlight.range.clone(), highlight.color))
13781    }
13782
13783    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13784    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13785    /// Allows to ignore certain kinds of highlights.
13786    pub fn highlighted_display_rows(
13787        &self,
13788        window: &mut Window,
13789        cx: &mut App,
13790    ) -> BTreeMap<DisplayRow, Background> {
13791        let snapshot = self.snapshot(window, cx);
13792        let mut used_highlight_orders = HashMap::default();
13793        self.highlighted_rows
13794            .iter()
13795            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13796            .fold(
13797                BTreeMap::<DisplayRow, Background>::new(),
13798                |mut unique_rows, highlight| {
13799                    let start = highlight.range.start.to_display_point(&snapshot);
13800                    let end = highlight.range.end.to_display_point(&snapshot);
13801                    let start_row = start.row().0;
13802                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13803                        && end.column() == 0
13804                    {
13805                        end.row().0.saturating_sub(1)
13806                    } else {
13807                        end.row().0
13808                    };
13809                    for row in start_row..=end_row {
13810                        let used_index =
13811                            used_highlight_orders.entry(row).or_insert(highlight.index);
13812                        if highlight.index >= *used_index {
13813                            *used_index = highlight.index;
13814                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13815                        }
13816                    }
13817                    unique_rows
13818                },
13819            )
13820    }
13821
13822    pub fn highlighted_display_row_for_autoscroll(
13823        &self,
13824        snapshot: &DisplaySnapshot,
13825    ) -> Option<DisplayRow> {
13826        self.highlighted_rows
13827            .values()
13828            .flat_map(|highlighted_rows| highlighted_rows.iter())
13829            .filter_map(|highlight| {
13830                if highlight.should_autoscroll {
13831                    Some(highlight.range.start.to_display_point(snapshot).row())
13832                } else {
13833                    None
13834                }
13835            })
13836            .min()
13837    }
13838
13839    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13840        self.highlight_background::<SearchWithinRange>(
13841            ranges,
13842            |colors| colors.editor_document_highlight_read_background,
13843            cx,
13844        )
13845    }
13846
13847    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13848        self.breadcrumb_header = Some(new_header);
13849    }
13850
13851    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13852        self.clear_background_highlights::<SearchWithinRange>(cx);
13853    }
13854
13855    pub fn highlight_background<T: 'static>(
13856        &mut self,
13857        ranges: &[Range<Anchor>],
13858        color_fetcher: fn(&ThemeColors) -> Hsla,
13859        cx: &mut Context<Self>,
13860    ) {
13861        self.background_highlights
13862            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13863        self.scrollbar_marker_state.dirty = true;
13864        cx.notify();
13865    }
13866
13867    pub fn clear_background_highlights<T: 'static>(
13868        &mut self,
13869        cx: &mut Context<Self>,
13870    ) -> Option<BackgroundHighlight> {
13871        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13872        if !text_highlights.1.is_empty() {
13873            self.scrollbar_marker_state.dirty = true;
13874            cx.notify();
13875        }
13876        Some(text_highlights)
13877    }
13878
13879    pub fn highlight_gutter<T: 'static>(
13880        &mut self,
13881        ranges: &[Range<Anchor>],
13882        color_fetcher: fn(&App) -> Hsla,
13883        cx: &mut Context<Self>,
13884    ) {
13885        self.gutter_highlights
13886            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13887        cx.notify();
13888    }
13889
13890    pub fn clear_gutter_highlights<T: 'static>(
13891        &mut self,
13892        cx: &mut Context<Self>,
13893    ) -> Option<GutterHighlight> {
13894        cx.notify();
13895        self.gutter_highlights.remove(&TypeId::of::<T>())
13896    }
13897
13898    #[cfg(feature = "test-support")]
13899    pub fn all_text_background_highlights(
13900        &self,
13901        window: &mut Window,
13902        cx: &mut Context<Self>,
13903    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13904        let snapshot = self.snapshot(window, cx);
13905        let buffer = &snapshot.buffer_snapshot;
13906        let start = buffer.anchor_before(0);
13907        let end = buffer.anchor_after(buffer.len());
13908        let theme = cx.theme().colors();
13909        self.background_highlights_in_range(start..end, &snapshot, theme)
13910    }
13911
13912    #[cfg(feature = "test-support")]
13913    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13914        let snapshot = self.buffer().read(cx).snapshot(cx);
13915
13916        let highlights = self
13917            .background_highlights
13918            .get(&TypeId::of::<items::BufferSearchHighlights>());
13919
13920        if let Some((_color, ranges)) = highlights {
13921            ranges
13922                .iter()
13923                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13924                .collect_vec()
13925        } else {
13926            vec![]
13927        }
13928    }
13929
13930    fn document_highlights_for_position<'a>(
13931        &'a self,
13932        position: Anchor,
13933        buffer: &'a MultiBufferSnapshot,
13934    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13935        let read_highlights = self
13936            .background_highlights
13937            .get(&TypeId::of::<DocumentHighlightRead>())
13938            .map(|h| &h.1);
13939        let write_highlights = self
13940            .background_highlights
13941            .get(&TypeId::of::<DocumentHighlightWrite>())
13942            .map(|h| &h.1);
13943        let left_position = position.bias_left(buffer);
13944        let right_position = position.bias_right(buffer);
13945        read_highlights
13946            .into_iter()
13947            .chain(write_highlights)
13948            .flat_map(move |ranges| {
13949                let start_ix = match ranges.binary_search_by(|probe| {
13950                    let cmp = probe.end.cmp(&left_position, buffer);
13951                    if cmp.is_ge() {
13952                        Ordering::Greater
13953                    } else {
13954                        Ordering::Less
13955                    }
13956                }) {
13957                    Ok(i) | Err(i) => i,
13958                };
13959
13960                ranges[start_ix..]
13961                    .iter()
13962                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13963            })
13964    }
13965
13966    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13967        self.background_highlights
13968            .get(&TypeId::of::<T>())
13969            .map_or(false, |(_, highlights)| !highlights.is_empty())
13970    }
13971
13972    pub fn background_highlights_in_range(
13973        &self,
13974        search_range: Range<Anchor>,
13975        display_snapshot: &DisplaySnapshot,
13976        theme: &ThemeColors,
13977    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13978        let mut results = Vec::new();
13979        for (color_fetcher, ranges) in self.background_highlights.values() {
13980            let color = color_fetcher(theme);
13981            let start_ix = match ranges.binary_search_by(|probe| {
13982                let cmp = probe
13983                    .end
13984                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13985                if cmp.is_gt() {
13986                    Ordering::Greater
13987                } else {
13988                    Ordering::Less
13989                }
13990            }) {
13991                Ok(i) | Err(i) => i,
13992            };
13993            for range in &ranges[start_ix..] {
13994                if range
13995                    .start
13996                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13997                    .is_ge()
13998                {
13999                    break;
14000                }
14001
14002                let start = range.start.to_display_point(display_snapshot);
14003                let end = range.end.to_display_point(display_snapshot);
14004                results.push((start..end, color))
14005            }
14006        }
14007        results
14008    }
14009
14010    pub fn background_highlight_row_ranges<T: 'static>(
14011        &self,
14012        search_range: Range<Anchor>,
14013        display_snapshot: &DisplaySnapshot,
14014        count: usize,
14015    ) -> Vec<RangeInclusive<DisplayPoint>> {
14016        let mut results = Vec::new();
14017        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14018            return vec![];
14019        };
14020
14021        let start_ix = match ranges.binary_search_by(|probe| {
14022            let cmp = probe
14023                .end
14024                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14025            if cmp.is_gt() {
14026                Ordering::Greater
14027            } else {
14028                Ordering::Less
14029            }
14030        }) {
14031            Ok(i) | Err(i) => i,
14032        };
14033        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14034            if let (Some(start_display), Some(end_display)) = (start, end) {
14035                results.push(
14036                    start_display.to_display_point(display_snapshot)
14037                        ..=end_display.to_display_point(display_snapshot),
14038                );
14039            }
14040        };
14041        let mut start_row: Option<Point> = None;
14042        let mut end_row: Option<Point> = None;
14043        if ranges.len() > count {
14044            return Vec::new();
14045        }
14046        for range in &ranges[start_ix..] {
14047            if range
14048                .start
14049                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14050                .is_ge()
14051            {
14052                break;
14053            }
14054            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14055            if let Some(current_row) = &end_row {
14056                if end.row == current_row.row {
14057                    continue;
14058                }
14059            }
14060            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14061            if start_row.is_none() {
14062                assert_eq!(end_row, None);
14063                start_row = Some(start);
14064                end_row = Some(end);
14065                continue;
14066            }
14067            if let Some(current_end) = end_row.as_mut() {
14068                if start.row > current_end.row + 1 {
14069                    push_region(start_row, end_row);
14070                    start_row = Some(start);
14071                    end_row = Some(end);
14072                } else {
14073                    // Merge two hunks.
14074                    *current_end = end;
14075                }
14076            } else {
14077                unreachable!();
14078            }
14079        }
14080        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14081        push_region(start_row, end_row);
14082        results
14083    }
14084
14085    pub fn gutter_highlights_in_range(
14086        &self,
14087        search_range: Range<Anchor>,
14088        display_snapshot: &DisplaySnapshot,
14089        cx: &App,
14090    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14091        let mut results = Vec::new();
14092        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14093            let color = color_fetcher(cx);
14094            let start_ix = match ranges.binary_search_by(|probe| {
14095                let cmp = probe
14096                    .end
14097                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14098                if cmp.is_gt() {
14099                    Ordering::Greater
14100                } else {
14101                    Ordering::Less
14102                }
14103            }) {
14104                Ok(i) | Err(i) => i,
14105            };
14106            for range in &ranges[start_ix..] {
14107                if range
14108                    .start
14109                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14110                    .is_ge()
14111                {
14112                    break;
14113                }
14114
14115                let start = range.start.to_display_point(display_snapshot);
14116                let end = range.end.to_display_point(display_snapshot);
14117                results.push((start..end, color))
14118            }
14119        }
14120        results
14121    }
14122
14123    /// Get the text ranges corresponding to the redaction query
14124    pub fn redacted_ranges(
14125        &self,
14126        search_range: Range<Anchor>,
14127        display_snapshot: &DisplaySnapshot,
14128        cx: &App,
14129    ) -> Vec<Range<DisplayPoint>> {
14130        display_snapshot
14131            .buffer_snapshot
14132            .redacted_ranges(search_range, |file| {
14133                if let Some(file) = file {
14134                    file.is_private()
14135                        && EditorSettings::get(
14136                            Some(SettingsLocation {
14137                                worktree_id: file.worktree_id(cx),
14138                                path: file.path().as_ref(),
14139                            }),
14140                            cx,
14141                        )
14142                        .redact_private_values
14143                } else {
14144                    false
14145                }
14146            })
14147            .map(|range| {
14148                range.start.to_display_point(display_snapshot)
14149                    ..range.end.to_display_point(display_snapshot)
14150            })
14151            .collect()
14152    }
14153
14154    pub fn highlight_text<T: 'static>(
14155        &mut self,
14156        ranges: Vec<Range<Anchor>>,
14157        style: HighlightStyle,
14158        cx: &mut Context<Self>,
14159    ) {
14160        self.display_map.update(cx, |map, _| {
14161            map.highlight_text(TypeId::of::<T>(), ranges, style)
14162        });
14163        cx.notify();
14164    }
14165
14166    pub(crate) fn highlight_inlays<T: 'static>(
14167        &mut self,
14168        highlights: Vec<InlayHighlight>,
14169        style: HighlightStyle,
14170        cx: &mut Context<Self>,
14171    ) {
14172        self.display_map.update(cx, |map, _| {
14173            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14174        });
14175        cx.notify();
14176    }
14177
14178    pub fn text_highlights<'a, T: 'static>(
14179        &'a self,
14180        cx: &'a App,
14181    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14182        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14183    }
14184
14185    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14186        let cleared = self
14187            .display_map
14188            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14189        if cleared {
14190            cx.notify();
14191        }
14192    }
14193
14194    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14195        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14196            && self.focus_handle.is_focused(window)
14197    }
14198
14199    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14200        self.show_cursor_when_unfocused = is_enabled;
14201        cx.notify();
14202    }
14203
14204    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14205        cx.notify();
14206    }
14207
14208    fn on_buffer_event(
14209        &mut self,
14210        multibuffer: &Entity<MultiBuffer>,
14211        event: &multi_buffer::Event,
14212        window: &mut Window,
14213        cx: &mut Context<Self>,
14214    ) {
14215        match event {
14216            multi_buffer::Event::Edited {
14217                singleton_buffer_edited,
14218                edited_buffer: buffer_edited,
14219            } => {
14220                self.scrollbar_marker_state.dirty = true;
14221                self.active_indent_guides_state.dirty = true;
14222                self.refresh_active_diagnostics(cx);
14223                self.refresh_code_actions(window, cx);
14224                if self.has_active_inline_completion() {
14225                    self.update_visible_inline_completion(window, cx);
14226                }
14227                if let Some(buffer) = buffer_edited {
14228                    let buffer_id = buffer.read(cx).remote_id();
14229                    if !self.registered_buffers.contains_key(&buffer_id) {
14230                        if let Some(project) = self.project.as_ref() {
14231                            project.update(cx, |project, cx| {
14232                                self.registered_buffers.insert(
14233                                    buffer_id,
14234                                    project.register_buffer_with_language_servers(&buffer, cx),
14235                                );
14236                            })
14237                        }
14238                    }
14239                }
14240                cx.emit(EditorEvent::BufferEdited);
14241                cx.emit(SearchEvent::MatchesInvalidated);
14242                if *singleton_buffer_edited {
14243                    if let Some(project) = &self.project {
14244                        #[allow(clippy::mutable_key_type)]
14245                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14246                            multibuffer
14247                                .all_buffers()
14248                                .into_iter()
14249                                .filter_map(|buffer| {
14250                                    buffer.update(cx, |buffer, cx| {
14251                                        let language = buffer.language()?;
14252                                        let should_discard = project.update(cx, |project, cx| {
14253                                            project.is_local()
14254                                                && !project.has_language_servers_for(buffer, cx)
14255                                        });
14256                                        should_discard.not().then_some(language.clone())
14257                                    })
14258                                })
14259                                .collect::<HashSet<_>>()
14260                        });
14261                        if !languages_affected.is_empty() {
14262                            self.refresh_inlay_hints(
14263                                InlayHintRefreshReason::BufferEdited(languages_affected),
14264                                cx,
14265                            );
14266                        }
14267                    }
14268                }
14269
14270                let Some(project) = &self.project else { return };
14271                let (telemetry, is_via_ssh) = {
14272                    let project = project.read(cx);
14273                    let telemetry = project.client().telemetry().clone();
14274                    let is_via_ssh = project.is_via_ssh();
14275                    (telemetry, is_via_ssh)
14276                };
14277                refresh_linked_ranges(self, window, cx);
14278                telemetry.log_edit_event("editor", is_via_ssh);
14279            }
14280            multi_buffer::Event::ExcerptsAdded {
14281                buffer,
14282                predecessor,
14283                excerpts,
14284            } => {
14285                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14286                let buffer_id = buffer.read(cx).remote_id();
14287                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14288                    if let Some(project) = &self.project {
14289                        get_uncommitted_diff_for_buffer(
14290                            project,
14291                            [buffer.clone()],
14292                            self.buffer.clone(),
14293                            cx,
14294                        )
14295                        .detach();
14296                    }
14297                }
14298                cx.emit(EditorEvent::ExcerptsAdded {
14299                    buffer: buffer.clone(),
14300                    predecessor: *predecessor,
14301                    excerpts: excerpts.clone(),
14302                });
14303                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14304            }
14305            multi_buffer::Event::ExcerptsRemoved { ids } => {
14306                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14307                let buffer = self.buffer.read(cx);
14308                self.registered_buffers
14309                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14310                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14311            }
14312            multi_buffer::Event::ExcerptsEdited { ids } => {
14313                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14314            }
14315            multi_buffer::Event::ExcerptsExpanded { ids } => {
14316                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14317                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14318            }
14319            multi_buffer::Event::Reparsed(buffer_id) => {
14320                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14321
14322                cx.emit(EditorEvent::Reparsed(*buffer_id));
14323            }
14324            multi_buffer::Event::DiffHunksToggled => {
14325                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14326            }
14327            multi_buffer::Event::LanguageChanged(buffer_id) => {
14328                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14329                cx.emit(EditorEvent::Reparsed(*buffer_id));
14330                cx.notify();
14331            }
14332            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14333            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14334            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14335                cx.emit(EditorEvent::TitleChanged)
14336            }
14337            // multi_buffer::Event::DiffBaseChanged => {
14338            //     self.scrollbar_marker_state.dirty = true;
14339            //     cx.emit(EditorEvent::DiffBaseChanged);
14340            //     cx.notify();
14341            // }
14342            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14343            multi_buffer::Event::DiagnosticsUpdated => {
14344                self.refresh_active_diagnostics(cx);
14345                self.scrollbar_marker_state.dirty = true;
14346                cx.notify();
14347            }
14348            _ => {}
14349        };
14350    }
14351
14352    fn on_display_map_changed(
14353        &mut self,
14354        _: Entity<DisplayMap>,
14355        _: &mut Window,
14356        cx: &mut Context<Self>,
14357    ) {
14358        cx.notify();
14359    }
14360
14361    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14362        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14363        self.refresh_inline_completion(true, false, window, cx);
14364        self.refresh_inlay_hints(
14365            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14366                self.selections.newest_anchor().head(),
14367                &self.buffer.read(cx).snapshot(cx),
14368                cx,
14369            )),
14370            cx,
14371        );
14372
14373        let old_cursor_shape = self.cursor_shape;
14374
14375        {
14376            let editor_settings = EditorSettings::get_global(cx);
14377            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14378            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14379            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14380        }
14381
14382        if old_cursor_shape != self.cursor_shape {
14383            cx.emit(EditorEvent::CursorShapeChanged);
14384        }
14385
14386        let project_settings = ProjectSettings::get_global(cx);
14387        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14388
14389        if self.mode == EditorMode::Full {
14390            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14391            if self.git_blame_inline_enabled != inline_blame_enabled {
14392                self.toggle_git_blame_inline_internal(false, window, cx);
14393            }
14394        }
14395
14396        cx.notify();
14397    }
14398
14399    pub fn set_searchable(&mut self, searchable: bool) {
14400        self.searchable = searchable;
14401    }
14402
14403    pub fn searchable(&self) -> bool {
14404        self.searchable
14405    }
14406
14407    fn open_proposed_changes_editor(
14408        &mut self,
14409        _: &OpenProposedChangesEditor,
14410        window: &mut Window,
14411        cx: &mut Context<Self>,
14412    ) {
14413        let Some(workspace) = self.workspace() else {
14414            cx.propagate();
14415            return;
14416        };
14417
14418        let selections = self.selections.all::<usize>(cx);
14419        let multi_buffer = self.buffer.read(cx);
14420        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14421        let mut new_selections_by_buffer = HashMap::default();
14422        for selection in selections {
14423            for (buffer, range, _) in
14424                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14425            {
14426                let mut range = range.to_point(buffer);
14427                range.start.column = 0;
14428                range.end.column = buffer.line_len(range.end.row);
14429                new_selections_by_buffer
14430                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14431                    .or_insert(Vec::new())
14432                    .push(range)
14433            }
14434        }
14435
14436        let proposed_changes_buffers = new_selections_by_buffer
14437            .into_iter()
14438            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14439            .collect::<Vec<_>>();
14440        let proposed_changes_editor = cx.new(|cx| {
14441            ProposedChangesEditor::new(
14442                "Proposed changes",
14443                proposed_changes_buffers,
14444                self.project.clone(),
14445                window,
14446                cx,
14447            )
14448        });
14449
14450        window.defer(cx, move |window, cx| {
14451            workspace.update(cx, |workspace, cx| {
14452                workspace.active_pane().update(cx, |pane, cx| {
14453                    pane.add_item(
14454                        Box::new(proposed_changes_editor),
14455                        true,
14456                        true,
14457                        None,
14458                        window,
14459                        cx,
14460                    );
14461                });
14462            });
14463        });
14464    }
14465
14466    pub fn open_excerpts_in_split(
14467        &mut self,
14468        _: &OpenExcerptsSplit,
14469        window: &mut Window,
14470        cx: &mut Context<Self>,
14471    ) {
14472        self.open_excerpts_common(None, true, window, cx)
14473    }
14474
14475    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14476        self.open_excerpts_common(None, false, window, cx)
14477    }
14478
14479    fn open_excerpts_common(
14480        &mut self,
14481        jump_data: Option<JumpData>,
14482        split: bool,
14483        window: &mut Window,
14484        cx: &mut Context<Self>,
14485    ) {
14486        let Some(workspace) = self.workspace() else {
14487            cx.propagate();
14488            return;
14489        };
14490
14491        if self.buffer.read(cx).is_singleton() {
14492            cx.propagate();
14493            return;
14494        }
14495
14496        let mut new_selections_by_buffer = HashMap::default();
14497        match &jump_data {
14498            Some(JumpData::MultiBufferPoint {
14499                excerpt_id,
14500                position,
14501                anchor,
14502                line_offset_from_top,
14503            }) => {
14504                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14505                if let Some(buffer) = multi_buffer_snapshot
14506                    .buffer_id_for_excerpt(*excerpt_id)
14507                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14508                {
14509                    let buffer_snapshot = buffer.read(cx).snapshot();
14510                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14511                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14512                    } else {
14513                        buffer_snapshot.clip_point(*position, Bias::Left)
14514                    };
14515                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14516                    new_selections_by_buffer.insert(
14517                        buffer,
14518                        (
14519                            vec![jump_to_offset..jump_to_offset],
14520                            Some(*line_offset_from_top),
14521                        ),
14522                    );
14523                }
14524            }
14525            Some(JumpData::MultiBufferRow {
14526                row,
14527                line_offset_from_top,
14528            }) => {
14529                let point = MultiBufferPoint::new(row.0, 0);
14530                if let Some((buffer, buffer_point, _)) =
14531                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14532                {
14533                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14534                    new_selections_by_buffer
14535                        .entry(buffer)
14536                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14537                        .0
14538                        .push(buffer_offset..buffer_offset)
14539                }
14540            }
14541            None => {
14542                let selections = self.selections.all::<usize>(cx);
14543                let multi_buffer = self.buffer.read(cx);
14544                for selection in selections {
14545                    for (buffer, mut range, _) in multi_buffer
14546                        .snapshot(cx)
14547                        .range_to_buffer_ranges(selection.range())
14548                    {
14549                        // When editing branch buffers, jump to the corresponding location
14550                        // in their base buffer.
14551                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14552                        let buffer = buffer_handle.read(cx);
14553                        if let Some(base_buffer) = buffer.base_buffer() {
14554                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14555                            buffer_handle = base_buffer;
14556                        }
14557
14558                        if selection.reversed {
14559                            mem::swap(&mut range.start, &mut range.end);
14560                        }
14561                        new_selections_by_buffer
14562                            .entry(buffer_handle)
14563                            .or_insert((Vec::new(), None))
14564                            .0
14565                            .push(range)
14566                    }
14567                }
14568            }
14569        }
14570
14571        if new_selections_by_buffer.is_empty() {
14572            return;
14573        }
14574
14575        // We defer the pane interaction because we ourselves are a workspace item
14576        // and activating a new item causes the pane to call a method on us reentrantly,
14577        // which panics if we're on the stack.
14578        window.defer(cx, move |window, cx| {
14579            workspace.update(cx, |workspace, cx| {
14580                let pane = if split {
14581                    workspace.adjacent_pane(window, cx)
14582                } else {
14583                    workspace.active_pane().clone()
14584                };
14585
14586                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14587                    let editor = buffer
14588                        .read(cx)
14589                        .file()
14590                        .is_none()
14591                        .then(|| {
14592                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14593                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14594                            // Instead, we try to activate the existing editor in the pane first.
14595                            let (editor, pane_item_index) =
14596                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14597                                    let editor = item.downcast::<Editor>()?;
14598                                    let singleton_buffer =
14599                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14600                                    if singleton_buffer == buffer {
14601                                        Some((editor, i))
14602                                    } else {
14603                                        None
14604                                    }
14605                                })?;
14606                            pane.update(cx, |pane, cx| {
14607                                pane.activate_item(pane_item_index, true, true, window, cx)
14608                            });
14609                            Some(editor)
14610                        })
14611                        .flatten()
14612                        .unwrap_or_else(|| {
14613                            workspace.open_project_item::<Self>(
14614                                pane.clone(),
14615                                buffer,
14616                                true,
14617                                true,
14618                                window,
14619                                cx,
14620                            )
14621                        });
14622
14623                    editor.update(cx, |editor, cx| {
14624                        let autoscroll = match scroll_offset {
14625                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14626                            None => Autoscroll::newest(),
14627                        };
14628                        let nav_history = editor.nav_history.take();
14629                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14630                            s.select_ranges(ranges);
14631                        });
14632                        editor.nav_history = nav_history;
14633                    });
14634                }
14635            })
14636        });
14637    }
14638
14639    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14640        let snapshot = self.buffer.read(cx).read(cx);
14641        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14642        Some(
14643            ranges
14644                .iter()
14645                .map(move |range| {
14646                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14647                })
14648                .collect(),
14649        )
14650    }
14651
14652    fn selection_replacement_ranges(
14653        &self,
14654        range: Range<OffsetUtf16>,
14655        cx: &mut App,
14656    ) -> Vec<Range<OffsetUtf16>> {
14657        let selections = self.selections.all::<OffsetUtf16>(cx);
14658        let newest_selection = selections
14659            .iter()
14660            .max_by_key(|selection| selection.id)
14661            .unwrap();
14662        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14663        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14664        let snapshot = self.buffer.read(cx).read(cx);
14665        selections
14666            .into_iter()
14667            .map(|mut selection| {
14668                selection.start.0 =
14669                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14670                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14671                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14672                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14673            })
14674            .collect()
14675    }
14676
14677    fn report_editor_event(
14678        &self,
14679        event_type: &'static str,
14680        file_extension: Option<String>,
14681        cx: &App,
14682    ) {
14683        if cfg!(any(test, feature = "test-support")) {
14684            return;
14685        }
14686
14687        let Some(project) = &self.project else { return };
14688
14689        // If None, we are in a file without an extension
14690        let file = self
14691            .buffer
14692            .read(cx)
14693            .as_singleton()
14694            .and_then(|b| b.read(cx).file());
14695        let file_extension = file_extension.or(file
14696            .as_ref()
14697            .and_then(|file| Path::new(file.file_name(cx)).extension())
14698            .and_then(|e| e.to_str())
14699            .map(|a| a.to_string()));
14700
14701        let vim_mode = cx
14702            .global::<SettingsStore>()
14703            .raw_user_settings()
14704            .get("vim_mode")
14705            == Some(&serde_json::Value::Bool(true));
14706
14707        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14708        let copilot_enabled = edit_predictions_provider
14709            == language::language_settings::EditPredictionProvider::Copilot;
14710        let copilot_enabled_for_language = self
14711            .buffer
14712            .read(cx)
14713            .settings_at(0, cx)
14714            .show_edit_predictions;
14715
14716        let project = project.read(cx);
14717        telemetry::event!(
14718            event_type,
14719            file_extension,
14720            vim_mode,
14721            copilot_enabled,
14722            copilot_enabled_for_language,
14723            edit_predictions_provider,
14724            is_via_ssh = project.is_via_ssh(),
14725        );
14726    }
14727
14728    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14729    /// with each line being an array of {text, highlight} objects.
14730    fn copy_highlight_json(
14731        &mut self,
14732        _: &CopyHighlightJson,
14733        window: &mut Window,
14734        cx: &mut Context<Self>,
14735    ) {
14736        #[derive(Serialize)]
14737        struct Chunk<'a> {
14738            text: String,
14739            highlight: Option<&'a str>,
14740        }
14741
14742        let snapshot = self.buffer.read(cx).snapshot(cx);
14743        let range = self
14744            .selected_text_range(false, window, cx)
14745            .and_then(|selection| {
14746                if selection.range.is_empty() {
14747                    None
14748                } else {
14749                    Some(selection.range)
14750                }
14751            })
14752            .unwrap_or_else(|| 0..snapshot.len());
14753
14754        let chunks = snapshot.chunks(range, true);
14755        let mut lines = Vec::new();
14756        let mut line: VecDeque<Chunk> = VecDeque::new();
14757
14758        let Some(style) = self.style.as_ref() else {
14759            return;
14760        };
14761
14762        for chunk in chunks {
14763            let highlight = chunk
14764                .syntax_highlight_id
14765                .and_then(|id| id.name(&style.syntax));
14766            let mut chunk_lines = chunk.text.split('\n').peekable();
14767            while let Some(text) = chunk_lines.next() {
14768                let mut merged_with_last_token = false;
14769                if let Some(last_token) = line.back_mut() {
14770                    if last_token.highlight == highlight {
14771                        last_token.text.push_str(text);
14772                        merged_with_last_token = true;
14773                    }
14774                }
14775
14776                if !merged_with_last_token {
14777                    line.push_back(Chunk {
14778                        text: text.into(),
14779                        highlight,
14780                    });
14781                }
14782
14783                if chunk_lines.peek().is_some() {
14784                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14785                        line.pop_front();
14786                    }
14787                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14788                        line.pop_back();
14789                    }
14790
14791                    lines.push(mem::take(&mut line));
14792                }
14793            }
14794        }
14795
14796        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14797            return;
14798        };
14799        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14800    }
14801
14802    pub fn open_context_menu(
14803        &mut self,
14804        _: &OpenContextMenu,
14805        window: &mut Window,
14806        cx: &mut Context<Self>,
14807    ) {
14808        self.request_autoscroll(Autoscroll::newest(), cx);
14809        let position = self.selections.newest_display(cx).start;
14810        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14811    }
14812
14813    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14814        &self.inlay_hint_cache
14815    }
14816
14817    pub fn replay_insert_event(
14818        &mut self,
14819        text: &str,
14820        relative_utf16_range: Option<Range<isize>>,
14821        window: &mut Window,
14822        cx: &mut Context<Self>,
14823    ) {
14824        if !self.input_enabled {
14825            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14826            return;
14827        }
14828        if let Some(relative_utf16_range) = relative_utf16_range {
14829            let selections = self.selections.all::<OffsetUtf16>(cx);
14830            self.change_selections(None, window, cx, |s| {
14831                let new_ranges = selections.into_iter().map(|range| {
14832                    let start = OffsetUtf16(
14833                        range
14834                            .head()
14835                            .0
14836                            .saturating_add_signed(relative_utf16_range.start),
14837                    );
14838                    let end = OffsetUtf16(
14839                        range
14840                            .head()
14841                            .0
14842                            .saturating_add_signed(relative_utf16_range.end),
14843                    );
14844                    start..end
14845                });
14846                s.select_ranges(new_ranges);
14847            });
14848        }
14849
14850        self.handle_input(text, window, cx);
14851    }
14852
14853    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14854        let Some(provider) = self.semantics_provider.as_ref() else {
14855            return false;
14856        };
14857
14858        let mut supports = false;
14859        self.buffer().update(cx, |this, cx| {
14860            this.for_each_buffer(|buffer| {
14861                supports |= provider.supports_inlay_hints(buffer, cx);
14862            });
14863        });
14864
14865        supports
14866    }
14867
14868    pub fn is_focused(&self, window: &Window) -> bool {
14869        self.focus_handle.is_focused(window)
14870    }
14871
14872    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14873        cx.emit(EditorEvent::Focused);
14874
14875        if let Some(descendant) = self
14876            .last_focused_descendant
14877            .take()
14878            .and_then(|descendant| descendant.upgrade())
14879        {
14880            window.focus(&descendant);
14881        } else {
14882            if let Some(blame) = self.blame.as_ref() {
14883                blame.update(cx, GitBlame::focus)
14884            }
14885
14886            self.blink_manager.update(cx, BlinkManager::enable);
14887            self.show_cursor_names(window, cx);
14888            self.buffer.update(cx, |buffer, cx| {
14889                buffer.finalize_last_transaction(cx);
14890                if self.leader_peer_id.is_none() {
14891                    buffer.set_active_selections(
14892                        &self.selections.disjoint_anchors(),
14893                        self.selections.line_mode,
14894                        self.cursor_shape,
14895                        cx,
14896                    );
14897                }
14898            });
14899        }
14900    }
14901
14902    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14903        cx.emit(EditorEvent::FocusedIn)
14904    }
14905
14906    fn handle_focus_out(
14907        &mut self,
14908        event: FocusOutEvent,
14909        _window: &mut Window,
14910        _cx: &mut Context<Self>,
14911    ) {
14912        if event.blurred != self.focus_handle {
14913            self.last_focused_descendant = Some(event.blurred);
14914        }
14915    }
14916
14917    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14918        self.blink_manager.update(cx, BlinkManager::disable);
14919        self.buffer
14920            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14921
14922        if let Some(blame) = self.blame.as_ref() {
14923            blame.update(cx, GitBlame::blur)
14924        }
14925        if !self.hover_state.focused(window, cx) {
14926            hide_hover(self, cx);
14927        }
14928        if !self
14929            .context_menu
14930            .borrow()
14931            .as_ref()
14932            .is_some_and(|context_menu| context_menu.focused(window, cx))
14933        {
14934            self.hide_context_menu(window, cx);
14935        }
14936        self.discard_inline_completion(false, cx);
14937        cx.emit(EditorEvent::Blurred);
14938        cx.notify();
14939    }
14940
14941    pub fn register_action<A: Action>(
14942        &mut self,
14943        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14944    ) -> Subscription {
14945        let id = self.next_editor_action_id.post_inc();
14946        let listener = Arc::new(listener);
14947        self.editor_actions.borrow_mut().insert(
14948            id,
14949            Box::new(move |window, _| {
14950                let listener = listener.clone();
14951                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14952                    let action = action.downcast_ref().unwrap();
14953                    if phase == DispatchPhase::Bubble {
14954                        listener(action, window, cx)
14955                    }
14956                })
14957            }),
14958        );
14959
14960        let editor_actions = self.editor_actions.clone();
14961        Subscription::new(move || {
14962            editor_actions.borrow_mut().remove(&id);
14963        })
14964    }
14965
14966    pub fn file_header_size(&self) -> u32 {
14967        FILE_HEADER_HEIGHT
14968    }
14969
14970    pub fn revert(
14971        &mut self,
14972        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14973        window: &mut Window,
14974        cx: &mut Context<Self>,
14975    ) {
14976        self.buffer().update(cx, |multi_buffer, cx| {
14977            for (buffer_id, changes) in revert_changes {
14978                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14979                    buffer.update(cx, |buffer, cx| {
14980                        buffer.edit(
14981                            changes.into_iter().map(|(range, text)| {
14982                                (range, text.to_string().map(Arc::<str>::from))
14983                            }),
14984                            None,
14985                            cx,
14986                        );
14987                    });
14988                }
14989            }
14990        });
14991        self.change_selections(None, window, cx, |selections| selections.refresh());
14992    }
14993
14994    pub fn to_pixel_point(
14995        &self,
14996        source: multi_buffer::Anchor,
14997        editor_snapshot: &EditorSnapshot,
14998        window: &mut Window,
14999    ) -> Option<gpui::Point<Pixels>> {
15000        let source_point = source.to_display_point(editor_snapshot);
15001        self.display_to_pixel_point(source_point, editor_snapshot, window)
15002    }
15003
15004    pub fn display_to_pixel_point(
15005        &self,
15006        source: DisplayPoint,
15007        editor_snapshot: &EditorSnapshot,
15008        window: &mut Window,
15009    ) -> Option<gpui::Point<Pixels>> {
15010        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15011        let text_layout_details = self.text_layout_details(window);
15012        let scroll_top = text_layout_details
15013            .scroll_anchor
15014            .scroll_position(editor_snapshot)
15015            .y;
15016
15017        if source.row().as_f32() < scroll_top.floor() {
15018            return None;
15019        }
15020        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15021        let source_y = line_height * (source.row().as_f32() - scroll_top);
15022        Some(gpui::Point::new(source_x, source_y))
15023    }
15024
15025    pub fn has_visible_completions_menu(&self) -> bool {
15026        !self.edit_prediction_preview_is_active()
15027            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15028                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15029            })
15030    }
15031
15032    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15033        self.addons
15034            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15035    }
15036
15037    pub fn unregister_addon<T: Addon>(&mut self) {
15038        self.addons.remove(&std::any::TypeId::of::<T>());
15039    }
15040
15041    pub fn addon<T: Addon>(&self) -> Option<&T> {
15042        let type_id = std::any::TypeId::of::<T>();
15043        self.addons
15044            .get(&type_id)
15045            .and_then(|item| item.to_any().downcast_ref::<T>())
15046    }
15047
15048    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15049        let text_layout_details = self.text_layout_details(window);
15050        let style = &text_layout_details.editor_style;
15051        let font_id = window.text_system().resolve_font(&style.text.font());
15052        let font_size = style.text.font_size.to_pixels(window.rem_size());
15053        let line_height = style.text.line_height_in_pixels(window.rem_size());
15054        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15055
15056        gpui::Size::new(em_width, line_height)
15057    }
15058
15059    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15060        self.load_diff_task.clone()
15061    }
15062
15063    fn read_selections_from_db(
15064        &mut self,
15065        item_id: u64,
15066        workspace_id: WorkspaceId,
15067        window: &mut Window,
15068        cx: &mut Context<Editor>,
15069    ) {
15070        if !self.is_singleton(cx)
15071            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15072        {
15073            return;
15074        }
15075        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15076            return;
15077        };
15078        if selections.is_empty() {
15079            return;
15080        }
15081
15082        let snapshot = self.buffer.read(cx).snapshot(cx);
15083        self.change_selections(None, window, cx, |s| {
15084            s.select_ranges(selections.into_iter().map(|(start, end)| {
15085                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15086            }));
15087        });
15088    }
15089}
15090
15091fn get_uncommitted_diff_for_buffer(
15092    project: &Entity<Project>,
15093    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15094    buffer: Entity<MultiBuffer>,
15095    cx: &mut App,
15096) -> Task<()> {
15097    let mut tasks = Vec::new();
15098    project.update(cx, |project, cx| {
15099        for buffer in buffers {
15100            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15101        }
15102    });
15103    cx.spawn(|mut cx| async move {
15104        let diffs = futures::future::join_all(tasks).await;
15105        buffer
15106            .update(&mut cx, |buffer, cx| {
15107                for diff in diffs.into_iter().flatten() {
15108                    buffer.add_diff(diff, cx);
15109                }
15110            })
15111            .ok();
15112    })
15113}
15114
15115fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15116    let tab_size = tab_size.get() as usize;
15117    let mut width = offset;
15118
15119    for ch in text.chars() {
15120        width += if ch == '\t' {
15121            tab_size - (width % tab_size)
15122        } else {
15123            1
15124        };
15125    }
15126
15127    width - offset
15128}
15129
15130#[cfg(test)]
15131mod tests {
15132    use super::*;
15133
15134    #[test]
15135    fn test_string_size_with_expanded_tabs() {
15136        let nz = |val| NonZeroU32::new(val).unwrap();
15137        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15138        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15139        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15140        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15141        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15142        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15143        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15144        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15145    }
15146}
15147
15148/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15149struct WordBreakingTokenizer<'a> {
15150    input: &'a str,
15151}
15152
15153impl<'a> WordBreakingTokenizer<'a> {
15154    fn new(input: &'a str) -> Self {
15155        Self { input }
15156    }
15157}
15158
15159fn is_char_ideographic(ch: char) -> bool {
15160    use unicode_script::Script::*;
15161    use unicode_script::UnicodeScript;
15162    matches!(ch.script(), Han | Tangut | Yi)
15163}
15164
15165fn is_grapheme_ideographic(text: &str) -> bool {
15166    text.chars().any(is_char_ideographic)
15167}
15168
15169fn is_grapheme_whitespace(text: &str) -> bool {
15170    text.chars().any(|x| x.is_whitespace())
15171}
15172
15173fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15174    text.chars().next().map_or(false, |ch| {
15175        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15176    })
15177}
15178
15179#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15180struct WordBreakToken<'a> {
15181    token: &'a str,
15182    grapheme_len: usize,
15183    is_whitespace: bool,
15184}
15185
15186impl<'a> Iterator for WordBreakingTokenizer<'a> {
15187    /// Yields a span, the count of graphemes in the token, and whether it was
15188    /// whitespace. Note that it also breaks at word boundaries.
15189    type Item = WordBreakToken<'a>;
15190
15191    fn next(&mut self) -> Option<Self::Item> {
15192        use unicode_segmentation::UnicodeSegmentation;
15193        if self.input.is_empty() {
15194            return None;
15195        }
15196
15197        let mut iter = self.input.graphemes(true).peekable();
15198        let mut offset = 0;
15199        let mut graphemes = 0;
15200        if let Some(first_grapheme) = iter.next() {
15201            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15202            offset += first_grapheme.len();
15203            graphemes += 1;
15204            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15205                if let Some(grapheme) = iter.peek().copied() {
15206                    if should_stay_with_preceding_ideograph(grapheme) {
15207                        offset += grapheme.len();
15208                        graphemes += 1;
15209                    }
15210                }
15211            } else {
15212                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15213                let mut next_word_bound = words.peek().copied();
15214                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15215                    next_word_bound = words.next();
15216                }
15217                while let Some(grapheme) = iter.peek().copied() {
15218                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15219                        break;
15220                    };
15221                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15222                        break;
15223                    };
15224                    offset += grapheme.len();
15225                    graphemes += 1;
15226                    iter.next();
15227                }
15228            }
15229            let token = &self.input[..offset];
15230            self.input = &self.input[offset..];
15231            if is_whitespace {
15232                Some(WordBreakToken {
15233                    token: " ",
15234                    grapheme_len: 1,
15235                    is_whitespace: true,
15236                })
15237            } else {
15238                Some(WordBreakToken {
15239                    token,
15240                    grapheme_len: graphemes,
15241                    is_whitespace: false,
15242                })
15243            }
15244        } else {
15245            None
15246        }
15247    }
15248}
15249
15250#[test]
15251fn test_word_breaking_tokenizer() {
15252    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15253        ("", &[]),
15254        ("  ", &[(" ", 1, true)]),
15255        ("Ʒ", &[("Ʒ", 1, false)]),
15256        ("Ǽ", &[("Ǽ", 1, false)]),
15257        ("", &[("", 1, false)]),
15258        ("⋑⋑", &[("⋑⋑", 2, false)]),
15259        (
15260            "原理,进而",
15261            &[
15262                ("", 1, false),
15263                ("理,", 2, false),
15264                ("", 1, false),
15265                ("", 1, false),
15266            ],
15267        ),
15268        (
15269            "hello world",
15270            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15271        ),
15272        (
15273            "hello, world",
15274            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15275        ),
15276        (
15277            "  hello world",
15278            &[
15279                (" ", 1, true),
15280                ("hello", 5, false),
15281                (" ", 1, true),
15282                ("world", 5, false),
15283            ],
15284        ),
15285        (
15286            "这是什么 \n 钢笔",
15287            &[
15288                ("", 1, false),
15289                ("", 1, false),
15290                ("", 1, false),
15291                ("", 1, false),
15292                (" ", 1, true),
15293                ("", 1, false),
15294                ("", 1, false),
15295            ],
15296        ),
15297        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15298    ];
15299
15300    for (input, result) in tests {
15301        assert_eq!(
15302            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15303            result
15304                .iter()
15305                .copied()
15306                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15307                    token,
15308                    grapheme_len,
15309                    is_whitespace,
15310                })
15311                .collect::<Vec<_>>()
15312        );
15313    }
15314}
15315
15316fn wrap_with_prefix(
15317    line_prefix: String,
15318    unwrapped_text: String,
15319    wrap_column: usize,
15320    tab_size: NonZeroU32,
15321) -> String {
15322    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15323    let mut wrapped_text = String::new();
15324    let mut current_line = line_prefix.clone();
15325
15326    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15327    let mut current_line_len = line_prefix_len;
15328    for WordBreakToken {
15329        token,
15330        grapheme_len,
15331        is_whitespace,
15332    } in tokenizer
15333    {
15334        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15335            wrapped_text.push_str(current_line.trim_end());
15336            wrapped_text.push('\n');
15337            current_line.truncate(line_prefix.len());
15338            current_line_len = line_prefix_len;
15339            if !is_whitespace {
15340                current_line.push_str(token);
15341                current_line_len += grapheme_len;
15342            }
15343        } else if !is_whitespace {
15344            current_line.push_str(token);
15345            current_line_len += grapheme_len;
15346        } else if current_line_len != line_prefix_len {
15347            current_line.push(' ');
15348            current_line_len += 1;
15349        }
15350    }
15351
15352    if !current_line.is_empty() {
15353        wrapped_text.push_str(&current_line);
15354    }
15355    wrapped_text
15356}
15357
15358#[test]
15359fn test_wrap_with_prefix() {
15360    assert_eq!(
15361        wrap_with_prefix(
15362            "# ".to_string(),
15363            "abcdefg".to_string(),
15364            4,
15365            NonZeroU32::new(4).unwrap()
15366        ),
15367        "# abcdefg"
15368    );
15369    assert_eq!(
15370        wrap_with_prefix(
15371            "".to_string(),
15372            "\thello world".to_string(),
15373            8,
15374            NonZeroU32::new(4).unwrap()
15375        ),
15376        "hello\nworld"
15377    );
15378    assert_eq!(
15379        wrap_with_prefix(
15380            "// ".to_string(),
15381            "xx \nyy zz aa bb cc".to_string(),
15382            12,
15383            NonZeroU32::new(4).unwrap()
15384        ),
15385        "// xx yy zz\n// aa bb cc"
15386    );
15387    assert_eq!(
15388        wrap_with_prefix(
15389            String::new(),
15390            "这是什么 \n 钢笔".to_string(),
15391            3,
15392            NonZeroU32::new(4).unwrap()
15393        ),
15394        "这是什\n么 钢\n"
15395    );
15396}
15397
15398pub trait CollaborationHub {
15399    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15400    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15401    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15402}
15403
15404impl CollaborationHub for Entity<Project> {
15405    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15406        self.read(cx).collaborators()
15407    }
15408
15409    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15410        self.read(cx).user_store().read(cx).participant_indices()
15411    }
15412
15413    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15414        let this = self.read(cx);
15415        let user_ids = this.collaborators().values().map(|c| c.user_id);
15416        this.user_store().read_with(cx, |user_store, cx| {
15417            user_store.participant_names(user_ids, cx)
15418        })
15419    }
15420}
15421
15422pub trait SemanticsProvider {
15423    fn hover(
15424        &self,
15425        buffer: &Entity<Buffer>,
15426        position: text::Anchor,
15427        cx: &mut App,
15428    ) -> Option<Task<Vec<project::Hover>>>;
15429
15430    fn inlay_hints(
15431        &self,
15432        buffer_handle: Entity<Buffer>,
15433        range: Range<text::Anchor>,
15434        cx: &mut App,
15435    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15436
15437    fn resolve_inlay_hint(
15438        &self,
15439        hint: InlayHint,
15440        buffer_handle: Entity<Buffer>,
15441        server_id: LanguageServerId,
15442        cx: &mut App,
15443    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15444
15445    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15446
15447    fn document_highlights(
15448        &self,
15449        buffer: &Entity<Buffer>,
15450        position: text::Anchor,
15451        cx: &mut App,
15452    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15453
15454    fn definitions(
15455        &self,
15456        buffer: &Entity<Buffer>,
15457        position: text::Anchor,
15458        kind: GotoDefinitionKind,
15459        cx: &mut App,
15460    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15461
15462    fn range_for_rename(
15463        &self,
15464        buffer: &Entity<Buffer>,
15465        position: text::Anchor,
15466        cx: &mut App,
15467    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15468
15469    fn perform_rename(
15470        &self,
15471        buffer: &Entity<Buffer>,
15472        position: text::Anchor,
15473        new_name: String,
15474        cx: &mut App,
15475    ) -> Option<Task<Result<ProjectTransaction>>>;
15476}
15477
15478pub trait CompletionProvider {
15479    fn completions(
15480        &self,
15481        buffer: &Entity<Buffer>,
15482        buffer_position: text::Anchor,
15483        trigger: CompletionContext,
15484        window: &mut Window,
15485        cx: &mut Context<Editor>,
15486    ) -> Task<Result<Vec<Completion>>>;
15487
15488    fn resolve_completions(
15489        &self,
15490        buffer: Entity<Buffer>,
15491        completion_indices: Vec<usize>,
15492        completions: Rc<RefCell<Box<[Completion]>>>,
15493        cx: &mut Context<Editor>,
15494    ) -> Task<Result<bool>>;
15495
15496    fn apply_additional_edits_for_completion(
15497        &self,
15498        _buffer: Entity<Buffer>,
15499        _completions: Rc<RefCell<Box<[Completion]>>>,
15500        _completion_index: usize,
15501        _push_to_history: bool,
15502        _cx: &mut Context<Editor>,
15503    ) -> Task<Result<Option<language::Transaction>>> {
15504        Task::ready(Ok(None))
15505    }
15506
15507    fn is_completion_trigger(
15508        &self,
15509        buffer: &Entity<Buffer>,
15510        position: language::Anchor,
15511        text: &str,
15512        trigger_in_words: bool,
15513        cx: &mut Context<Editor>,
15514    ) -> bool;
15515
15516    fn sort_completions(&self) -> bool {
15517        true
15518    }
15519}
15520
15521pub trait CodeActionProvider {
15522    fn id(&self) -> Arc<str>;
15523
15524    fn code_actions(
15525        &self,
15526        buffer: &Entity<Buffer>,
15527        range: Range<text::Anchor>,
15528        window: &mut Window,
15529        cx: &mut App,
15530    ) -> Task<Result<Vec<CodeAction>>>;
15531
15532    fn apply_code_action(
15533        &self,
15534        buffer_handle: Entity<Buffer>,
15535        action: CodeAction,
15536        excerpt_id: ExcerptId,
15537        push_to_history: bool,
15538        window: &mut Window,
15539        cx: &mut App,
15540    ) -> Task<Result<ProjectTransaction>>;
15541}
15542
15543impl CodeActionProvider for Entity<Project> {
15544    fn id(&self) -> Arc<str> {
15545        "project".into()
15546    }
15547
15548    fn code_actions(
15549        &self,
15550        buffer: &Entity<Buffer>,
15551        range: Range<text::Anchor>,
15552        _window: &mut Window,
15553        cx: &mut App,
15554    ) -> Task<Result<Vec<CodeAction>>> {
15555        self.update(cx, |project, cx| {
15556            project.code_actions(buffer, range, None, cx)
15557        })
15558    }
15559
15560    fn apply_code_action(
15561        &self,
15562        buffer_handle: Entity<Buffer>,
15563        action: CodeAction,
15564        _excerpt_id: ExcerptId,
15565        push_to_history: bool,
15566        _window: &mut Window,
15567        cx: &mut App,
15568    ) -> Task<Result<ProjectTransaction>> {
15569        self.update(cx, |project, cx| {
15570            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15571        })
15572    }
15573}
15574
15575fn snippet_completions(
15576    project: &Project,
15577    buffer: &Entity<Buffer>,
15578    buffer_position: text::Anchor,
15579    cx: &mut App,
15580) -> Task<Result<Vec<Completion>>> {
15581    let language = buffer.read(cx).language_at(buffer_position);
15582    let language_name = language.as_ref().map(|language| language.lsp_id());
15583    let snippet_store = project.snippets().read(cx);
15584    let snippets = snippet_store.snippets_for(language_name, cx);
15585
15586    if snippets.is_empty() {
15587        return Task::ready(Ok(vec![]));
15588    }
15589    let snapshot = buffer.read(cx).text_snapshot();
15590    let chars: String = snapshot
15591        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15592        .collect();
15593
15594    let scope = language.map(|language| language.default_scope());
15595    let executor = cx.background_executor().clone();
15596
15597    cx.background_spawn(async move {
15598        let classifier = CharClassifier::new(scope).for_completion(true);
15599        let mut last_word = chars
15600            .chars()
15601            .take_while(|c| classifier.is_word(*c))
15602            .collect::<String>();
15603        last_word = last_word.chars().rev().collect();
15604
15605        if last_word.is_empty() {
15606            return Ok(vec![]);
15607        }
15608
15609        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15610        let to_lsp = |point: &text::Anchor| {
15611            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15612            point_to_lsp(end)
15613        };
15614        let lsp_end = to_lsp(&buffer_position);
15615
15616        let candidates = snippets
15617            .iter()
15618            .enumerate()
15619            .flat_map(|(ix, snippet)| {
15620                snippet
15621                    .prefix
15622                    .iter()
15623                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15624            })
15625            .collect::<Vec<StringMatchCandidate>>();
15626
15627        let mut matches = fuzzy::match_strings(
15628            &candidates,
15629            &last_word,
15630            last_word.chars().any(|c| c.is_uppercase()),
15631            100,
15632            &Default::default(),
15633            executor,
15634        )
15635        .await;
15636
15637        // Remove all candidates where the query's start does not match the start of any word in the candidate
15638        if let Some(query_start) = last_word.chars().next() {
15639            matches.retain(|string_match| {
15640                split_words(&string_match.string).any(|word| {
15641                    // Check that the first codepoint of the word as lowercase matches the first
15642                    // codepoint of the query as lowercase
15643                    word.chars()
15644                        .flat_map(|codepoint| codepoint.to_lowercase())
15645                        .zip(query_start.to_lowercase())
15646                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15647                })
15648            });
15649        }
15650
15651        let matched_strings = matches
15652            .into_iter()
15653            .map(|m| m.string)
15654            .collect::<HashSet<_>>();
15655
15656        let result: Vec<Completion> = snippets
15657            .into_iter()
15658            .filter_map(|snippet| {
15659                let matching_prefix = snippet
15660                    .prefix
15661                    .iter()
15662                    .find(|prefix| matched_strings.contains(*prefix))?;
15663                let start = as_offset - last_word.len();
15664                let start = snapshot.anchor_before(start);
15665                let range = start..buffer_position;
15666                let lsp_start = to_lsp(&start);
15667                let lsp_range = lsp::Range {
15668                    start: lsp_start,
15669                    end: lsp_end,
15670                };
15671                Some(Completion {
15672                    old_range: range,
15673                    new_text: snippet.body.clone(),
15674                    resolved: false,
15675                    label: CodeLabel {
15676                        text: matching_prefix.clone(),
15677                        runs: vec![],
15678                        filter_range: 0..matching_prefix.len(),
15679                    },
15680                    server_id: LanguageServerId(usize::MAX),
15681                    documentation: snippet
15682                        .description
15683                        .clone()
15684                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
15685                    lsp_completion: lsp::CompletionItem {
15686                        label: snippet.prefix.first().unwrap().clone(),
15687                        kind: Some(CompletionItemKind::SNIPPET),
15688                        label_details: snippet.description.as_ref().map(|description| {
15689                            lsp::CompletionItemLabelDetails {
15690                                detail: Some(description.clone()),
15691                                description: None,
15692                            }
15693                        }),
15694                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15695                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15696                            lsp::InsertReplaceEdit {
15697                                new_text: snippet.body.clone(),
15698                                insert: lsp_range,
15699                                replace: lsp_range,
15700                            },
15701                        )),
15702                        filter_text: Some(snippet.body.clone()),
15703                        sort_text: Some(char::MAX.to_string()),
15704                        ..Default::default()
15705                    },
15706                    confirm: None,
15707                })
15708            })
15709            .collect();
15710
15711        Ok(result)
15712    })
15713}
15714
15715impl CompletionProvider for Entity<Project> {
15716    fn completions(
15717        &self,
15718        buffer: &Entity<Buffer>,
15719        buffer_position: text::Anchor,
15720        options: CompletionContext,
15721        _window: &mut Window,
15722        cx: &mut Context<Editor>,
15723    ) -> Task<Result<Vec<Completion>>> {
15724        self.update(cx, |project, cx| {
15725            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15726            let project_completions = project.completions(buffer, buffer_position, options, cx);
15727            cx.background_spawn(async move {
15728                let mut completions = project_completions.await?;
15729                let snippets_completions = snippets.await?;
15730                completions.extend(snippets_completions);
15731                Ok(completions)
15732            })
15733        })
15734    }
15735
15736    fn resolve_completions(
15737        &self,
15738        buffer: Entity<Buffer>,
15739        completion_indices: Vec<usize>,
15740        completions: Rc<RefCell<Box<[Completion]>>>,
15741        cx: &mut Context<Editor>,
15742    ) -> Task<Result<bool>> {
15743        self.update(cx, |project, cx| {
15744            project.lsp_store().update(cx, |lsp_store, cx| {
15745                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15746            })
15747        })
15748    }
15749
15750    fn apply_additional_edits_for_completion(
15751        &self,
15752        buffer: Entity<Buffer>,
15753        completions: Rc<RefCell<Box<[Completion]>>>,
15754        completion_index: usize,
15755        push_to_history: bool,
15756        cx: &mut Context<Editor>,
15757    ) -> Task<Result<Option<language::Transaction>>> {
15758        self.update(cx, |project, cx| {
15759            project.lsp_store().update(cx, |lsp_store, cx| {
15760                lsp_store.apply_additional_edits_for_completion(
15761                    buffer,
15762                    completions,
15763                    completion_index,
15764                    push_to_history,
15765                    cx,
15766                )
15767            })
15768        })
15769    }
15770
15771    fn is_completion_trigger(
15772        &self,
15773        buffer: &Entity<Buffer>,
15774        position: language::Anchor,
15775        text: &str,
15776        trigger_in_words: bool,
15777        cx: &mut Context<Editor>,
15778    ) -> bool {
15779        let mut chars = text.chars();
15780        let char = if let Some(char) = chars.next() {
15781            char
15782        } else {
15783            return false;
15784        };
15785        if chars.next().is_some() {
15786            return false;
15787        }
15788
15789        let buffer = buffer.read(cx);
15790        let snapshot = buffer.snapshot();
15791        if !snapshot.settings_at(position, cx).show_completions_on_input {
15792            return false;
15793        }
15794        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15795        if trigger_in_words && classifier.is_word(char) {
15796            return true;
15797        }
15798
15799        buffer.completion_triggers().contains(text)
15800    }
15801}
15802
15803impl SemanticsProvider for Entity<Project> {
15804    fn hover(
15805        &self,
15806        buffer: &Entity<Buffer>,
15807        position: text::Anchor,
15808        cx: &mut App,
15809    ) -> Option<Task<Vec<project::Hover>>> {
15810        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15811    }
15812
15813    fn document_highlights(
15814        &self,
15815        buffer: &Entity<Buffer>,
15816        position: text::Anchor,
15817        cx: &mut App,
15818    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15819        Some(self.update(cx, |project, cx| {
15820            project.document_highlights(buffer, position, cx)
15821        }))
15822    }
15823
15824    fn definitions(
15825        &self,
15826        buffer: &Entity<Buffer>,
15827        position: text::Anchor,
15828        kind: GotoDefinitionKind,
15829        cx: &mut App,
15830    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15831        Some(self.update(cx, |project, cx| match kind {
15832            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15833            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15834            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15835            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15836        }))
15837    }
15838
15839    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15840        // TODO: make this work for remote projects
15841        self.update(cx, |this, cx| {
15842            buffer.update(cx, |buffer, cx| {
15843                this.any_language_server_supports_inlay_hints(buffer, cx)
15844            })
15845        })
15846    }
15847
15848    fn inlay_hints(
15849        &self,
15850        buffer_handle: Entity<Buffer>,
15851        range: Range<text::Anchor>,
15852        cx: &mut App,
15853    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15854        Some(self.update(cx, |project, cx| {
15855            project.inlay_hints(buffer_handle, range, cx)
15856        }))
15857    }
15858
15859    fn resolve_inlay_hint(
15860        &self,
15861        hint: InlayHint,
15862        buffer_handle: Entity<Buffer>,
15863        server_id: LanguageServerId,
15864        cx: &mut App,
15865    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15866        Some(self.update(cx, |project, cx| {
15867            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15868        }))
15869    }
15870
15871    fn range_for_rename(
15872        &self,
15873        buffer: &Entity<Buffer>,
15874        position: text::Anchor,
15875        cx: &mut App,
15876    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15877        Some(self.update(cx, |project, cx| {
15878            let buffer = buffer.clone();
15879            let task = project.prepare_rename(buffer.clone(), position, cx);
15880            cx.spawn(|_, mut cx| async move {
15881                Ok(match task.await? {
15882                    PrepareRenameResponse::Success(range) => Some(range),
15883                    PrepareRenameResponse::InvalidPosition => None,
15884                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15885                        // Fallback on using TreeSitter info to determine identifier range
15886                        buffer.update(&mut cx, |buffer, _| {
15887                            let snapshot = buffer.snapshot();
15888                            let (range, kind) = snapshot.surrounding_word(position);
15889                            if kind != Some(CharKind::Word) {
15890                                return None;
15891                            }
15892                            Some(
15893                                snapshot.anchor_before(range.start)
15894                                    ..snapshot.anchor_after(range.end),
15895                            )
15896                        })?
15897                    }
15898                })
15899            })
15900        }))
15901    }
15902
15903    fn perform_rename(
15904        &self,
15905        buffer: &Entity<Buffer>,
15906        position: text::Anchor,
15907        new_name: String,
15908        cx: &mut App,
15909    ) -> Option<Task<Result<ProjectTransaction>>> {
15910        Some(self.update(cx, |project, cx| {
15911            project.perform_rename(buffer.clone(), position, new_name, cx)
15912        }))
15913    }
15914}
15915
15916fn inlay_hint_settings(
15917    location: Anchor,
15918    snapshot: &MultiBufferSnapshot,
15919    cx: &mut Context<Editor>,
15920) -> InlayHintSettings {
15921    let file = snapshot.file_at(location);
15922    let language = snapshot.language_at(location).map(|l| l.name());
15923    language_settings(language, file, cx).inlay_hints
15924}
15925
15926fn consume_contiguous_rows(
15927    contiguous_row_selections: &mut Vec<Selection<Point>>,
15928    selection: &Selection<Point>,
15929    display_map: &DisplaySnapshot,
15930    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15931) -> (MultiBufferRow, MultiBufferRow) {
15932    contiguous_row_selections.push(selection.clone());
15933    let start_row = MultiBufferRow(selection.start.row);
15934    let mut end_row = ending_row(selection, display_map);
15935
15936    while let Some(next_selection) = selections.peek() {
15937        if next_selection.start.row <= end_row.0 {
15938            end_row = ending_row(next_selection, display_map);
15939            contiguous_row_selections.push(selections.next().unwrap().clone());
15940        } else {
15941            break;
15942        }
15943    }
15944    (start_row, end_row)
15945}
15946
15947fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15948    if next_selection.end.column > 0 || next_selection.is_empty() {
15949        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15950    } else {
15951        MultiBufferRow(next_selection.end.row)
15952    }
15953}
15954
15955impl EditorSnapshot {
15956    pub fn remote_selections_in_range<'a>(
15957        &'a self,
15958        range: &'a Range<Anchor>,
15959        collaboration_hub: &dyn CollaborationHub,
15960        cx: &'a App,
15961    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15962        let participant_names = collaboration_hub.user_names(cx);
15963        let participant_indices = collaboration_hub.user_participant_indices(cx);
15964        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15965        let collaborators_by_replica_id = collaborators_by_peer_id
15966            .iter()
15967            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15968            .collect::<HashMap<_, _>>();
15969        self.buffer_snapshot
15970            .selections_in_range(range, false)
15971            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15972                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15973                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15974                let user_name = participant_names.get(&collaborator.user_id).cloned();
15975                Some(RemoteSelection {
15976                    replica_id,
15977                    selection,
15978                    cursor_shape,
15979                    line_mode,
15980                    participant_index,
15981                    peer_id: collaborator.peer_id,
15982                    user_name,
15983                })
15984            })
15985    }
15986
15987    pub fn hunks_for_ranges(
15988        &self,
15989        ranges: impl Iterator<Item = Range<Point>>,
15990    ) -> Vec<MultiBufferDiffHunk> {
15991        let mut hunks = Vec::new();
15992        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15993            HashMap::default();
15994        for query_range in ranges {
15995            let query_rows =
15996                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15997            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15998                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15999            ) {
16000                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16001                // when the caret is just above or just below the deleted hunk.
16002                let allow_adjacent = hunk.status().is_deleted();
16003                let related_to_selection = if allow_adjacent {
16004                    hunk.row_range.overlaps(&query_rows)
16005                        || hunk.row_range.start == query_rows.end
16006                        || hunk.row_range.end == query_rows.start
16007                } else {
16008                    hunk.row_range.overlaps(&query_rows)
16009                };
16010                if related_to_selection {
16011                    if !processed_buffer_rows
16012                        .entry(hunk.buffer_id)
16013                        .or_default()
16014                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16015                    {
16016                        continue;
16017                    }
16018                    hunks.push(hunk);
16019                }
16020            }
16021        }
16022
16023        hunks
16024    }
16025
16026    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16027        self.display_snapshot.buffer_snapshot.language_at(position)
16028    }
16029
16030    pub fn is_focused(&self) -> bool {
16031        self.is_focused
16032    }
16033
16034    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16035        self.placeholder_text.as_ref()
16036    }
16037
16038    pub fn scroll_position(&self) -> gpui::Point<f32> {
16039        self.scroll_anchor.scroll_position(&self.display_snapshot)
16040    }
16041
16042    fn gutter_dimensions(
16043        &self,
16044        font_id: FontId,
16045        font_size: Pixels,
16046        max_line_number_width: Pixels,
16047        cx: &App,
16048    ) -> Option<GutterDimensions> {
16049        if !self.show_gutter {
16050            return None;
16051        }
16052
16053        let descent = cx.text_system().descent(font_id, font_size);
16054        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16055        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16056
16057        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16058            matches!(
16059                ProjectSettings::get_global(cx).git.git_gutter,
16060                Some(GitGutterSetting::TrackedFiles)
16061            )
16062        });
16063        let gutter_settings = EditorSettings::get_global(cx).gutter;
16064        let show_line_numbers = self
16065            .show_line_numbers
16066            .unwrap_or(gutter_settings.line_numbers);
16067        let line_gutter_width = if show_line_numbers {
16068            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16069            let min_width_for_number_on_gutter = em_advance * 4.0;
16070            max_line_number_width.max(min_width_for_number_on_gutter)
16071        } else {
16072            0.0.into()
16073        };
16074
16075        let show_code_actions = self
16076            .show_code_actions
16077            .unwrap_or(gutter_settings.code_actions);
16078
16079        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16080
16081        let git_blame_entries_width =
16082            self.git_blame_gutter_max_author_length
16083                .map(|max_author_length| {
16084                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16085
16086                    /// The number of characters to dedicate to gaps and margins.
16087                    const SPACING_WIDTH: usize = 4;
16088
16089                    let max_char_count = max_author_length
16090                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16091                        + ::git::SHORT_SHA_LENGTH
16092                        + MAX_RELATIVE_TIMESTAMP.len()
16093                        + SPACING_WIDTH;
16094
16095                    em_advance * max_char_count
16096                });
16097
16098        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16099        left_padding += if show_code_actions || show_runnables {
16100            em_width * 3.0
16101        } else if show_git_gutter && show_line_numbers {
16102            em_width * 2.0
16103        } else if show_git_gutter || show_line_numbers {
16104            em_width
16105        } else {
16106            px(0.)
16107        };
16108
16109        let right_padding = if gutter_settings.folds && show_line_numbers {
16110            em_width * 4.0
16111        } else if gutter_settings.folds {
16112            em_width * 3.0
16113        } else if show_line_numbers {
16114            em_width
16115        } else {
16116            px(0.)
16117        };
16118
16119        Some(GutterDimensions {
16120            left_padding,
16121            right_padding,
16122            width: line_gutter_width + left_padding + right_padding,
16123            margin: -descent,
16124            git_blame_entries_width,
16125        })
16126    }
16127
16128    pub fn render_crease_toggle(
16129        &self,
16130        buffer_row: MultiBufferRow,
16131        row_contains_cursor: bool,
16132        editor: Entity<Editor>,
16133        window: &mut Window,
16134        cx: &mut App,
16135    ) -> Option<AnyElement> {
16136        let folded = self.is_line_folded(buffer_row);
16137        let mut is_foldable = false;
16138
16139        if let Some(crease) = self
16140            .crease_snapshot
16141            .query_row(buffer_row, &self.buffer_snapshot)
16142        {
16143            is_foldable = true;
16144            match crease {
16145                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16146                    if let Some(render_toggle) = render_toggle {
16147                        let toggle_callback =
16148                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16149                                if folded {
16150                                    editor.update(cx, |editor, cx| {
16151                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16152                                    });
16153                                } else {
16154                                    editor.update(cx, |editor, cx| {
16155                                        editor.unfold_at(
16156                                            &crate::UnfoldAt { buffer_row },
16157                                            window,
16158                                            cx,
16159                                        )
16160                                    });
16161                                }
16162                            });
16163                        return Some((render_toggle)(
16164                            buffer_row,
16165                            folded,
16166                            toggle_callback,
16167                            window,
16168                            cx,
16169                        ));
16170                    }
16171                }
16172            }
16173        }
16174
16175        is_foldable |= self.starts_indent(buffer_row);
16176
16177        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16178            Some(
16179                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16180                    .toggle_state(folded)
16181                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16182                        if folded {
16183                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16184                        } else {
16185                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16186                        }
16187                    }))
16188                    .into_any_element(),
16189            )
16190        } else {
16191            None
16192        }
16193    }
16194
16195    pub fn render_crease_trailer(
16196        &self,
16197        buffer_row: MultiBufferRow,
16198        window: &mut Window,
16199        cx: &mut App,
16200    ) -> Option<AnyElement> {
16201        let folded = self.is_line_folded(buffer_row);
16202        if let Crease::Inline { render_trailer, .. } = self
16203            .crease_snapshot
16204            .query_row(buffer_row, &self.buffer_snapshot)?
16205        {
16206            let render_trailer = render_trailer.as_ref()?;
16207            Some(render_trailer(buffer_row, folded, window, cx))
16208        } else {
16209            None
16210        }
16211    }
16212}
16213
16214impl Deref for EditorSnapshot {
16215    type Target = DisplaySnapshot;
16216
16217    fn deref(&self) -> &Self::Target {
16218        &self.display_snapshot
16219    }
16220}
16221
16222#[derive(Clone, Debug, PartialEq, Eq)]
16223pub enum EditorEvent {
16224    InputIgnored {
16225        text: Arc<str>,
16226    },
16227    InputHandled {
16228        utf16_range_to_replace: Option<Range<isize>>,
16229        text: Arc<str>,
16230    },
16231    ExcerptsAdded {
16232        buffer: Entity<Buffer>,
16233        predecessor: ExcerptId,
16234        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16235    },
16236    ExcerptsRemoved {
16237        ids: Vec<ExcerptId>,
16238    },
16239    BufferFoldToggled {
16240        ids: Vec<ExcerptId>,
16241        folded: bool,
16242    },
16243    ExcerptsEdited {
16244        ids: Vec<ExcerptId>,
16245    },
16246    ExcerptsExpanded {
16247        ids: Vec<ExcerptId>,
16248    },
16249    BufferEdited,
16250    Edited {
16251        transaction_id: clock::Lamport,
16252    },
16253    Reparsed(BufferId),
16254    Focused,
16255    FocusedIn,
16256    Blurred,
16257    DirtyChanged,
16258    Saved,
16259    TitleChanged,
16260    DiffBaseChanged,
16261    SelectionsChanged {
16262        local: bool,
16263    },
16264    ScrollPositionChanged {
16265        local: bool,
16266        autoscroll: bool,
16267    },
16268    Closed,
16269    TransactionUndone {
16270        transaction_id: clock::Lamport,
16271    },
16272    TransactionBegun {
16273        transaction_id: clock::Lamport,
16274    },
16275    Reloaded,
16276    CursorShapeChanged,
16277}
16278
16279impl EventEmitter<EditorEvent> for Editor {}
16280
16281impl Focusable for Editor {
16282    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16283        self.focus_handle.clone()
16284    }
16285}
16286
16287impl Render for Editor {
16288    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16289        let settings = ThemeSettings::get_global(cx);
16290
16291        let mut text_style = match self.mode {
16292            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16293                color: cx.theme().colors().editor_foreground,
16294                font_family: settings.ui_font.family.clone(),
16295                font_features: settings.ui_font.features.clone(),
16296                font_fallbacks: settings.ui_font.fallbacks.clone(),
16297                font_size: rems(0.875).into(),
16298                font_weight: settings.ui_font.weight,
16299                line_height: relative(settings.buffer_line_height.value()),
16300                ..Default::default()
16301            },
16302            EditorMode::Full => TextStyle {
16303                color: cx.theme().colors().editor_foreground,
16304                font_family: settings.buffer_font.family.clone(),
16305                font_features: settings.buffer_font.features.clone(),
16306                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16307                font_size: settings.buffer_font_size(cx).into(),
16308                font_weight: settings.buffer_font.weight,
16309                line_height: relative(settings.buffer_line_height.value()),
16310                ..Default::default()
16311            },
16312        };
16313        if let Some(text_style_refinement) = &self.text_style_refinement {
16314            text_style.refine(text_style_refinement)
16315        }
16316
16317        let background = match self.mode {
16318            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16319            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16320            EditorMode::Full => cx.theme().colors().editor_background,
16321        };
16322
16323        EditorElement::new(
16324            &cx.entity(),
16325            EditorStyle {
16326                background,
16327                local_player: cx.theme().players().local(),
16328                text: text_style,
16329                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16330                syntax: cx.theme().syntax().clone(),
16331                status: cx.theme().status().clone(),
16332                inlay_hints_style: make_inlay_hints_style(cx),
16333                inline_completion_styles: make_suggestion_styles(cx),
16334                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16335            },
16336        )
16337    }
16338}
16339
16340impl EntityInputHandler for Editor {
16341    fn text_for_range(
16342        &mut self,
16343        range_utf16: Range<usize>,
16344        adjusted_range: &mut Option<Range<usize>>,
16345        _: &mut Window,
16346        cx: &mut Context<Self>,
16347    ) -> Option<String> {
16348        let snapshot = self.buffer.read(cx).read(cx);
16349        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16350        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16351        if (start.0..end.0) != range_utf16 {
16352            adjusted_range.replace(start.0..end.0);
16353        }
16354        Some(snapshot.text_for_range(start..end).collect())
16355    }
16356
16357    fn selected_text_range(
16358        &mut self,
16359        ignore_disabled_input: bool,
16360        _: &mut Window,
16361        cx: &mut Context<Self>,
16362    ) -> Option<UTF16Selection> {
16363        // Prevent the IME menu from appearing when holding down an alphabetic key
16364        // while input is disabled.
16365        if !ignore_disabled_input && !self.input_enabled {
16366            return None;
16367        }
16368
16369        let selection = self.selections.newest::<OffsetUtf16>(cx);
16370        let range = selection.range();
16371
16372        Some(UTF16Selection {
16373            range: range.start.0..range.end.0,
16374            reversed: selection.reversed,
16375        })
16376    }
16377
16378    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16379        let snapshot = self.buffer.read(cx).read(cx);
16380        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16381        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16382    }
16383
16384    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16385        self.clear_highlights::<InputComposition>(cx);
16386        self.ime_transaction.take();
16387    }
16388
16389    fn replace_text_in_range(
16390        &mut self,
16391        range_utf16: Option<Range<usize>>,
16392        text: &str,
16393        window: &mut Window,
16394        cx: &mut Context<Self>,
16395    ) {
16396        if !self.input_enabled {
16397            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16398            return;
16399        }
16400
16401        self.transact(window, cx, |this, window, cx| {
16402            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16403                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16404                Some(this.selection_replacement_ranges(range_utf16, cx))
16405            } else {
16406                this.marked_text_ranges(cx)
16407            };
16408
16409            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16410                let newest_selection_id = this.selections.newest_anchor().id;
16411                this.selections
16412                    .all::<OffsetUtf16>(cx)
16413                    .iter()
16414                    .zip(ranges_to_replace.iter())
16415                    .find_map(|(selection, range)| {
16416                        if selection.id == newest_selection_id {
16417                            Some(
16418                                (range.start.0 as isize - selection.head().0 as isize)
16419                                    ..(range.end.0 as isize - selection.head().0 as isize),
16420                            )
16421                        } else {
16422                            None
16423                        }
16424                    })
16425            });
16426
16427            cx.emit(EditorEvent::InputHandled {
16428                utf16_range_to_replace: range_to_replace,
16429                text: text.into(),
16430            });
16431
16432            if let Some(new_selected_ranges) = new_selected_ranges {
16433                this.change_selections(None, window, cx, |selections| {
16434                    selections.select_ranges(new_selected_ranges)
16435                });
16436                this.backspace(&Default::default(), window, cx);
16437            }
16438
16439            this.handle_input(text, window, cx);
16440        });
16441
16442        if let Some(transaction) = self.ime_transaction {
16443            self.buffer.update(cx, |buffer, cx| {
16444                buffer.group_until_transaction(transaction, cx);
16445            });
16446        }
16447
16448        self.unmark_text(window, cx);
16449    }
16450
16451    fn replace_and_mark_text_in_range(
16452        &mut self,
16453        range_utf16: Option<Range<usize>>,
16454        text: &str,
16455        new_selected_range_utf16: Option<Range<usize>>,
16456        window: &mut Window,
16457        cx: &mut Context<Self>,
16458    ) {
16459        if !self.input_enabled {
16460            return;
16461        }
16462
16463        let transaction = self.transact(window, cx, |this, window, cx| {
16464            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16465                let snapshot = this.buffer.read(cx).read(cx);
16466                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16467                    for marked_range in &mut marked_ranges {
16468                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16469                        marked_range.start.0 += relative_range_utf16.start;
16470                        marked_range.start =
16471                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16472                        marked_range.end =
16473                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16474                    }
16475                }
16476                Some(marked_ranges)
16477            } else if let Some(range_utf16) = range_utf16 {
16478                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16479                Some(this.selection_replacement_ranges(range_utf16, cx))
16480            } else {
16481                None
16482            };
16483
16484            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16485                let newest_selection_id = this.selections.newest_anchor().id;
16486                this.selections
16487                    .all::<OffsetUtf16>(cx)
16488                    .iter()
16489                    .zip(ranges_to_replace.iter())
16490                    .find_map(|(selection, range)| {
16491                        if selection.id == newest_selection_id {
16492                            Some(
16493                                (range.start.0 as isize - selection.head().0 as isize)
16494                                    ..(range.end.0 as isize - selection.head().0 as isize),
16495                            )
16496                        } else {
16497                            None
16498                        }
16499                    })
16500            });
16501
16502            cx.emit(EditorEvent::InputHandled {
16503                utf16_range_to_replace: range_to_replace,
16504                text: text.into(),
16505            });
16506
16507            if let Some(ranges) = ranges_to_replace {
16508                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16509            }
16510
16511            let marked_ranges = {
16512                let snapshot = this.buffer.read(cx).read(cx);
16513                this.selections
16514                    .disjoint_anchors()
16515                    .iter()
16516                    .map(|selection| {
16517                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16518                    })
16519                    .collect::<Vec<_>>()
16520            };
16521
16522            if text.is_empty() {
16523                this.unmark_text(window, cx);
16524            } else {
16525                this.highlight_text::<InputComposition>(
16526                    marked_ranges.clone(),
16527                    HighlightStyle {
16528                        underline: Some(UnderlineStyle {
16529                            thickness: px(1.),
16530                            color: None,
16531                            wavy: false,
16532                        }),
16533                        ..Default::default()
16534                    },
16535                    cx,
16536                );
16537            }
16538
16539            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16540            let use_autoclose = this.use_autoclose;
16541            let use_auto_surround = this.use_auto_surround;
16542            this.set_use_autoclose(false);
16543            this.set_use_auto_surround(false);
16544            this.handle_input(text, window, cx);
16545            this.set_use_autoclose(use_autoclose);
16546            this.set_use_auto_surround(use_auto_surround);
16547
16548            if let Some(new_selected_range) = new_selected_range_utf16 {
16549                let snapshot = this.buffer.read(cx).read(cx);
16550                let new_selected_ranges = marked_ranges
16551                    .into_iter()
16552                    .map(|marked_range| {
16553                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16554                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16555                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16556                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16557                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16558                    })
16559                    .collect::<Vec<_>>();
16560
16561                drop(snapshot);
16562                this.change_selections(None, window, cx, |selections| {
16563                    selections.select_ranges(new_selected_ranges)
16564                });
16565            }
16566        });
16567
16568        self.ime_transaction = self.ime_transaction.or(transaction);
16569        if let Some(transaction) = self.ime_transaction {
16570            self.buffer.update(cx, |buffer, cx| {
16571                buffer.group_until_transaction(transaction, cx);
16572            });
16573        }
16574
16575        if self.text_highlights::<InputComposition>(cx).is_none() {
16576            self.ime_transaction.take();
16577        }
16578    }
16579
16580    fn bounds_for_range(
16581        &mut self,
16582        range_utf16: Range<usize>,
16583        element_bounds: gpui::Bounds<Pixels>,
16584        window: &mut Window,
16585        cx: &mut Context<Self>,
16586    ) -> Option<gpui::Bounds<Pixels>> {
16587        let text_layout_details = self.text_layout_details(window);
16588        let gpui::Size {
16589            width: em_width,
16590            height: line_height,
16591        } = self.character_size(window);
16592
16593        let snapshot = self.snapshot(window, cx);
16594        let scroll_position = snapshot.scroll_position();
16595        let scroll_left = scroll_position.x * em_width;
16596
16597        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16598        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16599            + self.gutter_dimensions.width
16600            + self.gutter_dimensions.margin;
16601        let y = line_height * (start.row().as_f32() - scroll_position.y);
16602
16603        Some(Bounds {
16604            origin: element_bounds.origin + point(x, y),
16605            size: size(em_width, line_height),
16606        })
16607    }
16608
16609    fn character_index_for_point(
16610        &mut self,
16611        point: gpui::Point<Pixels>,
16612        _window: &mut Window,
16613        _cx: &mut Context<Self>,
16614    ) -> Option<usize> {
16615        let position_map = self.last_position_map.as_ref()?;
16616        if !position_map.text_hitbox.contains(&point) {
16617            return None;
16618        }
16619        let display_point = position_map.point_for_position(point).previous_valid;
16620        let anchor = position_map
16621            .snapshot
16622            .display_point_to_anchor(display_point, Bias::Left);
16623        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16624        Some(utf16_offset.0)
16625    }
16626}
16627
16628trait SelectionExt {
16629    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16630    fn spanned_rows(
16631        &self,
16632        include_end_if_at_line_start: bool,
16633        map: &DisplaySnapshot,
16634    ) -> Range<MultiBufferRow>;
16635}
16636
16637impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16638    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16639        let start = self
16640            .start
16641            .to_point(&map.buffer_snapshot)
16642            .to_display_point(map);
16643        let end = self
16644            .end
16645            .to_point(&map.buffer_snapshot)
16646            .to_display_point(map);
16647        if self.reversed {
16648            end..start
16649        } else {
16650            start..end
16651        }
16652    }
16653
16654    fn spanned_rows(
16655        &self,
16656        include_end_if_at_line_start: bool,
16657        map: &DisplaySnapshot,
16658    ) -> Range<MultiBufferRow> {
16659        let start = self.start.to_point(&map.buffer_snapshot);
16660        let mut end = self.end.to_point(&map.buffer_snapshot);
16661        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16662            end.row -= 1;
16663        }
16664
16665        let buffer_start = map.prev_line_boundary(start).0;
16666        let buffer_end = map.next_line_boundary(end).0;
16667        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16668    }
16669}
16670
16671impl<T: InvalidationRegion> InvalidationStack<T> {
16672    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16673    where
16674        S: Clone + ToOffset,
16675    {
16676        while let Some(region) = self.last() {
16677            let all_selections_inside_invalidation_ranges =
16678                if selections.len() == region.ranges().len() {
16679                    selections
16680                        .iter()
16681                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16682                        .all(|(selection, invalidation_range)| {
16683                            let head = selection.head().to_offset(buffer);
16684                            invalidation_range.start <= head && invalidation_range.end >= head
16685                        })
16686                } else {
16687                    false
16688                };
16689
16690            if all_selections_inside_invalidation_ranges {
16691                break;
16692            } else {
16693                self.pop();
16694            }
16695        }
16696    }
16697}
16698
16699impl<T> Default for InvalidationStack<T> {
16700    fn default() -> Self {
16701        Self(Default::default())
16702    }
16703}
16704
16705impl<T> Deref for InvalidationStack<T> {
16706    type Target = Vec<T>;
16707
16708    fn deref(&self) -> &Self::Target {
16709        &self.0
16710    }
16711}
16712
16713impl<T> DerefMut for InvalidationStack<T> {
16714    fn deref_mut(&mut self) -> &mut Self::Target {
16715        &mut self.0
16716    }
16717}
16718
16719impl InvalidationRegion for SnippetState {
16720    fn ranges(&self) -> &[Range<Anchor>] {
16721        &self.ranges[self.active_index]
16722    }
16723}
16724
16725pub fn diagnostic_block_renderer(
16726    diagnostic: Diagnostic,
16727    max_message_rows: Option<u8>,
16728    allow_closing: bool,
16729    _is_valid: bool,
16730) -> RenderBlock {
16731    let (text_without_backticks, code_ranges) =
16732        highlight_diagnostic_message(&diagnostic, max_message_rows);
16733
16734    Arc::new(move |cx: &mut BlockContext| {
16735        let group_id: SharedString = cx.block_id.to_string().into();
16736
16737        let mut text_style = cx.window.text_style().clone();
16738        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16739        let theme_settings = ThemeSettings::get_global(cx);
16740        text_style.font_family = theme_settings.buffer_font.family.clone();
16741        text_style.font_style = theme_settings.buffer_font.style;
16742        text_style.font_features = theme_settings.buffer_font.features.clone();
16743        text_style.font_weight = theme_settings.buffer_font.weight;
16744
16745        let multi_line_diagnostic = diagnostic.message.contains('\n');
16746
16747        let buttons = |diagnostic: &Diagnostic| {
16748            if multi_line_diagnostic {
16749                v_flex()
16750            } else {
16751                h_flex()
16752            }
16753            .when(allow_closing, |div| {
16754                div.children(diagnostic.is_primary.then(|| {
16755                    IconButton::new("close-block", IconName::XCircle)
16756                        .icon_color(Color::Muted)
16757                        .size(ButtonSize::Compact)
16758                        .style(ButtonStyle::Transparent)
16759                        .visible_on_hover(group_id.clone())
16760                        .on_click(move |_click, window, cx| {
16761                            window.dispatch_action(Box::new(Cancel), cx)
16762                        })
16763                        .tooltip(|window, cx| {
16764                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16765                        })
16766                }))
16767            })
16768            .child(
16769                IconButton::new("copy-block", IconName::Copy)
16770                    .icon_color(Color::Muted)
16771                    .size(ButtonSize::Compact)
16772                    .style(ButtonStyle::Transparent)
16773                    .visible_on_hover(group_id.clone())
16774                    .on_click({
16775                        let message = diagnostic.message.clone();
16776                        move |_click, _, cx| {
16777                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16778                        }
16779                    })
16780                    .tooltip(Tooltip::text("Copy diagnostic message")),
16781            )
16782        };
16783
16784        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16785            AvailableSpace::min_size(),
16786            cx.window,
16787            cx.app,
16788        );
16789
16790        h_flex()
16791            .id(cx.block_id)
16792            .group(group_id.clone())
16793            .relative()
16794            .size_full()
16795            .block_mouse_down()
16796            .pl(cx.gutter_dimensions.width)
16797            .w(cx.max_width - cx.gutter_dimensions.full_width())
16798            .child(
16799                div()
16800                    .flex()
16801                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16802                    .flex_shrink(),
16803            )
16804            .child(buttons(&diagnostic))
16805            .child(div().flex().flex_shrink_0().child(
16806                StyledText::new(text_without_backticks.clone()).with_highlights(
16807                    &text_style,
16808                    code_ranges.iter().map(|range| {
16809                        (
16810                            range.clone(),
16811                            HighlightStyle {
16812                                font_weight: Some(FontWeight::BOLD),
16813                                ..Default::default()
16814                            },
16815                        )
16816                    }),
16817                ),
16818            ))
16819            .into_any_element()
16820    })
16821}
16822
16823fn inline_completion_edit_text(
16824    current_snapshot: &BufferSnapshot,
16825    edits: &[(Range<Anchor>, String)],
16826    edit_preview: &EditPreview,
16827    include_deletions: bool,
16828    cx: &App,
16829) -> HighlightedText {
16830    let edits = edits
16831        .iter()
16832        .map(|(anchor, text)| {
16833            (
16834                anchor.start.text_anchor..anchor.end.text_anchor,
16835                text.clone(),
16836            )
16837        })
16838        .collect::<Vec<_>>();
16839
16840    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16841}
16842
16843pub fn highlight_diagnostic_message(
16844    diagnostic: &Diagnostic,
16845    mut max_message_rows: Option<u8>,
16846) -> (SharedString, Vec<Range<usize>>) {
16847    let mut text_without_backticks = String::new();
16848    let mut code_ranges = Vec::new();
16849
16850    if let Some(source) = &diagnostic.source {
16851        text_without_backticks.push_str(source);
16852        code_ranges.push(0..source.len());
16853        text_without_backticks.push_str(": ");
16854    }
16855
16856    let mut prev_offset = 0;
16857    let mut in_code_block = false;
16858    let has_row_limit = max_message_rows.is_some();
16859    let mut newline_indices = diagnostic
16860        .message
16861        .match_indices('\n')
16862        .filter(|_| has_row_limit)
16863        .map(|(ix, _)| ix)
16864        .fuse()
16865        .peekable();
16866
16867    for (quote_ix, _) in diagnostic
16868        .message
16869        .match_indices('`')
16870        .chain([(diagnostic.message.len(), "")])
16871    {
16872        let mut first_newline_ix = None;
16873        let mut last_newline_ix = None;
16874        while let Some(newline_ix) = newline_indices.peek() {
16875            if *newline_ix < quote_ix {
16876                if first_newline_ix.is_none() {
16877                    first_newline_ix = Some(*newline_ix);
16878                }
16879                last_newline_ix = Some(*newline_ix);
16880
16881                if let Some(rows_left) = &mut max_message_rows {
16882                    if *rows_left == 0 {
16883                        break;
16884                    } else {
16885                        *rows_left -= 1;
16886                    }
16887                }
16888                let _ = newline_indices.next();
16889            } else {
16890                break;
16891            }
16892        }
16893        let prev_len = text_without_backticks.len();
16894        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16895        text_without_backticks.push_str(new_text);
16896        if in_code_block {
16897            code_ranges.push(prev_len..text_without_backticks.len());
16898        }
16899        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16900        in_code_block = !in_code_block;
16901        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16902            text_without_backticks.push_str("...");
16903            break;
16904        }
16905    }
16906
16907    (text_without_backticks.into(), code_ranges)
16908}
16909
16910fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16911    match severity {
16912        DiagnosticSeverity::ERROR => colors.error,
16913        DiagnosticSeverity::WARNING => colors.warning,
16914        DiagnosticSeverity::INFORMATION => colors.info,
16915        DiagnosticSeverity::HINT => colors.info,
16916        _ => colors.ignored,
16917    }
16918}
16919
16920pub fn styled_runs_for_code_label<'a>(
16921    label: &'a CodeLabel,
16922    syntax_theme: &'a theme::SyntaxTheme,
16923) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16924    let fade_out = HighlightStyle {
16925        fade_out: Some(0.35),
16926        ..Default::default()
16927    };
16928
16929    let mut prev_end = label.filter_range.end;
16930    label
16931        .runs
16932        .iter()
16933        .enumerate()
16934        .flat_map(move |(ix, (range, highlight_id))| {
16935            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16936                style
16937            } else {
16938                return Default::default();
16939            };
16940            let mut muted_style = style;
16941            muted_style.highlight(fade_out);
16942
16943            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16944            if range.start >= label.filter_range.end {
16945                if range.start > prev_end {
16946                    runs.push((prev_end..range.start, fade_out));
16947                }
16948                runs.push((range.clone(), muted_style));
16949            } else if range.end <= label.filter_range.end {
16950                runs.push((range.clone(), style));
16951            } else {
16952                runs.push((range.start..label.filter_range.end, style));
16953                runs.push((label.filter_range.end..range.end, muted_style));
16954            }
16955            prev_end = cmp::max(prev_end, range.end);
16956
16957            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16958                runs.push((prev_end..label.text.len(), fade_out));
16959            }
16960
16961            runs
16962        })
16963}
16964
16965pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16966    let mut prev_index = 0;
16967    let mut prev_codepoint: Option<char> = None;
16968    text.char_indices()
16969        .chain([(text.len(), '\0')])
16970        .filter_map(move |(index, codepoint)| {
16971            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16972            let is_boundary = index == text.len()
16973                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16974                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16975            if is_boundary {
16976                let chunk = &text[prev_index..index];
16977                prev_index = index;
16978                Some(chunk)
16979            } else {
16980                None
16981            }
16982        })
16983}
16984
16985pub trait RangeToAnchorExt: Sized {
16986    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16987
16988    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16989        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16990        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16991    }
16992}
16993
16994impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16995    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16996        let start_offset = self.start.to_offset(snapshot);
16997        let end_offset = self.end.to_offset(snapshot);
16998        if start_offset == end_offset {
16999            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17000        } else {
17001            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17002        }
17003    }
17004}
17005
17006pub trait RowExt {
17007    fn as_f32(&self) -> f32;
17008
17009    fn next_row(&self) -> Self;
17010
17011    fn previous_row(&self) -> Self;
17012
17013    fn minus(&self, other: Self) -> u32;
17014}
17015
17016impl RowExt for DisplayRow {
17017    fn as_f32(&self) -> f32 {
17018        self.0 as f32
17019    }
17020
17021    fn next_row(&self) -> Self {
17022        Self(self.0 + 1)
17023    }
17024
17025    fn previous_row(&self) -> Self {
17026        Self(self.0.saturating_sub(1))
17027    }
17028
17029    fn minus(&self, other: Self) -> u32 {
17030        self.0 - other.0
17031    }
17032}
17033
17034impl RowExt for MultiBufferRow {
17035    fn as_f32(&self) -> f32 {
17036        self.0 as f32
17037    }
17038
17039    fn next_row(&self) -> Self {
17040        Self(self.0 + 1)
17041    }
17042
17043    fn previous_row(&self) -> Self {
17044        Self(self.0.saturating_sub(1))
17045    }
17046
17047    fn minus(&self, other: Self) -> u32 {
17048        self.0 - other.0
17049    }
17050}
17051
17052trait RowRangeExt {
17053    type Row;
17054
17055    fn len(&self) -> usize;
17056
17057    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17058}
17059
17060impl RowRangeExt for Range<MultiBufferRow> {
17061    type Row = MultiBufferRow;
17062
17063    fn len(&self) -> usize {
17064        (self.end.0 - self.start.0) as usize
17065    }
17066
17067    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17068        (self.start.0..self.end.0).map(MultiBufferRow)
17069    }
17070}
17071
17072impl RowRangeExt for Range<DisplayRow> {
17073    type Row = DisplayRow;
17074
17075    fn len(&self) -> usize {
17076        (self.end.0 - self.start.0) as usize
17077    }
17078
17079    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17080        (self.start.0..self.end.0).map(DisplayRow)
17081    }
17082}
17083
17084/// If select range has more than one line, we
17085/// just point the cursor to range.start.
17086fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17087    if range.start.row == range.end.row {
17088        range
17089    } else {
17090        range.start..range.start
17091    }
17092}
17093pub struct KillRing(ClipboardItem);
17094impl Global for KillRing {}
17095
17096const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17097
17098fn all_edits_insertions_or_deletions(
17099    edits: &Vec<(Range<Anchor>, String)>,
17100    snapshot: &MultiBufferSnapshot,
17101) -> bool {
17102    let mut all_insertions = true;
17103    let mut all_deletions = true;
17104
17105    for (range, new_text) in edits.iter() {
17106        let range_is_empty = range.to_offset(&snapshot).is_empty();
17107        let text_is_empty = new_text.is_empty();
17108
17109        if range_is_empty != text_is_empty {
17110            if range_is_empty {
17111                all_deletions = false;
17112            } else {
17113                all_insertions = false;
17114            }
17115        } else {
17116            return false;
17117        }
17118
17119        if !all_insertions && !all_deletions {
17120            return false;
17121        }
17122    }
17123    all_insertions || all_deletions
17124}